# Local SAST with Baco Scanner: scan and patch codebases

Run a 24-phase security audit directly from your terminal, track token expenses down to the sub-cent with Brick Complexity Pro, and generate verified Git patches on European cloud infrastructure.

Most security scanners drop a 40-page PDF with 120 false positives in your lap and consider their job done and you still have to spend Friday afternoon figuring out what actually matters, cross-referencing Common Weakness Enumerations (CWEs), and writing the patches by hand.

Static Application Security Testing (SAST) should not be an exercise in alert fatigue or compliance theater. It's a "white-box" security testing method that analyzes source code (or binaries) at rest, without executing the application. It is used to identify vulnerabilities (such as SQL injection, XSS, or hardcoded credentials) and architectural flaws during the early stages of development ("shift-left"), prior to compilation or release to production.

In this tutorial, you will set up and run the **BACO Scanner with TUI and remediation feature using Brick Complexity Pro** . You will learn how to scan any local repository with zero manual configuration, monitor the 24-phase analysis pipeline in real time, audit your exact scan costs in EUR (€0.12 per million tokens), and generate ready-to-apply `.patch` files using European AI infrastructure with zero data retention.

https://youtu.be/Os4z0dbfRTI 

---

## What you will build and learn

By completing this walkthrough, you will:

1. Launch an interactive Terminal User Interface (TUI) requiring zero external Python dependencies.
2. Connect BACO to **Regolo.ai** using the **Brick Complexity Pro** model running entirely on EU infrastructure.
3. Target any local project via terminal drag-and-drop while automatically inheriting its `.gitignore` rules.
4. Observe a hybrid 24-phase pipeline combining Semgrep static rules with LLM-based static analysis, CWE classification, and threat modeling.
5. Inspect an executive cost card that calculates token consumption and EUR expenses in real time.
6. Generate a full remediation package containing unified `.patch` files, structured `fixes.json`, and prompt instructions for IDE agents (Cursor, Claude Code, GitHub Copilot).
7. Run headless CLI commands for continuous integration and automated auditing scripts.

```
┌────────────────────────────────────────────────────────────────────────┐
│                        BACO SCANNER TUI WORKFLOW                       │
├─────────────────┬───────────────────┬──────────────────┬───────────────┤
│ 1. Setup Env    │ 2. Scan Target    │ 3. View Summary  │ 4. Auto-Patch │
│ Regolo API key  │ Drag-and-drop     │ 24-Phase log     │ Unified diffs │
│ Model selection │ .gitignore merge  │ EUR cost (€0.12) │ git apply     │
└─────────────────┴───────────────────┴──────────────────┴───────────────┘Code language: Bash (bash)
```

---

## Prerequisites

Before starting, verify your machine has the following tools installed:

