torusguard 1.0.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/.torusguard/.manifest.json +89 -75
  2. package/.torusguard/references/csharp-security.md +41 -0
  3. package/.torusguard/references/go-security.md +41 -0
  4. package/.torusguard/references/java-security.md +40 -0
  5. package/.torusguard/references/polyglot-security-matrix.md +25 -0
  6. package/.torusguard/references/rust-security.md +40 -0
  7. package/.torusguard/rules/custom/.gitkeep +1 -0
  8. package/.torusguard/rules/custom/README.md +30 -0
  9. package/.torusguard/runs/report-latest.html +328 -0
  10. package/.torusguard/schemas/golden-recipe.schema.json +75 -0
  11. package/.torusguard/scripts/diff_guard.py +131 -4
  12. package/.torusguard/scripts/finding_scorer.py +33 -5
  13. package/.torusguard/scripts/html_reporter.py +628 -0
  14. package/.torusguard/scripts/manifest_builder.py +5 -5
  15. package/.torusguard/scripts/memory_engine.py +521 -99
  16. package/.torusguard/scripts/monorepo_detector.py +123 -10
  17. package/.torusguard/scripts/rules_sync.py +321 -0
  18. package/.torusguard/scripts/stack_detect.py +458 -26
  19. package/.torusguard/skills/torusguard/references/csharp-security.md +41 -0
  20. package/.torusguard/skills/torusguard/references/go-security.md +41 -0
  21. package/.torusguard/skills/torusguard/references/java-security.md +40 -0
  22. package/.torusguard/skills/torusguard/references/polyglot-security-matrix.md +25 -0
  23. package/.torusguard/skills/torusguard/references/rust-security.md +40 -0
  24. package/README.md +307 -410
  25. package/bin/torusguard.js +108 -4
  26. package/package.json +1 -1
  27. package/skills/torusguard/bootstrap.py +2 -2
  28. package/skills/torusguard/payload/.manifest.json +89 -75
  29. package/skills/torusguard/payload/references/csharp-security.md +41 -0
  30. package/skills/torusguard/payload/references/go-security.md +41 -0
  31. package/skills/torusguard/payload/references/java-security.md +40 -0
  32. package/skills/torusguard/payload/references/polyglot-security-matrix.md +25 -0
  33. package/skills/torusguard/payload/references/rust-security.md +40 -0
  34. package/skills/torusguard/payload/rules/custom/.gitkeep +1 -0
  35. package/skills/torusguard/payload/rules/custom/README.md +30 -0
  36. package/skills/torusguard/payload/schemas/golden-recipe.schema.json +75 -0
  37. package/skills/torusguard/payload/scripts/diff_guard.py +131 -4
  38. package/skills/torusguard/payload/scripts/finding_scorer.py +33 -5
  39. package/skills/torusguard/payload/scripts/html_reporter.py +628 -0
  40. package/skills/torusguard/payload/scripts/manifest_builder.py +5 -5
  41. package/skills/torusguard/payload/scripts/memory_engine.py +521 -99
  42. package/skills/torusguard/payload/scripts/monorepo_detector.py +123 -10
  43. package/skills/torusguard/payload/scripts/rules_sync.py +321 -0
  44. package/skills/torusguard/payload/scripts/stack_detect.py +458 -26
  45. package/skills/torusguard/payload/skills/torusguard/bootstrap.py +2 -2
  46. package/skills/torusguard/payload/skills/torusguard/references/csharp-security.md +41 -0
  47. package/skills/torusguard/payload/skills/torusguard/references/go-security.md +41 -0
  48. package/skills/torusguard/payload/skills/torusguard/references/java-security.md +40 -0
  49. package/skills/torusguard/payload/skills/torusguard/references/polyglot-security-matrix.md +25 -0
  50. package/skills/torusguard/payload/skills/torusguard/references/rust-security.md +40 -0
  51. package/.torusguard/scripts/__pycache__/diff_guard.cpython-311.pyc +0 -0
  52. package/.torusguard/scripts/__pycache__/finding_scorer.cpython-311.pyc +0 -0
  53. package/.torusguard/scripts/__pycache__/memory_engine.cpython-311.pyc +0 -0
  54. package/.torusguard/scripts/__pycache__/monorepo_detector.cpython-311.pyc +0 -0
  55. package/skills/torusguard/__pycache__/bootstrap.cpython-311.pyc +0 -0
