Skip to content
Regolo Logo
Tutorial & How‑to

Building a Self-Improving Secure Coding Loop with Deepsec, Open SWE e Cognee

Alex Genovese
6 min read
Share

How modern engineering teams build an autonomous, memory-augmented remediation pipeline using Open SWE, Deepsec, Cognee, and Brick (brick-complexity-pro) on Regolo to eliminate recurring vulnerabilities and cut LLM inference costs by over 80%.


Key takeaways

  • Stateless Coding Flaw Solved: traditional coding agents suffer from stateless blindness, repeating architectural and security mistakes across sessions. Integrating an enterprise Knowledge Graph (Cognee) ensures past security decisions, CWE remediations, and PR outcomes persist.
  • Dual-Agent Verification: Generative code production (Open SWE) is decoupled from zero-trust security audits (Deepsec), guaranteeing patches drop vulnerability counts to zero before opening a PR.
  • Dynamic Semantic Multi-Model Routing: Orchestrated via brick-complexity-pro on Regolo.ai, sub-tasks route dynamically to task-fit models (gpt-oss-20b for triage/graph ops, qwen3.5-122b for architecture/verification, Llama-3.3-70B-Instruct for patch writing, and GLM-5.2 for security auditing).
  • Cost Efficiency: Multi-model routing achieves parity with single-frontier systems (e.g., GPT-4o/Claude 3.5 Sonnet baselines) while slashing token costs by 83.3% and latency to ~2.1s per remediation cycle.
  • Human-in-the-Loop Governance: Generates unified diffs and PR_EVIDENCE.md reports alongside an explicit human approval gate before pushing changes to production repositories.

What is a self-improving secure coding loop?

A self-improving secure coding loop is an autonomous software engineering workflow that ingests vulnerability reports, plans and executes code repairs in isolated sandboxes, subjects patches to automated SAST/AST security gates, and permanently writes the architectural decision into an organizational knowledge graph.

┌────────────────────────────────────────────────────────────────────────────────────────┐
│                                 THE CLOSED-LOOP LIFECYCLE                              │
│                                                                                        │
│   Open SWE (Produce) ➔ Deepsec (Verify) ➔ Cognee (Remember) ➔ Brick (Govern)          │
│                                                                                        │
│   1. Triage & Route   : Classify intent and assign compute tier via Brick Meta-Router  │
│   2. Memory Recall    : Pull historical CWE rules & architectural constraints (Cognee) │
│   3. Plan Remediation : Generate step-by-step fix with reasoning model (qwen3.5-122b)  │
│   4. Human Approval   : Review structured implementation plan before code execution    │
│   5. Patch Execution  : Apply defensive code edits in sandbox (Llama-3.3-70B)          │
│   6. Zero-Trust Gate  : Re-scan sandbox to verify 0 findings (Deepsec / GLM-5.2)       │
│   7. Graph Mutation   : Store `Issue ➔ Patch ➔ Verification` link in Knowledge Graph   │
└────────────────────────────────────────────────────────────────────────────────────────┘Code language: JavaScript (javascript)

Unlike single-prompt coding assistants that generate untracked code snippets, a closed-loop system pairs code generation with deterministic verification and persistent contextual memory.


Why do single-frontier coding agents fail in production?

Standard AI developer tools and single-prompt coding agents introduce three major operational bottlenecks:

1. Stateless Blindness

LLMs process each prompt with an ephemeral context window. When an agent patches a cross-site scripting (CWE-79) or SQL injection (CWE-89) issue today, it retains zero context when a developer touches an adjacent authentication module months later.

2. Alert Fatigue Without Remediation

Traditional Static Application Security Testing (SAST) tools generate static alerts without patch capability. Conversely, standard code generation models often “hallucinate” security fixes—introducing subtle regressions or broken business logic that scanners fail to flag until staging.

3. Runaway Inference Costs

Routing trivial tasks (intent classification, JSON schema formatting, git commit message drafting) to massive frontier models drives infrastructure costs up without improving output quality


Architecture: dynamic multi-model routing with Brick Complexity Pro

To achieve enterprise-grade reliability at minimal cost, the pipeline decouples sub-agent responsibilities across specialized models hosted on Regolo, orchestrated via the brick-complexity-pro meta-router.

Brick is the runtime decision-maker (the dynamic semantic router), while the Matrix is the governed policy framework it operates within. It does not assign static hardcoded routes; it evaluates every incoming task at runtime using the brick-complexity-pro meta-model on Regolo.

Incoming Task Prompt + Stage Profile
                 │
                 ▼
