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

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%.

https://youtu.be/ddCECOq1EnQ 

---

### 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.

---

![](https://regolo.ai/wp-content/uploads/2026/08/self-improving-close-loop-1024x628.png)## 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](https://regolo.ai), 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 &amp; 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 &amp; 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:

![](https://regolo.ai/wp-content/uploads/2026/08/self-improving-close-loop-2-1024x944.png)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 Service | Framework | Target CWEs | Production Impact |
|---|---|---|---|
| **1. AuthService** | FastAPI | `CWE-89` (SQLi), `CWE-287` (JWT Confusion) | Database extraction &amp; forged admin privileges |
| **2. Webhook Gateway** | FastAPI / Requests | `CWE-918` (SSRF), `CWE-78` (Command Injection) | Cloud metadata exfiltration (`169.254.169.254`) &amp; Host RCE |
| **3. E-Commerce Cart** | FastAPI | `CWE-639` (IDOR), `CWE-20` (Input Tampering) | Cross-user order inspection &amp; checkout price manipulation |
| **4. File Storage API** | FastAPI / POSIX | `CWE-22` (Path Traversal), `CWE-434` (Unrestricted Upload) | Reading `/etc/passwd` &amp; arbitrary script execution |
| **5. Analytics Engine** | FastAPI / Python | `CWE-94` (Code Injection `eval`), `CWE-502` (Pickle Deserialization) | Unauthenticated remote code execution |
| **6. Crypto Wallet** | FastAPI / Cryptography | `CWE-798` (Hardcoded Secret), `CWE-338` (Weak PRNG) | Key leakage &amp; predictable address generation |
| **7. User Profile API** | FastAPI / HTML | `CWE-79` (Stored XSS), `CWE-915` (Mass Assignment) | Session hijacking &amp; unauthorized role updates |

---

## Cost &amp; 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 Stage | Routed Model | Tokens (Prompt / Completion) | Latency | Regolo Cost | Frontier Baseline | Cost Reduction |
|---|---|---|---|---|---|---|
| **Classify &amp; Triage** | `gpt-oss-20b` | 340 / 120 | 0.25s | $0.00009 | $0.00282 | **-96.8%** |
| **Cognee Memory &amp; Plan** | `qwen3.5-122b` | 620 / 310 | 0.42s | $0.00183 | $0.00651 | **-71.9%** |
| **Sandbox Implementation** | `Llama-3.3-70B-Instruct` | 950 / 480 | 0.51s | $0.00163 | $0.01005 | **-83.8%** |
| **Deepsec Initial Audit** | `GLM-5.2` | 840 / 390 | 0.40s | $0.00121 | $0.00837 | **-85.6%** |
| **Deepsec Revalidation** | `qwen3.5-122b` | 580 / 210 | 0.38s | $0.00143 | $0.00489 | **-70.8%** |
| **Cognee Graph Update** | `gpt-oss-20b` | 490 / 240 | 0.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](https://regolo.ai), 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](https://github.com/regolo-ai/tutorials/tree/main/self-Improving-secure-coding-loop) and configure your [Regolo API Key](https://regolo.ai).
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](https://discord.gg/gVcxQz7Y) 🤙

[Download the codes](https://github.com/regolo-ai/tutorials/tree/main/self-Improving-secure-coding-loop)

---

## 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 →](https://regolo.ai/?utm_source=blog&utm_medium=cta&utm_campaign=private-rag)

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

### 💬 [Join the Regolo Discord →](https://discord.gg/bqGrVJHeF)

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 →](https://regolo.ai/contact?utm_source=blog&utm_medium=cta&utm_campaign=private-rag)

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 →](https://github.com/regolo-ai/tutorials/)

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

- **Discord:** [Join the community →](https://discord.gg/bqGrVJHeF)
- **GitHub:** [Explore open-source workflows →](https://github.com/regolo-ai/tutorials/)
- **X / Twitter:** [Follow @regolo\_ai →](https://x.com/regolo_ai)
- **Reddit:** [Join the community →](https://www.reddit.com/r/regolo_ai/)
- **Documentation:** [Read the API docs →](https://docs.regolo.ai)
- **Contact:** [Talk to the team →](https://regolo.ai/contact)

---

*Built with ❤️ by the Regolo team. Questions? [regolo.ai/contact](https://regolo.ai/contact)* or chat with us on [Discord](https://discord.gg/bqGrVJHeF)