package/README.md CHANGED
@@ -1,410 +1,307 @@
1
- <div align="center">
2
- <img src="https://raw.githubusercontent.com/githubmofo/TorusGuard/main/TorusGuard.png" alt="TorusGuard Security Banner" width="480" style="max-width: 100%; height: auto; border-radius: 8px;">
3
-
4
- # TorusGuard
5
-
6
- **Autonomous Security Guardrails, Governed Remediation, and Authorized Runtime Validation for AI-Built Web Applications.**
7
-
8
- [![npm version](https://img.shields.io/npm/v/torusguard.svg?style=flat-square&color=cb3837&logo=npm)](https://www.npmjs.com/package/torusguard)
9
- [![GitHub Packages](https://img.shields.io/badge/GitHub%20Packages-v1.0.0-181717.svg?style=flat-square&logo=github)](https://github.com/githubmofo/TorusGuard/pkgs/npm/torusguard)
10
- [![Release](https://img.shields.io/badge/Release-v1.0.0-blue.svg?style=flat-square)](https://github.com/githubmofo/TorusGuard/releases/latest)
11
- [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](LICENSE)
12
- [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-blue.svg?style=flat-square&logo=python&logoColor=white)](https://python.org)
13
- [![Node.js 18+](https://img.shields.io/badge/Node.js-18%2B-339933.svg?style=flat-square&logo=node.js&logoColor=white)](https://nodejs.org)
14
- [![SARIF: v2.1.0](https://img.shields.io/badge/SARIF-v2.1.0%20OASIS-purple.svg?style=flat-square)](.torusguard/schemas/)
15
- [![Integrity: SHA--256](https://img.shields.io/badge/Integrity-SHA--256%20Verified-teal.svg?style=flat-square)](.torusguard/.manifest.json)
16
- [![OWASP: Top 10](https://img.shields.io/badge/OWASP-Top%2010%20Aligned-orange.svg?style=flat-square)](docs/architecture/SECURITY_ARCHITECTURE.md)
17
- </div>
18
-
19
- ---
20
-
21
- ## 💡 Executive Summary
22
-
23
- Modern AI coding agents generate full-stack web applications at unprecedented velocity. However, they consistently introduce critical security anti-patterns: leaking service-role credentials to browser bundles, omitting multi-tenant query boundaries, disabling CSRF defenses, or granting unconstrained tool permissions.
24
-
25
- **TorusGuard** is an autonomous application security co-pilot specifically engineered for AI-built software. It integrates natively into your development environment (Antigravity, Cursor, Claude Code, VS Code Copilot, Kimi, Windsurf, Cline) to deliver:
26
-
27
- 1. **Deterministic Static Auditing:** Scan Python and TypeScript source code using 71 specialized security rules across 11 families.
28
- 2. **Authorized Runtime Validation:** Execute bounded, non-destructive HTTP probes to eliminate false alarms and confirm real exploitability.
29
- 3. **Governed Minimal Remediation:** Generate surgical, reviewable patches constrained by the **Ponytail Protocol** ($\le 35$ additions, $\le 25$ deletions) to eliminate unintended regressions.
30
- 4. **Open Industry Standards:** Emit OASIS SARIF v2.1.0 telemetry with stable AST line-shift invariant hashes for native GitHub Code Scanning integration.
31
-
32
- ### 🌐 The Core Invariant: The Browser-Code Truth
33
- > **"If the browser receives it, users can inspect it."**
34
- > Frontend environment variables, JavaScript network bundles, and React Server Action payloads cannot conceal secrets. TorusGuard strictly enforces that database credentials, private API keys, and authorization barriers remain exclusively on trusted server boundaries.
35
-
36
- ---
37
-
38
- ## ⚡ Dual-Track Distribution Architecture
39
-
40
- TorusGuard features a decoupled **Dual-Track Architecture** allowing teams to choose between zero-setup in-memory agent intelligence and full repository governance:
41
-
42
- ```mermaid
43
- flowchart TD
44
- subgraph Core ["🛡️ TorusGuard Core Intelligence Engine"]
45
- Rules["71 Canonical Security Rules"]
46
- Ponytail["Ponytail Patch Governor (<=35 add, <=25 del)"]
47
- Scorer["5-Factor Mathematical Confidence Scorer"]
48
- end
49
-
50
- Core --> Track1["⚡ Track 1: Universal AI Agent Skill"]
51
- Core --> Track2["🛡️ Track 2: Production NPM Package"]
52
-
53
- subgraph Track1Scope ["Track 1: In-Memory Agent Execution"]
54
- T1Cmd["npx skills add ... -a universal -y"]
55
- T1Env["Works in ANY AI Agent (Cursor, Kimi, Antigravity, Copilot)"]
56
- T1Disk["Zero local file footprint (pure in-memory reasoning)"]
57
- T1Router["Single clean slash command: /torusguard"]
58
- end
59
-
60
- subgraph Track2Scope ["Track 2: Full Local Governance"]
61
- T2Cmd["npx torusguard init / npm i -D torusguard"]
62
- T2Env["Persistent .torusguard/ repository workspace"]
63
- T2CLI["Native Terminal CLI: npx torusguard status / audit"]
64
- T2Palette["Unlocks all 11 individual slash commands (/torusguard-*)"]
65
- end
66
-
67
- Track1 --> Track1Scope
68
- Track2 --> Track2Scope
69
-
70
- Track1Scope -. Harmonizes with .- Track2Scope
71
- ```
72
-
73
- ### Track Comparison Matrix
74
-
75
- | Capability | ⚡ Track 1: Universal AI Agent Skill | 🛡️ Track 2: Production NPM Package |
76
- | :--- | :--- | :--- |
77
- | **Primary Command** | `npx skills add https://github.com/githubmofo/TorusGuard -a universal -y` | `npx torusguard init` or `npm install -D torusguard` |
78
- | **Supported Agents** | All AI Agents (Antigravity, Cursor, Claude Code, Copilot, Kimi, Windsurf) | Any Node/Python repository, GitHub Actions CI/CD, Antigravity, Cursor |
79
- | **Disk Footprint** | In-memory agent context (`.agents/skills/torusguard/` only) | Complete local workspace (`.torusguard/` with config, rules, schemas, runs) |
80
- | **Slash Commands** | Single master dispatcher: `/torusguard` | Full 11-command palette: `/torusguard-audit`, `/torusguard-apply`, etc. |
81
- | **Terminal CLI** | None (AI chat-driven) | Native terminal runner: `npx torusguard status`, `npx torusguard audit` |
82
- | **Prerequisites** | None (pure AI agent execution) | Node.js 18+ (and Python 3.10+ for native verification scripts) |
83
- | **Best For** | Instant zero-setup security advice in chat | Production repositories, team compliance, CI/CD SARIF exports |
84
-
85
- ---
86
-
87
- ## 🚀 Installation & Quick Start
88
-
89
- ### Track 1: Universal AI Agent Skill (Zero Setup)
90
- Install directly into any AI assistant adhering to the Open Agent Skills standard:
91
- ```bash
92
- # Recommended one-liner (silent, zero-prompts, targets all IDE agents):
93
- npx skills add https://github.com/githubmofo/TorusGuard -a universal -y
94
- ```
95
- * **`-a universal`**: Automatically registers the skill for Antigravity, Cursor, Gemini CLI, Claude Code, VS Code Copilot, and Kimi without prompt friction.
96
- * **`-y`**: Bypasses interactive confirmation prompts and completes in **under 2 seconds**.
97
- * Once installed, simply type `/torusguard` in chat or ask: *"Audit this component for security flaws"*.
98
-
99
- ### Track 2: Production NPM Package (Full Governance)
100
- Scaffold your repository with local configuration, offline scripts, and granular workflows:
101
- ```bash
102
- # Direct runner (recommended):
103
- npx torusguard init
104
-
105
- # Or install as a development dependency:
106
- npm install -D torusguard
107
- ```
108
- * Generates the `.torusguard/` workspace directory.
109
- * Populates your IDE command palette with all 11 individual `/torusguard-*` workflows.
110
- * Run instant terminal checks anytime:
111
- ```bash
112
- npx torusguard status
113
- npx torusguard audit
114
- ```
115
-
116
- ### Standalone Python Installer (Alternative)
117
- For Python-only environments, Docker containers, or air-gapped CI/CD runners:
118
- ```bash
119
- # From cloned repository:
120
- python install.py
121
-
122
- # Or via remote one-liner:
123
- curl -sSL https://raw.githubusercontent.com/githubmofo/TorusGuard/main/install.py | python
124
- ```
125
-
126
- ---
127
-
128
- ## 📋 Comprehensive Command Catalog
129
-
130
- When Track 2 is initialized, the complete 11-command palette becomes available in your IDE (`.agent/workflows/`, `.agents/workflows/`, `.claude/commands/`, `.cursor/rules/`):
131
-
132
- | Slash Command | Specialist Skill | Lifecycle Phase | Operational Description | Code Changed? |
133
- | :--- | :--- | :---: | :--- | :---: |
134
- | `/torusguard` | `skills/torusguard` | Router | Master natural-language command dispatcher and prompt auditor. | No |
135
- | `/torusguard init`<br>*(or `/torusguard-init`)* | `skills/torusguard-init` | Phase 0 | Profiles repository stack, discovers frameworks, and enables matching rules. | Yes (`.torusguard/`) |
136
- | `/torusguard authorize`<br>*(or `/torusguard-authorize`)* | `skills/torusguard-authorize` | Phase 1 | Establishes target ownership, scopes URL boundaries, and sets scan rate limits. | Yes (`scope.json`) |
137
- | `/torusguard audit`<br>*(or `/torusguard-audit`)* | `skills/torusguard-audit` | Phase 2 | Scans source code and clusters repeated alerts by root-cause identity. | No |
138
- | `/torusguard verify`<br>*(or `/torusguard-verify`)* | `skills/torusguard-verify` | Phase 3 | Scores findings across a 5-factor mathematical rubric (0–100) to purge false alarms. | No |
139
- | `/torusguard web-validate`<br>*(or `/torusguard-web-validate`)* | `skills/torusguard-web-validate` | Phase 3 | Dispatches authorized, non-destructive HTTP requests with transparent audit headers. | No |
140
- | `/torusguard exploit-check`<br>*(or `/torusguard-exploit-check`)* | `skills/torusguard-exploit-check` | Phase 3 | Validates exploitability safely into 5 formal verification statuses. | No |
141
- | `/torusguard harden`<br>*(or `/torusguard-harden`)* | `skills/torusguard-harden` | Phase 4 | Packages 4-artifact Remediation Bundles with framework-idiomatic fixes. | No |
142
- | `/torusguard apply`<br>*(or `/torusguard-apply`)* | `skills/torusguard-apply` | Phase 5 | Applies surgical patches bounded by Ponytail limits ($\le 35$ additions, $\le 25$ deletions). | **Yes (Patch)** |
143
- | `/torusguard recheck`<br>*(or `/torusguard-recheck`)* | `skills/torusguard-recheck` | Phase 6 | Executes differential re-audit strictly on modified files to verify fix closure. | No |
144
- | `/torusguard report`<br>*(or `/torusguard-report`)* | `skills/torusguard-report` | Phase 7 | Emits executive summary markdown and OASIS SARIF v2.1.0 CI artifacts. | No |
145
- | `/torusguard status`<br>*(or `/torusguard-status`)* | `skills/torusguard-status` | Diagnostic | Inspects active security posture, thresholds, and recent run history. | No |
146
- | `/torusguard memory` | `skills/torusguard` | Intelligence | Inspects, exports, imports, or compacts persistent security memory context. | Yes (`.torusguard/memory/`) |
147
- | `/torusguard full` | `skills/torusguard-full` | End-to-End | Orchestrates the entire 7-stage security cycle in one coordinated sequence. | **Yes (Governed)** |
148
-
149
- ---
150
-
151
- ## 🔄 The 7-Stage Closed-Loop Finding Lifecycle
152
-
153
- Every candidate vulnerability transitions through an auditable, deterministic state machine with zero regression tolerance:
154
-
155
- ```mermaid
156
- flowchart LR
157
- Detect["1. Detect<br>/torusguard audit"] --> Classify["2. Classify<br>AST Line Hashing"]
158
- Classify --> Verify["3. Verify<br>verify / web-validate"]
159
- Verify --> Remediate["4. Remediate<br>/torusguard harden"]
160
- Remediate --> Apply["5. Apply<br>/torusguard apply"]
161
- Apply --> Recheck["6. Recheck<br>/torusguard recheck"]
162
- Recheck --> Report["7. Report<br>/torusguard report"]
163
-
164
- style Detect fill:#1e293b,stroke:#3b82f6,stroke-width:2px,color:#fff
165
- style Classify fill:#1e293b,stroke:#6366f1,stroke-width:2px,color:#fff
166
- style Verify fill:#1e293b,stroke:#8b5cf6,stroke-width:2px,color:#fff
167
- style Remediate fill:#1e293b,stroke:#ec4899,stroke-width:2px,color:#fff
168
- style Apply fill:#1e293b,stroke:#f59e0b,stroke-width:2px,color:#fff
169
- style Recheck fill:#1e293b,stroke:#10b981,stroke-width:2px,color:#fff
170
- style Report fill:#1e293b,stroke:#06b6d4,stroke-width:2px,color:#fff
171
- ```
172
-
173
- ### Lifecycle Stage Breakdown
174
-
175
- | Stage | Command | Responsible Agent | Primary Activity & Invariant Guarantee |
176
- | :---: | :--- | :---: | :--- |
177
- | **1. Detect** | `/torusguard audit` | `auditor` | Static AST and regex inspection flags potential vulnerabilities across Python and TypeScript. |
178
- | **2. Classify** | *(automatic)* | `auditor` | Computes line-shift invariant `primaryLocationLineHash` fingerprints and clusters repeated instances into root causes. |
179
- | **3. Verify** | `/torusguard verify` | `validator` | Applies a 5-factor mathematical scoring model (0–100) and executes authorized, bounded runtime HTTP probes. |
180
- | **4. Remediate** | `/torusguard harden` | `remediator` | Generates self-contained Remediation Bundles containing unified diffs and rollbacks. |
181
- | **5. Apply** | `/torusguard apply` | `remediator` | Takes pre-apply file snapshots and enforces **Ponytail bounds** ($\le 35$ additions, $\le 25$ deletions). |
182
- | **6. Recheck** | `/torusguard recheck` | `reviewer` | Performs differential re-audit strictly on modified files to verify fix closure without introducing new flaws. |
183
- | **7. Report** | `/torusguard report` | `reviewer` | Synthesizes an executive Markdown summary and exports an OASIS SARIF v2.1.0 file for CI/CD tracking. |
184
-
185
- ---
186
-
187
- ## 🎯 Specialist Agents & Authority Separation
188
-
189
- To eliminate AI confirmation bias, security responsibilities are divided across **5 formal, isolated roles**:
190
-
191
- ```mermaid
192
- flowchart TD
193
- subgraph DiscoveryPhase ["Discovery Phase"]
194
- P["🔍 Profiler Agent<br>profiler.md"]
195
- end
196
-
197
- subgraph DetectionPhase ["Detection Phase"]
198
- A["🔎 Auditor Agent<br>auditor.md"]
199
- end
200
-
201
- subgraph VerificationPhase ["Verification Phase"]
202
- V["🧪 Validator Agent<br>validator.md"]
203
- end
204
-
205
- subgraph RemediationPhase ["Remediation Phase"]
206
- R["🛠️ Remediator Agent<br>remediator.md"]
207
- end
208
-
209
- subgraph ReviewPhase ["Review & Sign-Off Phase"]
210
- REV["⚖️ Reviewer Agent<br>reviewer.md"]
211
- HumanGate["👤 Human Gate (Approval)"]
212
- end
213
-
214
- P -->|Stack Profile| A
215
- A -->|Static Findings| V
216
- V -->|Validated Evidence| R
217
- R -->|Remediation Diff| REV
218
- REV -->|Zero-Regress Sign-Off| HumanGate
219
-
220
- style P fill:#1e293b,stroke:#3b82f6,stroke-width:2px,color:#fff
221
- style A fill:#1e293b,stroke:#6366f1,stroke-width:2px,color:#fff
222
- style V fill:#1e293b,stroke:#8b5cf6,stroke-width:2px,color:#fff
223
- style R fill:#1e293b,stroke:#ec4899,stroke-width:2px,color:#fff
224
- style REV fill:#1e293b,stroke:#10b981,stroke-width:2px,color:#fff
225
- style HumanGate fill:#334155,stroke:#f59e0b,stroke-width:2px,color:#fff
226
- ```
227
-
228
- ### Agent Responsibilities & Isolation Rules
229
-
230
- | Agent | Specification | Dedicated Purpose | Anti-Bias Isolation Rule |
231
- | :--- | :--- | :--- | :--- |
232
- | **🔍 Profiler** | `.torusguard/agents/profiler.md` | Discovers frameworks, ORMs, and packages. | Cannot conduct vulnerability detection. |
233
- | **🔎 Auditor** | `.torusguard/agents/auditor.md` | AST pattern matching and root-cause clustering. | Cannot propose code modifications or execute probes. |
234
- | **🧪 Validator** | `.torusguard/agents/validator.md` | Bounded runtime HTTP validation and scoring. | Bound by `scope.json` authorization boundaries. |
235
- | **🛠️ Remediator** | `.torusguard/agents/remediator.md` | Formulates surgical, minimal code patches. | **Cannot approve its own patch.** |
236
- | **⚖️ Reviewer** | `.torusguard/agents/reviewer.md` | Pre-flight verification and compliance sign-off. | **Must be independent from Remediator.** |
237
-
238
- * **Zero Self-Review:** The agent that writes a patch (`Remediator`) can never sign off on its merge (`Reviewer` + Human Gate required).
239
- * **Cryptographic Provenance:** Every role handoff is recorded in `role-audit.json` with SHA-256 signatures.
240
-
241
- ---
242
-
243
- ## 🛡️ Core Innovation Highlights
244
-
245
- ### 1. The Ponytail Protocol (Minimal Patch Churn Bounds)
246
- Unbounded AI code generators frequently rewrite adjacent business logic, introduce accidental syntax errors, or strip comments. TorusGuard strictly enforces the **Ponytail Protocol**:
247
- * **$\le 35$ Additions** per remediation patch.
248
- * **$\le 25$ Deletions** per remediation patch.
249
- * **Deterministic Single Responsibility:** Every patch resolves exactly one root-cause cluster without side effects.
250
-
251
- ### 2. Auditable Mathematical Confidence Scoring (0–100)
252
- TorusGuard computes confidence scores using a formal 5-factor mathematical formula before escalating findings to developers:
253
- $$\text{Score} = (w_d \cdot D) + (w_e \cdot E) + (w_c \cdot C_{ast}) - P_{fp} - P_{drift}$$
254
- * **$D$ (Detection Determinism, 30%):** Exact string/AST regex matches vs speculative patterns.
255
- * **$E$ (Runtime Evidence, 25%):** Confirmed HTTP exploitability response status.
256
- * **$C_{ast}$ (AST Contextuality, 25%):** Direct assignment in critical execution path vs commented code.
257
- * **$P_{fp}$ (False Positive Penalty, up to -20):** Safe wrapper detection (e.g. parameterized queries, sanitizers).
258
- * **$P_{drift}$ (Line Drift Penalty, up to -10):** Unmatched surrounding file context.
259
-
260
- ### 3. Stable Line-Shift Invariant Fingerprinting (`primaryLocationLineHash`)
261
- Traditional static tools break finding identity when a developer inserts 2 lines at the top of a file. TorusGuard computes a stable SHA-256 hash across the AST node content, enclosing function scope, and syntactic tokens. Findings maintain permanent tracking identity across Git commits and branch renames.
262
-
263
- ### 4. Adaptive Security Memory Engine (`.torusguard/memory/`)
264
- Traditional scanners are stateless — they scan, report, and forget. TorusGuard v1.0.0 introduces persistent, local-first intelligence that learns from every audit, fix, and verification:
265
- * **4-Tier Intelligence Architecture:** Raw event append-log (`events/`) ──► Distilled pattern store (`patterns.json`) ──► Pre-computed context window (`context.json`) ──► Project security profile (`profile.json`).
266
- * **Structured JSON Cards:** Pre-computes context cards within a strict $\le 2,000$ token budget for instant, hallucination-free injection into AI coding agent prompts.
267
- * **Confidence Amplification & TTL Decay:** Multi-file fix verifications boost pattern confidence up to 98%, while unconfirmed patterns decay gracefully over 90 days.
268
- * **Zero-Leakage Guarantee:** Memory is strictly gitignored (`*`), excluded from npm distribution tarballs, and stored only in the user's project.
269
- * **CLI Memory Management:** Inspect, export, import, or compact memory via `npx torusguard memory`.
270
-
271
- ---
272
-
273
- ## 🛡️ Rule Catalog & Detection Families (71 Canonical Rules)
274
-
275
- TorusGuard enforces 71 rules across modern application stacks:
276
-
277
- | Rule Family | Target Domain | Invariant Guarantees & Detection Scope |
278
- | :--- | :--- | :--- |
279
- | **`TG-SEC-*`** | Secrets & Credentials | Blocks exposed API keys, private certs, Supabase service roles, and hardcoded tokens. |
280
- | **`TG-DB-*`** | Database & Queries | Enforces parameterized SQL queries and mandatory multi-tenant isolation filters (`.filter(tenant=...)`). |
281
- | **`TG-INPUT-*`** | Input Validation | Validates Pydantic/Zod boundaries, prevents path traversal, and blocks unsanitized command execution. |
282
- | **`TG-AUTH-*`** | Authentication & RBAC | Requires server-side route guards, enforces session TTLs, stops mass-assignment, and guards against IDOR. |
283
- | **`TG-CLIENT-*`** | Client Bundle Leaks | Blocks server-side environment variables (`SUPABASE_KEY`, `DATABASE_URL`) from browser bundles. |
284
- | **`TG-DIFF-*`** | Diff Line Inspection | Evaluates patch additions/deletions for auth bypass comments (`// nosec`), disabled TLS, or filter removals. |
285
- | **`TG-AGENT-*`** | AI Agent & MCP Security | Enforces prompt injection delimiters, sandboxes tool execution, and restricts destructive tool capabilities. |
286
- | **`TG-EDGE-*`** | Serverless & Edge | Prevents global memory leakage in V8 isolates (Cloudflare Workers) and cold-start state bleed in AWS Lambda. |
287
- | **`TG-SUPPLY-*`** | Supply Chain & CI/CD | Enforces GitHub Actions least-privilege permissions, validates Docker build secrets, and flags risky deps. |
288
- | **`TG-SSRF-*`** | Outbound Networking | Enforces webhook HMAC signature verification, prevents SSRF DNS rebinding, and blocks internal subnets. |
289
- | **`TG-BIZ-*`** | Business Logic | Protects multi-step financial transactions, race conditions, and currency rounding precision. |
290
-
291
- ---
292
-
293
- ## 🔬 Content-Aware Diff Line Scanner (`diff_guard.py`)
294
-
295
- Every patch generated by TorusGuard (or submitted via Pull Request) is analyzed by our unified diff inspector:
296
- * **`TG-DIFF-001` (Bypass Markers):** Detects bypass comments (`# bypass auth`, `// nosec`) and disabled TLS verification (`verify=False`).
297
- * **`TG-DIFF-002` (Credential Ingestion):** Intercepts live JWTs, Bearer tokens, or high-entropy secrets introduced in additions.
298
- * **`TG-DIFF-003` (Tenant Removal):** Blocks deletions that strip tenant isolation clauses (`.filter(tenant=...)`, `where tenant_id`).
299
-
300
- ---
301
-
302
- ## 🏢 Monorepo Sub-Scope Orchestration (`monorepo_detector.py`)
303
-
304
- TorusGuard natively discovers and isolates sub-projects in complex monorepos:
305
- * **Package Managers:** Turborepo, pnpm workspaces, npm/yarn workspaces, Lerna.
306
- * **Service Independence:** Profiles backend services (FastAPI/Django) and frontend applications (Next.js/React) separately.
307
- * **Targeted Scanning:** Audit the entire repository or focus strictly on a specific service:
308
- ```bash
309
- npx torusguard audit --target apps/api
310
- ```
311
-
312
- ---
313
-
314
- ## 🎮 Interactive Multi-Stack Playground (`demo/playground/`)
315
-
316
- Test TorusGuard against real, runnable vulnerable applications without exposing production code:
317
- ```bash
318
- # Explore FastAPI playground:
319
- python demo/playground/vulnerable_fastapi/main.py
320
-
321
- # Run TorusGuard audit against the playground:
322
- npx torusguard audit --target demo/playground/vulnerable_fastapi
323
- ```
324
- * **FastAPI Playground:** Demonstrates raw SQL string formatting, unauthenticated routes, and missing tenant scopes.
325
- * **Next.js Playground:** Demonstrates Next.js Server Action data leaks, prompt injection sinks, and exposed client secrets.
326
-
327
- ---
328
-
329
- ## 🚀 GitHub Actions CI/CD Integration
330
-
331
- Integrate TorusGuard directly into your GitHub Actions workflow to scan pull requests and export OASIS SARIF v2.1.0 to GitHub Advanced Security:
332
-
333
- ```yaml
334
- name: TorusGuard Security Scan
335
-
336
- on:
337
- push:
338
- branches: [main]
339
- pull_request:
340
- branches: [main]
341
-
342
- jobs:
343
- security-audit:
344
- runs-on: ubuntu-latest
345
- steps:
346
- - name: Checkout Code
347
- uses: actions/checkout@v4
348
-
349
- - name: Setup Node.js
350
- uses: actions/setup-node@v4
351
- with:
352
- node-version: 18
353
-
354
- - name: Setup Python
355
- uses: actions/setup-python@v5
356
- with:
357
- python-version: '3.11'
358
-
359
- - name: Initialize TorusGuard
360
- run: npx torusguard init --force
361
-
362
- - name: Execute Security Audit
363
- run: npx torusguard audit
364
-
365
- - name: Generate SARIF Telemetry
366
- run: npx torusguard report
367
-
368
- - name: Upload SARIF to GitHub Code Scanning
369
- uses: github/codeql-action/upload-sarif@v3
370
- with:
371
- sarif_file: .torusguard/runs/latest/report.sarif
372
- if: always()
373
- ```
374
-
375
- ---
376
-
377
- ## 🧪 Comprehensive Verification Battery (11/11 Passed)
378
-
379
- TorusGuard enforces strict testing standards. Every release must achieve a **100% pass rate** across our entire test suite:
380
-
381
- ```bash
382
- python harness/validate_v0_9_2_dual_track.py
383
- python harness/validate_v0_9_2_diff_and_monorepo.py
384
- python harness/validate_v0_9_2_workflows_and_skills.py
385
- python .torusguard/scripts/manifest_builder.py --check
386
- python harness/validate_v0_9_1_installer.py
387
- python harness/validate_v0_9_0_skills.py
388
- python harness/runner.py
389
- python harness/validate_v0_7_0_runtime.py
390
- python harness/validate_v0_8_0_part1.py
391
- python harness/validate_v0_8_0_part2.py
392
- python harness/validate_v0_8_0_part3.py
393
- ```
394
-
395
- * **Cryptographic Manifest:** All workspace templates are verified against SHA-256 signatures in `.torusguard/.manifest.json`.
396
- * **Token Budget Guarantee:** All skills and workflows strictly respect a **1,000–1,500 token budget** to avoid AI context bloat.
397
-
398
- ---
399
-
400
- ## 📄 License & Community
401
-
402
- TorusGuard is open-source software licensed under the [MIT License](LICENSE).
403
-
404
- * **Author:** Jenish Lad ([@githubmofo](https://github.com/githubmofo))
405
- * **Repository:** [https://github.com/githubmofo/TorusGuard](https://github.com/githubmofo/TorusGuard)
406
- * **NPM Package:** [https://www.npmjs.com/package/torusguard](https://www.npmjs.com/package/torusguard)
407
- * **Bug Reports & Issues:** [https://github.com/githubmofo/TorusGuard/issues](https://github.com/githubmofo/TorusGuard/issues)
408
- * **Security Policy:** [SECURITY.md](SECURITY.md)
409
- * **Contributing Guide:** [CONTRIBUTING.md](CONTRIBUTING.md)
410
- * **Maintainer Hygiene:** [MAINTAINERS.md](MAINTAINERS.md)
1
+ <div align="center">
2
+ <img src="https://raw.githubusercontent.com/githubmofo/TorusGuard/main/TorusGuard.png" alt="TorusGuard Security Banner" width="480" style="max-width: 100%; height: auto; border-radius: 8px;">
3
+
4
+ # TorusGuard
5
+
6
+ **Autonomous Security Guardrails, Governed Remediation, and Authorized Runtime Validation for AI-Built Web Applications.**
7
+
8
+ [![npm version](https://img.shields.io/npm/v/torusguard.svg?style=flat-square&color=cb3837&logo=npm)](https://www.npmjs.com/package/torusguard)
9
+ [![GitHub Packages](https://img.shields.io/badge/GitHub%20Packages-v1.3.0-181717.svg?style=flat-square&logo=github)](https://github.com/githubmofo/TorusGuard/pkgs/npm/torusguard)
10
+ [![Release](https://img.shields.io/badge/Release-v1.3.0-blue.svg?style=flat-square)](https://github.com/githubmofo/TorusGuard/releases/latest)
11
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](LICENSE)
12
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-blue.svg?style=flat-square&logo=python&logoColor=white)](https://python.org)
13
+ [![Node.js 18+](https://img.shields.io/badge/Node.js-18%2B-339933.svg?style=flat-square&logo=node.js&logoColor=white)](https://nodejs.org)
14
+ [![SARIF: v2.1.0](https://img.shields.io/badge/SARIF-v2.1.0%20OASIS-purple.svg?style=flat-square)](.torusguard/schemas/)
15
+ [![Integrity: SHA--256](https://img.shields.io/badge/Integrity-SHA--256%20(112%20Files)-teal.svg?style=flat-square)](.torusguard/.manifest.json)
16
+ [![OWASP: Top 10](https://img.shields.io/badge/OWASP-Top%2010%20Aligned-orange.svg?style=flat-square)](docs/architecture/SECURITY_ARCHITECTURE.md)
17
+ </div>
18
+
19
+ ---
20
+
21
+ ## 💡 Executive Summary
22
+
23
+ AI coding assistants generate application code at superhuman speeds. However, they routinely hallucinate critical security boundaries: leaking database credentials into client bundles, omitting multi-tenant filters in ORM queries, stripping CSRF protections, or granting unconstrained tool permissions to autonomous agents.
24
+
25
+ **TorusGuard** is an autonomous application security co-pilot and governed remediation engine built specifically for AI-written code. Operating natively within developer IDEs (Cursor, Claude Code, Antigravity, Windsurf, VS Code Copilot) and CI workflows, it deterministically audits, runtime-verifies, and surgically patches vulnerabilities without destructive full-file rewrites.
26
+
27
+ ### 🌐 The Core Invariant: The Browser-Code Truth
28
+ > **"If the browser receives it, users can inspect it."**
29
+ > Frontend environment variables, JavaScript network 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.
30
+
31
+ ---
32
+
33
+ ## ⚔️ Why TorusGuard? (Traditional SAST vs. AI Coding Agents)
34
+
35
+ | Capability | Traditional SAST (SonarQube, Snyk) | Raw AI Coding Agents | TorusGuard Engine |
36
+ |---|:---:|:---:|:---:|
37
+ | **Target Code Base** | Human-written legacy code | Fast, high-churn AI generations | **AI-built full-stack applications** |
38
+ | **Remediation Model** | Issue tickets & PDF reports | Destructive full-file rewrites | **Ponytail Protocol** ($\le 35$ additions, $\le 25$ deletions) |
39
+ | **Learning Feedback** | Static rules, zero memory | Forgets fixes across prompts | **Adaptive Security Memory** & Golden Recipes |
40
+ | **IDE Integration** | Heavy background language servers | Bloated prompt context | **AI IDE Rules Auto-Sync** ($\le 300$ tokens) |
41
+ | **Commit Interception** | Slow server-side webhooks | None (pushes broken code) | **Git Pre-Commit Diff Guard** ($< 200\text{ ms}$) |
42
+ | **Privacy & Telemetry** | Cloud code upload / SaaS | Third-party cloud LLMs | **100% Local, Zero-Egress Guarantee** |
43
+
44
+ ---
45
+
46
+ ## 🏛️ System Architecture & Visual Flowcharts
47
+
48
+ ### 1. End-to-End Governance Pipeline
49
+ The complete operational pipeline from developer prompt down to telemetry and IDE rule synchronization:
50
+
51
+ ```mermaid
52
+ flowchart TD
53
+ subgraph Execution ["1. Execution Layer"]
54
+ Agent["🤖 AI Agent (Cursor, Claude, Antigravity)"]
55
+ CLI["💻 Developer CLI / Local Git Hook"]
56
+ end
57
+
58
+ subgraph Profiling ["2. Profiling & Discovery"]
59
+ Profiler["🔍 Universal Stack Profiler (16+ Languages)"]
60
+ Monorepo["🏢 Monorepo Fleet Detector (pnpm, Cargo, Go)"]
61
+ end
62
+
63
+ subgraph Detection ["3. AST Audit & Scoring"]
64
+ Rules["⚙️ 71 Security Rules across 11 Families"]
65
+ TestFilter["🎯 Test-Path Noise Suppressor"]
66
+ Scorer["🧮 5-Factor Confidence Scorer (0–100)"]
67
+ end
68
+
69
+ subgraph Intelligence ["4. Memory & Runtime Verification"]
70
+ Memory["🧠 Adaptive Memory Engine (.torusguard/memory/)"]
71
+ RuntimeGate["🧪 Authorized Runtime Prober (Masked HTTP)"]
72
+ end
73
+
74
+ subgraph Governance ["5. Governed Remediation & Interception"]
75
+ Ponytail["✂️ Ponytail Remediation (&lt;= 35 Add, &lt;= 25 Del)"]
76
+ DiffGuard["🛑 Git Diff Guard (Pre-Commit Interception)"]
77
+ end
78
+
79
+ subgraph Output ["6. Telemetry & AI Sync"]
80
+ IDEs["🔄 AI IDE Rules Sync (&lt;= 300 Tokens)"]
81
+ HTML["📊 Standalone Dark-Mode HTML Report"]
82
+ SARIF["📋 OASIS SARIF v2.1.0 Export"]
83
+ end
84
+
85
+ Agent --> Profiler
86
+ CLI --> Profiler
87
+ CLI --> DiffGuard
88
+
89
+ Profiler --> Monorepo --> Rules --> TestFilter --> Scorer
90
+ Memory -.->|"Historical Boost"| Scorer
91
+ Scorer --> RuntimeGate --> Ponytail
92
+ Scorer --> Ponytail
93
+ Ponytail --> DiffGuard
94
+
95
+ Ponytail --> Memory
96
+ Memory --> IDEs
97
+ Scorer --> HTML
98
+ Scorer --> SARIF
99
+ ```
100
+
101
+ ---
102
+
103
+ ### 2. The 7-Stage Finding Lifecycle
104
+ Every finding follows a strict closed-loop state machine with an unskippable **Human Gate** and rollback backup before disk modifications:
105
+
106
+ ```mermaid
107
+ flowchart LR
108
+ Detect["1. DETECT<br/>Static AST Signal"] --> Classify["2. CLASSIFY<br/>0–100 Confidence"]
109
+ Classify --> Verify["3. VERIFY<br/>Authorized Probe"]
110
+ Verify --> Remediate["4. REMEDIATE<br/>Ponytail Patch Plan"]
111
+ Remediate --> Gate{"👤 Human Gate<br/>Approved?"}
112
+ Gate -- Yes --> Apply["5. APPLY<br/>Backup &amp; Surgical Patch"]
113
+ Gate -- No --> Reject["❌ Discarded"]
114
+ Apply --> Recheck["6. RE-CHECK<br/>Differential AST Audit"]
115
+ Recheck -- Fixed --> Archive["7. ARCHIVE<br/>Golden Recipe Distilled"]
116
+ Recheck -- Regressed --> Rollback["⏪ Instant Rollback<br/>(pre_apply/*.bak)"]
117
+ ```
118
+
119
+ ---
120
+
121
+ ### 3. Adaptive Memory & AI Rules Sync Loop
122
+ Verified patches are converted into Golden Fix Recipes and injected back into your AI editor's prompt instructions:
123
+
124
+ ```mermaid
125
+ flowchart TD
126
+ Fix["✅ Verified Fix Applied (/torusguard apply)"] --> Extract["🏆 Golden Recipe Distilled (Diff &lt;= 35/25)"]
127
+ Extract --> Ledger["📜 Event Appended (memory/events/)"]
128
+ Ledger --> Patterns["🧠 Pattern Store &amp; Profile Updated"]
129
+ Patterns --> Sync["🔄 Rules Compiler (rules_sync.py)"]
130
+ Sync --> Cursor["Cursor (.cursorrules)"]
131
+ Sync --> Claude["Claude Code (CLAUDE.md)"]
132
+ Sync --> Antigravity["Antigravity (.agent/rules/)"]
133
+ Sync --> Windsurf["Windsurf (.windsurfrules)"]
134
+ Cursor & Claude & Antigravity & Windsurf --> AgentPrompt["🤖 AI Editor Enforces Guardrails (&lt;= 300 Tokens)"]
135
+ ```
136
+
137
+ ---
138
+
139
+ ### 4. Git Pre-Commit Interception (Diff Guard)
140
+ Blocks security bypasses, exposed credentials, and tenant boundary removals in $< 200\text{ ms}$ before code enters git history:
141
+
142
+ ```mermaid
143
+ flowchart TD
144
+ Commit["💻 Developer or AI Agent runs: git commit"] --> Hook["⚡ Git Pre-Commit Hook (.git/hooks/pre-commit)"]
145
+ Hook --> Scanner["🔍 Content-Aware Diff Guard (diff_guard.py &lt; 200 ms)"]
146
+ Scanner --> Check1{"TG-DIFF-001<br/>Security Bypass?"}
147
+ Check1 -- Yes --> Block["🚨 COMMIT BLOCKED<br/>Detailed violation + remediation emitted"]
148
+ Check1 -- No --> Check2{"TG-DIFF-002<br/>Hardcoded Credential?"}
149
+ Check2 -- Yes --> Block
150
+ Check2 -- No --> Check3{"TG-DIFF-003<br/>Tenant Boundary Stripped?"}
151
+ Check3 -- Yes --> Block
152
+ Check3 -- No --> Pass["✅ COMMIT ALLOWED<br/>Clean diff merged into git history"]
153
+ ```
154
+
155
+ ---
156
+
157
+ ## ⚡ Core Subsystems (At a Glance)
158
+
159
+ ```text
160
+ ┌────────────────────────────────────────────────────────────────────────────────────────┐
161
+ │ TORUSGUARD SUBSYSTEMS │
162
+ ├──────────────────────────┬──────────────────────────┬──────────────────────────────────┤
163
+ │ 🔍 Detection & Profiling │ 🧠 Adaptive Intelligence │ 🛡️ Governance & Developer Flow │
164
+ ├──────────────────────────┼──────────────────────────┼──────────────────────────────────┤
165
+ │ • 16+ Languages Profiled │ • 0–100 Confidence Model │ • Ponytail Protocol (<= 35/25) │
166
+ │ • Monorepo Fleet Map │ • Persistent Event Store │ • Pre-Apply Byte Snapshots (.bak)│
167
+ │ • 71 AST Security Rules │ • Golden Recipe Learning │ • Pre-Commit Diff Hook (<200 ms) │
168
+ │ • Test-Path Suppression │ • 90-Day Auto TTL Decay │ • AI Rules Auto-Sync (<= 300 tok)│
169
+ └──────────────────────────┴──────────────────────────┴──────────────────────────────────┘
170
+ ```
171
+
172
+ - **Universal Profiler & Monorepo Detector:** Discovers manifests across 16+ languages (Go, Rust, Java, C#, PHP, Python, TS) and isolates nested packages (pnpm, Cargo, Gradle, Go work).
173
+ - **Context-Aware Static Auditing:** Evaluates 71 rules across 11 families (`TG-AUTH`, `TG-DB`, `TG-INPUT`, `TG-SEC`, `TG-AGENT`, etc.). Suppresses test mocks automatically via `is_test_path()`.
174
+ - **Adaptive Memory Engine:** Distills verified Before/After fixes into Golden Recipes. Proximity scoring injects targeted advice into a compact card ($\le 2,000$ tokens).
175
+ - **Ponytail Governed Remediation:** Restricts code fixes to $\le 35$ additions and $\le 25$ deletions. Automatically saves byte-for-byte `.bak` backups for instant rollbacks.
176
+ - **Pre-Commit Diff Guard:** 1-command installer (`diff-guard --install-hook`) blocks bypasses (`InsecureSkipVerify`, `[AllowAnonymous]`, `csrf().disable()`, `unsafe`) before git commit.
177
+ - **AI IDE Rules Auto-Sync:** Compiles project security invariants into Cursor, Claude Code, Antigravity, and Windsurf within a strict $\le 300$ token overhead ceiling.
178
+ - **Visual HTML Posture Dashboard:** Generates a 100% self-contained, offline-ready dark-mode report with animated SVG score gauges and interactive diff viewers.
179
+
180
+ ---
181
+
182
+ ## 🌐 Polyglot Ecosystem & Framework Matrix
183
+
184
+ | Language / Stack | Manifests & Ecosystem | Supported Frameworks | Data Layers / ORMs | Intercepted Bypasses (`TG-DIFF`) |
185
+ |---|---|---|---|---|
186
+ | **Python** | `pyproject.toml`, `requirements.txt` | FastAPI, Django, Flask, DRF | SQLAlchemy, Django ORM, Tortoise | Raw SQL formatting, unescaped templates |
187
+ | **TypeScript / JS** | `package.json` | Next.js, Express, NestJS, Nuxt | Prisma, Drizzle, TypeORM, Mongoose | Client-side secrets, tenant deletion |
188
+ | **Go** | `go.mod` | Gin, Fiber, Echo, Chi | GORM, Ent, SQLx | `InsecureSkipVerify: true`, GORM tenant drop |
189
+ | **Rust** | `Cargo.toml` | Actix-web, Axum, Rocket | Diesel, SeaORM, SQLx | Unvetted `unsafe {`, unverified TLS |
190
+ | **Java** | `pom.xml`, `build.gradle` | Spring Boot, Quarkus, Micronaut | Hibernate, JPA, MyBatis, jOOQ | `csrf().disable()`, `permitAll()` |
191
+ | **C# (.NET)** | `*.csproj`, `*.sln` | ASP.NET Core, Blazor | Entity Framework Core, Dapper | `[AllowAnonymous]`, LINQ tenant deletion |
192
+ | **PHP** | `composer.json` | Laravel, Symfony, Slim | Eloquent, Doctrine | `CURLOPT_SSL_VERIFYPEER => false` |
193
+ | **Ruby** | `Gemfile` | Ruby on Rails, Sinatra | ActiveRecord, Sequel | Raw unescaped SQL fragments |
194
+ | **Kotlin** | `build.gradle.kts` | Spring Boot, Ktor | Exposed, Hibernate | Unauthenticated route decorators |
195
+ | **Elixir** | `mix.exs` | Phoenix | Ecto | Unfiltered changeset mutations |
196
+ | **Dart** | `pubspec.yaml` | Flutter, Shelf | Drift | Permissive HTTP certificate overrides |
197
+ | **C / C++** | `CMakeLists.txt`, `Makefile` | Crow, Drogon, Oat++ | Raw SQLite, libpq | Unbounded buffers, raw pointer leaks |
198
+
199
+ ---
200
+
201
+ ## 🚀 60-Second Quickstart
202
+
203
+ ### Method A: Via Node.js / NPX (Zero Setup)
204
+ ```bash
205
+ # 1. Initialize TorusGuard in your workspace
206
+ npx torusguard init
207
+
208
+ # 2. Run static security audit
209
+ npx torusguard audit
210
+
211
+ # 3. Generate visual dark-mode HTML dashboard
212
+ npx torusguard report --html
213
+
214
+ # 4. Install Git Pre-Commit Diff Guard Hook (blocks dangerous commits)
215
+ npx torusguard diff-guard --install-hook
216
+
217
+ # 5. Synchronize prompt guardrails across AI editors (<= 300 tokens)
218
+ npx torusguard rules sync
219
+ ```
220
+
221
+ ### Method B: Via Pure Python 3.10+ (Standard Library)
222
+ ```bash
223
+ # 1. Initialize workspace
224
+ python .torusguard/scripts/bootstrap.py --workspace .
225
+
226
+ # 2. Run static audit
227
+ python .torusguard/scripts/finding_scorer.py --dir .
228
+
229
+ # 3. Install Pre-Commit Diff Guard
230
+ python .torusguard/scripts/diff_guard.py --install-hook
231
+
232
+ # 4. Sync AI IDE rules
233
+ python .torusguard/scripts/rules_sync.py --workspace . --format all
234
+ ```
235
+
236
+ ---
237
+
238
+ ## 💻 CLI Command Reference
239
+
240
+ | Command | Subcommands & Flags | Description |
241
+ |---|---|---|
242
+ | `torusguard init` | `[--stack <name>] [--profile <type>]` | Scaffolds `.torusguard/` with active security rules and workflows. |
243
+ | `torusguard audit` | `[--scope <path>] [--format md\|json]` | Audits source code against active rules and emits run folder. |
244
+ | `torusguard verify` | `[--id <finding_id>]` | Probes authorized endpoints with automated credential masking. |
245
+ | `torusguard harden` | `[--id <finding_id>]` | Generates 4-artifact Ponytail patch plans ($\le 35$ additions, $\le 25$ deletions). |
246
+ | `torusguard apply` | `[--id <finding_id>] [--dry-run]` | Saves pre-apply `.bak` snapshots and applies surgical patch to disk. |
247
+ | `torusguard recheck`| `[--id <finding_id>]` | Differentially re-evaluates AST sinks over modified scopes. |
248
+ | `torusguard report` | `[--sarif] [--html] [--out <path>]` | Exports OASIS SARIF v2.1.0 or single-file visual HTML posture report. |
249
+ | `torusguard status` | `[--json]` | Displays stack detection, active rule count, memory metrics, and run history. |
250
+ | `torusguard diff-guard`| `[--install-hook] [--diff <file>]` | Scans git diff for bypasses (`TG-DIFF-001..004`) or installs pre-commit hook. |
251
+ | `torusguard rules sync`| `[--format all\|cursor\|claude\|agent\|windsurf]` | Compiles project rules into AI IDE configs within $\le 300$ prompt tokens. |
252
+ | `torusguard memory` | `status \| context \| export \| learn` | Inspects adaptive memory, generates proximity cards, or exports team packs. |
253
+
254
+ ---
255
+
256
+ ## 🤖 AI IDE & Agent Setup
257
+
258
+ TorusGuard injects non-destructive comment fences so your personal instructions remain untouched:
259
+
260
+ ```markdown
261
+ <!-- TORUSGUARD-SECURITY-GUARDRAILS:START -->
262
+ ## TorusGuard Security Invariants
263
+ - Browser-Code Truth: Never expose database credentials or private keys in client code.
264
+ - Multi-Tenant Isolation: Always include tenantId/orgId filters on queries.
265
+ - CSRF Protection: Enforce CSRF validation on all state-changing routes.
266
+ <!-- TORUSGUARD-SECURITY-GUARDRAILS:END -->
267
+ ```
268
+
269
+ - **Cursor (`.cursorrules`):** Run `npx torusguard rules sync --format cursor`.
270
+ - **Claude Code (`CLAUDE.md`):** Run `npx torusguard rules sync --format claude`.
271
+ - **Antigravity (`.agent/rules/torusguard.md`):** Run `npx torusguard rules sync --format agent`.
272
+ - **Windsurf (`.windsurfrules`):** Run `npx torusguard rules sync --format windsurf`.
273
+ - **VS Code Copilot & Cline:** Add `SKILL.md` to your skill directory for zero-footprint cognitive guidance.
274
+
275
+ ---
276
+
277
+ ## 🛡️ The Ponytail Protocol & Rollback Guarantees
278
+
279
+ AI coding models often destroy working applications by attempting full-file rewrites to fix minor issues. TorusGuard enforces the **Ponytail Protocol**:
280
+
281
+ - **Strict Churn Limits:** Every fix is capped at $\le 35$ additions and $\le 25$ deletions.
282
+ - **Full-File Rewrite Ban:** Large destructive edits are rejected by the patch engine.
283
+ - **Rollback Snapshot Guarantee:** Before any file is modified, a byte-for-byte snapshot is saved to `pre_apply/<file>.bak`.
284
+ - **Instant Rollback:** Restoring an original file takes 1 command (`cp pre_apply/<file>.bak <file>`).
285
+
286
+ ---
287
+
288
+ ## 🔒 Zero-Telemetry Local Privacy Guarantee
289
+
290
+ TorusGuard operates under an uncompromising **Local Execution Guarantee**:
291
+ - **Zero Network Egress:** No source code, AST trees, credentials, or audit findings leave your machine.
292
+ - **Pure Local Execution:** 100% Python standard library and local Node.js. No background daemons or cloud SaaS accounts.
293
+ - **Automatic Secret Redaction:** Live API keys, JWTs, AWS credentials, and passwords are automatically masked before writing reports.
294
+ - **Sanitized Team Export:** `npx torusguard memory export --sanitized` strips developer usernames and local paths before sharing.
295
+
296
+ For security policies and responsible disclosure, please refer to [SECURITY.md](SECURITY.md).
297
+
298
+ ---
299
+
300
+ ## 📄 License & Community
301
+
302
+ TorusGuard is open-source software licensed under the [MIT License](LICENSE).
303
+
304
+ - **Documentation:** Architecture guides and specifications in [docs/](docs/).
305
+ - **Changelog:** Release milestones and updates in [CHANGELOG.md](CHANGELOG.md).
306
+ - **Security Policy:** Vulnerability reporting in [SECURITY.md](SECURITY.md).
307
+ - **Contributions:** Pull requests and discussions are welcomed via [CONTRIBUTING.md](CONTRIBUTING.md).