┌────────────────────────────────────────────────────────┐
│     Brick Router (`brick-complexity-pro` Meta-Model)   │
│                                                        │
│  Evaluates:                                            │
│  1. Semantic Complexity Score (1.0 - 10.0)             │
│  2. Sub-Agent Role & Requested Tools                   │
│  3. Residual Token Budget Ratio (% remaining)          │
│  4. Stage Criticality & Retry History                  │
└────────────────────────────────────────────────────────┘
                 │
                 ├─► Complexity >= 7.0 / Retry ──► ESCALATED Tier (`qwen3.5-122b`)
                 ├─► Budget < 20% & Non-Critical ─► DOWNSCALED Tier (`gpt-oss-20b`)
                 └─► Standard Conditions ────────► BALANCED/FAST Tier (e.g. `Llama-3.3-70B` / `GLM-5.2`)Code language: Bash (bash)

Getting Started

Follow these steps to deploy the closed-loop agent locally.

Step 1: system requirements & installation

Ensure Python 3.10+ and Docker are installed on your host machine:

# Clone and run automated environment setup
git clone <your-repo-url>
cd "Self-Improving Secure Coding Loop"
./setup.shCode language: Bash (bash)

Step 2: environment configuration

Create a .env file containing your Regolo API credentials:

cp .env.example .envCode language: Bash (bash)

Configure your API endpoint and model parameters:

REGOLO_API_KEY=your_regolo_api_key_here
REGOLO_BASE_URL=https://api.regolo.ai/v1
MODEL_BRICK_ROUTER=brick-complexity-proCode language: Bash (bash)

Step 3: service orchestration & port discovery

The agent requires local instances of Qdrant (vector search) and Cognee (knowledge graph backend). The built-in service manager (core/docker_manager.py) automatically scans host TCP ports to prevent conflicts:

  • Automatic Image Pull: Downloads qdrant/qdrant:latest and cognee/cognee:main.
  • Incremental Port Binding: If default ports 6333 or 8800 are busy, the orchestrator increments automatically (6333 ➔ 6334, 8800 ➔ 8801) and updates service connection URLs dynamically.

Launch the service manager or start the application directly:

./run.shCode language: Bash (bash)

Executing the bug fix workflow

When running the interactive Terminal User Interface (TUI), select [1] Run Full Closed Loop to execute the pipeline on a target repository:

╔═════════════════════════════════════════════════════════════════════════════════════════╗
║       ⚡ SELF-IMPROVING SECURE CODING LOOP ⚡                                            ║
║   Open SWE (Produce) ➔ Deepsec (Verify) ➔ Cognee (Remember) ➔ Brick (Govern)            ║
║   Inference: Regolo.ai • Router: Brick (brick-complexity-pro) • Multi-Model             ║
╚═════════════════════════════════════════════════════════════════════════════════════════╝Code language: Bash (bash)

Remediation lifecycle stages:

  1. Target Selection: Choose from pre-configured vulnerable microservices (or provide custom repo paths).
  2. Deepsec Initial Audit: An AST-level analysis flags vulnerable code paths, lines, and corresponding Common Weakness Enumerations (CWEs).
  3. Memory Graph Recall: Cognee queries past remediations to inject project-specific constraints and defensive coding standards into the prompt.
  4. Architectural Planning: Open SWE Planner (qwen3.5-122b) outputs a structured remediation plan.
  5. Human Approval Gate: The operator reviews the proposed approach and grants explicit authorization before code is modified.
  6. Sandbox Patch Application: Open SWE Executor (Llama-3.3-70B-Instruct) applies changes in an isolated workspace.
  7. Deepsec Independent Revalidation: Deepsec scans the modified codebase. If residual vulnerabilities or test failures exist, execution loops back for refinement.
  8. Knowledge Graph Ingestion: Upon passing all security gates, the fix is persisted into Cognee, and PR_EVIDENCE.md is compiled.

Supported Vulnerability Test Catalog

The project includes 7 production-grade microservice testbeds in sample_repos/ covering standard high-severity vulnerabilities:

Target ServiceFrameworkTarget CWEsProduction Impact
1. AuthServiceFastAPICWE-89 (SQLi), CWE-287 (JWT Confusion)Database extraction & forged admin privileges
2. Webhook GatewayFastAPI / RequestsCWE-918 (SSRF), CWE-78 (Command Injection)Cloud metadata exfiltration (169.254.169.254) & Host RCE
3. E-Commerce CartFastAPICWE-639 (IDOR), CWE-20 (Input Tampering)Cross-user order inspection & checkout price manipulation
4. File Storage APIFastAPI / POSIXCWE-22 (Path Traversal), CWE-434 (Unrestricted Upload)Reading /etc/passwd & arbitrary script execution
5. Analytics EngineFastAPI / PythonCWE-94 (Code Injection eval), CWE-502 (Pickle Deserialization)Unauthenticated remote code execution
6. Crypto WalletFastAPI / CryptographyCWE-798 (Hardcoded Secret), CWE-338 (Weak PRNG)Key leakage & predictable address generation
7. User Profile APIFastAPI / HTMLCWE-79 (Stored XSS), CWE-915 (Mass Assignment)Session hijacking & unauthorized role updates

