Super Debuggerpre-rendered · standalone · light/fast
raw Code index

Detect → Fix → Verify · never false-positive “done”

Standalone HTML app — content is pre-rendered at build time, so the browser paints the protocol immediately (no CDN markdown libs at runtime, no second fetch of the .md). Use the side list, code index, expand/collapse, and copy buttons for rapid navigation.

PASS only success FAIL stop & fix INCONCLUSIVE = block Pre-rendered instant Sections 15 Code blocks 36

Code block index — meaning & use

Filter by language, expand for parent section + first-line hint. Jump links open the section card.

python Python checkers, VerificationEngine snippets, enums, final_gate helpers. bash Shell one-liners: silent stack detect, SSH, scanners, CI glue. plain Protocol pseudocode, contracts, decision trees, rules text.
plain #1 · L32 0. Prime Directive
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: WHEN YOU RECEIVE ANY BUG / CRASH / TEST / SECURITY / FIX REQUEST:
plain #2 · L48 0. Prime Directive · Core Philosophy
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: Fixing bugs is a science, not luck.
python #3 · L90 1. Three-State Verdict Core
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: # ponytail: the entire anti-false-positive contract hinges on this enum.
plain #4 · L106 2. Auto-Pilot Protocol (Silent Classify → Detect → Execute) · 2.1 Task Auto-Classification
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: IF task is "check security of URL" / "scan headers" / "check TLS"
bash #5 · L138 2. Auto-Pilot Protocol (Silent Classify → Detect → Execute) · 2.3 Silent Stack Detection
Use: Shell one-liners: silent stack detect, SSH, scanners, CI glue.
Hint: #!/usr/bin/env bash
plain #6 · L202 3. DETECT — Classification & Scan Matrix · 3.2 Error Routing Matrix
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: ECONNREFUSED | 502 | 503 → Infra / Network (P0)
plain #7 · L217 3. DETECT — Classification & Scan Matrix · 3.3 Stack-Specific Scan Order
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: PIPELINE ORDER: SCA → SAST → Secrets → DAST → Headers/TLS → IaC
python #8 · L261 4. FIX — Instant Fixes & Tooling · 4.2 AST-Based Code Rewriter (never regex)
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: # ponytail: regex rewrites break on multiline imports; AST is correct by construction.
python #9 · L288 4. FIX — Instant Fixes & Tooling · 4.3 Git-Diff Aware File Watcher (capped fallback)
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: #!/usr/bin/env python3
python #10 · L327 4. FIX — Instant Fixes & Tooling · 4.4 Safe Install Gate (dependency whitelist)
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: import json, subprocess
plain #11 · L363 4. FIX — Instant Fixes & Tooling · 4.6 60-Second Diagnosis
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: T=0s Read stack trace
python #12 · L376 4. FIX — Instant Fixes & Tooling · 4.7 Structured Error Logger (errors.jsonl)
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: import json, hashlib, traceback
python #13 · L399 4. FIX — Instant Fixes & Tooling · 4.8 Memory Leak Tracer (tracemalloc)
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: import tracemalloc
bash #14 · L414 4. FIX — Instant Fixes & Tooling · 4.9 Universal Quality Scanner (`scan.sh`)
Use: Shell one-liners: silent stack detect, SSH, scanners, CI glue.
Hint: #!/usr/bin/env bash
bash #15 · L440 4. FIX — Instant Fixes & Tooling · 4.10 Remote Verify (rsync + scan on VPS)
Use: Shell one-liners: silent stack detect, SSH, scanners, CI glue.
Hint: #!/usr/bin/env bash
python #16 · L457 5. VERIFY — Anti-False-Positive VerificationEngine
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: """
plain #17 · L886 5. VERIFY — Anti-False-Positive VerificationEngine · 5.1 Per-Tool Verification Block (visual proof protocol)
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: ─────────────────────────────────────────────────
python #18 · L908 5. VERIFY — Anti-False-Positive VerificationEngine · 5.2 Mutation Testing (verify the verifier)
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: def test_engine_catches_failures(tmp_path):
python #19 · L927 6. SECURE — Hardening & NEVER/ALWAYS · 6.1 NEVER/ALWAYS Patterns per Stack
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: # SQL Injection
javascript #20 · L956 6. SECURE — Hardening & NEVER/ALWAYS · 6.1 NEVER/ALWAYS Patterns per Stack
Use: Browser/Node automation or lightweight client checks.
Hint: // XSS
plain #21 · L996 6. SECURE — Hardening & NEVER/ALWAYS · 6.3 Security Headers
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
plain #22 · L1011 6. SECURE — Hardening & NEVER/ALWAYS · 6.4 Secret Remediation
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: IF HARDCODED SECRETS FOUND:
plain #23 · L1024 6. SECURE — Hardening & NEVER/ALWAYS · 6.5 Banned Commands (never generate)
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: ❌ npm audit fix --force → breaks semver
plain #24 · L1045 6. SECURE — Hardening & NEVER/ALWAYS · 6.6 Incident Response — Phase A→E
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: PHASE A — CONTAIN (first 5 min)
plain #25 · L1085 7. Debug Loop — CHECK→READ→CLASSIFY→ISOLATE→FIX→RE-VERIFY
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: ┌─────────────────────────────────────────────────────────────┐
markdown #26 · L1120 7. Debug Loop — CHECK→READ→CLASSIFY→ISOLATE→FIX→RE-VERIFY · Five-Hypothesis Prompt (when stuck)
Use: Report templates and structured agent output formats.
Hint: Error: [stack trace]
plain #27 · L1131 7. Debug Loop — CHECK→READ→CLASSIFY→ISOLATE→FIX→RE-VERIFY · Four Quality Gates (before any fix ships)
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: GATE 1 COMPREHENSION — read full file; rg callers
python #28 · L1172 9. Real-World Bug Case Studies · 9.1 Cookie Normalizer — `expires: -1` Session Cookies
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: # BROKEN — discards valid session cookies
python #29 · L1180 9. Real-World Bug Case Studies · 9.1 Cookie Normalizer — `expires: -1` Session Cookies
Use: Python checkers, VerificationEngine snippets, enums, final_gate helpers.
Hint: # CORRECT — only discard if exp is a positive timestamp in the past
bash #30 · L1232 10. CLI / One-Liner Cheat Sheet · Daily Rhythm
Use: Shell one-liners: silent stack detect, SSH, scanners, CI glue.
Hint: # Morning
plain #31 · L1274 10. CLI / One-Liner Cheat Sheet · Safe Dependency Commands
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: npm: npm audit → npm update <specific-package>
bash #32 · L1283 10. CLI / One-Liner Cheat Sheet · Quick triage (rapid Linux)
Use: Shell one-liners: silent stack detect, SSH, scanners, CI glue.
Hint: # What's broken on this box?
markdown #33 · L1305 11. Mandatory Report Format
Use: Report templates and structured agent output formats.
Hint: ## Analysis
plain #34 · L1333 Verification · Per-Finding Output (security)
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: Confidence: [score]/100
plain #35 · L1348 12. Final Gate
Use: Protocol pseudocode, contracts, decision trees, rules text.
Hint: ┌──────────────────────────────────────────────────────────────┐
markdown #36 · L1367 12. Final Gate · VIP Note Template
Use: Report templates and structured agent output formats.
Hint: [ID] BUG-2026-0001

Super Debugger — Unified Hybrid Detect → Fix → Verify Engine

Canonical merge of five fixer/security/verification specs: Ai-security.md · best-hybrid-server-fixing-toolkit.md · Code of Anti-False-Positive Verification layer.md · Fixation-scripts of automation.md · rapid-linux-fixing-skill.md

Contract: Zero-config · Three-state verdict · Never crash · Bounded self-heal · No paid SaaS · No Ollama in loops · Pinned versions only · Mac laptop + Linux server.

One-line identity: Detect errors objectively → fix the root cause surgically → prove correctness with the VerificationEngine → never say "done" until final_gate() returns all_pass == True.


Table of Contents section
0. Prime Directive section
plain
WHEN YOU RECEIVE ANY BUG / CRASH / TEST / SECURITY / FIX REQUEST:

1. DO NOT ask the user for stack versions — detect silently (§2.3)
2. DO NOT ask clarifying questions unless genuinely ambiguous
3. CLASSIFY severity (P0–P3) and error type (§3.1, §3.2)
4. RUN git-diff checker or rg before editing
5. FIX the root cause with the smallest possible diff (§4)
6. VERIFY with the VerificationEngine — three-state, never crash (§5)
7. NEVER say "done" until final_gate() returns all_pass == True (§12)

DELIVER IN ONE RESPONSE:
  Analysis → Root Cause → Fix → Tests → Verification → Risk

Core Philosophy

plain
Fixing bugs is a science, not luck.
Deterministic CLI tools first. The AI agent reasons — no Ollama loop inside checkers.
One surgical change. One regression test. One verification command.
The verifier must be able to say "I don't know." Otherwise it defaults to "yes" —
which is exactly the false positive you are trying to eliminate.

Hard Rules (Non-Negotiable)

Code

  • No eval() / exec() in production paths
  • Parameterized SQL only
  • No hardcoded secrets — env vars or server-side secret files (never committed)
  • set -euo pipefail in all shell scripts
  • Type-check: mypy (Python), tsc --noEmit (TypeScript)

Process

  • Reproduce → Isolate → Fix → Verify — always in this order
  • Every bug fix gets a regression test
  • One logical change per commit
  • Document why, not what
  • Never change more than necessary; no "while-I-am-here" refactors

Server / Agent

  • Heavy scans run on the Linux VPS (cron), not on every keystroke
  • No Ollama — do not call local LLM endpoints from watchers, scanners, or CI scripts
  • AI agent uses this doc + repo files + tool output — not a second model runtime
  • No paid SaaS (Sentry, Snyk, SonarCloud) — use errors.jsonl + Trivy + Semgrep CLI

1. Three-State Verdict Core section

The single most important anti-false-positive design decision. Two-state verifiers default to "yes" under uncertainty — three-state verifiers say "I don't know."

State Meaning Action
PASS Objectively proven correct (file valid, duration matches, hash identical, within limits) Proceed
FAIL Objectively proven incorrect (file missing, wrong duration, RAM exceeded, return code ≠ 0) Stop, diagnose, fix, re-verify
INCONCLUSIVE Could not measure (binary missing, output unhashable, tool timed out) Treat as FAIL. Investigate the cause. Never promote to PASS.
python
# ponytail: the entire anti-false-positive contract hinges on this enum.
class Status(str, Enum):
    PASS = "PASS"
    FAIL = "FAIL"
    INCONCLUSIVE = "INCONCLUSIVE"  # could not measure -> must NOT count as pass

RULE 0: PASS is the only success. FAIL and INCONCLUSIVE both block "done".


2. Auto-Pilot Protocol (Silent Classify → Detect → Execute) section

2.1 Task Auto-Classification

plain
IF task is "check security of URL" / "scan headers" / "check TLS"
  → QUICK_AUDIT      → Headers + TLS + passive nuclei
IF task is "full audit" / repo or path provided
  → FULL_SCAN        → SCA → SAST → Secrets → DAST → Headers → IaC
IF task is "we've been hacked" / "breach" / "active attack"
  → INCIDENT_RESPONSE → Phase A→E emergency lockdown (§6.6)
IF task is "harden" / "secure this code" / "fix vulnerabilities"
  → HARDENING        → NEVER/ALWAYS remediation (§6.1)
IF task is "CI/CD security" / "DevSecOps"
  → DEVSECOPS        → Generate CI/CD security workflows
IF task is LLM/AI app security / "prompt injection"
  → AI_SECURITY      → OWASP LLM Top 10 audit
IF task is "code review" / "is this secure"
  → CODE_REVIEW      → Manual SAST + NEVER/ALWAYS check
IF task is bug/crash/test
  → DEBUG            → §3.2 error routing → §4 fix → §5 verify

DEFAULT → FULL_SCAN with cross-validation

2.2 Severity Routing

Priority Trigger Action
P0 Security vuln, data loss, prod down Minimal fix → verify → VIP note
P1 Broken build, failing tests, user bug Full diagnosis protocol
P2 Performance, missing tests Profile → fix → test
P3 Style, docs Lint/format only

2.3 Silent Stack Detection

bash
#!/usr/bin/env bash
# ponytail: detect silently — never ask the user for stack versions.
set -euo pipefail
D="${1:-.}"
langs=""
[ -f "$D/package.json" ] && langs="$langs js/ts"
[ -f "$D/pyproject.toml" ] || [ -f "$D/requirements.txt" ] && langs="$langs python"
[ -f "$D/go.mod" ] && langs="$langs go"
[ -f "$D/Cargo.toml" ] && langs="$langs rust"
[ -f "$D/composer.json" ] && langs="$langs php"
[ -f "$D/Gemfile" ] && langs="$langs ruby"
echo "langs:${langs:-unknown}"
[ -f "$D/package.json" ] && grep -q '"next"' "$D/package.json" && echo "framework:nextjs"
[ -f "$D/manage.py" ] && echo "framework:django"
[ -f "$D/pytest.ini" ] && echo "test:pytest"
grep -q '"vitest"' "$D/package.json" 2>/dev/null && echo "test:vitest"
[ -f "$D/Dockerfile" ] && echo "containers:yes"
[ -f "$D/.env" ] && echo "env_present:HIGH_RISK"

2.4 Pre-Authorized SSH Hosts

Alias Command
hostinger ssh hostinger
contabo2 ssh -i ~/.ssh/contabo2_new1 root@149.102.150.185
hetzner-dokploy ssh -i ~/.ssh/hetzner_dokploy root@46.62.228.173
ai-developer ssh -i ~/.ssh/ai_developer_key root@213.199.36.17

Run non-interactively: ssh <host> '<command>'. Prefix output with [alias]. Confirm before rm -rf, reboot, drop DB, force-push.


3. DETECT — Classification &amp; Scan Matrix section

3.1 Confidence Scoring (0–100 additive) — per finding

Component Condition Points
Source confirmation ≥2 independent tools +30
Source confirmation 1 tool only +10
Source confirmation Pattern match only +0
CVE/CWE database Matched in NVD/OSV +25
CVE/CWE database CWE only +10
CVE/CWE database No match +0
Exploitability Public endpoint reachable +20
Exploitability Behind auth +10
Exploitability Library not called +5
Remediation clarity file:line + fix +15
Remediation clarity File only +8
False-positive filter Passes baseline FP +10
False-positive filter Known high-FP rule −15

Status tag from total:

  • 85–100 → VERIFIED
  • 65–84 → LIKELY_TRUE
  • 40–64 → NEEDS_REVIEW (report only if Critical)
  • 0–39 → FALSE_POSITIVE (omit; count only)

Minimum reporting threshold: ≥40/100.

3.2 Error Routing Matrix

plain
ECONNREFUSED | 502 | 503        → Infra / Network (P0)
Cannot find module | ENOENT     → Build / Import (P1)
TypeError | undefined is not    → Runtime (P1)
CORS | Access-Control           → Backend / proxy (P1)
hydration | did not match       → SSR mismatch (P1)
OOM | heap | SIGKILL            → Memory (P2)
timeout | ETIMEDOUT | slow      → Performance (P2)
403 | permission denied         → Auth (P1)
deadlock | race | intermittent  → Concurrency (P1)
SQLITE_BUSY                     → Concurrent writes (P1)

3.3 Stack-Specific Scan Order

plain
PIPELINE ORDER: SCA → SAST → Secrets → DAST → Headers/TLS → IaC
GRACEFUL DEGRADATION: one tool failure does not halt the pipeline

3.4 OWASP Top 10 (2021) Detection Matrix

⚠️ XXE was REMOVED in 2021 (subsumed under A03). Do NOT cite it as a standalone item.

# Category Detection Tools Secure Fix CWE
A01 Broken Access Control Semgrep, manual RBAC, deny-by-default CWE-200,284,639
A02 Cryptographic Failures Trivy, GitLeaks, testssl AES-256, TLS 1.2+, bcrypt CWE-259,326,327
A03 Injection (SQLi/XSS/XXE/Cmd) Semgrep, Nuclei, ZAP, Dalfox Parameterized queries, DOMPurify, CSP CWE-79,89,78
A04 Insecure Design Manual + threat model STRIDE, secure defaults CWE-209,501
A05 Security Misconfiguration Trivy, Checkov, testssl Security headers, restrict public CWE-16,611
A06 Vulnerable Components Trivy, OWASP Dep-Check Pinned targeted upgrades CWE-937,1035
A07 Auth Failures Nuclei, manual MFA, bcrypt≥12, rate limit CWE-287,384
A08 Data Integrity Failures Semgrep, Bandit yaml.safe_load, signed CI CWE-502,565
A09 Logging Failures Manual + Splunk Log auth, SIEM CWE-778,532
A10 SSRF Semgrep, Nuclei URL allowlist, block RFC1918 CWE-918
+LLM Prompt Injection Custom + manual Sanitize, delimiters, least-priv OWASP LLM01

4. FIX — Instant Fixes &amp; Tooling section

4.1 Top Instant Fixes

Error Likely Cause Fix
Cannot find module 'X' Missing dep or wrong path Check lockfile; npm i X only via safe_install; verify package.json paths
ModuleNotFoundError: X venv / PYTHONPATH pip install -r requirements.txt; check pyproject.toml package layout
CORS policy blocked Missing headers on API Set Access-Control-Allow-Origin on server; never fix only in frontend
Hydration failed Server HTML ≠ client Remove browser-only APIs from SSR; match useId/dates/random
ECONNREFUSED 127.0.0.1 Service not running Start service; check Docker port map; verify env HOST/PORT
SQLITE_BUSY / deadlock Concurrent writes Retry with backoff; WAL mode; shorten transactions
EACCES permission denied File perms / user chown/chmod; correct user; check volume mounts
ENOMEM / OOMKilled Memory leak or limit tracemalloc profile; raise limit only after fixing leak
git divergent branches Local/remote split git pull --rebase; never force-push without approval
pytest collected 0 items Wrong path/config Check pytest.ini, test_*.py naming, pythonpath

4.2 AST-Based Code Rewriter (never regex)

python
# ponytail: regex rewrites break on multiline imports; AST is correct by construction.
import ast
from pathlib import Path

class ImportRemover(ast.NodeTransformer):
    def __init__(self, names: set[str]):
        self.names = names
    def visit_Import(self, node: ast.Import):
        node.names = [a for a in node.names if a.name not in self.names]
        return node if node.names else None
    def visit_ImportFrom(self, node: ast.ImportFrom):
        node.names = [a for a in node.names if a.name not in self.names]
        return node if node.names else None

def remove_unused_imports(path: str, unused: set[str]):
    p = Path(path)
    tree = ast.parse(p.read_text(encoding="utf-8"))
    fixed = ImportRemover(unused).visit(tree)
    ast.fix_missing_locations(fixed)
    p.write_text(ast.unparse(fixed), encoding="utf-8")

For JS/TS, use npx biome check --write . (Biome's AST fixer).

4.3 Git-Diff Aware File Watcher (capped fallback)

python
#!/usr/bin/env python3
"""Lint only modified files. Falls back to capped 50-file scan if not a git repo."""
import subprocess
from pathlib import Path

def modified() -> list[Path]:
    cmd = "git diff --name-only && git diff --cached --name-only && git ls-files --others --exclude-standard"
    try:
        r = subprocess.run(cmd, shell=True, capture_output=True, text=True, check=True)
        return [Path(f.strip()).resolve() for f in r.stdout.splitlines() if f.strip()]
    except subprocess.CalledProcessError:
        # ponytail: cap at 50 files — never rglob entire monorepo
        out = []
        for ext in ("*.py", "*.ts", "*.js", "*.tsx", "*.sh", "*.go"):
            out.extend(Path(".").rglob(ext))
            if len(out) >= 50:
                break
        return [p.resolve() for p in out[:50]]

def lint(p: Path):
    ext = p.suffix.lower()
    if ext == ".py":
        subprocess.run(["python3", "-m", "py_compile", str(p)], check=False)
        subprocess.run(["ruff", "check", "--fix", str(p)], check=False)
    elif ext in {".js", ".ts", ".tsx", ".jsx"}:
        subprocess.run(["npx", "biome", "check", "--write", str(p)], check=False)
    elif ext == ".sh":
        subprocess.run(["shellcheck", str(p)], check=False)
    elif ext == ".go":
        subprocess.run(["go", "fmt", str(p)], check=False)

for f in modified():
    if f.exists() and f.is_file():
        lint(f)

4.4 Safe Install Gate (dependency whitelist)

python
import json, subprocess
from pathlib import Path

SAFE = {"pytest", "ruff", "mypy", "fastapi", "biome", "vitest", "typescript", "zod", "react", "next"}

def safe_install(name: str, lang: str = "python") -> bool:
    n = name.strip().lower()
    if n not in SAFE:
        if lang == "python":
            lock = Path("requirements.txt").read_text().lower() if Path("requirements.txt").exists() else ""
            if n not in lock:
                print(f"Blocked: {name}"); return False
        elif Path("package.json").exists():
            pkg = json.loads(Path("package.json").read_text())
            deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})}
            if n not in {d.lower() for d in deps}:
                print(f"Blocked: {name}"); return False
    cmd = ["pip", "install", n] if lang == "python" else ["npm", "install", n]
    return subprocess.run(cmd).returncode == 0

4.5 Command Modes

Mode Trigger Behavior
BUGFIX_STRICT BUGFIX_STRICT: ... Full protocol + VIP note
CLEAN_REFACTOR CLEAN_REFACTOR: ... Tests first; incremental only
TEST_DESIGN_MAX TEST_DESIGN_MAX: ... Unit + edge; 80% coverage target
SECURITY_HARDEN SECURITY_HARDEN: ... Semgrep → Gitleaks → Trivy → Bandit
PERF_OPTIMIZE PERF_OPTIMIZE: ... py-spy/perf; measure before/after
FULL_SCAN FULL_SCAN Run ./scan.sh; report all failures
REMOTE_VERIFY REMOTE_VERIFY: host Run remote-verify.sh on authorized VPS

4.6 60-Second Diagnosis

plain
T=0s   Read stack trace
T=5s   rg "symbol" --type py|ts
T=15s  git log --oneline -10 -- <path>
T=20s  Reproduce minimal case
T=25s  git bisect if unknown regression
T=30s  Top 3 hypotheses
T=50s  Minimal fix + regression test
T=60s  ./scan.sh or targeted test command

4.7 Structured Error Logger (errors.jsonl)

python
import json, hashlib, traceback
from dataclasses import dataclass, asdict
from datetime import datetime, timezone

@dataclass
class ErrorLog:
    timestamp: str; error_type: str; message: str; location: str; fingerprint: str

def log_error(err: Exception, path: str = "errors.jsonl") -> str:
    tb = traceback.extract_tb(err.__traceback__)
    frame = tb[-1] if tb else None
    loc = f"{frame.filename}:{frame.lineno}" if frame else "unknown"
    fp = hashlib.md5(f"{type(err).__name__}|{loc}".encode()).hexdigest()[:12]
    entry = ErrorLog(datetime.now(timezone.utc).isoformat(),
                     type(err).__name__, str(err), loc, fp)
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(asdict(entry)) + "\n")
    return fp

4.8 Memory Leak Tracer (tracemalloc)

python
import tracemalloc

def check_memory_allocation(target_func, *args, **kwargs):
    tracemalloc.start()
    before = tracemalloc.take_snapshot()
    target_func(*args, **kwargs)
    after = tracemalloc.take_snapshot()
    tracemalloc.stop()
    for stat in after.compare_to(before, "lineno")[:5]:
        print(stat)

4.9 Universal Quality Scanner (scan.sh)

bash
#!/usr/bin/env bash
# Usage: ./scan.sh [--fix] [--lang python|js|all]
set -euo pipefail
FIX=false; LANG="all"; FAILURES=0
for a in "$@"; do case $a in --fix) FIX=true ;; --lang) shift; LANG="$1" ;; esac; done
pass() { echo "[PASS] $*"; }; fail() { echo "[FAIL] $*"; FAILURES=$((FAILURES+1)); }

lint_py() { $FIX && ruff check --fix . && ruff format . || ruff check . && ruff format --check .; pass "Python lint"; }
lint_js() { $FIX && npx biome check --write . || npx biome check .; pass "JS lint"; }
test_py() { pytest -q --tb=short 2>/dev/null && pass "pytest" || fail "pytest"; }
test_js() { npx vitest run 2>/dev/null && pass "vitest" || fail "vitest"; }
security() {
  semgrep --config=p/default --quiet . && pass "Semgrep" || fail "Semgrep"
  gitleaks detect --source=. --no-banner 2>/dev/null && pass "Gitleaks" || fail "Gitleaks"
  trivy fs --severity HIGH,CRITICAL --quiet . && pass "Trivy" || fail "Trivy"
}
case $LANG in python) lint_py; mypy src/ 2>/dev/null || true; test_py ;;
  js) lint_js; npx tsc --noEmit 2>/dev/null || true; test_js ;;
  all) lint_py; lint_js; test_py; test_js ;; esac
security
[ $FAILURES -eq 0 ] && echo "ALL PASSED" || { echo "$FAILURES FAILED"; exit 1; }

4.10 Remote Verify (rsync + scan on VPS)

bash
#!/usr/bin/env bash
# remote-verify.sh
set -euo pipefail
TARGET="${1:-hetzner-dokploy}"
REMOTE_DIR="${2:-/opt/app-dev}"
rsync -avz --exclude node_modules --exclude .git --exclude .venv \
  ./ "${TARGET}:${REMOTE_DIR}"
ssh "$TARGET" "cd ${REMOTE_DIR} && ./scan.sh"

5. VERIFY — Anti-False-Positive VerificationEngine section

Drop-in verification_engine.py. Every check returns a CheckResult, never raises. Every subprocess gets a timeout. INCONCLUSIVE blocks "done".

python
"""
verification_engine.py — Anti-False-Positive Verification Layer.

