eslint-plugin-ai-guard 1.4.8 → 1.4.10

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.
package/README.md CHANGED
@@ -1,821 +1,834 @@
1
- <p align="center">
2
- <a href="https://getaiguard.dev">
3
- <img src="./assets/logo/ai-guard-logo.png" alt="AI Guard Logo" width="260" />
4
- </a>
5
- </p>
6
-
7
- <h1 align="center">AI Guard</h1>
8
-
9
- <p align="center">
10
- <strong>Deterministic AST safety layer and CI guardrails for AI-assisted JavaScript and TypeScript code.</strong>
11
- </p>
12
-
13
- <p align="center">
14
- <a href="https://getaiguard.dev"><strong>Website</strong></a> &nbsp;•&nbsp;
15
- <a href="https://www.npmjs.com/package/eslint-plugin-ai-guard"><strong>npm Package</strong></a> &nbsp;•&nbsp;
16
- <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard"><strong>GitHub Repository</strong></a> &nbsp;•&nbsp;
17
- <a href="./docs/rules/"><strong>Rules Catalog</strong></a> &nbsp;•&nbsp;
18
- <a href="./docs/benchmarks.md"><strong>Benchmarks</strong></a> &nbsp;•&nbsp;
19
- <a href="./docs/integrations/claude-code.md"><strong>Claude Code</strong></a> &nbsp;•&nbsp;
20
- <a href="./docs/getting-started.md"><strong>Documentation</strong></a>
21
- </p>
22
-
23
- <p align="center">
24
- <a href="https://www.npmjs.com/package/eslint-plugin-ai-guard"><img src="https://img.shields.io/npm/v/eslint-plugin-ai-guard.svg?style=flat-square&color=0284c7" alt="npm version"></a>
25
- <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/ai-guard-dev/eslint-plugin-ai-guard/ci.yml?style=flat-square&label=CI&color=10b981" alt="CI Status"></a>
26
- <a href="https://www.npmjs.com/package/eslint-plugin-ai-guard"><img src="https://img.shields.io/npm/dm/eslint-plugin-ai-guard.svg?style=flat-square&color=3b82f6" alt="npm downloads"></a>
27
- <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-64748b?style=flat-square" alt="MIT License"></a>
28
- <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard/blob/main/SECURITY.md"><img src="https://img.shields.io/badge/security-policy-orange?style=flat-square" alt="Security Policy"></a>
29
- <a href="https://getaiguard.dev"><img src="https://img.shields.io/badge/website-getaiguard.dev-0ea5e9?style=flat-square" alt="Website"></a>
30
- </p>
31
-
32
- ---
33
-
34
- ## What is AI Guard?
35
-
36
- **AI Guard** (`eslint-plugin-ai-guard`) provides:
37
- - **ESLint plugin** with 33 deterministic rules and 4 presets (`recommended`, `strict`, `security`, `agent`)
38
- - **CLI** (`ai-guard`) for terminal, changed-file, and CI scanning
39
- - **GitHub Action** with native SARIF 2.1.0 output for GitHub Code Scanning
40
- - **Check integrity** (`ai-guard integrity`) — detects changes that weaken checks: new suppressions, skipped or removed tests, lowered ESLint/TypeScript/coverage settings, removed CI steps
41
- - **Agent safety**: `ai-guard verify` (one verdict for a change), `ai-guard scan-agent-config` (hidden text and prompt injection in `CLAUDE.md`, skills and MCP config), and `changed --test-integrity` (weakened tests)
42
- - **Hooks for Claude Code, Cursor and Codex** (`ai-guard init-hooks`): findings go back to the agent as it works, and it is stopped once before finishing on weakened checks or problems it introduced
43
- - **A pre-commit gate** (`ai-guard init-git-hook`) that checks every commit, whichever agent or person wrote it
44
- - **Works with Oxlint** as a JS plugin, with identical results checked in CI (`ai-guard init-oxlint`)
45
- - **Package checks** (`ai-guard verify-deps`, an opt-in pre-install hook, and the `ai_guard_check_package` MCP tool): names that do not exist on npm, typosquats and npm security placeholders are blocked; install scripts, deprecations and releases from the last day are flagged
46
- - **MCP server** (`ai-guard-mcp`, 9 tools) for local AI-agent workflows over STDIO
47
-
48
- ### Results on real projects
49
-
50
- Measured on 12 November 2026 with 1.4.6. Methods, raw numbers and the commands to reproduce them: [docs/evidence.md](./docs/evidence.md).
51
-
52
- - **0 of 1,361** real dependencies blocked (763 from 15 large open-source projects, 598 from 9 apps)
53
- - **34 of 36** names from the 2017 crossenv malware campaign blocked
54
- - **3.0%** of the 5,000 most-downloaded packages had a latest release under a day old, the window the fresh-release check covers
55
- - **27 of 27** rules give identical results in ESLint and Oxlint, checked in CI
56
-
57
- It is engineered to detect reliability bugs, async hazards, security vulnerabilities, and code-scaffolding defects frequently introduced during AI-assisted development (GitHub Copilot, Cursor, Claude Code, Gemini Code Assist, etc.).
58
-
59
- AI Guard analyzes Abstract Syntax Trees (AST) using ESLint's native engine. It runs locally in your editor, in your terminal via the zero-config CLI, and in your CI/CD pipelines via native SARIF 2.1.0 integration with GitHub Code Scanning.
60
-
61
- ### What AI Guard is NOT
62
-
63
- > [!IMPORTANT]
64
- > - **AI Guard is NOT an AI detector.** It does not attempt to predict whether code was authored by an LLM or a human.
65
- > - **AI Guard detects dangerous or fragile code patterns** that LLMs repeatedly introduce due to incomplete context, hallucinated patterns, or probabilistic generation.
66
- > - **AI Guard does NOT replace ESLint.** It extends ESLint with 33 specialized, high-impact rules that core ESLint and standard configurations omit.
67
-
68
- ---
69
-
70
- ## Why AI Guard?
71
-
72
- AI coding assistants write code at remarkable velocity, but generated code repeatedly suffers from predictable reliability and security anti-patterns that conventional linters miss:
73
-
74
- | Pattern | Why AI Assistants Generate It | Real-World Impact |
75
- | :--- | :--- | :--- |
76
- | **Floating Promises** | Omits `await`, `return`, or `.catch()` on async calls | Unhandled promise rejections, silent failures in background jobs |
77
- | **Async Array Iteration** | Passes async callbacks into `array.map()` or `.filter()` | Returns unawaited `Promise[]` instead of resolved values |
78
- | **Sequential Awaits in Loops** | Loops over items with sequential `await` | Significant latency bottlenecks; blocks event loop execution |
79
- | **Empty Catch Blocks** | Inserts generic `try { ... } catch (e) {}` blocks | Swallows production exceptions silently without telemetry |
80
- | **Hardcoded Secrets** | Injects placeholder or real API keys/tokens | Credential leakage in version control and deployment bundles |
81
- | **Dynamic `eval()`** | Generates dynamic function compilation | Arbitrary code execution and code injection |
82
- | **Raw SQL Concatenation** | Concatenates query strings with variables | Severe SQL injection vulnerabilities |
83
- | **Unsafe Deserialization** | Calls `JSON.parse(req.body)` directly without schema checks | Denial of service and unhandled runtime crashes |
84
- | **Missing Route Auth & Authz** | Emits boilerplate endpoints without auth middleware | Unprotected API endpoints and IDOR privilege escalations |
85
- | **Dead Branches & Scaffolding** | Leaves `if (true)` or conflicting conditions from prompt iterations | Bloated bundles and dead code paths |
86
-
87
- AI Guard provides an instantaneous, deterministic feedback loop that catches these issues before they reach pull requests or production.
88
-
89
- ---
90
-
91
- ## Architecture & Workflow
92
-
93
- ```mermaid
94
- flowchart TD
95
- subgraph Dev["1. Development & Prompt Phase"]
96
- A["Developer + AI Coding Assistant\n(Copilot, Cursor, Claude Code)"] --> B["JavaScript / TypeScript Code"]
97
- end
98
-
99
- subgraph ShiftLeft["Shift Left — Context Injection"]
100
- SL["npx ai-guard init-context"] -.-> CTX["CLAUDE.md\n.cursorrules\ncopilot-instructions.md"]
101
- CTX -.-> A
102
- end
103
-
104
- subgraph Analysis["2. Deterministic AST Analysis"]
105
- B --> C["ESLint Parser\n(espree / @typescript-eslint/parser)"]
106
- C --> D["AST Representation"]
107
- D --> E["AI Guard Rules Engine\n(33 Deterministic Rules)"]
108
- end
109
-
110
- subgraph Tiers["3. Classification & Presets"]
111
- E --> F{"Active Preset\n(recommended | strict | security | agent)"}
112
- F --> G["Confidence Tiering & AST Filtering"]
113
- end
114
-
115
- subgraph Outputs["4. Output & Remediation"]
116
- G --> H["Local CLI Scanning\n(ai-guard run / changed)"]
117
- G --> I["Autofix Remediation\n(eslint --fix)"]
118
- G --> J["HTML Dashboard\n(ai-guard report)"]
119
- G --> K["SARIF 2.1.0 Artifact\n(ai-guard --sarif)"]
120
- end
121
-
122
- subgraph CI["5. GitHub Pull Request & CI/CD"]
123
- K --> L["GitHub Action\nai-guard-dev/eslint-plugin-ai-guard@v1"]
124
- L --> M["GitHub Code Scanning Alerts"]
125
- L --> N["Inline PR Code Annotations"]
126
- L --> O["PR Status Check (Blocks Merge)"]
127
- end
128
- ```
129
-
130
- ---
131
-
132
- ## Rules Catalog
133
-
134
- AI Guard includes **33 deterministic rules** divided into four specialized categories. Every rule is engineered with low false-positive heuristics and validated against real-world production codebases:
135
-
136
- ### 🔴 Security (13 Rules)
137
-
138
- | Rule | Recommended | What It Catches | Fixable? |
139
- | :--- | :---: | :--- | :---: |
140
- | [`no-hardcoded-secret`](./docs/rules/no-hardcoded-secret.md) | **`error`** | API keys, bearer tokens, passwords, and private keys committed directly in source code. | **Yes** (`process.env.*`) |
141
- | [`no-eval-dynamic`](./docs/rules/no-eval-dynamic.md) | **`error`** | `eval()`, `new Function()`, and `setTimeout`/`setInterval` with dynamic/non-literal string expressions. | No |
142
- | [`no-sql-string-concat`](./docs/rules/no-sql-string-concat.md) | `warn` | SQL queries constructed by string concatenation or raw template literals — SQL injection risks. | No |
143
- | [`no-unsafe-deserialize`](./docs/rules/no-unsafe-deserialize.md) | `warn` | Unchecked `JSON.parse()` called directly on HTTP request inputs (`req.body`, `req.query`, `req.params`). | No |
144
- | [`require-auth-middleware`](./docs/rules/require-auth-middleware.md) | `warn` | Express and Fastify route definitions exposed without authentication middleware. | No |
145
- | [`require-authz-check`](./docs/rules/require-authz-check.md) | `warn` | Endpoints accessing sensitive resources or user IDs without tenant/ownership authorization checks. | No |
146
- | [`no-client-exposed-secret`](./docs/rules/no-client-exposed-secret.md) | **`error`** | Server secrets that reach the browser: `NEXT_PUBLIC_`/`VITE_`/`EXPO_PUBLIC_` prefixes on secret keys, server secrets in `"use client"` files, `dangerouslyAllowBrowser` with the app's own key. | No |
147
- | [`no-invisible-unicode`](./docs/rules/no-invisible-unicode.md) | **`error`** | Trojan Source bidi overrides, zero-width and Hangul-filler characters, and Unicode tag characters that hide instructions for AI tools (decoded in the message). | **Yes** (escapes in strings, removal in comments) |
148
- | [`no-unsanitized-html`](./docs/rules/no-unsanitized-html.md) | `warn` | Dynamic values in `innerHTML`, `insertAdjacentHTML`, `document.write` and `dangerouslySetInnerHTML`, with sharper messages for URL input, LLM output, markdown and JSON-LD. | No |
149
- | [`no-undeclared-import`](./docs/rules/no-undeclared-import.md) | `warn` | Imports of packages missing from package.json: hallucinated names (slopsquatting) and phantom dependencies. Offline and monorepo-aware. | No |
150
- | [`no-insecure-random`](./docs/rules/no-insecure-random.md) | `warn` | `Math.random()` used for tokens, passwords, one-time codes, reset links and other values that must be unguessable. | No |
151
- | [`no-jwt-decode-as-verify`](./docs/rules/no-jwt-decode-as-verify.md) | `warn` | `jsonwebtoken` `decode()` in a file that never calls `verify()`: the signature is never checked, so tokens can be forged. | No |
152
- | [`no-permissive-cors`](./docs/rules/no-permissive-cors.md) | `warn` | CORS that accepts every origin (`origin: true`, an allow-all callback, a reflected `Origin` header) while allowing credentials. | No |
153
-
154
- ### 🟠 Reliability (6 Rules)
155
-
156
- | Rule | Recommended | What It Catches | Fixable? |
157
- | :--- | :---: | :--- | :---: |
158
- | [`no-empty-catch`](./docs/rules/no-empty-catch.md) | **`error`** | Empty `catch (e) {}` blocks that silently swallow exceptions without logging or rethrowing. | No (editor suggestion: rethrow) |
159
- | [`no-broad-exception`](./docs/rules/no-broad-exception.md) | `warn` | Catching broad exception types like `catch (e: any)` that mask system faults and typing. | No |
160
- | [`no-catch-log-rethrow`](./docs/rules/no-catch-log-rethrow.md) | `off`* | Catch blocks that only log to `console` and rethrow without adding context or diagnostic info. | No |
161
- | [`no-catch-without-use`](./docs/rules/no-catch-without-use.md) | `off`* | Caught error variables that are declared in catch parameters but never referenced. | No |
162
- | [`no-silent-fallback`](./docs/rules/no-silent-fallback.md) | `warn` | Secret env vars with hardcoded fallbacks (`process.env.JWT_SECRET \|\| 'secret'`) and `catch { return [] }` around awaited I/O. | No |
163
- | [`no-unvalidated-cast`](./docs/rules/no-unvalidated-cast.md) | `off`* | `res.json()`, `JSON.parse()` or `req.body` cast to a type (`as User`) without runtime validation. TypeScript only. | No |
164
-
165
- ### 🟡 Async Stability (5 Rules)
166
-
167
- | Rule | Recommended | What It Catches | Fixable? |
168
- | :--- | :---: | :--- | :---: |
169
- | [`no-floating-promise`](./docs/rules/no-floating-promise.md) | **`error`** | Async function invocations without `await`, `.catch()`, or `return` — leading to silent dropped errors. | No (editor suggestions: `await`, or `void` if intended) |
170
- | [`no-async-array-callback`](./docs/rules/no-async-array-callback.md) | `warn` | Async callbacks passed to `map()`, `filter()`, `forEach()`, or `reduce()` returning `Promise[]`. | No |
171
- | [`no-await-in-loop`](./docs/rules/no-await-in-loop.md) | `warn` | Sequential `await` in loops where iterations can be safely executed concurrently with `Promise.all`. | **Yes** (rewrites to `Promise.all`) |
172
- | [`no-async-without-await`](./docs/rules/no-async-without-await.md) | `warn` | Functions declared `async` that never execute an `await` expression, adding unnecessary Promise overhead. | No |
173
- | [`no-redundant-await`](./docs/rules/no-redundant-await.md) | `off`* | Redundant `return await` statements outside of `try...catch` blocks. | No |
174
-
175
- ### 🔵 AI Patterns (9 Rules)
176
-
177
- | Rule | Recommended | What It Catches | Fixable? |
178
- | :--- | :---: | :--- | :---: |
179
- | [`no-dead-branch`](./docs/rules/no-dead-branch.md) | `warn` | Unreachable or tautological branches (`if (true)`, `if (false)`, `x && !x`) left behind from LLM code synthesis. | No |
180
- | [`no-duplicate-logic-block`](./docs/rules/no-duplicate-logic-block.md) | `off`* | Consecutive duplicate code blocks or repeated conditional branches duplicated during AI edits. | No |
181
- | [`no-console-in-handler`](./docs/rules/no-console-in-handler.md) | `off`* | Unstructured `console.log` statements left in HTTP route handlers instead of production loggers. | No |
182
- | [`no-placeholder-implementation`](./docs/rules/no-placeholder-implementation.md) | `warn` | Code an agent left unfinished: `// ... rest of the code` elisions that delete code, TODO-only stubs, `throw new Error('Not implemented')` bodies, and mock data served from production code. | No |
183
- | [`no-unknown-export`](./docs/rules/no-unknown-export.md) | `warn` | Names, subpaths and default imports the installed package does not export: `import { useQueryState } from 'react-router'`. Reports only when the package's full export list is proven (checked against Node's loader and the TypeScript compiler on 400+ packages). Suggests the closest real export. | No |
184
- | [`no-stale-api`](./docs/rules/no-stale-api.md) | `warn` | APIs the installed package version has removed, which models keep writing from older training data: `ReactDOM.render` on React 19, `useHistory` on React Router 6, the openai v3 client, Express 5 removals. Reads the installed version offline. | No |
185
- | [`no-tautological-assertion`](./docs/rules/no-tautological-assertion.md) | `warn` | Assertions that always pass: `expect(true).toBe(true)`, `expect(x).toEqual(x)`, `assert.ok(1)`. | No |
186
- | [`no-assertionless-test`](./docs/rules/no-assertionless-test.md) | `warn` | Test cases with no assertion, which pass whatever the code does. | No |
187
- | [`no-test-env-branch`](./docs/rules/no-test-env-branch.md) | `warn` | Production code that returns a canned result under a test runner (`if (NODE_ENV === 'test') return true`). | No |
188
-
189
- *\* Enabled at `error` level in the `strict` preset.*
190
-
191
- ---
192
-
193
- ## Agent Safety
194
-
195
- Linting checks the code. These check the agent:
196
-
197
- | Feature | What it does |
198
- | :--- | :--- |
199
- | [`ai-guard verify`](./docs/cli/verify.md) | One verdict for the current change: lint findings it introduced, weakened tests, and agent-config issues. Pre-existing problems never block. |
200
- | [`ai-guard integrity`](./docs/integrity.md) | Everything that weakens checks vs a base revision: new suppressions, skipped or removed tests, lowered coverage and TypeScript settings, removed CI steps. |
201
- | [`ai-guard changed --test-integrity`](./docs/cli/test-integrity.md) | A test-focused comparison: focused, skipped, removed or weakened tests, rewritten snapshots, and test commands that can no longer fail. Overlaps with `integrity`; use `integrity` for the full set. |
202
- | [`ai-guard verify-deps`](./docs/cli/verify-deps.md) | Checks npm packages before they are installed: names that don't exist (invented by assistants), look-alikes of popular packages, new or rarely used packages, install scripts, deprecations, and releases published in the last day (skipped when the package manager enforces a release cooldown). Also as a pre-install hook for Claude Code, Cursor and Codex (`init-hooks --check-installs`) and the `ai_guard_check_package` MCP tool. Uses the npm registry; private registries are skipped. |
203
- | [`ai-guard scan-agent-config`](./docs/cli/scan-agent-config.md) | Scans `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, skills and MCP configs for hidden text, prompt injection, unpinned MCP servers and inline secrets. |
204
- | [`ai-guard duplicates`](./docs/cli/duplicates.md) | Code the change copied from elsewhere in the repository, renamed variables and changed literals included (winnowing over parser tokens; 38–39 of 40 real copies found in every variant of the validation benchmark, no false reports on unrelated code). Also disclosed by `verify`, so agents are told before they finish. |
205
- | [Agent hooks: Claude Code, Cursor, Codex](./docs/integrations/agents.md) | `ai-guard init-hooks` sets up every agent a project uses. Findings reach the agent after edits; before it finishes, the whole change is verified once; `git commit --no-verify` and risky installs are caught before they run. |
206
- | [Pre-commit gate](./docs/integrations/git-hook.md) | `ai-guard init-git-hook` runs `verify --staged` on every commit through husky, lefthook, simple-git-hooks or pre-commit. Only problems the commit introduces block it. |
207
- | [MCP tools](./docs/mcp-server.md) | `ai_guard_scan_file`, `ai_guard_scan_diff`, `ai_guard_scan_project`, `ai_guard_rules`, `ai_guard_check_integrity`, `ai_guard_verify_change`, `ai_guard_scan_agent_config`, `ai_guard_check_package`, and `ai_guard_fix` (a diff, unless `apply` is set). |
208
-
209
- ---
210
-
211
- ## Presets
212
-
213
- AI Guard exports four official configurations ready for flat config or legacy setups:
214
-
215
- | Preset | Description | Configuration Focus |
216
- | :--- | :--- | :--- |
217
- | **`recommended`** | **Default.** Balanced adoption preset. Enables 6 high-confidence critical rules at `error`, 21 context-sensitive rules at `warn`, and disables 6 noisy rules. Zero noise on day one. | Production codebases, new teams |
218
- | **`strict`** | Enforces **all 33 rules at `error`**. Designed for zero-tolerance CI gates, high-assurance software, and mature teams. | Strict CI/CD quality gates |
219
- | **`security`** | Focuses on the **14 security-relevant rules** (secrets, eval, SQL, client-exposed secrets, invisible Unicode and HTML sinks at `error`; the rest at `warn`). | AppSec auditing & security scans |
220
- | **`agent`** | **8 high-signal rules at `error`**. Optimized for AI-agent editing workflows where lint feedback runs immediately after each file edit (e.g., PostToolUse hooks). | Claude Code, Cursor, real-time agent loops |
221
-
222
- ---
223
-
224
- ## Quick Start & Installation
225
-
226
- **Try it first, without installing anything or touching your config:**
227
-
228
- ```bash
229
- npx eslint-plugin-ai-guard run
230
- ```
231
-
232
- It scans the current project with the `recommended` preset and changes no files. No ESLint configuration is needed. In a TypeScript project without `@typescript-eslint/parser`, add `-p @typescript-eslint/parser` (`npx -p eslint-plugin-ai-guard -p @typescript-eslint/parser ai-guard run`) so `.ts` files are parsed.
233
-
234
- **One command sets up everything:**
235
-
236
- ```bash
237
- npx eslint-plugin-ai-guard protect
238
- ```
239
-
240
- It installs AI Guard as a devDependency (plus `@typescript-eslint/parser` in TypeScript projects), adds hooks for the coding agents the project uses (Claude Code, Cursor, Codex), adds a pre-commit gate, checks `CLAUDE.md`, `AGENTS.md` and MCP config, and prints one screen saying what is now protected. Running it again changes nothing. Preview with `--dry-run`; agents can read `--json`. See [protect](./docs/cli/protect.md).
241
-
242
- Or install the package yourself as a development dependency:
243
-
244
- ```bash
245
- # npm
246
- npm install --save-dev eslint-plugin-ai-guard
247
-
248
- # pnpm
249
- pnpm add -D eslint-plugin-ai-guard
250
-
251
- # yarn
252
- yarn add -D eslint-plugin-ai-guard
253
-
254
- # bun
255
- bun add -d eslint-plugin-ai-guard
256
- ```
257
-
258
- > [!NOTE]
259
- > Once AI Guard is installed in a project, its CLI is `ai-guard` (`npx ai-guard run`). Before it is installed, use the package name: `npx eslint-plugin-ai-guard run`. A bare `npx ai-guard` in a project without AI Guard fetches a different npm package that happens to be called `ai-guard`.
260
-
261
- ### Add a badge to your README
262
-
263
- ```bash
264
- npx eslint-plugin-ai-guard badge
265
- ```
266
-
267
- It scans the project, writes the result to `.github/ai-guard-badge.json` (a [shields.io endpoint](https://shields.io/badges/endpoint-badge) file) and prints the Markdown for your README. The badge shows what the scan found: `passing`, a warning count or an error count. Commit the file. To keep the badge current, run the command in CI on pushes to your default branch; see [badge](./docs/cli/badge.md). Nothing is sent anywhere: shields.io reads the file from your repository.
268
-
269
- ### Requirements
270
-
271
- - **Node.js:** `>= 20.0.0`
272
- - **ESLint:** `>= 8.0.0` (Supports both Flat Config and legacy configs)
273
- - **TypeScript (optional):** `@typescript-eslint/parser >= 6.0.0` for TypeScript AST parsing
274
-
275
- ---
276
-
277
- ## ESLint Configuration
278
-
279
- ### 1. Flat Config (ESLint 9 and 10: `eslint.config.mjs` / `eslint.config.js`)
280
-
281
- Each `flat/` preset is a complete flat config that registers the plugin itself:
282
-
283
- ```javascript
284
- // eslint.config.mjs
285
- import aiGuard from 'eslint-plugin-ai-guard';
286
-
287
- export default [aiGuard.configs['flat/recommended']];
288
- ```
289
-
290
- Use `aiGuard.configs['flat/strict']` (all 33 rules at error), `aiGuard.configs['flat/security']` (security rules only) or `aiGuard.configs['flat/agent']` (8 high-signal rules for agent hooks) the same way. To override a rule, add a config object after the preset:
291
-
292
- ```javascript
293
- export default [
294
- aiGuard.configs['flat/recommended'],
295
- {
296
- rules: {
297
- 'ai-guard/no-floating-promise': 'error',
298
- },
299
- },
300
- ];
301
- ```
302
-
303
- Spreading the rules into your own config object (`plugins: { 'ai-guard': aiGuard }, rules: { ...aiGuard.configs.recommended.rules }`) keeps working.
304
-
305
- ### 2. Legacy Config (ESLint 8, or ESLint 9 with `ESLINT_USE_FLAT_CONFIG=false`)
306
-
307
- ```javascript
308
- // .eslintrc.js
309
- module.exports = {
310
- plugins: ['ai-guard'],
311
- extends: ['plugin:ai-guard/recommended'],
312
- };
313
- ```
314
-
315
- > [!NOTE]
316
- > 2.0 will make the plain preset names (`recommended`, `strict`, `security`, `agent`) flat configs. To be ready, `.eslintrc` files can already use the aliases `plugin:ai-guard/legacy-recommended` (and `legacy-strict`, `legacy-security`, `legacy-agent`), which keep working after that upgrade. ESLint 10 no longer reads `.eslintrc` files at all.
317
-
318
- ---
319
-
320
- ## CLI Reference
321
-
322
- AI Guard includes a full-featured CLI binary (`ai-guard`) that runs out of the box with zero ESLint configuration files required:
323
-
324
- ```bash
325
- npx ai-guard <command> [options] # AI Guard installed in the project
326
- npx eslint-plugin-ai-guard <command> [options] # not installed (first run, one-off scans)
327
- ```
328
-
329
- ### Core Commands
330
-
331
- | Command | Purpose | Common Options |
332
- | :--- | :--- | :--- |
333
- | `protect` | Set up everything in one step: install, agent hooks, pre-commit gate, agent-config check ([docs](./docs/cli/protect.md)) | `--agent <list>`, `--manager <name>`, `--check-installs`, `--no-install`, `--no-agent-hooks`, `--no-git-hook`, `--dry-run`, `--json` |
334
- | `run` | Scan your workspace using AI Guard AST rules | `--path <dir>`, `--strict`, `--security`, `--json`, `--sarif`, `--fail-on <level>`, `--max-warnings <n>`, `--inline-suppressions <mode>` |
335
- | `changed` | Fast CI scan — only scans modified files in git | `--pr`, `--staged`, `--base <branch>`, `--baseline [file]`, `--integrity <off\|report\|enforce>`, `--test-integrity`, `--inline-suppressions <mode>`, `--strict`, `--sarif`, `--sarif-output <file>`, `--fail-on <level>` |
336
- | `verify` | One verdict for the current change ([docs](./docs/cli/verify.md)) | `--base <ref>`, `--staged`, `--preset <name>`, `--strict`, `--json` |
337
- | `verify-deps` | Check npm packages before they are installed ([docs](./docs/cli/verify-deps.md)) | `[packages...]`, `--base <ref>`, `--staged`, `--all`, `--json`, `--sarif`, `--fail-on <level>` |
338
- | `scan-agent-config` | Scan agent instructions and MCP config ([docs](./docs/cli/scan-agent-config.md)) | `--path <dir>`, `--json`, `--sarif`, `--fail-on <level>`, `--update-lock` |
339
- | `duplicates` | Report code a change copied from elsewhere in the repository ([docs](./docs/cli/duplicates.md)) | `--base <ref>`, `--staged`, `--all`, `--include-tests`, `--min-tokens <n>`, `--json`, `--sarif`, `--fail-on <level>` |
340
- | `integrity` | Detect changes that weaken checks vs a base revision ([docs](./docs/integrity.md)) | `--base <ref>`, `--pr`, `--staged`, `--enforce`, `--json`, `--sarif`, `--accept <fingerprints\|all>` |
341
- | `init` | Automatically detect environment & configure ESLint | `--preset <name>`, `--flat`, `--dry-run`, `-y, --yes` |
342
- | `init-hooks` | Hooks for Claude Code, Cursor and Codex ([docs](./docs/integrations/agents.md)) | `--agent <list>`, `--check-installs`, `--no-stop-hook`, `--no-bash-guard`, `--dry-run` |
343
- | `init-git-hook` | Pre-commit gate running `verify --staged` ([docs](./docs/integrations/git-hook.md)) | `--manager <name>`, `--check-deps`, `--dry-run` |
344
- | `init-oxlint` | Add AI Guard to `.oxlintrc.json` ([docs](./docs/integrations/oxlint.md)) | `--preset <name>`, `--dry-run` |
345
- | `init-context` | Generate prompt instruction files for AI coding agents | `-a, --all`, `--force`, `--dry-run`, `--rules <categories>` |
346
- | `doctor` | Diagnose your ESLint, parser, and plugin environment | (No options needed — prints actionable diagnostic report) |
347
- | `baseline` | Record existing findings, then report only new ones | `create`, `check`, `--fail-on <level>`, `--json`, `--mode <strict\|stable>`, `--preset <name>` |
348
- | `badge` | Scan and write a README badge with the result ([docs](./docs/cli/badge.md)) | `--path <dir>`, `--preset <name>`, `--output <file>`, `--json` |
349
- | `report` | Generate an interactive standalone HTML audit report | `--path <dir>`, `--preset <name>`, `--output <file>`, `--no-open`, `--json` |
350
- | `preset` | Interactively select and switch active preset in config | (Interactive prompt with automatic config patch & backup) |
351
- | `ignore` | Add standard ignore paths (`.next`, `dist`, `build`) to config | (Patches flat config or legacy ignores safely) |
352
-
353
- **`run` exit codes:** `0` no errors · `1` errors found (or `--max-warnings` exceeded) · `2` scan did not run — the file passed to `--path` matches a built-in ignore pattern (`node_modules/`, `dist/`, `build/`, `generated/`, `vendor/`, …), so nothing was analyzed. Directory scans skip ignored files silently and never exit `2`.
354
-
355
- ### CLI Usage Examples
356
-
357
- ```bash
358
- # 0. Set up hooks, the pre-commit gate and the agent-config check in one step
359
- npx eslint-plugin-ai-guard protect
360
-
361
- # 1. Immediate scan of current directory (no install needed)
362
- npx eslint-plugin-ai-guard run
363
-
364
- # 2. Strict CI scan failing only on high-confidence issues
365
- npx ai-guard run --strict --fail-on high
366
-
367
- # 3. Pull Request scan (diffs against PR target branch)
368
- npx ai-guard changed --pr --sarif --sarif-output results.sarif
369
-
370
- # 4. Generate AI agent guardrails for Cursor, Claude Code, and Copilot
371
- npx ai-guard init-context --all
372
-
373
- # 5. Generate interactive HTML diagnostic report
374
- npx ai-guard report --output ai-guard-report.html
375
-
376
- # 6. Save existing issues as baseline and only fail on new regressions
377
- npx ai-guard baseline create # writes .ai-guard-baseline.json (commit it)
378
- npx ai-guard baseline check # exit 1 if any new finding
379
- npx ai-guard baseline check --fail-on high # fail only on new high-confidence findings
380
- npx ai-guard baseline check --json # machine-readable new findings
381
-
382
- # 7. Fail a PR that skips tests, adds eslint-disable, or lowers coverage thresholds
383
- npx ai-guard changed --pr --integrity enforce
384
- ```
385
-
386
- ### Inline suppressions never hide findings silently
387
-
388
- AI Guard reads `eslint-disable` directives itself; ESLint's own inline config is disabled in AI Guard's private ESLint instance, so a comment cannot make a finding vanish without a trace. `--inline-suppressions` selects the policy:
389
-
390
- | Mode | Effect |
391
- |---|---|
392
- | `allow` (default) | A covering directive hides the finding from totals and exit codes; it is listed under "Hidden by inline directives" (JSON `suppressedIssues`, step summary, SARIF `suppressedFindingsCount`) |
393
- | `require-reason` | Only directives with a ` -- reason` hide findings (used by the Claude Code hook) |
394
- | `ignore` | Directives never hide AI Guard findings (always used by the MCP server) |
395
-
396
- This applies to `ai-guard run`, `changed`, the GitHub Action, the Claude Code hook and MCP. It does not change how your own `eslint .` treats directives. TypeScript comments (`@ts-ignore`, `@ts-nocheck`) never affect AI Guard findings; `ai-guard integrity` reports newly added ones.
397
-
398
- ---
399
-
400
- ## AI Agent Integration (`init-context`)
401
-
402
- Standard linters only run **after** code has already been written. The `init-context` command shifts your guardrails left by embedding AI Guard's rules directly into the instruction files loaded by your AI coding tools:
403
-
404
- ```bash
405
- npx ai-guard init-context --all
406
- ```
407
-
408
- This generates three targeted context files:
409
- 1. **`CLAUDE.md`** — Automatically loaded by **Claude Code**
410
- 2. **`.cursorrules`** — Automatically loaded by **Cursor**
411
- 3. **`.github/copilot-instructions.md`** — Automatically loaded by **GitHub Copilot**
412
-
413
- ### How Shift-Left Works
414
-
415
- ```
416
- AI Guard (init-context)
417
- ↓
418
- Generates project guardrail files (CLAUDE.md, .cursorrules, copilot-instructions.md)
419
- ↓
420
- AI coding assistant reads safety rules before generating code
421
- ↓
422
- Model avoids floating promises, empty catches, and hardcoded secrets at prompt time
423
- ↓
424
- AI Guard CLI & GitHub Action deterministically verifies the output in CI
425
- ```
426
-
427
- This dual-layer defense minimizes review friction and ensures generated code meets your security standard on the first pass.
428
-
429
- ---
430
-
431
- ## Claude Code Integration
432
-
433
- Using Cursor or Codex too? `npx ai-guard init-hooks` sets up every agent the project uses; see [Agent hooks](./docs/integrations/agents.md).
434
-
435
- Two ways to use it with Claude Code. Pick one:
436
-
437
- - **In a project (recommended):** `npm install --save-dev eslint-plugin-ai-guard`, then `npx ai-guard init-claude`. This writes the hooks into the project's `.claude/settings.json`, so everyone on the project gets them.
438
- - **As a Claude Code plugin** (adds the MCP tools and the `/ai-guard:verify-changes` skill, and works in projects without AI Guard installed): `claude plugin marketplace add ai-guard-dev/eslint-plugin-ai-guard`, then `claude plugin install ai-guard@ai-guard-plugins`.
439
-
440
- AI Guard integrates directly with [Claude Code](https://code.claude.com/docs/en/hooks) through hooks:
441
-
442
- ```bash
443
- # One-command setup
444
- npx ai-guard init-claude
445
- ```
446
-
447
- - **PostToolUse** — after each edit, findings from the `agent` preset and newly weakened checks in the edited file are sent back to Claude (`decision: "block"` + `reason`, per the hooks protocol). Earlier versions printed plain stdout, which Claude Code does not show to Claude.
448
- - **SessionStart + Stop** — before Claude finishes, [check integrity](./docs/integrity.md) runs on everything changed in the session. High-confidence weakenings (a new `.skip`, `eslint-disable`, lowered threshold…) block stopping once per finding set; advisories are shown to you, never block. The same hook then [verifies](./docs/cli/verify.md) lint findings and agent-config issues the session introduced (placeholder code, a canned return under a test runner, a hidden instruction in `CLAUDE.md`), which also block once. Skip both with `--no-stop-hook`.
449
- - **PreToolUse (Bash)** — `git commit --no-verify` / `HUSKY=0` ask for confirmation. With `--check-installs` (opt-in, uses the npm registry), packages in install commands are checked first: names that don't exist are blocked; look-alikes of popular packages and releases from the last day ask you.
450
-
451
- ```bash
452
- # Preview before applying
453
- npx ai-guard init-claude --dry-run
454
-
455
- # Use per-machine settings (gitignored)
456
- npx ai-guard init-claude --local
457
- ```
458
-
459
- **Agent preset rules (8):** `no-hardcoded-secret`, `no-eval-dynamic`, `no-empty-catch`, `no-sql-string-concat`, `no-floating-promise`, `no-client-exposed-secret`, `no-invisible-unicode`, `no-undeclared-import`
460
-
461
- → [Full documentation](./docs/integrations/claude-code.md)
462
-
463
- ---
464
-
465
- ## GitHub Action
466
-
467
- The official AI Guard GitHub Action runs on PRs, detects changed files, provides step summaries, outputs SARIF 2.1.0, and posts inline PR annotations directly on GitHub:
468
-
469
- ```yaml
470
- # .github/workflows/ai-guard.yml
471
- name: AI Guard
472
-
473
- on:
474
- pull_request:
475
- branches: [main, develop]
476
- push:
477
- branches: [main]
478
-
479
- jobs:
480
- ai-guard-scan:
481
- name: AI Guard Code Review
482
- runs-on: ubuntu-latest
483
-
484
- permissions:
485
- contents: read
486
- security-events: write
487
- actions: read
488
-
489
- steps:
490
- - name: Checkout Code
491
- uses: actions/checkout@v4
492
- with:
493
- fetch-depth: 0 # Required for git diff comparison
494
-
495
- - name: Setup Node.js
496
- uses: actions/setup-node@v4
497
- with:
498
- node-version: 20
499
- cache: 'npm'
500
-
501
- - name: Run AI Guard
502
- id: aiguard
503
- uses: ai-guard-dev/eslint-plugin-ai-guard@v1
504
- with:
505
- preset: 'recommended'
506
- fail-on: 'high'
507
- changed-only: 'true'
508
-
509
- # The Action writes SARIF; this step sends it to Code Scanning.
510
- # if: always() uploads it even when the scan step fails the job.
511
- - name: Upload to GitHub Code Scanning
512
- if: always()
513
- uses: github/codeql-action/upload-sarif@v3
514
- with:
515
- sarif_file: ${{ steps.aiguard.outputs.sarif-file }}
516
- category: ai-guard
517
- ```
518
-
519
- The Action annotates the pull request and writes the job summary by itself. Alerts in **Security → Code scanning** need the upload step.
520
-
521
- ### Action Inputs (`action.yml`)
522
-
523
- | Input | Description | Default |
524
- | :--- | :--- | :---: |
525
- | `preset` | Rule preset: `recommended` \| `strict` \| `security` | `'recommended'` |
526
- | `fail-on` | Severity threshold to fail CI: `high` \| `medium` \| `any` \| `none` | `'high'` |
527
- | `changed-only` | Scan only files changed in this PR / commit | `'true'` |
528
- | `path` | Target file or directory to scan | `'.'` |
529
- | `upload-sarif` | Always write the SARIF file (`sarif-file` output) for an `upload-sarif` step, even when the scan produced none. The Action does not upload to Code Scanning by itself | `'true'` |
530
- | `github-summary` | Write an execution breakdown to the GitHub Actions Job Summary | `'true'` |
531
- | `working-directory`| Working directory for scanning (ideal for monorepos) | `'.'` |
532
- | `package-manager` | Package manager: `auto` \| `npm` \| `pnpm` \| `yarn` | `'auto'` |
533
- | `sarif-output` | Output filepath for generated SARIF report | `'ai-guard-results.sarif'` |
534
- | `install-deps` | Install project dependencies prior to scanning | `'true'` |
535
- | `baseline` | Committed baseline file; with `changed-only`, report only findings not in it | `''` |
536
- | `integrity` | Check integrity: `off` \| `report` \| `enforce` (needs `changed-only` and `fetch-depth: 0`) | `'off'` |
537
- | `test-integrity` | With `changed-only`, also flag tests the PR deleted, skipped, focused or weakened (needs `fetch-depth: 0`) | `'false'` |
538
- | `inline-suppressions` | `allow` \| `require-reason` \| `ignore` for eslint-disable directives covering AI Guard findings | `''` (allow) |
539
-
540
- ### Action Outputs
541
-
542
- | Output | Description |
543
- | :--- | :--- |
544
- | `issues-found` | Total number of issues found across scanned files |
545
- | `high-confidence-count` | Number of high-confidence issues flagged |
546
- | `medium-confidence-count` | Number of medium-confidence issues flagged |
547
- | `files-scanned` | Count of files analyzed during the execution |
548
- | `integrity-high-count` | High-confidence check-integrity findings (when `integrity` is enabled) |
549
- | `integrity-advisory-count` | Advisory check-integrity findings (when `integrity` is enabled) |
550
- | `sarif-file` | Absolute path to the generated SARIF 2.1.0 artifact |
551
- | `duration-ms` | Total scan execution duration in milliseconds |
552
-
553
- ---
554
-
555
- ## SARIF & GitHub Code Scanning
556
-
557
- AI Guard natively outputs **SARIF 2.1.0** (`Static Analysis Results Interchange Format`). When uploaded via the GitHub Action or `github/codeql-action/upload-sarif@v3`, findings integrate directly with GitHub Advanced Security:
558
-
559
- - **Inline PR Annotations:** Direct comments on the exact source lines where flaws exist.
560
- - **Security Dashboard:** Persistent alerts under your repository's `Security → Code scanning` tab.
561
- - **Merge Protection:** Block merges automatically when high-confidence security or async bugs are detected.
562
-
563
- ### Visual Previews
564
-
565
- #### Inline Pull Request Annotations
566
- <img src="./assets/ss9.jpg" alt="AI Guard PR Inline Annotations" width="1000" />
567
-
568
- #### GitHub Advanced Security Summary
569
- <img src="./assets/ss10.jpg" alt="GitHub Advanced Security Summary for AI Guard" width="1000" />
570
-
571
- #### Persistent Code Scanning Dashboard
572
- <img src="./assets/ss11.jpg" alt="GitHub Code Scanning Alerts List" width="1000" />
573
-
574
- ---
575
-
576
- ## Rule Examples (Before & After)
577
-
578
- ### 1. `no-floating-promise` (Unhandled Promises)
579
-
580
- ```typescript
581
- // ❌ BAD: Floating promise. Errors are dropped silently.
582
- async function syncUserProfile(user: User) {
583
- sendTelemetryEvent('user_sync', user.id);
584
- database.save(user);
585
- }
586
-
587
- // ✅ GOOD: Awaited, explicitly handled, or marked with void
588
- async function syncUserProfile(user: User) {
589
- await database.save(user);
590
- void sendTelemetryEvent('user_sync', user.id); // Explicitly unhandled
591
- }
592
- ```
593
-
594
- ### 2. `no-hardcoded-secret` (Committed Credentials)
595
-
596
- ```typescript
597
- // ❌ BAD: Secret committed inline
598
- const client = new PaymentGateway({
599
- apiKey: 'sk-prod-983427598273498273948273',
600
- });
601
-
602
- // ✅ GOOD: Read from environment variable (Autofixable!)
603
- const client = new PaymentGateway({
604
- apiKey: process.env.API_KEY,
605
- });
606
- ```
607
-
608
- ### 3. `no-await-in-loop` (Sequential Latency Trap)
609
-
610
- ```typescript
611
- // ❌ BAD: Consecutive awaits block each iteration sequentially
612
- async function fetchAllUsers(ids: string[]) {
613
- const users = [];
614
- for (const id of ids) {
615
- users.push(await fetchUser(id));
616
- }
617
- return users;
618
- }
619
-
620
- // ✅ GOOD: Concurrently fetched with Promise.all (Autofixable!)
621
- async function fetchAllUsers(ids: string[]) {
622
- return await Promise.all(ids.map((id) => fetchUser(id)));
623
- }
624
- ```
625
-
626
- ### 4. `no-empty-catch` (Swallowed Errors)
627
-
628
- ```typescript
629
- // ❌ BAD: Exception swallowed without trace
630
- try {
631
- parseConfiguration(rawConfig);
632
- } catch (e) {}
633
-
634
- // ✅ GOOD: Logged, rethrown, or documented (Autofixable!)
635
- try {
636
- parseConfiguration(rawConfig);
637
- } catch (e) {
638
- logger.error('Configuration parsing failed', { error: e });
639
- throw e;
640
- }
641
- ```
642
-
643
- ### 5. `no-sql-string-concat` (SQL Injection)
644
-
645
- ```typescript
646
- // ❌ BAD: Dynamic string interpolation in SQL
647
- const query = `SELECT * FROM users WHERE organization_id = '${orgId}' AND role = '${role}'`;
648
- await db.query(query);
649
-
650
- // ✅ GOOD: Parameterized query binding
651
- const query = 'SELECT * FROM users WHERE organization_id = $1 AND role = $2';
652
- await db.query(query, [orgId, role]);
653
- ```
654
-
655
- ---
656
-
657
- ## Automatic Remediation (Autofix)
658
-
659
- Rules that have deterministic solutions provide automatic autofix handlers. Run ESLint's native `--fix` flag to automatically resolve them:
660
-
661
- ```bash
662
- npx eslint . --fix
663
- ```
664
-
665
- | Rule | Automatic Fix Behavior |
666
- | :--- | :--- |
667
- | `no-hardcoded-secret` | Replaces hardcoded string literal with `process.env.VARIABLE_NAME` |
668
- | `no-await-in-loop` | Rewrites straightforward sequential loops to `await Promise.all(...)` |
669
-
670
- `no-empty-catch` and `no-floating-promise` have no automatic fix on purpose. A fix that inserted a comment or `void` would make the finding disappear without handling the error, and an agent running `--fix` would do exactly that. Editors offer them as suggestions instead (rethrow; `await`, or `void` for an intended fire-and-forget call), which a person applies one at a time.
671
-
672
- ---
673
-
674
- ## Benchmarks & Empirical Evaluation
675
-
676
- AI Guard has been empirically evaluated across multiple benchmarks comparing runtime scan performance, coverage gaps vs. standard tooling, and detection accuracy across real-world codebases.
677
-
678
- ### 1. What AI Guard Catches vs. Conventional Linters
679
-
680
- Conventional linters either omit AI-specific hazards entirely or require heavyweight TypeScript type-checking (`parserOptions.project`) that significantly slows down CI:
681
-
682
- | Pattern | AI Guard Rule | ESLint Core | `@typescript-eslint` |
683
- | :--- | :--- | :---: | :--- |
684
- | **Floating Promises** (unawaited async call) | [`no-floating-promise`](./docs/rules/no-floating-promise.md) | ❌ None | `@typescript-eslint/no-floating-promises` *(requires type info)* |
685
- | **Async Array Callbacks** (`.map(async ...)`) | [`no-async-array-callback`](./docs/rules/no-async-array-callback.md) | ❌ None | Partial: `no-misused-promises` *(requires type info)* |
686
- | **Empty Catch Blocks** (swallowed errors) | [`no-empty-catch`](./docs/rules/no-empty-catch.md) | `no-empty` *(weaker)* | ❌ None |
687
- | **Hardcoded Secrets / API Tokens** | [`no-hardcoded-secret`](./docs/rules/no-hardcoded-secret.md) | ❌ None | ❌ None |
688
- | **Raw SQL String Concatenation** | [`no-sql-string-concat`](./docs/rules/no-sql-string-concat.md) | ❌ None | ❌ None |
689
- | **Missing Route Auth Middleware** | [`require-auth-middleware`](./docs/rules/require-auth-middleware.md) | ❌ None | ❌ None |
690
- | **Missing Route Authorization Checks** | [`require-authz-check`](./docs/rules/require-authz-check.md) | ❌ None | ❌ None |
691
- | **Dynamic `eval()` / `new Function()`** | [`no-eval-dynamic`](./docs/rules/no-eval-dynamic.md) | `no-eval` *(blanket ban)* | ❌ None |
692
- | **Unsafe `JSON.parse(req.body)`** | [`no-unsafe-deserialize`](./docs/rules/no-unsafe-deserialize.md) | ❌ None | ❌ None |
693
- | **Async Without Await** | [`no-async-without-await`](./docs/rules/no-async-without-await.md) | ❌ None | `require-await` |
694
- | **Sequential Await in Loop** | [`no-await-in-loop`](./docs/rules/no-await-in-loop.md) | `no-await-in-loop` *(no fix)* | ❌ None |
695
- | **Dead Code Branches (`if (true)`)** | [`no-dead-branch`](./docs/rules/no-dead-branch.md) | ❌ None | ❌ None |
696
- | **Secrets exposed to the browser** (`NEXT_PUBLIC_*_SECRET`) | [`no-client-exposed-secret`](./docs/rules/no-client-exposed-secret.md) | ❌ None | ❌ None |
697
- | **Trojan Source / hidden Unicode instructions** | [`no-invisible-unicode`](./docs/rules/no-invisible-unicode.md) | Partial: `no-irregular-whitespace` *(whitespace only)* | ❌ None |
698
- | **Hallucinated / undeclared packages** | [`no-undeclared-import`](./docs/rules/no-undeclared-import.md) | ❌ None | ❌ None |
699
- | **Unsanitized HTML sinks (XSS)** | [`no-unsanitized-html`](./docs/rules/no-unsanitized-html.md) | ❌ None | ❌ None |
700
- | **Hardcoded secret fallbacks** | [`no-silent-fallback`](./docs/rules/no-silent-fallback.md) | ❌ None | ❌ None |
701
- | **Elided / stubbed code left by agents** | [`no-placeholder-implementation`](./docs/rules/no-placeholder-implementation.md) | Partial: `no-warning-comments` *(TODO text only)* | ❌ None |
702
-
703
- > [!TIP]
704
- > **Minimal Type-Information Dependency:** 32 of 33 AI Guard rules operate in pure syntax/scope-analysis mode without `projectService` or `tsconfig.json`. The `no-floating-promise` rule optionally uses TypeScript parser services for higher recall on cross-module Promise calls, with syntax/scope-based heuristics as a zero-config fallback.
705
-
706
- ---
707
-
708
- ### 2. Runtime Performance
709
-
710
- Benchmark: scanning 196 TypeScript / JavaScript files (`algorithm-automata-simulator`, Windows 11, Node.js 20, median of 3 runs):
711
-
712
- | Tool / Mode | Scan Time | Configuration Overhead |
713
- | :--- | :---: | :--- |
714
- | **`ai-guard run --strict`** | **~1.8s** | **Zero config** (18 AST heuristic rules, no `tsconfig.json` needed) |
715
- | `eslint .` (recommended) | ~2.5s | Core syntax rules only (misses floating promises & secrets) |
716
- | `eslint .` (type-aware `@typescript-eslint`) | **~8–12s** | Requires full TS compiler graph binding (**4x–6x slower**) |
717
-
718
- AI Guard executes **4x–6x faster** than type-aware linting suites because it leverages deterministic AST heuristics rather than reconstructing the full TypeScript symbol graph.
719
-
720
- ---
721
-
722
- ### 3. Empirical Bug Detection & Precision Study
723
-
724
- Two comprehensive empirical benchmark evaluations were conducted to measure real-world precision and detection yields:
725
-
726
- #### A. Accuracy & False Positive Audit (4 Real-World Repositories, 378 Files)
727
-
728
- | Category | Findings | True Positives | False Positive Rate |
729
- | :--- | :---: | :---: | :---: |
730
- | **Security** (`no-hardcoded-secret`, `no-eval-dynamic`, etc.) | 15 | 15 | **0%** |
731
- | **Reliability** (`no-empty-catch`, broad exceptions) | 53 | 53 | **0%** |
732
- | **Async Stability** (`no-floating-promise`, async callbacks) | 43 | ~40 | **~7%** |
733
- | **AI Patterns** (duplicate logic, dead branches) | 58 | 43 | **26%** *(reduced in v1.2.8+)* |
734
-
735
- #### B. Dual-Mode Detection Study (48 Call Sites & Real Production Target)
736
-
737
- Audited across a controlled multi-file test corpus (13 files, 48 call sites) and a real-world Express + MongoDB production application (`Truvita New`):
738
-
739
- - **High Precision:** **100% precision** on type-aware exclusive findings (26 of 26 verified True Positives; 0 false alarms on synchronous controls).
740
- - **Critical Detection:** Detected **1 critical database startup race condition** in production (`server/index.ts connectDB()`) where an unawaited connection call allowed requests to hit the database before initialization.
741
- - **Single-File Actionability:** **100%** of findings were resolvable locally at the call site (`await`, `.catch()`, or `void`).
742
-
743
- For the complete methodology, raw findings, and benchmark harness, see [**`docs/benchmarks.md`**](./docs/benchmarks.md).
744
-
745
- ---
746
-
747
- ## Performance & Philosophy
748
-
749
- - **Zero LLM Overhead:** AI Guard does not call external APIs, does not incur token costs, and does not add LLM latency. A scan of 100+ files executes in milliseconds.
750
- - **100% Deterministic:** Every finding is derived strictly from Abstract Syntax Tree analysis. No probabilistic drift, no non-deterministic hallucinated findings.
751
- - **Low False Positives:** Built with precision-first design. Context-sensitive rules are configured at `warn` or `off` in the recommended preset so developers are never blocked by noise.
752
- - **Self-Scanning:** AI Guard enforces its own rules on its own codebase in CI using the `strict` preset.
753
-
754
- ---
755
-
756
- ## MCP Server (Model Context Protocol)
757
-
758
- AI Guard includes a local MCP server that exposes its deterministic analysis engine to MCP-capable AI clients (Claude Code, Claude Desktop, and other MCP-compatible integrations).
759
-
760
- ```bash
761
- npx --yes --package eslint-plugin-ai-guard ai-guard-mcp
762
- ```
763
-
764
- **Available tools:**
765
-
766
- | Tool | Description |
767
- | :--- | :--- |
768
- | `ai_guard_scan_file` | Scan a single JS/TS file with structured findings |
769
- | `ai_guard_scan_diff` | Scan changed files in git diff (including newly created untracked JS/TS files) |
770
- | `ai_guard_scan_project` | Scan a bounded workspace directory (at most 500 files; fails instead of truncating) |
771
- | `ai_guard_rules` | List rules and presets, or look up specific rules (`rules: ["no-floating-promise"]`) with remediation and docs link |
772
- | `ai_guard_check_integrity` | Report checks weakened by current Git changes (new suppressions, skipped/removed tests, lowered configs, removed CI steps), with `tier` and `hasBlockingFindings` |
773
-
774
- All tools declare an `outputSchema`; the text content is the same result as compact JSON. Scan tools accept `maxIssues` (default 50, errors first, exact `totalIssues` and `truncated`). The `verify_changes` prompt runs the scan → fix → rescan loop.
775
-
776
- **Claude Code configuration** (project-root `.mcp.json`):
777
-
778
- ```json
779
- {
780
- "mcpServers": {
781
- "ai-guard": {
782
- "type": "stdio",
783
- "command": "node",
784
- "args": ["/absolute/path/to/ai-guard/dist/mcp/server.js"],
785
- "env": { "AI_GUARD_WORKSPACE": "/absolute/path/to/project" }
786
- }
787
- }
788
- }
789
- ```
790
-
791
- The SDK in-memory and built STDIO integrations are tested, plus a headless Claude Code CLI smoke test (see the MCP guide for scope). Use the built checkout to test unreleased changes. Scan, fix, then rescan; a partial or failed scan is never clean. For setup, result status, limits, and client verification scope, see [**`docs/mcp-server.md`**](./docs/mcp-server.md).
792
-
793
- ---
794
-
795
- ## Learn More & Ecosystem
796
-
797
- Visit [getaiguard.dev](https://getaiguard.dev) to explore interactive documentation, rule catalogs, benchmarks, and deep-dive engineering articles.
798
-
799
- ### Official Links
800
-
801
- - **Website:** [https://getaiguard.dev](https://getaiguard.dev)
802
- - **GitHub Organization:** [https://github.com/ai-guard-dev](https://github.com/ai-guard-dev)
803
- - **Repository:** [https://github.com/ai-guard-dev/eslint-plugin-ai-guard](https://github.com/ai-guard-dev/eslint-plugin-ai-guard)
804
- - **npm Registry:** [https://www.npmjs.com/package/eslint-plugin-ai-guard](https://www.npmjs.com/package/eslint-plugin-ai-guard)
805
- - **GitHub Action:** [ai-guard-dev/eslint-plugin-ai-guard@v1](https://github.com/ai-guard-dev/eslint-plugin-ai-guard)
806
-
807
- ---
808
-
809
- ## Contributing
810
-
811
- We welcome contributions, new rule ideas, bug reports, and false-positive reports!
812
-
813
- 1. Check out our [Contributing Guide](CONTRIBUTING.md) for local setup and testing standards.
814
- 2. Review our [Security Policy](SECURITY.md) to report vulnerabilities responsibly.
815
- 3. Check open issues or submit new ones on our [Issue Tracker](https://github.com/ai-guard-dev/eslint-plugin-ai-guard/issues).
816
-
817
- ---
818
-
819
- ## License
820
-
821
- [MIT](LICENSE) © AI Guard Authors. Free and open source forever.
1
+ <p align="center">
2
+ <a href="https://getaiguard.dev">
3
+ <img src="./assets/logo/ai-guard-logo.png" alt="AI Guard Logo" width="260" />
4
+ </a>
5
+ </p>
6
+
7
+ <h1 align="center">AI Guard</h1>
8
+
9
+ <p align="center">
10
+ <strong>Deterministic AST safety layer and CI guardrails for AI-assisted JavaScript and TypeScript code.</strong>
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://getaiguard.dev"><strong>Website</strong></a> &nbsp;•&nbsp;
15
+ <a href="https://www.npmjs.com/package/eslint-plugin-ai-guard"><strong>npm Package</strong></a> &nbsp;•&nbsp;
16
+ <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard"><strong>GitHub Repository</strong></a> &nbsp;•&nbsp;
17
+ <a href="./docs/rules/"><strong>Rules Catalog</strong></a> &nbsp;•&nbsp;
18
+ <a href="./docs/benchmarks.md"><strong>Benchmarks</strong></a> &nbsp;•&nbsp;
19
+ <a href="./docs/integrations/claude-code.md"><strong>Claude Code</strong></a> &nbsp;•&nbsp;
20
+ <a href="./docs/getting-started.md"><strong>Documentation</strong></a>
21
+ </p>
22
+
23
+ <p align="center">
24
+ <a href="https://www.npmjs.com/package/eslint-plugin-ai-guard"><img src="https://img.shields.io/npm/v/eslint-plugin-ai-guard.svg?style=flat-square&color=0284c7" alt="npm version"></a>
25
+ <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/ai-guard-dev/eslint-plugin-ai-guard/ci.yml?style=flat-square&label=CI&color=10b981" alt="CI Status"></a>
26
+ <a href="https://www.npmjs.com/package/eslint-plugin-ai-guard"><img src="https://img.shields.io/npm/dm/eslint-plugin-ai-guard.svg?style=flat-square&color=3b82f6" alt="npm downloads"></a>
27
+ <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-64748b?style=flat-square" alt="MIT License"></a>
28
+ <a href="https://github.com/ai-guard-dev/eslint-plugin-ai-guard/blob/main/SECURITY.md"><img src="https://img.shields.io/badge/security-policy-orange?style=flat-square" alt="Security Policy"></a>
29
+ <a href="https://getaiguard.dev"><img src="https://img.shields.io/badge/website-getaiguard.dev-0ea5e9?style=flat-square" alt="Website"></a>
30
+ </p>
31
+
32
+ ---
33
+
34
+ ## What is AI Guard?
35
+
36
+ **AI Guard** (`eslint-plugin-ai-guard`) provides:
37
+ - **ESLint plugin** with 33 deterministic rules and 4 presets (`recommended`, `strict`, `security`, `agent`)
38
+ - **CLI** (`ai-guard`) for terminal, changed-file, and CI scanning
39
+ - **GitHub Action** with native SARIF 2.1.0 output for GitHub Code Scanning
40
+ - **Check integrity** (`ai-guard integrity`) — detects changes that weaken checks, in JavaScript, TypeScript and Python projects: new suppressions (`eslint-disable`, `@ts-ignore`, `# noqa`, `# type: ignore`), skipped or removed tests (Jest, Vitest, pytest, unittest), `conftest.py` hooks that turn failures into passes, lowered ESLint/TypeScript/mypy/Pyright/Ruff/coverage settings, removed CI steps and Git-hook bypasses
41
+ - **Agent safety**: `ai-guard verify` (one verdict for a change), `ai-guard scan-agent-config` (hidden text and prompt injection in `CLAUDE.md`, skills and MCP config), and `changed --test-integrity` (weakened tests)
42
+ - **Hooks for Claude Code, Cursor and Codex** (`ai-guard init-hooks`): findings go back to the agent as it works, and it is stopped once before finishing on weakened checks or problems it introduced
43
+ - **A pre-commit gate** (`ai-guard init-git-hook`) that checks every commit, whichever agent or person wrote it
44
+ - **Works with Oxlint** as a JS plugin, with identical results checked in CI (`ai-guard init-oxlint`)
45
+ - **Package checks** (`ai-guard verify-deps`, an opt-in pre-install hook, and the `ai_guard_check_package` MCP tool): names that do not exist on npm or PyPI (including Python import names such as `cv2`), typosquats and npm security placeholders are blocked; install scripts, deprecations, yanked Python releases and releases from the last day are flagged
46
+ - **MCP server** (`ai-guard-mcp`, 9 tools) for local AI-agent workflows over STDIO
47
+
48
+ ### Results on real projects
49
+
50
+ Measured on 12 November 2026 with 1.4.6. Methods, raw numbers and the commands to reproduce them: [docs/evidence.md](./docs/evidence.md).
51
+
52
+ - **0 of 1,361** real dependencies blocked (763 from 15 large open-source projects, 598 from 9 apps)
53
+ - **34 of 36** names from the 2017 crossenv malware campaign blocked
54
+ - **3.0%** of the 5,000 most-downloaded packages had a latest release under a day old, the window the fresh-release check covers
55
+ - **33 of 33** rules give identical results in ESLint and Oxlint, checked in CI
56
+
57
+ It is engineered to detect reliability bugs, async hazards, security vulnerabilities, and code-scaffolding defects frequently introduced during AI-assisted development (GitHub Copilot, Cursor, Claude Code, Gemini Code Assist, etc.).
58
+
59
+ AI Guard analyzes Abstract Syntax Trees (AST) using ESLint's native engine. It runs locally in your editor, in your terminal via the zero-config CLI, and in your CI/CD pipelines via native SARIF 2.1.0 integration with GitHub Code Scanning.
60
+
61
+ ### What AI Guard is NOT
62
+
63
+ > [!IMPORTANT]
64
+ > - **AI Guard is NOT an AI detector.** It does not attempt to predict whether code was authored by an LLM or a human.
65
+ > - **AI Guard detects dangerous or fragile code patterns** that LLMs repeatedly introduce due to incomplete context, hallucinated patterns, or probabilistic generation.
66
+ > - **AI Guard does NOT replace ESLint.** It extends ESLint with 33 specialized, high-impact rules that core ESLint and standard configurations omit.
67
+
68
+ ---
69
+
70
+ ## Why AI Guard?
71
+
72
+ AI coding assistants write code at remarkable velocity, but generated code repeatedly suffers from predictable reliability and security anti-patterns that conventional linters miss:
73
+
74
+ | Pattern | Why AI Assistants Generate It | Real-World Impact |
75
+ | :--- | :--- | :--- |
76
+ | **Floating Promises** | Omits `await`, `return`, or `.catch()` on async calls | Unhandled promise rejections, silent failures in background jobs |
77
+ | **Async Array Iteration** | Passes async callbacks into `array.map()` or `.filter()` | Returns unawaited `Promise[]` instead of resolved values |
78
+ | **Sequential Awaits in Loops** | Loops over items with sequential `await` | Significant latency bottlenecks; blocks event loop execution |
79
+ | **Empty Catch Blocks** | Inserts generic `try { ... } catch (e) {}` blocks | Swallows production exceptions silently without telemetry |
80
+ | **Hardcoded Secrets** | Injects placeholder or real API keys/tokens | Credential leakage in version control and deployment bundles |
81
+ | **Dynamic `eval()`** | Generates dynamic function compilation | Arbitrary code execution and code injection |
82
+ | **Raw SQL Concatenation** | Concatenates query strings with variables | Severe SQL injection vulnerabilities |
83
+ | **Unsafe Deserialization** | Calls `JSON.parse(req.body)` directly without schema checks | Denial of service and unhandled runtime crashes |
84
+ | **Missing Route Auth & Authz** | Emits boilerplate endpoints without auth middleware | Unprotected API endpoints and IDOR privilege escalations |
85
+ | **Dead Branches & Scaffolding** | Leaves `if (true)` or conflicting conditions from prompt iterations | Bloated bundles and dead code paths |
86
+
87
+ AI Guard provides an instantaneous, deterministic feedback loop that catches these issues before they reach pull requests or production.
88
+
89
+ ---
90
+
91
+ ## Architecture & Workflow
92
+
93
+ ```mermaid
94
+ flowchart TD
95
+ subgraph Dev["1. Development & Prompt Phase"]
96
+ A["Developer + AI Coding Assistant\n(Copilot, Cursor, Claude Code)"] --> B["JavaScript / TypeScript Code"]
97
+ end
98
+
99
+ subgraph ShiftLeft["Shift Left — Context Injection"]
100
+ SL["npx ai-guard init-context"] -.-> CTX["CLAUDE.md\n.cursorrules\ncopilot-instructions.md"]
101
+ CTX -.-> A
102
+ end
103
+
104
+ subgraph Analysis["2. Deterministic AST Analysis"]
105
+ B --> C["ESLint Parser\n(espree / @typescript-eslint/parser)"]
106
+ C --> D["AST Representation"]
107
+ D --> E["AI Guard Rules Engine\n(33 Deterministic Rules)"]
108
+ end
109
+
110
+ subgraph Tiers["3. Classification & Presets"]
111
+ E --> F{"Active Preset\n(recommended | strict | security | agent)"}
112
+ F --> G["Confidence Tiering & AST Filtering"]
113
+ end
114
+
115
+ subgraph Outputs["4. Output & Remediation"]
116
+ G --> H["Local CLI Scanning\n(ai-guard run / changed)"]
117
+ G --> I["Autofix Remediation\n(eslint --fix)"]
118
+ G --> J["HTML Dashboard\n(ai-guard report)"]
119
+ G --> K["SARIF 2.1.0 Artifact\n(ai-guard --sarif)"]
120
+ end
121
+
122
+ subgraph CI["5. GitHub Pull Request & CI/CD"]
123
+ K --> L["GitHub Action\nai-guard-dev/eslint-plugin-ai-guard@v1"]
124
+ L --> M["GitHub Code Scanning Alerts"]
125
+ L --> N["Inline PR Code Annotations"]
126
+ L --> O["PR Status Check (Blocks Merge)"]
127
+ end
128
+ ```
129
+
130
+ ---
131
+
132
+ ## Rules Catalog
133
+
134
+ AI Guard includes **33 deterministic rules** divided into four specialized categories. Every rule is engineered with low false-positive heuristics and validated against real-world production codebases:
135
+
136
+ ### 🔴 Security (13 Rules)
137
+
138
+ | Rule | Recommended | What It Catches | Fixable? |
139
+ | :--- | :---: | :--- | :---: |
140
+ | [`no-hardcoded-secret`](./docs/rules/no-hardcoded-secret.md) | **`error`** | API keys, bearer tokens, passwords, and private keys committed directly in source code. | **Yes** (`process.env.*`) |
141
+ | [`no-eval-dynamic`](./docs/rules/no-eval-dynamic.md) | **`error`** | `eval()`, `new Function()`, and `setTimeout`/`setInterval` with dynamic/non-literal string expressions. | No |
142
+ | [`no-sql-string-concat`](./docs/rules/no-sql-string-concat.md) | `warn` | SQL queries constructed by string concatenation or raw template literals — SQL injection risks. | No |
143
+ | [`no-unsafe-deserialize`](./docs/rules/no-unsafe-deserialize.md) | `warn` | Unchecked `JSON.parse()` called directly on HTTP request inputs (`req.body`, `req.query`, `req.params`). | No |
144
+ | [`require-auth-middleware`](./docs/rules/require-auth-middleware.md) | `warn` | Express and Fastify route definitions exposed without authentication middleware. | No |
145
+ | [`require-authz-check`](./docs/rules/require-authz-check.md) | `warn` | Endpoints accessing sensitive resources or user IDs without tenant/ownership authorization checks. | No |
146
+ | [`no-client-exposed-secret`](./docs/rules/no-client-exposed-secret.md) | **`error`** | Server secrets that reach the browser: `NEXT_PUBLIC_`/`VITE_`/`EXPO_PUBLIC_` prefixes on secret keys, server secrets in `"use client"` files, `dangerouslyAllowBrowser` with the app's own key. | No |
147
+ | [`no-invisible-unicode`](./docs/rules/no-invisible-unicode.md) | **`error`** | Trojan Source bidi overrides, zero-width and Hangul-filler characters, and Unicode tag characters that hide instructions for AI tools (decoded in the message). | **Yes** (escapes in strings, removal in comments) |
148
+ | [`no-unsanitized-html`](./docs/rules/no-unsanitized-html.md) | `warn` | Dynamic values in `innerHTML`, `insertAdjacentHTML`, `document.write` and `dangerouslySetInnerHTML`, with sharper messages for URL input, LLM output, markdown and JSON-LD. | No |
149
+ | [`no-undeclared-import`](./docs/rules/no-undeclared-import.md) | `warn` | Imports of packages missing from package.json: hallucinated names (slopsquatting) and phantom dependencies. Offline and monorepo-aware. | No |
150
+ | [`no-insecure-random`](./docs/rules/no-insecure-random.md) | `warn` | `Math.random()` used for tokens, passwords, one-time codes, reset links and other values that must be unguessable. | No |
151
+ | [`no-jwt-decode-as-verify`](./docs/rules/no-jwt-decode-as-verify.md) | `warn` | `jsonwebtoken` `decode()` in a file that never calls `verify()`: the signature is never checked, so tokens can be forged. | No |
152
+ | [`no-permissive-cors`](./docs/rules/no-permissive-cors.md) | `warn` | CORS that accepts every origin (`origin: true`, an allow-all callback, a reflected `Origin` header) while allowing credentials. | No |
153
+
154
+ ### 🟠 Reliability (6 Rules)
155
+
156
+ | Rule | Recommended | What It Catches | Fixable? |
157
+ | :--- | :---: | :--- | :---: |
158
+ | [`no-empty-catch`](./docs/rules/no-empty-catch.md) | **`error`** | Empty `catch (e) {}` blocks that silently swallow exceptions without logging or rethrowing. | No (editor suggestion: rethrow) |
159
+ | [`no-broad-exception`](./docs/rules/no-broad-exception.md) | `warn` | Catching broad exception types like `catch (e: any)` that mask system faults and typing. | No |
160
+ | [`no-catch-log-rethrow`](./docs/rules/no-catch-log-rethrow.md) | `off`* | Catch blocks that only log to `console` and rethrow without adding context or diagnostic info. | No |
161
+ | [`no-catch-without-use`](./docs/rules/no-catch-without-use.md) | `off`* | Caught error variables that are declared in catch parameters but never referenced. | No |
162
+ | [`no-silent-fallback`](./docs/rules/no-silent-fallback.md) | `warn` | Secret env vars with hardcoded fallbacks (`process.env.JWT_SECRET \|\| 'secret'`) and `catch { return [] }` around awaited I/O. | No |
163
+ | [`no-unvalidated-cast`](./docs/rules/no-unvalidated-cast.md) | `off`* | `res.json()`, `JSON.parse()` or `req.body` cast to a type (`as User`) without runtime validation. TypeScript only. | No |
164
+
165
+ ### 🟡 Async Stability (5 Rules)
166
+
167
+ | Rule | Recommended | What It Catches | Fixable? |
168
+ | :--- | :---: | :--- | :---: |
169
+ | [`no-floating-promise`](./docs/rules/no-floating-promise.md) | **`error`** | Async function invocations without `await`, `.catch()`, or `return` — leading to silent dropped errors. | No (editor suggestions: `await`, or `void` if intended) |
170
+ | [`no-async-array-callback`](./docs/rules/no-async-array-callback.md) | `warn` | Async callbacks passed to `map()`, `filter()`, `forEach()`, or `reduce()` returning `Promise[]`. | No |
171
+ | [`no-await-in-loop`](./docs/rules/no-await-in-loop.md) | `warn` | Sequential `await` in loops where iterations can be safely executed concurrently with `Promise.all`. | Suggestion (`Promise.all`) |
172
+ | [`no-async-without-await`](./docs/rules/no-async-without-await.md) | `warn` | Functions declared `async` that never execute an `await` expression, adding unnecessary Promise overhead. | No |
173
+ | [`no-redundant-await`](./docs/rules/no-redundant-await.md) | `off`* | Redundant `return await` statements outside of `try...catch` blocks. | No |
174
+
175
+ ### 🔵 AI Patterns (9 Rules)
176
+
177
+ | Rule | Recommended | What It Catches | Fixable? |
178
+ | :--- | :---: | :--- | :---: |
179
+ | [`no-dead-branch`](./docs/rules/no-dead-branch.md) | `warn` | Unreachable or tautological branches (`if (true)`, `if (false)`, `x && !x`) left behind from LLM code synthesis. | No |
180
+ | [`no-duplicate-logic-block`](./docs/rules/no-duplicate-logic-block.md) | `off`* | Consecutive duplicate code blocks or repeated conditional branches duplicated during AI edits. | No |
181
+ | [`no-console-in-handler`](./docs/rules/no-console-in-handler.md) | `off`* | Unstructured `console.log` statements left in HTTP route handlers instead of production loggers. | No |
182
+ | [`no-placeholder-implementation`](./docs/rules/no-placeholder-implementation.md) | `warn` | Code an agent left unfinished: `// ... rest of the code` elisions that delete code, TODO-only stubs, `throw new Error('Not implemented')` bodies, and mock data served from production code. | No |
183
+ | [`no-unknown-export`](./docs/rules/no-unknown-export.md) | `warn` | Names, subpaths and default imports the installed package does not export: `import { useQueryState } from 'react-router'`. Reports only when the package's full export list is proven (checked against Node's loader and the TypeScript compiler on 400+ packages). Suggests the closest real export. | No |
184
+ | [`no-stale-api`](./docs/rules/no-stale-api.md) | `warn` | APIs the installed package version has removed, which models keep writing from older training data: `ReactDOM.render` on React 19, `useHistory` on React Router 6, the openai v3 client, Express 5 removals. Reads the installed version offline. | No |
185
+ | [`no-tautological-assertion`](./docs/rules/no-tautological-assertion.md) | `warn` | Assertions that always pass: `expect(true).toBe(true)`, `expect(x).toEqual(x)`, `assert.ok(1)`. | No |
186
+ | [`no-assertionless-test`](./docs/rules/no-assertionless-test.md) | `warn` | Test cases with no assertion, which pass whatever the code does. | No |
187
+ | [`no-test-env-branch`](./docs/rules/no-test-env-branch.md) | `warn` | Production code that returns a canned result under a test runner (`if (NODE_ENV === 'test') return true`). | No |
188
+
189
+ *\* Enabled at `error` level in the `strict` preset.*
190
+
191
+ ---
192
+
193
+ ## Agent Safety
194
+
195
+ Linting checks the code. These check the agent:
196
+
197
+ | Feature | What it does |
198
+ | :--- | :--- |
199
+ | [`ai-guard verify`](./docs/cli/verify.md) | One verdict for the current change: lint findings it introduced, weakened tests, and agent-config issues. Pre-existing problems never block. |
200
+ | [`ai-guard integrity`](./docs/integrity.md) | Everything that weakens checks vs a base revision: new suppressions, skipped or removed tests, lowered coverage and TypeScript settings, removed CI steps. |
201
+ | [`ai-guard changed --test-integrity`](./docs/cli/test-integrity.md) | A test-focused comparison: focused, skipped, removed or weakened tests, rewritten snapshots, and test commands that can no longer fail. Overlaps with `integrity`; use `integrity` for the full set. |
202
+ | [`ai-guard verify-deps`](./docs/cli/verify-deps.md) | Checks npm and PyPI packages (package.json, requirements files, pyproject.toml, Pipfile) before they are installed: names that don't exist (invented by assistants), look-alikes of popular packages, new or rarely used packages, install scripts, deprecations, and releases published in the last day (skipped when the package manager enforces a release cooldown). Also as a pre-install hook for Claude Code, Cursor and Codex (`init-hooks --check-installs`) and the `ai_guard_check_package` MCP tool. Uses the npm registry and PyPI; private registries and other Python indexes are skipped. |
203
+ | [`ai-guard scan-agent-config`](./docs/cli/scan-agent-config.md) | Scans `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, skills and MCP configs for hidden text, prompt injection, unpinned MCP servers and inline secrets. |
204
+ | [`ai-guard duplicates`](./docs/cli/duplicates.md) | Code the change copied from elsewhere in the repository, renamed variables and changed literals included (winnowing over parser tokens; 38–39 of 40 real copies found in every variant of the validation benchmark, no false reports on unrelated code). Also disclosed by `verify`, so agents are told before they finish. |
205
+ | [Agent hooks: Claude Code, Cursor, Codex](./docs/integrations/agents.md) | `ai-guard init-hooks` sets up every agent a project uses. Findings reach the agent after edits; before it finishes, the whole change is verified once; `git commit --no-verify` and risky installs are caught before they run. |
206
+ | [Pre-commit gate](./docs/integrations/git-hook.md) | `ai-guard init-git-hook` runs `verify --staged` on every commit through husky, lefthook, simple-git-hooks or pre-commit. Only problems the commit introduces block it. |
207
+ | [MCP tools](./docs/mcp-server.md) | `ai_guard_scan_file`, `ai_guard_scan_diff`, `ai_guard_scan_project`, `ai_guard_rules`, `ai_guard_check_integrity`, `ai_guard_verify_change`, `ai_guard_scan_agent_config`, `ai_guard_check_package`, and `ai_guard_fix` (a diff, unless `apply` is set). |
208
+ | [Kits and shared configs](./docs/integrations/kits.md) | Ship AI Guard rules in your own lint kit or preset: version ranges, what stays stable in 1.x, ESLint and Oxlint setup, and which rules to pick. |
209
+
210
+ ---
211
+
212
+ ## Presets
213
+
214
+ AI Guard exports four official configurations ready for flat config or legacy setups:
215
+
216
+ | Preset | Description | Configuration Focus |
217
+ | :--- | :--- | :--- |
218
+ | **`recommended`** | **Default.** Balanced adoption preset. Enables 6 high-confidence critical rules at `error`, 21 context-sensitive rules at `warn`, and disables 6 noisy rules. Zero noise on day one. | Production codebases, new teams |
219
+ | **`strict`** | Enforces **all 33 rules at `error`**. Designed for zero-tolerance CI gates, high-assurance software, and mature teams. | Strict CI/CD quality gates |
220
+ | **`security`** | Focuses on the **14 security-relevant rules** (secrets, eval, SQL, client-exposed secrets, invisible Unicode and HTML sinks at `error`; the rest at `warn`). | AppSec auditing & security scans |
221
+ | **`agent`** | **8 high-signal rules at `error`**. Optimized for AI-agent editing workflows where lint feedback runs immediately after each file edit (e.g., PostToolUse hooks). | Claude Code, Cursor, real-time agent loops |
222
+
223
+ ---
224
+
225
+ ## Quick Start & Installation
226
+
227
+ **Try it first, without installing anything or touching your config:**
228
+
229
+ ```bash
230
+ npx eslint-plugin-ai-guard run
231
+ ```
232
+
233
+ It scans the current project with the `recommended` preset and changes no files. No ESLint configuration is needed. In a TypeScript project without `@typescript-eslint/parser`, add `-p @typescript-eslint/parser` (`npx -p eslint-plugin-ai-guard -p @typescript-eslint/parser ai-guard run`) so `.ts` files are parsed.
234
+
235
+ **One command sets up everything:**
236
+
237
+ ```bash
238
+ npx eslint-plugin-ai-guard protect
239
+ ```
240
+
241
+ It installs AI Guard as a devDependency (plus `@typescript-eslint/parser` in TypeScript projects), adds hooks for the coding agents the project uses (Claude Code, Cursor, Codex), adds a pre-commit gate, checks `CLAUDE.md`, `AGENTS.md` and MCP config, and prints one screen saying what is now protected. Running it again changes nothing. Preview with `--dry-run`; agents can read `--json`. See [protect](./docs/cli/protect.md).
242
+
243
+ Or install the package yourself as a development dependency:
244
+
245
+ ```bash
246
+ # npm
247
+ npm install --save-dev eslint-plugin-ai-guard
248
+
249
+ # pnpm
250
+ pnpm add -D eslint-plugin-ai-guard
251
+
252
+ # yarn
253
+ yarn add -D eslint-plugin-ai-guard
254
+
255
+ # bun
256
+ bun add -d eslint-plugin-ai-guard
257
+ ```
258
+
259
+ > [!NOTE]
260
+ > Once AI Guard is installed in a project, its CLI is `ai-guard` (`npx ai-guard run`). Before it is installed, use the package name: `npx eslint-plugin-ai-guard run`. A bare `npx ai-guard` in a project without AI Guard fetches a different npm package that happens to be called `ai-guard`.
261
+
262
+ ### Add a badge to your README
263
+
264
+ ```bash
265
+ npx eslint-plugin-ai-guard badge
266
+ ```
267
+
268
+ It scans the project, writes the result to `.github/ai-guard-badge.json` (a [shields.io endpoint](https://shields.io/badges/endpoint-badge) file) and prints the Markdown for your README. The badge shows what the scan found: `passing`, a warning count or an error count. Commit the file. To keep the badge current, run the command in CI on pushes to your default branch; see [badge](./docs/cli/badge.md). Nothing is sent anywhere: shields.io reads the file from your repository.
269
+
270
+ ### Requirements
271
+
272
+ - **Node.js:** `>= 20.0.0`
273
+ - **ESLint:** `>= 8.0.0` (Supports both Flat Config and legacy configs)
274
+ - **TypeScript (optional):** `@typescript-eslint/parser >= 6.0.0` for TypeScript AST parsing
275
+
276
+ ---
277
+
278
+ ## ESLint Configuration
279
+
280
+ ### 1. Flat Config (ESLint 9 and 10: `eslint.config.mjs` / `eslint.config.js`)
281
+
282
+ Each `flat/` preset is a complete flat config that registers the plugin itself:
283
+
284
+ ```javascript
285
+ // eslint.config.mjs
286
+ import aiGuard from 'eslint-plugin-ai-guard';
287
+
288
+ export default [aiGuard.configs['flat/recommended']];
289
+ ```
290
+
291
+ Use `aiGuard.configs['flat/strict']` (all 33 rules at error), `aiGuard.configs['flat/security']` (security rules only) or `aiGuard.configs['flat/agent']` (8 high-signal rules for agent hooks) the same way. To override a rule, add a config object after the preset:
292
+
293
+ ```javascript
294
+ export default [
295
+ aiGuard.configs['flat/recommended'],
296
+ {
297
+ rules: {
298
+ 'ai-guard/no-floating-promise': 'error',
299
+ },
300
+ },
301
+ ];
302
+ ```
303
+
304
+ Spreading the rules into your own config object (`plugins: { 'ai-guard': aiGuard }, rules: { ...aiGuard.configs.recommended.rules }`) keeps working.
305
+
306
+ ### 2. Legacy Config (ESLint 8, or ESLint 9 with `ESLINT_USE_FLAT_CONFIG=false`)
307
+
308
+ ```javascript
309
+ // .eslintrc.js
310
+ module.exports = {
311
+ plugins: ['ai-guard'],
312
+ extends: ['plugin:ai-guard/recommended'],
313
+ };
314
+ ```
315
+
316
+ > [!NOTE]
317
+ > 2.0 will make the plain preset names (`recommended`, `strict`, `security`, `agent`) flat configs. To be ready, `.eslintrc` files can already use the aliases `plugin:ai-guard/legacy-recommended` (and `legacy-strict`, `legacy-security`, `legacy-agent`), which keep working after that upgrade. ESLint 10 no longer reads `.eslintrc` files at all.
318
+
319
+ ---
320
+
321
+ ## CLI Reference
322
+
323
+ AI Guard includes a full-featured CLI binary (`ai-guard`) that runs out of the box with zero ESLint configuration files required:
324
+
325
+ ```bash
326
+ npx ai-guard <command> [options] # AI Guard installed in the project
327
+ npx eslint-plugin-ai-guard <command> [options] # not installed (first run, one-off scans)
328
+ ```
329
+
330
+ ### Core Commands
331
+
332
+ | Command | Purpose | Common Options |
333
+ | :--- | :--- | :--- |
334
+ | `protect` | Set up everything in one step: install, agent hooks, pre-commit gate, agent-config check ([docs](./docs/cli/protect.md)) | `--agent <list>`, `--manager <name>`, `--check-installs`, `--no-install`, `--no-agent-hooks`, `--no-git-hook`, `--dry-run`, `--json` |
335
+ | `run` | Scan your workspace using AI Guard AST rules | `--path <dir>`, `--strict`, `--security`, `--json`, `--sarif`, `--fail-on <level>`, `--max-warnings <n>`, `--inline-suppressions <mode>` |
336
+ | `changed` | Fast CI scan — only scans modified files in git | `--pr`, `--staged`, `--base <branch>`, `--baseline [file]`, `--integrity <off\|report\|enforce>`, `--test-integrity`, `--inline-suppressions <mode>`, `--strict`, `--sarif`, `--sarif-output <file>`, `--fail-on <level>` |
337
+ | `verify` | One verdict for the current change ([docs](./docs/cli/verify.md)) | `--base <ref>`, `--staged`, `--preset <name>`, `--strict`, `--json` |
338
+ | `verify-deps` | Check npm and PyPI packages before they are installed ([docs](./docs/cli/verify-deps.md)) | `[packages...]`, `--base <ref>`, `--staged`, `--all`, `--pypi`, `--json`, `--sarif`, `--fail-on <level>` |
339
+ | `scan-agent-config` | Scan agent instructions and MCP config ([docs](./docs/cli/scan-agent-config.md)) | `--path <dir>`, `--json`, `--sarif`, `--fail-on <level>`, `--update-lock` |
340
+ | `duplicates` | Report code a change copied from elsewhere in the repository ([docs](./docs/cli/duplicates.md)) | `--base <ref>`, `--staged`, `--all`, `--include-tests`, `--min-tokens <n>`, `--json`, `--sarif`, `--fail-on <level>` |
341
+ | `integrity` | Detect changes that weaken checks vs a base revision ([docs](./docs/integrity.md)) | `--base <ref>`, `--pr`, `--staged`, `--enforce`, `--json`, `--sarif`, `--accept <fingerprints\|all>` |
342
+ | `init` | Automatically detect environment & configure ESLint | `--preset <name>`, `--flat`, `--dry-run`, `-y, --yes` |
343
+ | `init-hooks` | Hooks for Claude Code, Cursor and Codex ([docs](./docs/integrations/agents.md)) | `--agent <list>`, `--check-installs`, `--no-stop-hook`, `--no-bash-guard`, `--dry-run` |
344
+ | `init-git-hook` | Pre-commit gate running `verify --staged` ([docs](./docs/integrations/git-hook.md)) | `--manager <name>`, `--check-deps`, `--dry-run` |
345
+ | `init-oxlint` | Add AI Guard to `.oxlintrc.json` ([docs](./docs/integrations/oxlint.md)) | `--preset <name>`, `--dry-run` |
346
+ | `init-context` | Generate prompt instruction files for AI coding agents | `-a, --all`, `--force`, `--dry-run`, `--rules <categories>` |
347
+ | `doctor` | Diagnose your ESLint, parser, and plugin environment | (No options needed — prints actionable diagnostic report) |
348
+ | `baseline` | Record existing findings, then report only new ones | `create`, `check`, `--fail-on <level>`, `--json`, `--mode <strict\|stable>`, `--preset <name>` |
349
+ | `badge` | Scan and write a README badge with the result ([docs](./docs/cli/badge.md)) | `--path <dir>`, `--preset <name>`, `--output <file>`, `--json` |
350
+ | `report` | Generate an interactive standalone HTML audit report | `--path <dir>`, `--preset <name>`, `--output <file>`, `--no-open`, `--json` |
351
+ | `preset` | Interactively select and switch active preset in config | (Interactive prompt with automatic config patch & backup) |
352
+ | `ignore` | Add standard ignore paths (`.next`, `dist`, `build`) to config | (Patches flat config or legacy ignores safely) |
353
+
354
+ **`run` exit codes:** `0` no errors · `1` errors found (or `--max-warnings` exceeded) · `2` scan did not run — the file passed to `--path` matches a built-in ignore pattern (`node_modules/`, `dist/`, `build/`, `generated/`, `vendor/`, …), so nothing was analyzed, or a file could not be parsed and was not checked (install `@typescript-eslint/parser` for TypeScript; `--fail-on none` exits `0`). Directory scans skip ignored files silently.
355
+
356
+ ### CLI Usage Examples
357
+
358
+ ```bash
359
+ # 0. Set up hooks, the pre-commit gate and the agent-config check in one step
360
+ npx eslint-plugin-ai-guard protect
361
+
362
+ # 1. Immediate scan of current directory (no install needed)
363
+ npx eslint-plugin-ai-guard run
364
+
365
+ # 2. Strict CI scan failing only on high-confidence issues
366
+ npx ai-guard run --strict --fail-on high
367
+
368
+ # 3. Pull Request scan (diffs against PR target branch)
369
+ npx ai-guard changed --pr --sarif --sarif-output results.sarif
370
+
371
+ # 4. Generate AI agent guardrails for Cursor, Claude Code, and Copilot
372
+ npx ai-guard init-context --all
373
+
374
+ # 5. Generate interactive HTML diagnostic report
375
+ npx ai-guard report --output ai-guard-report.html
376
+
377
+ # 6. Save existing issues as baseline and only fail on new regressions
378
+ npx ai-guard baseline create # writes .ai-guard-baseline.json (commit it)
379
+ npx ai-guard baseline check # exit 1 if any new finding
380
+ npx ai-guard baseline check --fail-on high # fail only on new high-confidence findings
381
+ npx ai-guard baseline check --json # machine-readable new findings
382
+
383
+ # 7. Fail a PR that skips tests, adds eslint-disable, or lowers coverage thresholds
384
+ npx ai-guard changed --pr --integrity enforce
385
+ ```
386
+
387
+ ### Inline suppressions never hide findings silently
388
+
389
+ AI Guard reads `eslint-disable` directives itself; ESLint's own inline config is disabled in AI Guard's private ESLint instance, so a comment cannot make a finding vanish without a trace. `--inline-suppressions` selects the policy:
390
+
391
+ | Mode | Effect |
392
+ |---|---|
393
+ | `allow` (default) | A covering directive hides the finding from totals and exit codes; it is listed under "Hidden by inline directives" (JSON `suppressedIssues`, step summary, SARIF `suppressedFindingsCount`) |
394
+ | `require-reason` | Only directives with a ` -- reason` hide findings (used by the Claude Code hook) |
395
+ | `ignore` | Directives never hide AI Guard findings (always used by the MCP server) |
396
+
397
+ This applies to `ai-guard run`, `changed`, the GitHub Action, the Claude Code hook and MCP. It does not change how your own `eslint .` treats directives. TypeScript comments (`@ts-ignore`, `@ts-nocheck`) never affect AI Guard findings; `ai-guard integrity` reports newly added ones.
398
+
399
+ ---
400
+
401
+ ## AI Agent Integration (`init-context`)
402
+
403
+ Standard linters only run **after** code has already been written. The `init-context` command shifts your guardrails left by embedding AI Guard's rules directly into the instruction files loaded by your AI coding tools:
404
+
405
+ ```bash
406
+ npx ai-guard init-context --all
407
+ ```
408
+
409
+ This generates three targeted context files:
410
+ 1. **`CLAUDE.md`** — Automatically loaded by **Claude Code**
411
+ 2. **`.cursorrules`** — Automatically loaded by **Cursor**
412
+ 3. **`.github/copilot-instructions.md`** — Automatically loaded by **GitHub Copilot**
413
+
414
+ ### How Shift-Left Works
415
+
416
+ ```
417
+ AI Guard (init-context)
418
+ ↓
419
+ Generates project guardrail files (CLAUDE.md, .cursorrules, copilot-instructions.md)
420
+ ↓
421
+ AI coding assistant reads safety rules before generating code
422
+ ↓
423
+ Model avoids floating promises, empty catches, and hardcoded secrets at prompt time
424
+ ↓
425
+ AI Guard CLI & GitHub Action deterministically verifies the output in CI
426
+ ```
427
+
428
+ This dual-layer defense minimizes review friction and ensures generated code meets your security standard on the first pass.
429
+
430
+ ---
431
+
432
+ ## Claude Code Integration
433
+
434
+ Using Cursor or Codex too? `npx ai-guard init-hooks` sets up every agent the project uses; see [Agent hooks](./docs/integrations/agents.md).
435
+
436
+ Two ways to use it with Claude Code. Pick one:
437
+
438
+ - **In a project (recommended):** `npm install --save-dev eslint-plugin-ai-guard`, then `npx ai-guard init-claude`. This writes the hooks into the project's `.claude/settings.json`, so everyone on the project gets them.
439
+ - **As a Claude Code plugin** (adds the MCP tools and the `/ai-guard:verify-changes` skill, and works in projects without AI Guard installed): `claude plugin marketplace add ai-guard-dev/eslint-plugin-ai-guard`, then `claude plugin install ai-guard@ai-guard-plugins`.
440
+
441
+ AI Guard integrates directly with [Claude Code](https://code.claude.com/docs/en/hooks) through hooks:
442
+
443
+ ```bash
444
+ # One-command setup
445
+ npx ai-guard init-claude
446
+ ```
447
+
448
+ - **PostToolUse** — after each edit, findings from the `agent` preset and newly weakened checks in the edited file are sent back to Claude (`decision: "block"` + `reason`, per the hooks protocol). Earlier versions printed plain stdout, which Claude Code does not show to Claude.
449
+ - **SessionStart + Stop** — before Claude finishes, [check integrity](./docs/integrity.md) runs on everything changed in the session. High-confidence weakenings (a new `.skip`, `eslint-disable`, lowered threshold…) block stopping once per finding set; advisories are shown to you, never block. The same hook then [verifies](./docs/cli/verify.md) lint findings and agent-config issues the session introduced (placeholder code, a canned return under a test runner, a hidden instruction in `CLAUDE.md`), which also block once. Skip both with `--no-stop-hook`.
450
+ - **PreToolUse (Bash)** — `git commit --no-verify` / `HUSKY=0` ask for confirmation. With `--check-installs` (opt-in, uses the npm registry), packages in install commands are checked first: names that don't exist are blocked; look-alikes of popular packages and releases from the last day ask you.
451
+
452
+ ```bash
453
+ # Preview before applying
454
+ npx ai-guard init-claude --dry-run
455
+
456
+ # Use per-machine settings (gitignored)
457
+ npx ai-guard init-claude --local
458
+ ```
459
+
460
+ **Agent preset rules (8):** `no-hardcoded-secret`, `no-eval-dynamic`, `no-empty-catch`, `no-sql-string-concat`, `no-floating-promise`, `no-client-exposed-secret`, `no-invisible-unicode`, `no-undeclared-import`
461
+
462
+ → [Full documentation](./docs/integrations/claude-code.md)
463
+
464
+ ---
465
+
466
+ ## GitHub Action
467
+
468
+ The official AI Guard GitHub Action runs on PRs, detects changed files, provides step summaries, outputs SARIF 2.1.0, and posts inline PR annotations directly on GitHub:
469
+
470
+ ```yaml
471
+ # .github/workflows/ai-guard.yml
472
+ name: AI Guard
473
+
474
+ on:
475
+ pull_request:
476
+ branches: [main, develop]
477
+ push:
478
+ branches: [main]
479
+
480
+ jobs:
481
+ ai-guard-scan:
482
+ name: AI Guard Code Review
483
+ runs-on: ubuntu-latest
484
+
485
+ permissions:
486
+ contents: read
487
+ security-events: write
488
+ actions: read
489
+
490
+ steps:
491
+ - name: Checkout Code
492
+ uses: actions/checkout@v4
493
+ with:
494
+ fetch-depth: 0 # Required for git diff comparison
495
+
496
+ - name: Setup Node.js
497
+ uses: actions/setup-node@v4
498
+ with:
499
+ node-version: 20
500
+ cache: 'npm'
501
+
502
+ - name: Run AI Guard
503
+ id: aiguard
504
+ uses: ai-guard-dev/eslint-plugin-ai-guard@v1
505
+ with:
506
+ preset: 'recommended'
507
+ fail-on: 'high'
508
+ changed-only: 'true'
509
+
510
+ # The Action writes SARIF; this step sends it to Code Scanning.
511
+ # if: always() uploads it even when the scan step fails the job.
512
+ - name: Upload to GitHub Code Scanning
513
+ if: always()
514
+ uses: github/codeql-action/upload-sarif@v3
515
+ with:
516
+ sarif_file: ${{ steps.aiguard.outputs.sarif-file }}
517
+ category: ai-guard
518
+ ```
519
+
520
+ The Action annotates the pull request and writes the job summary by itself. Alerts in **Security → Code scanning** need the upload step.
521
+
522
+ ### Action Inputs (`action.yml`)
523
+
524
+ | Input | Description | Default |
525
+ | :--- | :--- | :---: |
526
+ | `preset` | Rule preset: `recommended` \| `strict` \| `security` | `'recommended'` |
527
+ | `fail-on` | Severity threshold to fail CI: `high` \| `medium` \| `any` \| `none` | `'high'` |
528
+ | `changed-only` | Scan only files changed in this PR / commit | `'true'` |
529
+ | `path` | Target file or directory to scan | `'.'` |
530
+ | `upload-sarif` | Always write the SARIF file (`sarif-file` output) for an `upload-sarif` step, even when the scan produced none. The Action does not upload to Code Scanning by itself | `'true'` |
531
+ | `github-summary` | Write an execution breakdown to the GitHub Actions Job Summary | `'true'` |
532
+ | `working-directory`| Working directory for scanning (ideal for monorepos) | `'.'` |
533
+ | `package-manager` | Package manager: `auto` \| `npm` \| `pnpm` \| `yarn` | `'auto'` |
534
+ | `sarif-output` | Output filepath for generated SARIF report | `'ai-guard-results.sarif'` |
535
+ | `install-deps` | Install project dependencies prior to scanning | `'true'` |
536
+ | `baseline` | Committed baseline file; with `changed-only`, report only findings not in it | `''` |
537
+ | `integrity` | Check integrity: `off` \| `report` \| `enforce` (needs `changed-only` and `fetch-depth: 0`) | `'off'` |
538
+ | `test-integrity` | With `changed-only`, also flag tests the PR deleted, skipped, focused or weakened (needs `fetch-depth: 0`) | `'false'` |
539
+ | `inline-suppressions` | `allow` \| `require-reason` \| `ignore` for eslint-disable directives covering AI Guard findings | `''` (allow) |
540
+
541
+ ### Action Outputs
542
+
543
+ | Output | Description |
544
+ | :--- | :--- |
545
+ | `issues-found` | Total number of issues found across scanned files |
546
+ | `high-confidence-count` | Number of high-confidence issues flagged |
547
+ | `medium-confidence-count` | Number of medium-confidence issues flagged |
548
+ | `files-scanned` | Count of files analyzed during the execution |
549
+ | `integrity-high-count` | High-confidence check-integrity findings (when `integrity` is enabled) |
550
+ | `integrity-advisory-count` | Advisory check-integrity findings (when `integrity` is enabled) |
551
+ | `sarif-file` | Absolute path to the generated SARIF 2.1.0 artifact |
552
+ | `duration-ms` | Total scan execution duration in milliseconds |
553
+
554
+ ---
555
+
556
+ ## SARIF & GitHub Code Scanning
557
+
558
+ AI Guard natively outputs **SARIF 2.1.0** (`Static Analysis Results Interchange Format`). When uploaded via the GitHub Action or `github/codeql-action/upload-sarif@v3`, findings integrate directly with GitHub Advanced Security:
559
+
560
+ - **Inline PR Annotations:** Direct comments on the exact source lines where flaws exist.
561
+ - **Security Dashboard:** Persistent alerts under your repository's `Security → Code scanning` tab.
562
+ - **Merge Protection:** Block merges automatically when high-confidence security or async bugs are detected.
563
+
564
+ ### Visual Previews
565
+
566
+ #### Inline Pull Request Annotations
567
+ <img src="./assets/ss9.jpg" alt="AI Guard PR Inline Annotations" width="1000" />
568
+
569
+ #### GitHub Advanced Security Summary
570
+ <img src="./assets/ss10.jpg" alt="GitHub Advanced Security Summary for AI Guard" width="1000" />
571
+
572
+ #### Persistent Code Scanning Dashboard
573
+ <img src="./assets/ss11.jpg" alt="GitHub Code Scanning Alerts List" width="1000" />
574
+
575
+ ---
576
+
577
+ ## Rule Examples (Before & After)
578
+
579
+ ### 1. `no-floating-promise` (Unhandled Promises)
580
+
581
+ ```typescript
582
+ // ❌ BAD: Floating promise. Errors are dropped silently.
583
+ async function syncUserProfile(user: User) {
584
+ sendTelemetryEvent('user_sync', user.id);
585
+ database.save(user);
586
+ }
587
+
588
+ // ✅ GOOD: Awaited, explicitly handled, or marked with void
589
+ async function syncUserProfile(user: User) {
590
+ await database.save(user);
591
+ void sendTelemetryEvent('user_sync', user.id); // Explicitly unhandled
592
+ }
593
+ ```
594
+
595
+ ### 2. `no-hardcoded-secret` (Committed Credentials)
596
+
597
+ ```typescript
598
+ // ❌ BAD: Secret committed inline
599
+ const client = new PaymentGateway({
600
+ apiKey: 'sk-prod-983427598273498273948273',
601
+ });
602
+
603
+ // ✅ GOOD: Read from environment variable (Autofixable!)
604
+ const client = new PaymentGateway({
605
+ apiKey: process.env.API_KEY,
606
+ });
607
+ ```
608
+
609
+ ### 3. `no-await-in-loop` (Sequential Latency Trap)
610
+
611
+ ```typescript
612
+ // ❌ BAD: Consecutive awaits block each iteration sequentially
613
+ async function fetchAllUsers(ids: string[]) {
614
+ const users = [];
615
+ for (const id of ids) {
616
+ users.push(await fetchUser(id));
617
+ }
618
+ return users;
619
+ }
620
+
621
+ // ✅ GOOD: Concurrently fetched with Promise.all (editor suggestion)
622
+ async function fetchAllUsers(ids: string[]) {
623
+ return await Promise.all(ids.map((id) => fetchUser(id)));
624
+ }
625
+ ```
626
+
627
+ ### 4. `no-empty-catch` (Swallowed Errors)
628
+
629
+ ```typescript
630
+ // ❌ BAD: Exception swallowed without trace
631
+ try {
632
+ parseConfiguration(rawConfig);
633
+ } catch (e) {}
634
+
635
+ // ✅ GOOD: Logged, rethrown, or documented (Autofixable!)
636
+ try {
637
+ parseConfiguration(rawConfig);
638
+ } catch (e) {
639
+ logger.error('Configuration parsing failed', { error: e });
640
+ throw e;
641
+ }
642
+ ```
643
+
644
+ ### 5. `no-sql-string-concat` (SQL Injection)
645
+
646
+ ```typescript
647
+ // ❌ BAD: Dynamic string interpolation in SQL
648
+ const query = `SELECT * FROM users WHERE organization_id = '${orgId}' AND role = '${role}'`;
649
+ await db.query(query);
650
+
651
+ // ✅ GOOD: Parameterized query binding
652
+ const query = 'SELECT * FROM users WHERE organization_id = $1 AND role = $2';
653
+ await db.query(query, [orgId, role]);
654
+ ```
655
+
656
+ ---
657
+
658
+ ## Automatic Remediation (Autofix)
659
+
660
+ Rules that have deterministic solutions provide automatic autofix handlers. Run ESLint's native `--fix` flag to automatically resolve them:
661
+
662
+ ```bash
663
+ npx eslint . --fix
664
+ ```
665
+
666
+ | Rule | Automatic Fix Behavior |
667
+ | :--- | :--- |
668
+ | `no-hardcoded-secret` | Replaces hardcoded string literal with `process.env.VARIABLE_NAME` |
669
+
670
+ `no-await-in-loop` offers `await Promise.all(...)` as an editor suggestion only: running iterations in parallel changes their order and concurrency, so `--fix` never applies it.
671
+
672
+ `no-empty-catch` and `no-floating-promise` have no automatic fix on purpose. A fix that inserted a comment or `void` would make the finding disappear without handling the error, and an agent running `--fix` would do exactly that. Editors offer them as suggestions instead (rethrow; `await`, or `void` for an intended fire-and-forget call), which a person applies one at a time.
673
+
674
+ ---
675
+
676
+ ## Benchmarks & Empirical Evaluation
677
+
678
+ AI Guard has been empirically evaluated across multiple benchmarks comparing runtime scan performance, coverage gaps vs. standard tooling, and detection accuracy across real-world codebases.
679
+
680
+ ### 1. What AI Guard Catches vs. Conventional Linters
681
+
682
+ Conventional linters either omit AI-specific hazards entirely or require heavyweight TypeScript type-checking (`parserOptions.project`) that significantly slows down CI:
683
+
684
+ | Pattern | AI Guard Rule | ESLint Core | `@typescript-eslint` |
685
+ | :--- | :--- | :---: | :--- |
686
+ | **Floating Promises** (unawaited async call) | [`no-floating-promise`](./docs/rules/no-floating-promise.md) | ❌ None | `@typescript-eslint/no-floating-promises` *(requires type info)* |
687
+ | **Async Array Callbacks** (`.map(async ...)`) | [`no-async-array-callback`](./docs/rules/no-async-array-callback.md) | ❌ None | Partial: `no-misused-promises` *(requires type info)* |
688
+ | **Empty Catch Blocks** (swallowed errors) | [`no-empty-catch`](./docs/rules/no-empty-catch.md) | `no-empty` *(weaker)* | ❌ None |
689
+ | **Hardcoded Secrets / API Tokens** | [`no-hardcoded-secret`](./docs/rules/no-hardcoded-secret.md) | ❌ None | ❌ None |
690
+ | **Raw SQL String Concatenation** | [`no-sql-string-concat`](./docs/rules/no-sql-string-concat.md) | ❌ None | ❌ None |
691
+ | **Missing Route Auth Middleware** | [`require-auth-middleware`](./docs/rules/require-auth-middleware.md) | ❌ None | ❌ None |
692
+ | **Missing Route Authorization Checks** | [`require-authz-check`](./docs/rules/require-authz-check.md) | ❌ None | ❌ None |
693
+ | **Dynamic `eval()` / `new Function()`** | [`no-eval-dynamic`](./docs/rules/no-eval-dynamic.md) | `no-eval` *(blanket ban)* | ❌ None |
694
+ | **Unsafe `JSON.parse(req.body)`** | [`no-unsafe-deserialize`](./docs/rules/no-unsafe-deserialize.md) | ❌ None | ❌ None |
695
+ | **Async Without Await** | [`no-async-without-await`](./docs/rules/no-async-without-await.md) | ❌ None | `require-await` |
696
+ | **Sequential Await in Loop** | [`no-await-in-loop`](./docs/rules/no-await-in-loop.md) | `no-await-in-loop` *(no fix)* | ❌ None |
697
+ | **Dead Code Branches (`if (true)`)** | [`no-dead-branch`](./docs/rules/no-dead-branch.md) | ❌ None | ❌ None |
698
+ | **Secrets exposed to the browser** (`NEXT_PUBLIC_*_SECRET`) | [`no-client-exposed-secret`](./docs/rules/no-client-exposed-secret.md) | ❌ None | ❌ None |
699
+ | **Trojan Source / hidden Unicode instructions** | [`no-invisible-unicode`](./docs/rules/no-invisible-unicode.md) | Partial: `no-irregular-whitespace` *(whitespace only)* | ❌ None |
700
+ | **Hallucinated / undeclared packages** | [`no-undeclared-import`](./docs/rules/no-undeclared-import.md) | ❌ None | ❌ None |
701
+ | **Unsanitized HTML sinks (XSS)** | [`no-unsanitized-html`](./docs/rules/no-unsanitized-html.md) | ❌ None | ❌ None |
702
+ | **Hardcoded secret fallbacks** | [`no-silent-fallback`](./docs/rules/no-silent-fallback.md) | ❌ None | ❌ None |
703
+ | **Elided / stubbed code left by agents** | [`no-placeholder-implementation`](./docs/rules/no-placeholder-implementation.md) | Partial: `no-warning-comments` *(TODO text only)* | ❌ None |
704
+
705
+ > [!TIP]
706
+ > **Minimal Type-Information Dependency:** 32 of 33 AI Guard rules operate in pure syntax/scope-analysis mode without `projectService` or `tsconfig.json`. The `no-floating-promise` rule optionally uses TypeScript parser services for higher recall on cross-module Promise calls, with syntax/scope-based heuristics as a zero-config fallback.
707
+
708
+ ---
709
+
710
+ ### 2. Runtime Performance
711
+
712
+ Benchmark: scanning 196 TypeScript / JavaScript files (`algorithm-automata-simulator`, Windows 11, Node.js 20, median of 3 runs):
713
+
714
+ | Tool / Mode | Scan Time | Configuration Overhead |
715
+ | :--- | :---: | :--- |
716
+ | **`ai-guard run --strict`** | **~1.8s** | **Zero config** (18 AST heuristic rules, no `tsconfig.json` needed) |
717
+ | `eslint .` (recommended) | ~2.5s | Core syntax rules only (misses floating promises & secrets) |
718
+ | `eslint .` (type-aware `@typescript-eslint`) | **~8–12s** | Requires full TS compiler graph binding (**4x–6x slower**) |
719
+
720
+ AI Guard executes **4x–6x faster** than type-aware linting suites because it leverages deterministic AST heuristics rather than reconstructing the full TypeScript symbol graph.
721
+
722
+ ---
723
+
724
+ ### 3. Empirical Bug Detection & Precision Study
725
+
726
+ Two comprehensive empirical benchmark evaluations were conducted to measure real-world precision and detection yields:
727
+
728
+ #### A. Accuracy & False Positive Audit (4 Real-World Repositories, 378 Files)
729
+
730
+ | Category | Findings | True Positives | False Positive Rate |
731
+ | :--- | :---: | :---: | :---: |
732
+ | **Security** (`no-hardcoded-secret`, `no-eval-dynamic`, etc.) | 15 | 15 | **0%** |
733
+ | **Reliability** (`no-empty-catch`, broad exceptions) | 53 | 53 | **0%** |
734
+ | **Async Stability** (`no-floating-promise`, async callbacks) | 43 | ~40 | **~7%** |
735
+ | **AI Patterns** (duplicate logic, dead branches) | 58 | 43 | **26%** *(reduced in v1.2.8+)* |
736
+
737
+ #### B. Dual-Mode Detection Study (48 Call Sites & Real Production Target)
738
+
739
+ Audited across a controlled multi-file test corpus (13 files, 48 call sites) and a real-world Express + MongoDB production application (`Truvita New`):
740
+
741
+ - **High Precision:** **100% precision** on type-aware exclusive findings (26 of 26 verified True Positives; 0 false alarms on synchronous controls).
742
+ - **Critical Detection:** Detected **1 critical database startup race condition** in production (`server/index.ts connectDB()`) where an unawaited connection call allowed requests to hit the database before initialization.
743
+ - **Single-File Actionability:** **100%** of findings were resolvable locally at the call site (`await`, `.catch()`, or `void`).
744
+
745
+ For the complete methodology, raw findings, and benchmark harness, see [**`docs/benchmarks.md`**](./docs/benchmarks.md).
746
+
747
+ ---
748
+
749
+ ## Performance & Philosophy
750
+
751
+ - **Zero LLM Overhead:** AI Guard does not call external APIs, does not incur token costs, and does not add LLM latency. A scan of 100+ files executes in milliseconds.
752
+ - **100% Deterministic:** Every finding is derived strictly from Abstract Syntax Tree analysis. No probabilistic drift, no non-deterministic hallucinated findings.
753
+ - **Low False Positives:** Built with precision-first design. Context-sensitive rules are configured at `warn` or `off` in the recommended preset so developers are never blocked by noise.
754
+ - **Self-Scanning:** AI Guard enforces its own rules on its own codebase in CI using the `strict` preset.
755
+
756
+ ---
757
+
758
+ ## MCP Server (Model Context Protocol)
759
+
760
+ AI Guard includes a local MCP server that exposes its deterministic analysis engine to MCP-capable AI clients (Claude Code, Claude Desktop, and other MCP-compatible integrations).
761
+
762
+ ```bash
763
+ npx --yes --package eslint-plugin-ai-guard ai-guard-mcp
764
+ ```
765
+
766
+ **Available tools:**
767
+
768
+ | Tool | Description |
769
+ | :--- | :--- |
770
+ | `ai_guard_scan_file` | Scan a single JS/TS file with structured findings |
771
+ | `ai_guard_scan_diff` | Scan changed files in git diff (including newly created untracked JS/TS files) |
772
+ | `ai_guard_scan_project` | Scan a bounded workspace directory (at most 500 files; fails instead of truncating) |
773
+ | `ai_guard_rules` | List rules and presets, or look up specific rules (`rules: ["no-floating-promise"]`) with remediation and docs link |
774
+ | `ai_guard_check_integrity` | Report checks weakened by current Git changes (new suppressions, skipped/removed tests, lowered configs, removed CI steps), with `tier` and `hasBlockingFindings` |
775
+ | `ai_guard_verify_change` | One verdict before calling work done: introduced lint findings, weakened tests and agent-config issues (`pass`, `blocking`, `disclosures`) |
776
+ | `ai_guard_scan_agent_config` | Check CLAUDE.md, AGENTS.md, skills and MCP config for hidden text and prompt injection |
777
+ | `ai_guard_fix` | Apply deterministic autofixes to one file; returns a diff and writes only with `apply: true` |
778
+ | `ai_guard_check_package` | Check npm or PyPI packages before installing them: missing names, look-alikes of popular packages, new or rarely used packages, install scripts (the only tool that uses the network: `registry.npmjs.org`, `pypi.org`) |
779
+
780
+ All tools declare an `outputSchema`; the text content is the same result as compact JSON. Scan tools accept `maxIssues` (default 50, errors first, exact `totalIssues` and `truncated`). The `verify_changes` prompt runs the scan → fix → rescan loop.
781
+
782
+ **Claude Code configuration** (project-root `.mcp.json`):
783
+
784
+ ```json
785
+ {
786
+ "mcpServers": {
787
+ "ai-guard": {
788
+ "type": "stdio",
789
+ "command": "node",
790
+ "args": ["/absolute/path/to/ai-guard/dist/mcp/server.js"],
791
+ "env": { "AI_GUARD_WORKSPACE": "/absolute/path/to/project" }
792
+ }
793
+ }
794
+ }
795
+ ```
796
+
797
+ The SDK in-memory and built STDIO integrations are tested, plus a headless Claude Code CLI smoke test (see the MCP guide for scope). Use the built checkout to test unreleased changes. Scan, fix, then rescan; a partial or failed scan is never clean. For setup, result status, limits, and client verification scope, see [**`docs/mcp-server.md`**](./docs/mcp-server.md).
798
+
799
+ ### Glama listing
800
+
801
+ <a href="https://glama.ai/mcp/servers/ai-guard-dev/eslint-plugin-ai-guard"><img width="380" src="https://glama.ai/mcp/servers/ai-guard-dev/eslint-plugin-ai-guard/badge" alt="AI Guard MCP server" /></a>
802
+
803
+ AI Guard is listed on [Glama](https://glama.ai/mcp/servers/ai-guard-dev/eslint-plugin-ai-guard). There you can browse the server's tools, check its quality score, and test it online with [MCP Inspector](https://glama.ai/mcp/inspector).
804
+
805
+
806
+ ---
807
+
808
+ ## Learn More & Ecosystem
809
+
810
+ Visit [getaiguard.dev](https://getaiguard.dev) to explore interactive documentation, rule catalogs, benchmarks, and deep-dive engineering articles.
811
+
812
+ ### Official Links
813
+
814
+ - **Website:** [https://getaiguard.dev](https://getaiguard.dev)
815
+ - **GitHub Organization:** [https://github.com/ai-guard-dev](https://github.com/ai-guard-dev)
816
+ - **Repository:** [https://github.com/ai-guard-dev/eslint-plugin-ai-guard](https://github.com/ai-guard-dev/eslint-plugin-ai-guard)
817
+ - **npm Registry:** [https://www.npmjs.com/package/eslint-plugin-ai-guard](https://www.npmjs.com/package/eslint-plugin-ai-guard)
818
+ - **GitHub Action:** [ai-guard-dev/eslint-plugin-ai-guard@v1](https://github.com/ai-guard-dev/eslint-plugin-ai-guard)
819
+
820
+ ---
821
+
822
+ ## Contributing
823
+
824
+ We welcome contributions, new rule ideas, bug reports, and false-positive reports!
825
+
826
+ 1. Check out our [Contributing Guide](CONTRIBUTING.md) for local setup and testing standards.
827
+ 2. Review our [Security Policy](SECURITY.md) to report vulnerabilities responsibly.
828
+ 3. Check open issues or submit new ones on our [Issue Tracker](https://github.com/ai-guard-dev/eslint-plugin-ai-guard/issues).
829
+
830
+ ---
831
+
832
+ ## License
833
+
834
+ [MIT](LICENSE) © AI Guard Authors. Free and open source forever.