Autonomous Security Guardrails, Governed Remediation & Living Verification for AI-Built Applications
Zero Telemetry ยท Zero External Python Dependencies ยท Pure Standard-Library Architecture ยท 100% Local-First
The Developer Reality: AI coding assistants (Cursor, Claude Code, Copilot, Windsurf, Antigravity) 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 across 74 rules, 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, Go & CLI)
- Quickstart: The 5-Step Core Lifecycle
- Dual-Strategy Command Matrix (CLI & AI Chat Parity)
- Polyglot Go Engine & Native Runner
- Package Self-Update Engine (
update) - 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 (133/133 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) - Go (Optional): 1.22 or higher (for native Go CLI compilation & Go module workflows)
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 status
npx torusguard updateLock 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",
"security:update": "torusguard update"
}
}For Go ecosystem developers, TorusGuard ships with a native Go runner module (go.mod):
# Run zero-dependency Go CLI entrypoint directly
go run cmd/torusguard/main.go audit
# Or install globally into your $GOPATH/bin
go install github.com/torusguard/torusguard/cmd/torusguard@latest
torusguard statusIf 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 (or npx torusguard init --template golang) 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 (optional: --template golang|nextjs|fastapi)
npx torusguard init
# Step 2: Run AST static security audit across 74 rules (optional: --watch, --sarif)
npx torusguard audit
# Step 3: Synthesize minimal surgical candidate patches (optional: --dry-run, --severity high)
npx torusguard harden
# Step 4: Review syntax-highlighted diffs and apply with rollback backup (optional: --diff, --selective)
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. All commands support --target <dir> / -t <dir> for monorepo and subproject isolation.
| Lifecycle Stage | Mode A: Terminal CLI | Mode B: AI Chat Command | Governed Action & Primary Artifact |
|---|---|---|---|
| 1. Init | npx torusguard init [--template <name>] [--audit] |
/torusguard init |
Profiles workspace, activates rules, scaffolds .torusguard/
|
| 2. Status | npx torusguard status |
/torusguard status |
75-column diagnostic overview of health score, stack, memory & rules |
| 3. Audit | npx torusguard audit [--watch] [--sarif] |
/torusguard audit |
74-rule AST scan, line-shift fingerprints, throughput metrics, living ledger |
| 4. Verify | npx torusguard verify |
/torusguard verify |
Asserts evidence sufficiency & live disk line-shift fingerprint matches |
| 5. Harden | npx torusguard harden [--dry-run] [--severity <s\>] |
/torusguard harden |
Synthesizes Ponytail diffs ( |
| 6. Apply | npx torusguard apply [--diff] [--selective] [--yes] |
/torusguard apply |
Human Gate, pre-apply .bak snapshots, Golden Fix distillation |
| 7. Rollback | npx torusguard rollback [--run <id>] |
/torusguard rollback |
Instant restoration from pre-apply snapshots in .torusguard/snapshots/
|
| 8. Recheck | npx torusguard recheck |
/torusguard recheck |
Differential AST re-scan; marks findings RESOLVED ๐ข in living report |
| 9. Recipes | npx torusguard recipes [--search <q>] [--export <p>] |
/torusguard recipes |
Explores and exports verified Golden Fix patterns from .torusguard/memory/
|
| 10. Report | npx torusguard report --html [--sarif] |
/torusguard report |
Emits single-file dark-mode HTML posture dashboard & OASIS SARIF v2.1.0 |
| 11. Update | npx torusguard update [--install] |
/torusguard update |
Verifies npm registry for latest versions and provides 1-command upgrade |
| 12. Rules Sync | npx torusguard rules sync |
/torusguard rules sync |
Synchronizes prompt guardrails across Cursor, Claude, Antigravity, Windsurf |
| 13. Diff Guard | npx torusguard diff-guard [--install-hook] |
/torusguard diff-guard |
Audits git diffs for security bypasses; binds pre-commit git hook |
| 14. Authorize | npx torusguard authorize |
/torusguard authorize |
Target domain allowlisting, cryptographic ownership proof, TTL limits |
| 15. Validate | npx torusguard web-validate |
/torusguard web-validate |
Authorized non-destructive HTTP probing with transparent audit headers |
| 16. Exploit | npx torusguard exploit-check |
/torusguard exploit-check |
Bounded single-step exploitability confirmation using inert sentinels |
TorusGuard v1.4.0 introduces native, zero-dependency Go ecosystem support:
TG-INPUT-002(Raw SQL Concatenation): Detects unparameterized string concatenation andfmt.Sprintfquery interpolation indatabase/sql,sqlx, and GORM.TG-INPUT-006(Path Traversal): Detects unsanitized file reads (os.Open,os.ReadFile) using user request parameters.TG-SSRF-004(Unbounded HTTP Requests): Flags&http.Client{}andhttp.DefaultClientlacking explicit timeout boundaries to prevent connection pooling denial-of-service.TG-DIFF-001(Security Bypasses): Prevents insecure TLS validation (InsecureSkipVerify: true).TG-SUPPLY-001(Supply Chain): Asserts lockfile presence and cryptographic tracking forgo.sum.
Patches for Go follow strict Ponytail line churn limits (
// Example: TG-SSRF-004 Remediation
- client := &http.Client{}
+ client := &http.Client{Timeout: 10 * time.Second}
// Example: TG-INPUT-006 Path Traversal Remediation
- data, err := os.ReadFile("/data/" + c.Query("file"))
+ data, err := os.ReadFile(filepath.Join("/data", filepath.Base(c.Query("file"))))Keep your security guardrails continuously synchronized with the latest threat models:
# Check registry for newer versions
npx torusguard update
# Automatically upgrade to latest version
npx torusguard update --install- Zero-Dependency Registry Check: Queries
https://registry.npmjs.org/torusguard/latestnatively. - SemVer Delta Analysis: Displays current version against registry latest in standard 75-column cards.
- Automated Upgrade Flow: Executes package installation upon user authorization.
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 133 tests in 21 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.
-
Polyglot Go Engine: Go module definition, Go stack detection (Gin, Fiber, GORM), and Go AST rules (
TG-INPUT-002,TG-INPUT-006,TG-SSRF-004). - 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). - Deepened Command Verification: Audit watch loop & SARIF export, Harden dry-run & severity floor, Recipes search & export, Apply diff preview & snapshot ledger, and Bootstrap templates.
-
Living Security Report State Transitions: Discovery (
OPEN ๐ด), Candidate (CANDIDATE ๐ก), Applied (APPLIED ๐ต), and Verified Closure (RESOLVED ๐ข). - Cryptographic Manifest Parity: 100% SHA-256 match across all indexed workspace files.
# Run formal TorusGuard test harness
npm test
# Expected Output:
# ================================================================================
# SUMMARY: 133 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).