Cost & Latency Benchmark: Regolo Multi-Model vs. Single-Frontier

By leveraging Regolo.ai’s dynamic routing, teams eliminate the financial overhead of running monolithic frontier models for routine pipeline operations.

Empirical Performance Comparison

Pipeline StageRouted ModelTokens (Prompt / Completion)LatencyRegolo CostFrontier BaselineCost Reduction
Classify & Triagegpt-oss-20b340 / 1200.25s$0.00009$0.00282-96.8%
Cognee Memory & Planqwen3.5-122b620 / 3100.42s$0.00183$0.00651-71.9%
Sandbox ImplementationLlama-3.3-70B-Instruct950 / 4800.51s$0.00163$0.01005-83.8%
Deepsec Initial AuditGLM-5.2840 / 3900.40s$0.00121$0.00837-85.6%
Deepsec Revalidationqwen3.5-122b580 / 2100.38s$0.00143$0.00489-70.8%
Cognee Graph Updategpt-oss-20b490 / 2400.22s$0.00015$0.00507-97.0%
TOTALS~6,070 tokens~2.1s~$0.0063~$0.0377~83.3% Savings

Frequently Asked Questions (FAQ)

How does generator-verifier separation prevent hallucinated security fixes?

Standard code generators evaluate their own code optimistically. Decoupling the generator (Open SWE) from the validator (Deepsec) ensures that patches are audited by a separate, zero-trust evaluation model using static AST parsing and security policies, rejecting code if findings are not zero.

Why does Qwen 3.5 require a higher max_tokens threshold?

qwen3.5-122b is a reasoning model. Setting max_tokens >= 800 is mandatory to avoid token exhaustion during its internal chain-of-thought (thinking) phase, ensuring a complete, valid patch is returned.

How does Cognee prevent repeat vulnerabilities across development teams?

Cognee constructs an interconnected semantic graph mapping Issue ➔ CWE ➔ Defensive Fix ➔ Decision. During subsequent pipeline executions, vector and graph searches retrieve historical mitigation strategies, preventing regression to known flawed patterns.


Start downloading the code

Use our self-improving secure coding pipeline transforms vulnerability triage from a manual chore into an autonomous, cost-effective engineering asset: you can start downloading the repo and select your custom project folder to scan and detect security issues.

By combining persistent memory graphs with zero-trust security audits and dynamic semantic routing on Regolo, development teams can fix security vulnerabilities faster while retaining institutional knowledge across every pull request.

To integrate this architecture into your CI/CD workflow:

  1. Clone the repository and configure your Regolo API Key.
  2. Run ./setup.sh and initialize the Docker backend services.
  3. Test the loop against the pre-packaged microservices in sample_repos/ before attaching your production git repositories.

Github code

You can download the codes on our Github repo, just download and follow the README steps. If need help you can always reach out our team on Discord 🤙


Ship Private AI. Not Infrastructure.

You have the private AI App architecture, bow give it an inference layer built for production.

Regolo gives European teams fast, OpenAI-compatible access to Mistral, Llama, Qwen, DeepSeek, GLM, and more — with zero data retention, EU data residency, and no new SDK to learn.

Change your base_url. Keep your LangChain code. Start shipping.

🚀 Start your 30-day free trial →

Build, test, and deploy with no infrastructure to maintain.
No credit card. No migration project. No compromise on data control.

💬 Join the Regolo Discord →

Meet builders working on private RAG, local LLMs, LangChain, Ollama, and production AI systems. Share your setup, get feedback from the community, and speak directly with the Regolo team.

🤝 Talk to an AI Infrastructure Engineer →

Running a sensitive workload, scaling beyond a proof of concept, or assessing a managed EU inference provider? Get a tailored architecture and commercial proposal for your team.

📂 Clone the GitHub repository →

Get the full implementation from this guide: ingestion scripts, ChromaDB setup, hybrid retrieval, the 30-Question RAG Floor, evaluation examples, and deployment configuration.

Private AI should not require a private data center.
Regolo gives your team an EU-native path from local experimentation to production-grade inference.


Build with Regolo


Built with ❤️ by the Regolo team. Questions? regolo.ai/contact or chat with us on Discord