| Tool | Minimum Version | Purpose | Installation Command |
|---|---|---|---|
| **Python** | 3.10+ | Runs the interactive TUI (standard library only) | `python3 --version` |
| **Rust / Cargo** | 1.70+ | Compiles the core BACO scanner engine | `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \| sh` |
| **Semgrep** | Optional | High-speed static pattern matching | `brew install semgrep` or `pipx install semgrep` |
| **Regolo API Key** | Active account | Inference endpoint for static analysis and auto-patching | Obtain at [regolo.ai](https://regolo.ai) |

> **Privacy Note:** Regolo operates exclusively within the European Union under strict zero data retention policies. Your source code snippets analyzed during the scan are neither logged nor used for model training.

---

![](http://regolo.ai/wp-content/uploads/2026/09/Regolo-get-30-days-free-green.jpg)

### **Try GLM 5.2 or Qwen3.8 27 for 30 days free**

Sign up, grab your API key, and route between frontier open source models with zero data retention in EU infrastructure.

[Start your free 30-day trial](https://regolo.ai/signup?utm_source=blog&utm_medium=article_cta&utm_campaign=benchmarks_sept26&utm_content=flash-tier)

---

## Step 1: environment &amp; model configuration

The BACO TUI manages its own configuration through an automated setup wizard. It talks to the Regolo OpenAI-compatible endpoint (`https://api.regolo.ai/v1`) and tunes local configuration parameters without requiring you to write raw TOML.

### 1. Launch the TUI

From the project root directory, run the launcher script:

```
chmod +x launch.sh
./launch.shCode language: Bash (bash)
```

Alternatively, invoke Python directly:

```
python3 baco_tui.pyCode language: Bash (bash)
```

On first launch, if the BACO Rust binary is not yet compiled, the TUI automatically clones `https://github.com/CodeAtCode/baco-scanner.git` and triggers `cargo build --release --locked`.

### 2. Run Option \[1\] Setup Environment

You will see the main menu:

```
╔══════════════════════════════════════════════════════════════════════╗
║  BACO — Bug Analysis & Cross-reference Orchestrator                  ║
║  Powered by Regolo - Zero Data Retention, EU infra                   ║
║  Cost: €0.12 / 1M tokens (Brick Complexity Pro)                      ║
╚══════════════════════════════════════════════════════════════════════╝
  [1] Setup Environment (Regolo.ai API Key & Model Selection)
  [2] Scan Repository & View Findings + Brick Complexity Pro Cost
  [3] Generate AI Fixes for Vulnerabilities (Regolo LLM)
  [4] ExitCode language: Bash (bash)
```

Type `1` and press `Enter`.

1. **Enter your API Key:** Paste your `REGOLO_API_KEY`. The TUI will mask the key and save it into `.env` (which is excluded from Git).
2. **Model Selection:** The TUI queries `https://api.regolo.ai/v1/models` in real time. It presents the active catalog, prioritizing `brick-complexity-pro`:

```
Available Models on Regolo.ai:
  [1] brick-complexity-pro (Default / Recommended)
  [2] qwen3-coder-next
  [3] mistral-small-4-119b
  [4] Llama-3.3-70B-Instruct

Select model [1-4] or press Enter for brick-complexity-pro:Code language: Bash (bash)
```

Press `Enter` to confirm `brick-complexity-pro`.

The TUI automatically writes an optimized `my-config.toml` that routes all analysis phases (discovery, verification, aggregation, and complexity classification) through your chosen Regolo model:

```
# Generated snippet from my-config.toml
[llm.phases.discovery]
base_url = "https://api.regolo.ai/v1"
api_key = "regolo_sk_..."
model = "brick-complexity-pro"

[brick]
base_url = "https://api.regolo.ai/v1"
api_key = "regolo_sk_..."
model = "brick-complexity-pro"Code language: Bash (bash)
```

---

## Step 2: scanning a local project the easy way

Traditional scanners force you to write ignore files, adjust root paths, and battle path escaping, the BACO TUI eliminates this friction through two built-in mechanisms:

1. **Terminal Drag-and-Drop Path Sanitization:** you can drag any folder from macOS Finder or Linux file managers directly into your terminal. The TUI automatically strips single quotes, double quotes, backslash-escaped spaces (`\` ), and resolves home directory tildes (`~`).
2. **Automatic `.gitignore` Ingestion:** when you select a local folder, BACO inspects whether that project contains a `.gitignore`. If present, all project-specific ignore patterns are read and appended to the scanner's exclude list alongside defaults (`node_modules/**`, `.venv/**`, `target/**`, `dist/**`, `.git/**`, and secret keys).

### Testing with the Included Demo App

The repository includes a sample target in `demo-vulnerable-app/`. Let's scan it first to see the pipeline in action.

1. From the main menu, select **\[2\] Scan Repository &amp; View Findings + Brick Complexity Pro Cost**.
2. When prompted for the path:

```
Repository or folder path to scan [Press Enter for .]: demo-vulnerable-appCode language: Bash (bash)
```

Press `Enter`.

The TUI immediately normalizes the target path and parses its exclusion rules:

```
 ✓ Target selected: /Users/alexgenovese/Desktop/regolo/video/6 - Baco Scanner/demo-vulnerable-app
 ℹ Loaded 14 exclusion patterns from .gitignore
 ℹ Starting Baco Scanner 24-phase pipeline...Code language: Bash (bash)
```

### Scanning Any External Local Project

To scan any independent codebase on your machine, simply choose **\[2\]** and drag the target folder into the prompt:

```
Repository or folder path to scan [Press Enter for .]: '/Users/alexgenovese/Projects/my-express-api'Code language: Bash (bash)
```

The sanitizer resolves the path to `/Users/alexgenovese/Projects/my-express-api`, dynamically reconfigures `my-config.toml`, and begins analysis without modifying your original project files.

---

## Step 3: observing the 24-phase pipeline

Once initiated, BACO executes its 24-phase security pipeline. Rather than dumping unreadable JSON or swallowing logs, the TUI streams colorized, categorized log badges:

| Badge | Subsystem | Responsibility |
|---|---|---|
| `[SCANNER]` | Pipeline Orchestrator | Controls parallel execution, state tracking, and memory limits |
| `[INDEXING]` | File Enumerator | Maps project files and computes SHA-256 hashes for incremental scanning |
| `[SEMGREP]` | Static Analysis | Executes deterministic AST pattern matching across standard CWEs |
| `[LLM]` | Semantic Review | Dispatches AST slices and code blocks to Regolo.ai for contextual review |
| `[CWE-ROUTING]` | Vulnerability Triage | Groups findings into formal Common Weakness Enumeration hierarchies |
| `[REPORTING]` | Output Generator | Emits structured JSON, SARIF, and an interactive HTML report |

Here is an authentic excerpt of the live terminal output during a local run:

```
  2026-09-08T19:14:12.102Z  INFO   [SCANNER]     Starting scan orchestrator (Parallel Mode: 2 tasks)
  2026-09-08T19:14:12.154Z  INFO   [INDEXING]    Enumerating files in /demo-vulnerable-app
  2026-09-08T19:14:12.210Z  INFO   [INDEXING]    Tracked 2 source files (Python 3)
  2026-09-08T19:14:12.890Z  INFO   [SEMGREP]     Running static ruleset: 4 patterns matched
  2026-09-08T19:14:13.412Z  INFO   [LLM]         Static analysis phase dispatched to Regolo.ai
  2026-09-08T19:14:15.110Z  INFO   [CWE-ROUTING] Categorized finding: CWE-89 (SQL Injection) in server.py:41
  2026-09-08T19:14:15.654Z  INFO   [CWE-ROUTING] Categorized finding: CWE-78 (OS Command Injection) in server.py:53
  2026-09-08T19:14:16.201Z  INFO   [CWE-ROUTING] Categorized finding: CWE-327 (Weak Cryptography) in utils.py:18
  2026-09-08T19:14:16.890Z  INFO   [CWE-ROUTING] Categorized finding: CWE-502 (Untrusted Deserialization) in utils.py:34
  2026-09-08T19:14:18.012Z  INFO   [REPORTING]   Compiling reports into ./baco-output/Code language: Bash (bash)
```

### Why Semgrep + LLM?

Pure static analysis (Semgrep) is fast and deterministic, but flags false positives whenever sanitization occurs across helper boundaries. Pure LLM scanning understands semantic context, but can hallucinate vulnerabilities that are unreachable.

BACO uses Semgrep for high-speed candidate filtering (Phase 2), feeds candidates into Regolo.ai for verification (Phases 4, 7, and 8), validates reachability (Phase 9), and runs confidence scoring (Phase 14). The result is high signal with minimal noise.

---

## Step 4: the executive summary &amp; real-time cost breakdown

When the scan finishes, the TUI prints an executive summary card. Unlike cloud SaaS platforms with opaque billing tiers, BACO calculates the exact token usage and financial cost in EUR:

```
╔══════════════════════════════════════════════════════════════════════╗
║          SCAN RESULTS & BRICK COMPLEXITY PRO COST BREAKDOWN          ║
╠══════════════════════════════════════════════════════════════════════╣
║  Target:             demo-vulnerable-app                             ║
║  Scan Duration:      6.8 seconds                                     ║
║  Total Findings:     4 vulnerabilities identified                    ║
║  Severity Counts:    Crit: 0 | High: 2 | Med: 2 | Low: 0             ║
╠══════════════════════════════════════════════════════════════════════╣
║  REGOLO.AI / BRICK COMPLEXITY PRO PRICING:                           ║
║  • Router Model:      brick-complexity-pro (Regolo.ai)               ║
║  • Complexity Tier:   Standard                                       ║
║  • Codebase Analyzed: 2 files processed                              ║
║  • Estimated Tokens:  ~18,800 tokens                                 ║
║  • Regolo Token Rate: €0.12 per 1,000,000 tokens                     ║
║  • TOTAL SCAN COST:   €0.002256 EUR                                  ║
╠══════════════════════════════════════════════════════════════════════╣
║  Generated Reports:                                                  ║
║  • JSON:   baco-output/findings.json                                 ║
║  • HTML:   baco-output/report.html                                   ║
║  • SARIF:  baco-output/report.sarif                                  ║
╚══════════════════════════════════════════════════════════════════════╝Code language: Bash (bash)
```

### How Scan Cost is Computed

1. **Base File Analysis:** ~5,800 tokens per source file for Phase 4 LLM Static Review.
2. **Code Chunk Tokens:** Source code bytes divided by 4.
3. **Finding Triage:** ~1,800 tokens per confirmed vulnerability for verification and routing.

Even on a medium-sized project with 30 source files and 10 findings, a comprehensive 24-phase scan costs less than **€0.02 EUR**.

### Viewing the HTML Report

The TUI will immediately prompt:

```
Open interactive HTML report in browser? [y/N]: yCode language: Bash (bash)
```

Typing `y` invokes your native operating system browser (`open` on macOS, `xdg-open` on Linux) to view `baco-output/report.html`. The interactive report displays code snippets, call chains, CWE definitions, and CVSS scores.

---

## Step 5: generating and applying AI fixes

Identifying vulnerabilities is only half the battle. Option **\[3\]** turns BACO from a detection tool into an automated remediation pipeline.

After viewing scan results, the TUI asks:

```
Generate AI fixes for all 4 vulnerabilities now? [Y/n]: YCode language: Bash (bash)
```

You can also trigger this at any time from the main menu by selecting **\[3\] Generate AI Fixes for Vulnerabilities**.

### What Happens During Remediation

For each vulnerability recorded in `baco-output/findings.json`, the TUI extracts the offending code snippet, constructs an isolated prompt containing the CWE specification, and queries `brick-complexity-pro` on Regolo.ai.

The engine requests a strict JSON payload containing:

- **Root-cause explanation:** Why the defect exists.
- **Security rationale:** The defensive programming principle applied.
- **Fixed code snippet:** Clean replacement code.
- **Unified diff hunk:** A valid patch header and line offsets.

All outputs are saved into an isolated, timestamped folder under `remediations/`:

```
remediations/2026-09-08_19-14-11_demo-vulnerable-app/
├── README.md                 # Summary table of all patches
├── fixes.json                # Structured remediation data
├── llm_fix_instructions.md   # Copy-paste prompt for IDE AI agents
└── patches/
    ├── fix_01_CWE_327_utils.patch
    ├── fix_02_CWE_502_utils.patch
    ├── fix_03_CWE_89_server.patch
    └── fix_04_CWE_78_server.patchCode language: Bash (bash)
```

### Inspecting a Generated Patch

Let's examine `patches/fix_03_CWE_89_server.patch`:

```
# Patch for CWE-89: SQL Injection in demo-vulnerable-app/server.py:41
# Explanation: Raw string formatting directly interpolates user variables into SQL.
# Security rationale: Use DB-API parameterized queries with placeholder tuples.

--- a/server.py
+++ b/server.py
@@ -38,7 +38,7 @@
 def authenticate_user(username: str, password_input: str):
     conn = sqlite3.connect(DATABASE_PATH)
     cursor = conn.cursor()
-    query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password_input}'"
-    cursor.execute(query)
+    query = "SELECT * FROM users WHERE username = ? AND password = ?"
+    cursor.execute(query, (username, password_input))
     user = cursor.fetchone()
     conn.close()
     return userCode language: Bash (bash)
```

### Applying the Patch

Because the output is standard unified diff format, you can review and apply the patch using standard Git tooling:

```
# Check if the patch applies cleanly without errors
git apply --check remediations/2026-09-08_19-14-11_demo-vulnerable-app/patches/fix_03_CWE_89_server.patch

# Apply the patch to your working tree
git apply remediations/2026-09-08_19-14-11_demo-vulnerable-app/patches/fix_03_CWE_89_server.patchCode language: Bash (bash)
```

### Using `llm_fix_instructions.md` with AI Agents

If you use tools like Cursor, Claude Code, GitHub Copilot, or Kilo, open `llm_fix_instructions.md`. It contains a pre-engineered prompt listing every finding, its file location, its CWE definition, and instructions for the agent to refactor the code and update unit tests accordingly.

---

## Step 6: non-interactive CLI &amp; scripting

While the interactive TUI is ideal for local development, BACO TUI can be driven headlessly from bash scripts, pre-commit hooks, or CI/CD pipelines.

### Headless Commands

```
# 1. Non-interactive scan of a target repository
python3 baco_tui.py scan /path/to/my-repo

# 2. Automatically generate AI fixes for the last scan
python3 baco_tui.py fix

# 3. Print the token and cost breakdown of the latest scan
python3 baco_tui.py cost

# 4. Re-run environment setup headlessly
python3 baco_tui.py setupCode language: Bash (bash)
```

### Example: pre-push Git hook

You can prevent vulnerable code from being pushed to remote branches by adding a lightweight hook to `.git/hooks/pre-push`:

```
#!/usr/bin/env bash
set -e

echo "Running local BACO security check..."
python3 /path/to/baco-scanner-tui/baco_tui.py scan .

# Check if critical or high vulnerabilities were found
CRITICAL_COUNT=$(jq '[.[] | select(.severity=="Critical" or .severity=="High")] | length' baco-output/findings.json)

if [ "$CRITICAL_COUNT" -gt 0 ]; then
    echo "❌ Push blocked: $CRITICAL_COUNT Critical/High vulnerabilities detected."
    echo "Run './launch.sh' and choose Option [3] to review and apply AI patches."
    exit 1
fi

echo "✅ Security check passed. Pushing..."
exit 0Code language: Bash (bash)
```

---

## Verification &amp; Troubleshooting

### 1. "Compiled binary not found" on Startup

The BACO engine is written in Rust. The TUI compiles it on first run via `cargo build --release --locked`.

- **Check Rust installation:** Run `rustc --version` and `cargo --version`. Ensure you are running Rust 1.70 or newer.
- **Manual build fallback:** If the automated compile is interrupted, build the binary manually:

```
cd baco-scanner
cargo build --release
```

The resulting executable must exist at `baco-scanner/target/release/baco`.

### 2. Scan Reports "0 Findings" on Vulnerable Code

BACO utilizes content-addressable hash tracking (`baco-output/file_hashes.json`) to skip unmodified files during consecutive scans.

- When running through the TUI, the `--force` flag is automatically passed to override unchanged file caching.
- If you suspect stale state, clear the output directory and re-run:

```
rm -rf baco-output/
python3 baco_tui.py scan demo-vulnerable-app
```

### 3. Missing `node_modules` or `.venv` Exclusions

If you notice BACO scanning third-party dependencies:

- Verify that your target project directory contains a valid `.gitignore` file.
- Check `my-config.toml` under `[scanner]` to confirm `exclude_paths` contains `"node_modules/**"` and `".venv/**"`.

---

## Audit your local codebase

> ### Ready to scan your codebase in under 2 minutes?
> 
> Run 24-phase static analysis and generate ready-to-apply Git patches on European cloud infrastructure with zero data retention and transparent token pricing (€0.12 / 1M tokens).
> 
> ```
> git clone https://github.com/CodeAtCode/baco-scanner.git
> cd baco-scanner && ./launch.shCode language: PHP (php)
> ```
> 
> [Get a Regolo.ai API Key →](https://regolo.ai)
> 
> *Free trial credits included. No credit card required to start.*

---

![](http://regolo.ai/wp-content/uploads/2026/09/Regolo-get-30-days-free-green.jpg)

### **Try GLM 5.2 or Qwen3.8 27 for 30 days free**

Sign up, grab your API key, and route between frontier open source models with zero data retention in EU infrastructure.

[Start your free 30-day trial](https://regolo.ai/signup?utm_source=blog&utm_medium=article_cta&utm_campaign=benchmarks_sept26&utm_content=flash-tier)

---

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