Design goals:
  - NEVER report success unless objectively provable.
  - NEVER crash the agent: every check returns a structured result.
  - Deterministic where claimed; tolerance-based otherwise.
  - No silent failures: unmeasurable => INCONCLUSIVE, never PASS.
"""
from __future__ import annotations

import hashlib, json, logging, os, shutil, subprocess, time
from dataclasses import dataclass, field, asdict
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Optional

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger("verify")


class Status(str, Enum):
    PASS = "PASS"
    FAIL = "FAIL"
    INCONCLUSIVE = "INCONCLUSIVE"  # could not measure -> NOT a pass


@dataclass
class CheckResult:
    name: str
    status: Status
    detail: str = ""
    evidence: dict[str, Any] = field(default_factory=dict)

    @property
    def ok(self) -> bool:
        return self.status is Status.PASS

    def to_dict(self) -> dict[str, Any]:
        d = asdict(self); d["status"] = self.status.value; return d


def run_cmd(args: list[str], timeout: int = 120,
            binary_required: Optional[str] = None) -> tuple[bool, str, str]:
    """Returns (success, stdout, stderr). Never raises."""
    if binary_required and shutil.which(binary_required) is None:
        return False, "", f"Required binary not found on PATH: {binary_required}"
    try:
        proc = subprocess.run(args, capture_output=True, text=True,
                              timeout=timeout, check=False)
        return proc.returncode == 0, proc.stdout, proc.stderr
    except subprocess.TimeoutExpired:
        return False, "", f"Timeout after {timeout}s: {' '.join(args[:3])}..."
    except FileNotFoundError as e:
        return False, "", f"Binary missing: {e}"
    except Exception as e:  # last-resort guard so the agent never crashes
        return False, "", f"Unexpected error: {e!r}"


def _safe_path(path: str | os.PathLike) -> Path:
    return Path(path).expanduser().resolve()


class VerificationEngine:
    def __init__(self, work_dir: str = "./work", max_ram_mb: int = 2048,
                 max_time_sec: int = 600, duration_tolerance_sec: float = 1.0,
                 progress_file: str = "progress.json"):
        self.work_dir = _safe_path(work_dir)
        self.work_dir.mkdir(parents=True, exist_ok=True)
        self.max_ram_mb = max_ram_mb
        self.max_time_sec = max_time_sec
        self.duration_tol = duration_tolerance_sec
        self.progress_file = _safe_path(progress_file)
        self.progress: dict[str, dict[str, Any]] = self._load_progress()

    def _load_progress(self) -> dict[str, dict[str, Any]]:
        if self.progress_file.exists():
            try:
                return json.loads(self.progress_file.read_text())
            except (json.JSONDecodeError, OSError):
                log.warning("progress.json corrupt; starting fresh")
        return {}

    def _save_progress(self) -> None:
        tmp = self.progress_file.with_suffix(".tmp")
        tmp.write_text(json.dumps(self.progress, indent=2))
        tmp.replace(self.progress_file)  # atomic write

    # ----------------------------- duration ------------------------------ #
    def probe_duration(self, path: str | os.PathLike) -> Optional[float]:
        """Return duration in seconds, or None if undeterminable (image, raw)."""
        p = _safe_path(path)
        if not p.exists():
            return None
        ok, out, _ = run_cmd(
            ["ffprobe", "-v", "error",
             "-show_entries", "format=duration:stream=duration",
             "-of", "json", str(p)],
            binary_required="ffprobe",
        )
        if not ok:
            return None
        try:
            data = json.loads(out)
        except json.JSONDecodeError:
            return None
        fmt_dur = data.get("format", {}).get("duration")
        if fmt_dur not in (None, "N/A"):
            try:
                return float(fmt_dur)
            except ValueError:
                pass
        for stream in data.get("streams", []):
            sd = stream.get("duration")
            if sd not in (None, "N/A"):
                try:
                    return float(sd)
                except ValueError:
                    continue
        return None

    # --------------------------- utility test ---------------------------- #
    def verify_file(self, path: str | os.PathLike,
                    expected_duration: Optional[float] = None) -> CheckResult:
        name = f"verify_file:{Path(path).name}"
        p = _safe_path(path)
        if not p.exists():
            return CheckResult(name, Status.FAIL, "File missing", {"path": str(p)})
        size = p.stat().st_size
        if size == 0:
            return CheckResult(name, Status.FAIL, "File empty", {"size": 0})
        ok, _, err = run_cmd(
            ["ffprobe", "-v", "error", "-show_entries", "format=duration",
             "-of", "json", str(p)], binary_required="ffprobe",
        )
        if not ok:
            return CheckResult(name, Status.FAIL, f"Invalid media: {err.strip()}",
                               {"size": size})
        duration = self.probe_duration(p)
        if duration is None:
            if expected_duration is not None:
                return CheckResult(name, Status.INCONCLUSIVE,
                                   "Cannot measure duration but one was expected",
                                   {"size": size})
            return CheckResult(name, Status.PASS, "Valid (no duration applicable)",
                               {"size": size})
        if expected_duration is not None:
            diff = abs(duration - expected_duration)
            if diff > self.duration_tol:
                return CheckResult(
                    name, Status.FAIL,
                    f"Duration mismatch: got {duration:.3f}s, "
                    f"expected {expected_duration:.3f}s (tol {self.duration_tol}s)",
                    {"duration": duration, "expected": expected_duration, "diff": diff},
                )
        return CheckResult(name, Status.PASS, f"Valid, duration={duration:.3f}s",
                           {"duration": duration, "size": size})

    # --------------------- live frame inspection ------------------------- #
    def capture_inspection_frame(self, video_path: str | os.PathLike,
                                 output_dir: str | os.PathLike,
                                 pct: float = 0.5) -> CheckResult:
        name = f"inspect_frame:{int(pct * 100)}pct"
        if not (0.0 <= pct <= 1.0):
            return CheckResult(name, Status.FAIL, f"pct out of range: {pct}")
        duration = self.probe_duration(video_path)
        if duration is None or duration <= 0:
            return CheckResult(name, Status.INCONCLUSIVE,
                               "Cannot determine video duration")
        out_dir = _safe_path(output_dir)
        out_dir.mkdir(parents=True, exist_ok=True)
        ss = duration * pct
        frame_path = out_dir / f"inspect_{int(pct * 100)}pct.jpg"
        ok, _, err = run_cmd(
            ["ffmpeg", "-y", "-ss", f"{ss:.3f}", "-i", str(_safe_path(video_path)),
             "-vframes", "1", "-q:v", "2", str(frame_path)],
            binary_required="ffmpeg",
        )
        if not ok or not frame_path.exists() or frame_path.stat().st_size == 0:
            return CheckResult(name, Status.FAIL, f"Frame extraction failed: {err.strip()}")
        return CheckResult(name, Status.PASS, f"Frame captured at {ss:.2f}s",
                           {"frame_path": str(frame_path), "timestamp": ss})

    # --------------------------- scene count ----------------------------- #
    def count_scene_changes(self, video_path: str | os.PathLike,
                            threshold: float = 0.3) -> Optional[int]:
        ok, _, err = run_cmd(
            ["ffmpeg", "-i", str(_safe_path(video_path)), "-vf",
             f"select='gt(scene,{threshold})',metadata=print", "-an",
             "-f", "null", "-"],
            timeout=self.max_time_sec, binary_required="ffmpeg",
        )
        if not ok and "scene" not in err:
            return None
        cuts = err.count("lavfi.scene_score")
        return cuts + 1  # scenes, not cuts

    # ---------------------------- sync / E2E ----------------------------- #
    def sync_test(self, video_path: str | os.PathLike,
                  expected_scene_count: Optional[int] = None,
                  min_audio_words: int = 1,
                  transcribe: bool = True) -> CheckResult:
        name = "sync_test"
        vp = _safe_path(video_path)
        evidence: dict[str, Any] = {}

        # 1. Extract audio
        audio_path = self.work_dir / (vp.stem + ".wav")
        ok, _, err = run_cmd(
            ["ffmpeg", "-y", "-i", str(vp), "-vn", "-ac", "1", "-ar", "16000",
             str(audio_path)], binary_required="ffmpeg",
        )
        if not ok or not audio_path.exists() or audio_path.stat().st_size == 0:
            return CheckResult(name, Status.FAIL,
                               f"Audio extraction failed: {err.strip()}")
        evidence["audio_bytes"] = audio_path.stat().st_size

        # 2. Mean volume (silence check)
        ok, _, vol_err = run_cmd(
            ["ffmpeg", "-i", str(audio_path), "-af", "volumedetect",
             "-f", "null", "-"], binary_required="ffmpeg",
        )
        mean_vol = None
        for line in vol_err.splitlines():
            if "mean_volume:" in line:
                try:
                    mean_vol = float(line.split("mean_volume:")[1].split("dB")[0])
                except (ValueError, IndexError):
                    pass
        evidence["mean_volume_db"] = mean_vol
        audio_audible = mean_vol is not None and mean_vol > -60.0

        # 3. Optional transcription
        word_count = None
        if transcribe and shutil.which("whisper"):
            ok, _, _ = run_cmd(
                ["whisper", str(audio_path), "--model", "tiny",
                 "--output_format", "json", "--output_dir", str(self.work_dir)],
                timeout=self.max_time_sec, binary_required="whisper",
            )
            json_out = self.work_dir / (audio_path.stem + ".json")
            if ok and json_out.exists():
                try:
                    tdata = json.loads(json_out.read_text())
                    word_count = len(tdata.get("text", "").split())
                    evidence["transcript_words"] = word_count
                except (json.JSONDecodeError, OSError):
                    word_count = None

        # 4. Scene count
        scene_count = self.count_scene_changes(vp)
        evidence["scene_count"] = scene_count

        # ---- Decide status ----
        failures: list[str] = []
        inconclusive: list[str] = []
        if not audio_audible:
            failures.append(f"audio inaudible (mean_volume={mean_vol})")
        if transcribe:
            if word_count is None:
                inconclusive.append("transcription unavailable")
            elif word_count < min_audio_words:
                failures.append(f"too few words: {word_count} < {min_audio_words}")
        if expected_scene_count is not None:
            if scene_count is None:
                inconclusive.append("scene count unmeasurable")
            elif scene_count != expected_scene_count:
                failures.append(
                    f"scene count {scene_count} != expected {expected_scene_count}")

        if failures:
            return CheckResult(name, Status.FAIL, "; ".join(failures), evidence)
        if inconclusive:
            return CheckResult(name, Status.INCONCLUSIVE, "; ".join(inconclusive), evidence)
        return CheckResult(name, Status.PASS, "A/V verified", evidence)

    # --------------------- deterministic stability ----------------------- #
    def stability_test(self, pipeline_func: Callable[[Any], str],
                       input_data: Any, runs: int = 3) -> CheckResult:
        """
        Encoded media is rarely byte-identical. We hash *decoded, normalized
        content* via ffmpeg framemd5, which IS deterministic for the same frames.
        """
        name = "stability_test"
        if runs < 2:
            return CheckResult(name, Status.INCONCLUSIVE, "runs must be >= 2")
        content_hashes: list[str] = []
        for i in range(runs):
            try:
                output = pipeline_func(input_data)
            except Exception as e:
                return CheckResult(name, Status.FAIL, f"Run {i} crashed: {e!r}")
            out_p = _safe_path(output)
            if not out_p.exists():
                return CheckResult(name, Status.FAIL, f"Run {i} produced no file")
            h = self._content_hash(out_p)
            if h is None:
                return CheckResult(name, Status.INCONCLUSIVE,
                                   f"Run {i} content not hashable")
            content_hashes.append(h)
        identical = len(set(content_hashes)) == 1
        return CheckResult(
            name, Status.PASS if identical else Status.FAIL,
            "Deterministic" if identical else "Non-deterministic output",
            {"hashes": content_hashes, "identical": identical},
        )

    def _content_hash(self, path: Path) -> Optional[str]:
        ok, out, _ = run_cmd(
            ["ffmpeg", "-i", str(path), "-map", "0", "-f", "framemd5", "-"],
            timeout=self.max_time_sec, binary_required="ffmpeg",
        )
        if not ok:
            try:
                return hashlib.sha256(path.read_bytes()).hexdigest()
            except OSError:
                return None
        payload = "\n".join(l for l in out.splitlines() if l and not l.startswith("#"))
        return hashlib.sha256(payload.encode()).hexdigest()

    # ------------------------- performance ------------------------------- #
    def performance_monitor(self, cmd_args: list[str],
                            timeout: Optional[int] = None) -> CheckResult:
        """Runs a subprocess (so we can kill IT) and enforces RAM + time limits."""
        try:
            import psutil
        except ImportError:
            return CheckResult("performance", Status.INCONCLUSIVE,
                               "psutil not installed")
        name = "performance_monitor"
        timeout = timeout or self.max_time_sec
        peak_ram_mb = 0.0
        start = time.time()
        try:
            proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE, text=True)
        except (FileNotFoundError, OSError) as e:
            return CheckResult(name, Status.FAIL, f"Launch failed: {e!r}")
        ps = psutil.Process(proc.pid)
        killed_reason = None
        while proc.poll() is None:
            elapsed = time.time() - start
            try:
                rss = ps.memory_info().rss
                for child in ps.children(recursive=True):
                    try:
                        rss += child.memory_info().rss
                    except (psutil.NoSuchProcess, psutil.AccessDenied):
                        pass
                peak_ram_mb = max(peak_ram_mb, rss / 1024 / 1024)
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass
            if peak_ram_mb > self.max_ram_mb:
                killed_reason = f"RAM limit exceeded: {peak_ram_mb:.0f}MB"
            elif elapsed > timeout:
                killed_reason = f"Time limit exceeded: {elapsed:.0f}s"
            if killed_reason:
                proc.kill()
                proc.wait(timeout=5)
                break
            time.sleep(0.2)
        elapsed = time.time() - start
        evidence = {"peak_ram_mb": round(peak_ram_mb, 1),
                    "time_sec": round(elapsed, 2),
                    "return_code": proc.returncode}
        if killed_reason:
            return CheckResult(name, Status.FAIL, killed_reason, evidence)
        if proc.returncode != 0:
            return CheckResult(name, Status.FAIL,
                               f"Process exited {proc.returncode}", evidence)
        return CheckResult(name, Status.PASS, "Within limits", evidence)

    # ---------------------------- checkpoint ----------------------------- #
    def checkpoint(self, task_name: str, status: str,
                   evidence_path: Optional[str] = None) -> dict[str, Any]:
        self.progress[task_name] = {
            "status": status,
            "timestamp": time.time(),
            "evidence": evidence_path,
            "verified": False,
        }
        self._save_progress()
        return self.progress[task_name]

    # ------------------------------ final gate --------------------------- #
    def final_gate(self, required_outputs: dict[str, str | os.PathLike],
                   expected_durations: Optional[dict[str, float]] = None
                   ) -> tuple[bool, dict[str, Any]]:
        """
        The agent CANNOT declare success unless EVERY required output is PASS.
        INCONCLUSIVE counts as NOT passing (anti-false-positive core rule).
        """
        expected_durations = expected_durations or {}
        all_pass = True
        report: dict[str, Any] = {}
        for name, path in required_outputs.items():
            res = self.verify_file(path, expected_durations.get(name))
            report[name] = res.to_dict()
            self.progress.setdefault(name, {})
            self.progress[name]["verified"] = res.ok
            self.progress[name]["verify_info"] = res.detail
            if not res.ok:
                all_pass = False
        self._save_progress()
        return all_pass, report


# ---------------------------------------------------------------------------- #
# Bounded self-heal: max 3 attempts, evidence-based, never fake-pass.
# ---------------------------------------------------------------------------- #
def verify_with_self_heal(check_fn: Callable[[], CheckResult],
                          fix_fn: Callable[[CheckResult], None],
                          max_attempts: int = 3) -> CheckResult:
    result = check_fn()
    for attempt in range(max_attempts):
        if result.status is Status.PASS:
            return result
        log.warning(f"Attempt {attempt+1} {result.status}: {result.detail}")
        if attempt < max_attempts - 1:
            fix_fn(result)            # apply targeted fix using result.detail
            result = check_fn()       # re-verify
    return result                     # final (failing) result, never a fake pass

5.1 Per-Tool Verification Block (visual proof protocol)

After each tool runs, produce this block BEFORE reporting findings:

plain
─────────────────────────────────────────────────
TOOL VERIFY: [tool name] [version]
Command run:  [exact command with all flags — no placeholders]
Exit code:    [actual numeric: 0, 1, 2...]
Duration:     [elapsed seconds]
Output size:  [bytes or line count]
Sample line:  [first non-empty line of real stdout/stderr, max 120 chars]
Status:       EXECUTED | SKIPPED (reason: ...) | FAILED (error: ...)
─────────────────────────────────────────────────

Rules:

  • ✗ Exit code 0 + zero bytes output → Status = FAILED (scanned nothing)
  • ✗ Tool status FAILED → its findings DISCARDED, not reported
  • ✗ No sample line → findings tagged NEEDS_REVIEW, never VERIFIED
  • ✗ Docker pull fails → log SKIPPED, attempt native install, new verify block

5.2 Mutation Testing (verify the verifier)

The #1 method: feed deliberately broken inputs and confirm the engine reports FAIL.

python
def test_engine_catches_failures(tmp_path):
    eng = VerificationEngine(work_dir=tmp_path)
    empty = tmp_path / "empty.mp4"; empty.touch()
    assert eng.verify_file(empty).status is Status.FAIL
    assert eng.verify_file(tmp_path / "nope.mp4").status is Status.FAIL
    res = eng.verify_file(known_5s_video, expected_duration=30.0)
    assert res.status is Status.FAIL

If your verifier passes a known-bad file, the verifier is broken.


6. SECURE — Hardening &amp; NEVER/ALWAYS section

6.1 NEVER/ALWAYS Patterns per Stack

PYTHON / DJANGO / FLASK / FASTAPI

python
# SQL Injection
NEVER:  cursor.execute("SELECT * FROM users WHERE id=" + user_id)
ALWAYS: cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
ALWAYS: User.objects.filter(id=user_id)  # Django ORM

# Password Hashing
NEVER:  hashlib.md5(password.encode()).hexdigest()
NEVER:  hashlib.sha256(password.encode()).hexdigest()
ALWAYS: bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))

# Deserialization
NEVER:  pickle.loads(user_data)
NEVER:  yaml.load(user_data)             # without Loader=
ALWAYS: yaml.safe_load(user_data)
ALWAYS: json.loads(user_data)            # for untrusted input

# Secrets
NEVER:  API_KEY = "sk-abc123"
ALWAYS: API_KEY = os.environ.get("API_KEY"); assert API_KEY, "API_KEY not set"

# Session (settings.py)
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Strict"
CSRF_COOKIE_SECURE = True

JAVASCRIPT / NODE / EXPRESS / NEXT

javascript
// XSS
NEVER:  element.innerHTML = userInput
ALWAYS: element.textContent = userInput
ALWAYS: DOMPurify.sanitize(userInput)

// Prototype Pollution
NEVER:  Object.assign({}, req.body)
ALWAYS: structuredClone(req.body)        // Node 17+

// JWT
NEVER:  jwt.verify(token, "hardcoded-secret")
NEVER:  localStorage.setItem("token", jwt)
ALWAYS: jwt.verify(token, process.env.JWT_SECRET, { algorithms: ["HS256"], expiresIn: "15m" })
ALWAYS: store in httpOnly + Secure + SameSite=Strict cookie

// Headers
import helmet from "helmet";     // min 7.1.0
app.use(helmet());

PHP / LARAVEL · JAVA / SPRING · GO — same pattern: parameterized queries, ORM-preferred, least-privilege, env-based secrets.

6.2 Pinned Tool Versions (minimum)

Tool Min Version Category Install
semgrep 1.45.0 SAST pip install semgrep==1.45.0
bandit 1.7.7 SAST (Py) pip install bandit==1.7.7
ruff latest stable Lint+Format pip install ruff
biome latest stable JS lint+format npm i -D @biomejs/biome
trivy 0.50.0 SCA+IaC docker pull aquasec/trivy:0.50.0
gitleaks 8.18.0 Secrets docker pull zricethezav/gitleaks:v8.18.0
nuclei 3.1.5 DAST docker pull projectdiscovery/nuclei:v3.1.5
checkov 3.2.0 IaC docker pull bridgecrew/checkov:3.2.0

⚠️ Never use :latest or @latest. Always pin.

6.3 Security Headers

plain
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), microphone=(), camera=()
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin

Verify: curl -sI https://[target] | grep -iE 'strict|content-security|x-frame|x-content|referrer|permissions'

6.4 Secret Remediation

plain
IF HARDCODED SECRETS FOUND:
1. ROTATE IMMEDIATELY — the secret is already compromised
2. PURGE FROM HISTORY:
   git filter-repo --path <file> --invert-paths
   OR BFG: docker run --rm -v "$(pwd):/repo" erikvanzijst/bfg:latest --delete-files <file> /repo
   THEN:  git push --force-with-lease --all     # NEVER --force
3. ADD TO .gitignore: .env, *.pem, *.key, secrets/
4. MIGRATE to env vars or secret manager (Vault, AWS SSM)

6.5 Banned Commands (never generate)

plain
❌ npm audit fix --force             → breaks semver
❌ pip install --break-system-packages → corrupts system Python
❌ npm update                        → uncontrolled mass upgrade
❌ docker run --privileged           → full host kernel access
❌ docker run --cap-add SYS_ADMIN    → dangerous kernel caps
❌ docker pull [image]:latest        → unpinned
❌ go install [module]@latest        → unpinned
❌ git push --force                  → use --force-with-lease

Banned advice:

  • ❌ "Just disable SSL verification"
  • ❌ "Set CORS to allow all origins (*)"
  • ❌ "chmod 777" as a fix
  • ❌ Disabling security features as a solution
  • ❌ Mixing OWASP categories from different years
  • ❌ Citing XXE as a standalone OWASP 2021 item (removed)

6.6 Incident Response — Phase A→E

plain
PHASE A — CONTAIN (first 5 min)
  1. WAF → full block for non-whitelisted IPs
  2. Invalidate ALL session tokens + API keys
  3. Force MFA re-enrollment for admins
  4. If breach confirmed → take service offline

PHASE B — PRESERVE EVIDENCE (5–15 min)
  5. Snapshot ALL VM disks + container states BEFORE cleanup
  6. Export 30-day logs to immutable storage
  7. Record UTC timestamp of each action

PHASE C — ISOLATE (15–30 min)
  8. DB → promote read-only replica, primary rejects writes
  9. DNS → maintenance page
 10. Rotate ALL TLS certs, secrets, API keys, DB creds
 11. Zero-trust: deny all, allowlist verified IPs

PHASE D — ANALYZE (1–24 h)
 12. Build attack timeline → MITRE ATT&CK IDs
 13. RCA: entry vector, scope, data exposed, permanent fix

PHASE E — RECOVER & HARDEN (1–7 d)
 14. Apply NEVER/ALWAYS fixes for the entry vector
 15. Re-run FULL_SCAN to confirm vuln closed
 16. Activate monitoring queries
 17. Threat-model review of affected components

6.7 Trusted Source Hierarchy

TIER 1 (authoritative): NVD · OSV · CISA KEV · GitHub Security Advisories · OWASP · Vendor bulletins · NIST · CWE TIER 2 (high quality): Snyk DB · PortSwigger Research · Google Project Zero · HackerOne disclosed TIER 3 (verify): Authored blogs · Conference papers · Tool docs (check version) REJECT: Anonymous blogs · StackOverflow for CVE · Reddit/Discord · AI-generated content as source · Undated advice · "Disable SSL" / "CORS *" / "chmod 777"


7. Debug Loop — CHECK→READ→CLASSIFY→ISOLATE→FIX→RE-VERIFY section
plain
┌─────────────────────────────────────────────────────────────┐
│ 1. CHECK     Run verify_file / scan.sh / pytest              │
│              → CheckResult { PASS | FAIL | INCONCLUSIVE }    │
│                                                             │
│ 2. READ      If FAIL/INCONCLUSIVE:                          │
│              - result.detail + result.evidence              │
│              - rg "error string" --type py|ts               │
│              - git log --oneline -10 -- <path>              │
│              - read the actual file at the flagged line     │
│                                                             │
│ 3. CLASSIFY  Map to §3.2 error routing matrix               │
│              Assign P0–P3 severity                          │
│                                                             │
│ 4. ISOLATE   Reproduce minimal case                         │
│              git bisect if unknown regression               │
│              Form top 3 hypotheses                          │
│                                                             │
│ 5. FIX       Apply SMALLEST possible diff at root cause     │
│              - AST rewriter (§4.2) over regex               │
│              - One logical change                           │
│              - Add regression test                          │
│              - No "while-I-am-here" refactors               │
│                                                             │
│ 6. RE-VERIFY Run the SAME check that failed                 │
│              → must return PASS                             │
│              If still FAIL/INCONCLUSIVE → loop (max 3)      │
│                                                             │
│ LOOP BOUND: max 3 attempts. Then STOP and report.           │
│             Never weaken the check. Never fake a pass.      │
└─────────────────────────────────────────────────────────────┘

Five-Hypothesis Prompt (when stuck)

markdown
Error: [stack trace]
For each of 5 hypotheses:
  - theory: ...
  - why: ...
  - one verify command: ...
  - minimal patch if confirmed: ...

Four Quality Gates (before any fix ships)

plain
GATE 1 COMPREHENSION — read full file; rg callers
GATE 2 CORRECTNESS   — root cause; minimal change; lockfile versions match
GATE 3 SAFETY        — no new lint/type errors; no secrets; error paths handled
GATE 4 VERIFICATION  — regression test; ./scan.sh; rollback plan
IF ANY GATE FAILS → DO NOT SHIP

8. Anti-Mutation Rules (Do NOT Weaken the Verifier) section

During execution, NEVER:

  • ❌ Weaken checks to make them pass
  • ❌ Skip the verification step "just this once"
  • ❌ Hardcode PASS results
  • ❌ Catch exceptions from the engine and continue
  • ❌ Modify verification_engine.py mid-execution
  • ❌ Collapse INCONCLUSIVE into PASS
  • ❌ Promote a NEEDS_REVIEW to VERIFIED
  • ❌ Fabricate CVE numbers, tool output, or code fixes
  • ❌ Report findings from a tool that failed §5.1 verification
  • ❌ Report findings without evidence (file:line or tool output)
  • ❌ Use :latest / @latest tags
  • ❌ Output placeholders (<YOUR_PATH>, <TARGET>, <API_KEY>)
  • ❌ Add manual steps ("Install Java first", "Download this file")

If a check cannot be executed → status = INCONCLUSIVE → blocks "done". Investigate the cause (missing binary, unmeasurable output) and resolve it.


9. Real-World Bug Case Studies section

Source: Fixation-scripts of automation.md — practical patterns observed in production automation.

Symptom: Browser launches logged-out every time, even right after manual login.

Root cause:

python
# BROKEN — discards valid session cookies
if exp is not None and isinstance(exp, (int, float)) and exp <= now:
    return None

Browser exports set session cookies (Twitter's auth_token, ct0) to expires: -1. Since -1 <= now, the normalizer discarded them as expired.

Fix:

python
# CORRECT — only discard if exp is a positive timestamp in the past
if exp is not None and isinstance(exp, (int, float)) and exp > 0 and exp <= now:
    return None

Lesson: When a real-world value violates an assumption (-1 is "session", not "expired"), the assumption is wrong, not the data.

9.2 Twitter 280-Character Caption Limit

Symptom: ❌ Twitter post button disabled.

Root cause: Generated caption was 284 chars (11 hashtags + double newlines), exceeding X's 280-char limit by 4. The Post button greys out, so the script waited 5 min for a button that would never enable.

Fix: Trim to 270 chars (safety margin), reduce hashtag pool to 4, single newlines, progressive trim.

Defense added: publish_twitter() now detects login-redirect (URL pattern) and fails fast with a clear message instead of wasting 5 min.

9.3 Stale Persistent Session Override

Symptom: Fresh cookies injected, but browser still showed logged-out page.

Root cause: sessions/universal_twitter_acc1/ held 1.1 GB of stale persistent context that overrode the cookie injection on every launch.

Fix: Delete stale session dir; fresh one created on next launch with the new cookies.

Lesson: Persistent context and cookie injection are two separate auth channels. When both exist, the persistent one usually wins. Clean state before injecting.

9.4 auto_responder.py Race Conditions

Symptom: Clicking "Stop" in the web UI didn't kill Chromium — browsers kept spawning every 15 min.

Root cause: Start/Stop/RunOnce handlers had race conditions; Stop didn't actually cancel the loop task.

Fix: Proper task.cancel() with awaited cleanup; Stop blocks until the task is confirmed dead.

9.5 engage_growth_overgrowth.py Broken Imports

Symptom: Script crashed instantly on launch.

Root cause: Imported core.cookie_controller and hybrid_scheduler which didn't exist in the deployment tree.

Fix: Rewrote to be self-contained with its own cookie parsing (no cross-module imports that aren't guaranteed present).

Lesson: Scripts that depend on sibling modules must either (a) ship those modules alongside, or (b) be self-contained. The latter is more robust for distributed deployment.


10. CLI / One-Liner Cheat Sheet section

Daily Rhythm

bash
# Morning
just scan                          # or ./scan.sh
rg "\[TYPE\] BUG" knowledge/vip_notes/

# Coding (git-diff aware watcher running)
# Pre-commit
pre-commit run --all-files

# Pre-push
./scan.sh                          # exit 0 required

# Weekly (server)
ssh hetzner-dokploy 'tail -n 100 /var/log/scan.log'

Consensus Top 10 Tools

# Tool Role Command
1 ripgrep Search rg "pattern"
2 fzf Navigate rg "x" | fzf
3 Ruff Py lint+format ruff check --fix . && ruff format .
4 Biome JS/TS lint+format npx biome check --write .
5 ShellCheck Shell shellcheck *.sh
6 Semgrep SAST semgrep --config=p/default .
7 Trivy Deps/containers trivy fs --severity HIGH,CRITICAL .
8 Gitleaks Secrets gitleaks detect --source=.
9 pytest / Vitest Tests pytest / npx vitest run
10 pre-commit Hooks pre-commit run --all-files

By Language

Language Lint Types Test Security
Python Ruff mypy pytest Bandit
JS/TS Biome tsc Vitest Semgrep
Go golangci-lint compiler go test govulncheck
Shell ShellCheck bats

Safe Dependency Commands

plain
npm:    npm audit → npm update <specific-package>
pip:    python -m venv .venv && source .venv/bin/activate → pip-audit → pip install --upgrade <specific-package>
go:     govulncheck ./... → go get <module>@<specific-version>
cargo:  cargo audit → cargo update -p <specific-crate>

Quick triage (rapid Linux)

bash
# What's broken on this box?
systemctl --failed
journalctl -p err -b --no-pager | tail -n 50
df -h | grep -vE '^Filesystem|tmpfs|loop'
free -h
ss -tlnp | head -n 20

# Find the noisy process
ps aux --sort=-%mem | head -n 10
ps aux --sort=-%cpu | head -n 10

# Git state
git status --short
git log --oneline -10
git diff --stat

11. Mandatory Report Format section
markdown
## Analysis
[What is happening, in one paragraph. Cite file:line.]

## Root Cause
[The why. Not the what. Distinguish symptom from cause.]

## Solution
[The surgical fix. Smallest possible diff. Why this approach over alternatives.]

## Changes
[Diff or file:line list. One logical change per commit.]

## Tests
[Regression test added. Existing tests that cover the path.]

## Risk Assessment
[What could break. Rollback plan. P0–P3.]

## Verification
[CheckResult output. final_gate() output. Status: PASS.]
[If any check is INCONCLUSIVE → DO NOT report done.]

Condensed format OK for trivial lint/format only.

Per-Finding Output (security)

plain
Confidence: [score]/100
Breakdown: source(+N) cve(+N) exploit(+N) clarity(+N) fp(+N or -N)
Status: VERIFIED / LIKELY_TRUE / NEEDS_REVIEW / FALSE_POSITIVE
OWASP: [A0X:2021] | CWE: [CWE-NNN]
NEVER (vulnerable): [code snippet ≤5 lines]
ALWAYS (secure):    [code snippet ≤10 lines, annotated]
Language/version:   [e.g. Python 3.11 / Django 4.2]
Source: [Tier 1/2/3 + URL]

12. Final Gate section
plain
┌──────────────────────────────────────────────────────────────┐
│ AGENT CANNOT SAY "done" UNTIL:                               │
│                                                              │
│  1. Every fix has a regression test                          │
│  2. Every fix passed the four quality gates (§7)            │
│  3. final_gate(required_outputs) returns all_pass == True    │
│  4. No check has status INCONCLUSIVE                         │
│  5. No verification tool has status FAILED or SKIPPED        │
│  6. ./scan.sh exit 0                                         │
│  7. VIP note written for non-trivial bugs                    │
│                                                              │
│  IF ANY OF THE ABOVE FAILS → CONTINUE THE DEBUG LOOP (§7)    │
│  AFTER 3 ATTEMPTS → STOP AND REPORT, do not fake a pass      │
└──────────────────────────────────────────────────────────────┘

VIP Note Template

markdown
[ID]           BUG-2026-0001
[TYPE]         BUG | PATTERN | DECISION | SECURITY | PERF
[CONTEXT]      Module file name and line range
[SYMPTOM]      Failing condition or console crash trace
[ROOT CAUSE]   Why it failed (not what)
[PROOF]        Local unit test output or verification log
[FIX]          Unified git diff or surgical code patch
[TEST]         Command run to verify fix locally
[CODE]         Minimal repro snippet
[META]         Confidence (1-5), Status (Fixed), Tags

Search: rg "\[TYPE\] BUG" knowledge/vip_notes/


Sources Merged section
Source Kept
Ai-security.md Auto-classify, OWASP 2021 matrix, pinned versions, confidence scoring 0–100, NEVER/ALWAYS per stack, Phase A–E incident, banned commands, trusted-source hierarchy
best-hybrid-server-fixing-toolkit.md scan.sh, pre-commit, AST import remover, safe_install, errors.jsonl, 4-layer gate, 60-sec diagnosis, error routing matrix, command modes, hypothesis tracker
Code of Anti-False-Positive Verification layer.md Status enum, CheckResult, safe run_cmd, full VerificationEngine (verify_file / inspection frame / sync_test / framemd5 stability / psutil perf monitor / checkpoint / final_gate), bounded self-heal, mutation testing
Fixation-scripts of automation.md Real bug case studies: expires=-1 cookie bug, Twitter 280-char limit, stale persistent session override, race conditions, broken imports
rapid-linux-fixing-skill.md Git-diff watcher (capped 50-file fallback), AST rewriter, safe_install gate, tracemalloc tracer, VIP note template, SSH pre-auth roster

Super Debugger: agent reasons · CLI proves · VerificationEngine decides · server scans on schedule · VIP notes remember. Three-state verdict everywhere. Never crash. Bounded self-heal. No Ollama. No paid SaaS. No :latest. ./scan.sh before every push. final_gate() before every "done".