Autonomous Security Guardrails, Governed Remediation & Living Verification for AI-Built Applications
Zero Telemetry ยท Zero External Python Dependencies ยท Pure Standard-Library Architecture ยท 100% Local-First
In the emblem above, the central golden keyhole shield represents unbreakable secret protection, authentication integrity, and tenant isolation. It is enveloped by a continuous, interlocking torus ringโsymbolizing TorusGuard's closed-loop autonomous security lifecycle:
flowchart LR
subgraph Torus ["๐ 360ยฐ Closed-Loop Torus Lifecycle"]
direction LR
Detect["1. Detect (74 AST Rules)"] --> Verify["2. Verify (Evidence & Fingerprints)"]
Verify --> Harden["3. Harden (Ponytail Protocol)"]
Harden --> Apply["4. Apply (Human Gate & Snapshots)"]
Apply --> Recheck["5. Recheck (Differential Closure)"]
Recheck --> Memory["6. Memory (Golden Fix Recipes)"]
Memory -.->|Continuous Guardrail| Detect
end
subgraph Shield ["๐ก๏ธ Central Golden Keyhole Shield"]
direction TB
Inv1["Browser-Code Truth: Zero Client Secrets"]
Inv2["Tenant Partitioning: Scoped Lookups"]
Inv3["Zero Bypasses: No verify=False"]
Inv4["Living Source of Truth: security_report.md"]
end
Torus === Shield
The Developer Reality: AI coding assistants (Cursor, Claude Code, Copilot, Windsurf) build software at superhuman speed, but routinely leak private keys into client bundles, drop tenant partition filters, or inject raw user input into LLM system prompts.
TorusGuard forms an unbroken local guardrail around your codebase. It audits static ASTs, runtime-verifies exploitability with inert canaries, synthesizes minimal surgical diffs adhering to the Ponytail Protocol ($\le 35$ additions,$\le 25$ deletions), and eliminates hallucinations by maintaining a verifiable single source of truth insecurity_report.md.
- Developer Overview & Value Proposition
- End-to-End Autonomous Architecture
- Why TorusGuard? (Traditional SAST vs. AI Coding vs. TorusGuard)
- Installation & Setup Guide (npm & CLI)
- Quickstart: The 5-Step Core Lifecycle
- Dual-Strategy Command Matrix (CLI & AI Chat Parity)
- 74 Canonical Security Rules Catalog (18 Families Across 6 Pillars)
- Ponytail Remediation Protocol & Rollback Safety
- Living Security Report Ground Truth (
security_report.md) - Visual HTML Dashboard & SARIF v2.1.0 Export
- AI Editor Guardrails Auto-Sync
- Monorepo Fleet Support & Git Pre-Commit Diff Guard
- Verification & Test Harness (120/120 Passing Harness Explained)
- Security Policy & Responsible Disclosure
- License
When developers use AI coding agents to write features, models optimize for getting the code to run rather than defensive architecture. Common failure modes include:
- Exposing Private Credentials: Leaking
process.env.SUPABASE_SERVICE_ROLE_KEYor master database connection strings into Next.js'use client'bundles. - Dropping Tenant Boundaries: Querying Prisma or Mongoose by record ID without scoping by tenant (
where: { id }instead ofwhere: { id, tenantId }). - Prompt Injection Vulnerabilities: Interpolating untrusted user chat messages directly into system prompts.
- Destructive AI Rewrites: When asked to fix a minor bug, AI models rewrite entire 500-line files, introducing fresh regressions and breaking surrounding business logic.
TorusGuard solves this deterministically:
- Zero-Egress Local Execution: 100% of scanning and patching happens on your machine. Zero code or tokens are transmitted to external servers.
-
Zero Pip Dependencies: Pure Python standard library (
pathlib,re,json,difflib,shutil). No virtualenv conflicts or broken build wheels. -
Ponytail Churn Bounds: Patches are constrained strictly to
$\le 35$ additions and$\le 25$ deletions. Surrounding business logic is never rewritten. -
Human Gate & Instant Undo: Every change requires interactive approval with syntax-highlighted diffs, backed up byte-for-byte in
.torusguard/snapshots/with instant 1-command rollback.
"If the browser receives it, users can inspect it via DevTools."
Frontend environment variables, client JavaScript bundles, and React Server Action payloads cannot conceal secrets. TorusGuard strictly enforces that database credentials, service role keys, private API secrets, and tenant boundaries remain exclusively on trusted server runtimes.
The following flowchart illustrates how TorusGuard safeguards your repository from initial developer input to verified, regression-free output:
flowchart TD
subgraph In ["1. Workspace & AI Context"]
A1["Polyglot Source Tree (16+ Languages)"]
A2["AI Coding Assistant (Cursor / Claude / Antigravity)"]
A3["Git Staged Diffs / Pre-Commit Hook"]
end
subgraph Core ["2. TorusGuard Engine (100% Local-First & Zero-Egress)"]
direction TB
B1["Static AST Engine: 74 Canonical Rules Across 18 Families"]
B2["Living Ledger Sync: security_report.md (0-100 Score)"]
B3["Ponytail Synthesizer: Minimal Surgical Diffs (≤35 Add / ≤25 Del)"]
B4["Pre-Apply Snapshot Engine: Byte-for-Byte .bak Backups"]
B5["Human Gate: Interactive Syntax-Highlighted Approval"]
B6["Targeted Differential Re-Scan: Confirmed Fixed State"]
B1 --> B2 --> B3 --> B4 --> B5 --> B6
end
subgraph Out ["3. Verified Deliverables & Artifacts"]
C1["Hardened Production Code (Zero Regressions)"]
C2["Self-Contained Dark-Mode HTML Dashboard"]
C3["OASIS SARIF v2.1.0 for CI/CD Pipeline"]
C4["Auto-Synced AI Rules (.cursorrules, CLAUDE.md, etc.)"]
end
In --> Core --> Out
| Security Dimension | Traditional SAST (SonarQube, Snyk) | Raw AI Coding Agents | TorusGuard v1.3.6 Engine |
|---|---|---|---|
| Target Architecture | Human-written legacy codebases | High-churn AI code generation | AI-built full-stack applications |
| Remediation Model | PDF reports & Jira tickets | Destructive full-file rewrites |
Ponytail Protocol ( |
| Fix Preservation | None (scans from scratch) | Forgets context across chats | Adaptive Security Memory & Golden Recipes |
| Editor Sync | Heavy background language daemons | Bloated prompt context ( |
Stack-Adaptive Rules ( |
| Ground-Truth State | External proprietary web dashboard | Ephemeral chat context (hallucinates) |
Living Security Ledger (security_report.md) |
| Pre-Commit Defense | Slow server-side webhooks | None (commits insecure code) |
Git Pre-Commit Diff Guard ( |
| Privacy & Telemetry | Cloud code upload / SaaS | Third-party cloud LLMs | 100% Local, Zero-Egress Guarantee |
TorusGuard is designed to be effortless to adopt in any project. There are no configuration servers, databases, or complex background daemons.
- Node.js: 18.0.0 or higher
- Python: 3.10 or higher (Pure standard library โ zero
pipdependencies required)
Important
Zero Pip Dependencies Guarantee: TorusGuard's core Python engine relies strictly on the Python standard library (pathlib, re, json, difflib, shutil, sys, os, argparse, hashlib). You never need to create a Python virtualenv (venv), run pip install, or configure external wheels. It works out of the box with your system Python.
Run TorusGuard instantly in any repository without installing anything globally:
# Run any command directly via npx
npx torusguard init
npx torusguard audit
npx torusguard statusLock TorusGuard into your project's package.json for all team members and CI/CD pipelines:
npm install -D torusguardAdd convenience scripts to your package.json:
{
"scripts": {
"security:audit": "torusguard audit",
"security:harden": "torusguard harden",
"security:recheck": "torusguard recheck",
"security:status": "torusguard status"
}
}If you prefer having the torusguard binary available system-wide across all terminal sessions:
npm install -g torusguardInstall TorusGuard as a native AI assistant skill for Cursor, Claude Code, Cline, or Antigravity:
npx skills add torusguardWhen you execute npx torusguard init in your repository:
- Polyglot Profiling: Automatically detects 16+ languages (Go, Rust, Java, C#, PHP, Python, TypeScript) and 30+ frameworks without manual configuration.
-
Scaffolding: Creates a local
.torusguard/directory containing active security rules, schemas, and runners. -
Editor Rules Synchronization: Automatically compiles compact, language-specific guardrails into
.cursorrules,CLAUDE.md,.agent/rules/torusguard.md, and.windsurfrules($\le 300$ prompt tokens). -
Living Ledger Initialization: Creates
security_report.mdat workspace root to track finding states without hallucination. -
Baseline Policy: Emits a production-ready
SECURITY.mdfor responsible disclosure.
Run the complete autonomous governance cycle in 60 seconds from your terminal:
# Step 1: Initialize workspace and profile stack
npx torusguard init
# Step 2: Run AST static security audit across 74 rules
npx torusguard audit
# Step 3: Synthesize minimal surgical candidate patches
npx torusguard harden
# Step 4: Review syntax-highlighted diffs and apply with rollback backup
npx torusguard apply
# Step 5: Differentially recheck modified files to verify fix closure
npx torusguard recheck๐ก Prefer AI Chat? Every step above can be triggered directly in your AI assistant chat using
/torusguard init,/torusguard audit,/torusguard harden,/torusguard apply, and/torusguard recheck!
TorusGuard guarantees 100% operational parity between terminal CLI execution and AI chat slash commands. Terminal outputs strictly adhere to a 75-column visual width with Unicode emojis and ANSI stripping.
| Lifecycle Stage | Mode A: Terminal CLI | Mode B: AI Chat Command | Governed Action & Primary Artifact |
|---|---|---|---|
| 1. Init | npx torusguard init |
/torusguard init |
Profiles workspace, activates rules, initializes .torusguard/
|
| 2. Audit | npx torusguard audit |
/torusguard audit |
74-rule AST scan, line-shift fingerprints, updates security_report.md
|
| 3. Harden | npx torusguard harden |
/torusguard harden |
Synthesizes Ponytail diffs ( |
| 4. Apply | npx torusguard apply [--yes] |
/torusguard apply |
Human Gate, pre-apply .bak snapshots, Golden Fix distillation |
| 5. Rollback | npx torusguard rollback |
/torusguard rollback |
Instant restoration from pre-apply snapshots in .torusguard/snapshots/
|
| 6. Recheck | npx torusguard recheck |
/torusguard recheck |
Differential AST re-scan; marks findings RESOLVED ๐ข in living report |
| Capability | Mode A: Terminal CLI | Mode B: AI Chat Command | Governed Action & Primary Artifact |
|---|---|---|---|
| Status | npx torusguard status |
/torusguard status |
75-column diagnostic overview of health score, stack, memory & rules |
| Recipes | npx torusguard recipes |
/torusguard recipes |
Explores verified Golden Fix patterns stored in .torusguard/memory/ |
| Report | npx torusguard report --html |
/torusguard report |
Emits single-file dark-mode HTML posture report & OASIS SARIF v2.1.0 |
| Rules Sync | npx torusguard rules sync |
/torusguard rules sync |
Synchronizes prompt guardrails across Cursor, Claude, Antigravity, Windsurf |
| Diff Guard | npx torusguard diff-guard |
/torusguard diff-guard |
Audits git diffs for security bypasses; --install-hook binds pre-commit |
| Capability | Mode A: Terminal CLI | Mode B: AI Chat Command | Governed Action & Primary Artifact |
|---|---|---|---|
| Authorize | npx torusguard authorize |
/torusguard authorize |
Target domain allowlisting, cryptographic ownership proof, TTL limits |
| Verify | npx torusguard verify |
/torusguard verify |
Asserts evidence sufficiency & live disk line-shift fingerprint matches |
| Validate | npx torusguard web-validate |
/torusguard web-validate |
Authorized non-destructive HTTP probing with transparent audit headers |
| Exploit | npx torusguard exploit-check |
/torusguard exploit-check |
Bounded single-step exploitability confirmation using inert sentinels |
TorusGuard's AST scanner inspects polyglot source trees across 74 canonical security rules organized into 6 core security pillars across 18 families:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 74 CANONICAL RULES ACROSS 6 PILLARS โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. Secrets & Identity โโโบ TG-SEC (7) ยท TG-AUTH (8) ยท TG-CLIENT (2)
2. Data & Injection Defense โโโบ TG-DB (4) ยท TG-INPUT (6) ยท TG-CSRF (2)
3. AI Agent & LLM Security โโโบ TG-AGENT (4)
4. Network & Real-Time โโโบ TG-SSRF (4) ยท TG-WEBHOOK (4) ยท TG-WS (4)
5. Platform & API Limits โโโบ TG-RATE (3) ยท TG-GQL (4) ยท TG-PLATFORM (4)
TG-CACHE (3) ยท TG-EDGE (2)
6. Supply Chain & Governanceโโโบ TG-SUPPLY (6) ยท TG-BIZ (4) ยท TG-DIFF (3)
| Pillar | Family Prefix | Rules | Critical Invariant Enforced |
|---|---|---|---|
| ๐ Secrets & Client Bundles | TG-SEC, TG-CLIENT |
9 | Zero hardcoded API keys, JWT secrets, private certificates, or server keys in client bundles. |
| ๐ก๏ธ Authentication & Sessions | TG-AUTH, TG-CSRF |
10 | Timing-safe string compares, strong password hashing, algorithm verification, SameSite cookies. |
| ๐๏ธ Database & Input Safety | TG-DB, TG-INPUT |
10 | Parameterized SQL queries, multi-tenant isolation (where: { tenantId }), path sanitization. |
| ๐ค AI Agent & LLM Guardrails | TG-AGENT |
4 | Structural user prompt isolation, delimiter wrapping, shell tool sandboxing, MCP least-privilege. |
| ๐ Network, Webhooks & WS | TG-SSRF, TG-WEBHOOK, TG-WS |
12 | Private IP range blocking (169.254.169.254), HMAC-SHA256 signature checks, WS origin validation. |
| โก Platform, Edge & Governance | TG-RATE, TG-GQL, TG-PLATFORM, TG-CACHE, TG-EDGE, TG-SUPPLY, TG-BIZ, TG-DIFF |
29 | Auth rate limiting, GraphQL depth bounds, Helmet headers, lockfile integrity, zero # nosec bypasses. |
๐ Click to expand full 18-family catalog breakdown
TG-SEC(Secrets & API Tokens โ 7 rules): Detects hardcoded JWT secrets, private certificates, cloud API keys, environment variable leakage, and secrets in URL queries or logs.TG-AUTH(Authentication & Access Control โ 8 rules): Enforces constant-time string comparisons, strong password hashing (bcrypt/argon2), JWT algorithm pinning, mass assignment prevention, and server-side role verification.TG-DB(Database Partitioning & Injection โ 4 rules): Mandates tenant-scoped queries across Prisma, Mongoose, SQLAlchemy, and GORM; eliminates raw SQL string concatenation.TG-INPUT(Input Validation & Traversal โ 6 rules): Enforces safe path sanitization (path.basename), command argument escaping, safe DOM text assignments, and server-side file upload bounds.TG-RATE(Rate Limiting & Resource Protection โ 3 rules): Enforces rate-limiting middleware on authentication routes, pagination bounds, and request payload size limits.TG-AGENT(AI Agent & LLM Defense โ 4 rules): Enforces structural separation of user prompts from system instructions, inert XML delimiters, and containerized tool execution.TG-SSRF(Server-Side Request Forgery โ 4 rules): Restricts dynamic outbound HTTP calls, blocks AWS/cloud metadata access (169.254.169.254), and enforces request timeouts.TG-WEBHOOK(Webhook Verification โ 4 rules): Mandates cryptographic HMAC-SHA256 signature validation before body parsing, replay prevention, and timestamp expiration.TG-WS(WebSocket Security โ 4 rules): Enforces handshake authentication, origin validation, channel-level authorization, and frame size caps.TG-CSRF(Cross-Site Request Forgery โ 2 rules): Enforces anti-CSRF tokens on state-changing operations andSameSitecookie attributes.TG-GQL(GraphQL Protection โ 4 rules): Enforces query depth limiting, production introspection suppression, and field-level resolver authorization.TG-SUPPLY(Supply Chain Integrity โ 6 rules): Audits dependency lockfile presence, checks against known CVEs, prevents--no-auditbuild flags, and inspects build scripts.TG-BIZ(Business Logic Bounds โ 4 rules): Validates negative quantity inputs, coupon/discount boundaries, and race-condition transaction locks.TG-CACHE(Cache Isolation โ 3 rules): EnforcesCache-Control: no-store, privateon authenticated responses and sanitizes unkeyed request headers.TG-CLIENT(Client Bundle Hygiene โ 2 rules): Forbids importing private server environment variables into browser bundles and suppresses production source maps.TG-PLATFORM(Server Hardening โ 4 rules): Enforces Helmet HTTP security headers, CORS origin whitelisting, cookiesecureflags, and debug mode suppression.TG-DIFF(Polyglot Diff Integrity โ 3 rules): Intercepts security bypass comments (# nosec,InsecureSkipVerify: true) and asserts Ponytail patch budgets.TG-EDGE(Edge & Serverless Limits โ 2 rules): Prevents cross-request memory leaks in Cloudflare Workers and enforces subrequest fan-out limits.
Traditional AI coding assistants routinely destroy functional features by attempting full-file rewrites. TorusGuard strictly enforces the Ponytail Protocol:
Before modifying a single file on disk, apply_runner.py creates a byte-for-byte backup:
.torusguard/snapshots/<run_id>/<target_file>.bak
If a patch causes unforeseen behavior or test failures, execute an instant 1-command rollback:
npx torusguard rollbackAll affected files are immediately restored to their exact pre-patch byte state.
To eliminate AI hallucination, TorusGuard maintains security_report.md at the workspace root as the single source of truth across all CLI commands and AI chat sessions.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SECURITY REPORT LIFECYCLE STATE MACHINE โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
[ OPEN ๐ด ] โโ(verify)โโโบ [ VERIFIED ๐ ] โโ(harden)โโโบ [ CANDIDATE ๐ก ]
โ
(apply)
โ
โผ
[ RESOLVED ๐ข ] โโโ(recheck: confirmed)โโ [ APPLIED ๐ต ]
โ
โโโ(recheck: failed)โโโบ [ REGRESSED โ ]
The Health Score dynamically reflects the open risk ledger:
When all findings are verified closed via differential recheck, the repository achieves Health Score: 100/100 ๐ข Hardened & Secure.
Generate a standalone, zero-external-CDN, dark-mode visual posture dashboard:
npx torusguard report --html-
SVG Circular Posture Gauge: Animated visual health score (
$0-100$ ). - 7-Stage Closed-Loop Pipeline: Visual state timeline across all lifecycle phases.
- Golden Fix Recipes Grid: Syntax-highlighted unified diffs with Ponytail metrics.
- Zero-CDN Architecture: Completely offline-ready; embeds all styles and assets inline.
To integrate with GitHub Code Scanning, export standard SARIF:
npx torusguard report > results.sarifTorusGuard compiles project security invariants, golden recipes, and active guardrails into prompt-optimized rule files:
npx torusguard rules sync- Cursor: Injects non-destructive rules into
.cursorrules - Claude Code: Injects non-destructive rules into
CLAUDE.md - Antigravity IDE: Injects non-destructive rules into
.agent/rules/torusguard.md - Windsurf: Injects non-destructive rules into
.windsurfrules
All rules are compiled under a strict overhead ceiling of $\le 300$ prompt tokens to preserve AI reasoning context.
TorusGuard automatically discovers and profiles multi-package workspaces:
- Monorepo Ecosystems: pnpm workspaces, npm/yarn workspaces, Cargo workspaces, Go multi-module workspaces, Gradle multi-project builds.
- Universal Polyglot Profiler: Automatically identifies 16+ languages and maps ORM boundaries independently per sub-package.
- Pre-Commit Diff Guard: Run
npx torusguard diff-guard --install-hookto bind.git/hooks/pre-commitand block security bypasses before code is committed.
TorusGuard enforces a strict 100% pass requirement across 120 test suites before every release. The test harness runs with zero third-party dependencies via standard Python 3:
npm test
# Equivalent to: python harness/runner.pyWhen a developer runs:
npm testThe test harness invokes python harness/runner.py directly using the Python standard library. It systematically verifies:
-
JSON Schema Validity: 10 formal schemas (
finding,evidence,remediation,rule,lifecycle,provenance, etc.). - 74-Rule Catalog Integrity: AST detection accuracy across all 18 security families.
- Line-Shift Fingerprinting: Stable anchor matching across file edits without line number drift.
- Secret Redaction: Stripe secret keys and JWT tokens safely masked.
- Deterministic Replay: 3-pass differential validation across Django, DRF, FastAPI, Flask, and SQLAlchemy fixtures.
-
Ponytail Patch Churn Bounds: Verifying line budgets (
$\le 35$ additions,$\le 25$ deletions). -
Living Security Report State Transitions: Discovery (
OPEN ๐ด), Candidate (CANDIDATE ๐ก), Applied (APPLIED ๐ต), and Verified Closure (RESOLVED ๐ข).
# Run formal TorusGuard test harness
npm test
# Expected Output:
# ================================================================================
# SUMMARY: 120 Passed | 0 Failed
# ================================================================================To validate diff guard and monorepo profiling independently:
python harness/validate_v0_9_2_diff_and_monorepo.pyIf you believe you have discovered a security vulnerability in TorusGuard itself, please report it responsibly and privately through GitHub Private Vulnerability Reporting or contact the project maintainers. Do not file public issues for undisclosed security flaws. For complete details, consult SECURITY.md.
TorusGuard is released under the MIT License.
Copyright (c) 2026 Jenish Lad (@githubmofo).