ai-guard
Installs a Git pre-commit hook and scans commits/changed files so AI Guard checks run on every commit.
Provides a GitHub Action that publishes SARIF 2.1.0 results to GitHub Code Scanning, adds inline pull-request annotations, and can block merges through a PR status check.
Checks npm package names and metadata for nonexistent packages, typosquats, security placeholders, install scripts, deprecations, and freshly published releases.
What is AI Guard?
AI Guard (eslint-plugin-ai-guard) provides:
ESLint plugin with 33 deterministic rules and 4 presets (
recommended,strict,security,agent)CLI (
ai-guard) for terminal, changed-file, and CI scanningGitHub Action with native SARIF 2.1.0 output for GitHub Code Scanning
Check integrity (
ai-guard integrity) — detects changes that weaken checks: new suppressions, skipped or removed tests, lowered ESLint/TypeScript/coverage settings, removed CI stepsAgent safety:
ai-guard verify(one verdict for a change),ai-guard scan-agent-config(hidden text and prompt injection inCLAUDE.md, skills and MCP config), andchanged --test-integrity(weakened tests)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 introducedA pre-commit gate (
ai-guard init-git-hook) that checks every commit, whichever agent or person wrote itWorks with Oxlint as a JS plugin, with identical results checked in CI (
ai-guard init-oxlint)Package checks (
ai-guard verify-deps, an opt-in pre-install hook, and theai_guard_check_packageMCP 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 flaggedMCP server (
ai-guard-mcp, 9 tools) for local AI-agent workflows over STDIO
Results on real projects
Measured on 12 November 2026 with 1.4.6. Methods, raw numbers and the commands to reproduce them: docs/evidence.md.
0 of 1,361 real dependencies blocked (763 from 15 large open-source projects, 598 from 9 apps)
34 of 36 names from the 2017 crossenv malware campaign blocked
3.0% of the 5,000 most-downloaded packages had a latest release under a day old, the window the fresh-release check covers
27 of 27 rules give identical results in ESLint and Oxlint, checked in CI
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.).
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.
What AI Guard is NOT
AI Guard is NOT an AI detector. It does not attempt to predict whether code was authored by an LLM or a human.
AI Guard detects dangerous or fragile code patterns that LLMs repeatedly introduce due to incomplete context, hallucinated patterns, or probabilistic generation.
AI Guard does NOT replace ESLint. It extends ESLint with 33 specialized, high-impact rules that core ESLint and standard configurations omit.
Related MCP server: CodeInspectus
Why AI Guard?
AI coding assistants write code at remarkable velocity, but generated code repeatedly suffers from predictable reliability and security anti-patterns that conventional linters miss:
Pattern | Why AI Assistants Generate It | Real-World Impact |
Floating Promises | Omits | Unhandled promise rejections, silent failures in background jobs |
Async Array Iteration | Passes async callbacks into | Returns unawaited |
Sequential Awaits in Loops | Loops over items with sequential | Significant latency bottlenecks; blocks event loop execution |
Empty Catch Blocks | Inserts generic | Swallows production exceptions silently without telemetry |
Hardcoded Secrets | Injects placeholder or real API keys/tokens | Credential leakage in version control and deployment bundles |
Dynamic | Generates dynamic function compilation | Arbitrary code execution and code injection |
Raw SQL Concatenation | Concatenates query strings with variables | Severe SQL injection vulnerabilities |
Unsafe Deserialization | Calls | Denial of service and unhandled runtime crashes |
Missing Route Auth & Authz | Emits boilerplate endpoints without auth middleware | Unprotected API endpoints and IDOR privilege escalations |
Dead Branches & Scaffolding | Leaves | Bloated bundles and dead code paths |
AI Guard provides an instantaneous, deterministic feedback loop that catches these issues before they reach pull requests or production.
Architecture & Workflow
flowchart TD
subgraph Dev["1. Development & Prompt Phase"]
A["Developer + AI Coding Assistant\n(Copilot, Cursor, Claude Code)"] --> B["JavaScript / TypeScript Code"]
end
subgraph ShiftLeft["Shift Left — Context Injection"]
SL["npx ai-guard init-context"] -.-> CTX["CLAUDE.md\n.cursorrules\ncopilot-instructions.md"]
CTX -.-> A
end
subgraph Analysis["2. Deterministic AST Analysis"]
B --> C["ESLint Parser\n(espree / @typescript-eslint/parser)"]
C --> D["AST Representation"]
D --> E["AI Guard Rules Engine\n(33 Deterministic Rules)"]
end
subgraph Tiers["3. Classification & Presets"]
E --> F{"Active Preset\n(recommended | strict | security | agent)"}
F --> G["Confidence Tiering & AST Filtering"]
end
subgraph Outputs["4. Output & Remediation"]
G --> H["Local CLI Scanning\n(ai-guard run / changed)"]
G --> I["Autofix Remediation\n(eslint --fix)"]
G --> J["HTML Dashboard\n(ai-guard report)"]
G --> K["SARIF 2.1.0 Artifact\n(ai-guard --sarif)"]
end
subgraph CI["5. GitHub Pull Request & CI/CD"]
K --> L["GitHub Action\nai-guard-dev/eslint-plugin-ai-guard@v1"]
L --> M["GitHub Code Scanning Alerts"]
L --> N["Inline PR Code Annotations"]
L --> O["PR Status Check (Blocks Merge)"]
endRules Catalog
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:
🔴 Security (13 Rules)
Rule | Recommended | What It Catches | Fixable? |
| API keys, bearer tokens, passwords, and private keys committed directly in source code. | Yes ( | |
|
| No | |
| SQL queries constructed by string concatenation or raw template literals — SQL injection risks. | No | |
| Unchecked | No | |
| Express and Fastify route definitions exposed without authentication middleware. | No | |
| Endpoints accessing sensitive resources or user IDs without tenant/ownership authorization checks. | No | |
| Server secrets that reach the browser: | No | |
| 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) | |
| Dynamic values in | No | |
| Imports of packages missing from package.json: hallucinated names (slopsquatting) and phantom dependencies. Offline and monorepo-aware. | No | |
|
| No | |
|
| No | |
| CORS that accepts every origin ( | No |
🟠 Reliability (6 Rules)
Rule | Recommended | What It Catches | Fixable? |
| Empty | No (editor suggestion: rethrow) | |
| Catching broad exception types like | No | |
| Catch blocks that only log to | No | |
| Caught error variables that are declared in catch parameters but never referenced. | No | |
| Secret env vars with hardcoded fallbacks ( | No | |
|
| No |
🟡 Async Stability (5 Rules)
Rule | Recommended | What It Catches | Fixable? |
| Async function invocations without | No (editor suggestions: | |
| Async callbacks passed to | No | |
| Sequential | Yes (rewrites to | |
| Functions declared | No | |
| Redundant | No |
🔵 AI Patterns (9 Rules)
Rule | Recommended | What It Catches | Fixable? |
| Unreachable or tautological branches ( | No | |
| Consecutive duplicate code blocks or repeated conditional branches duplicated during AI edits. | No | |
| Unstructured | No | |
| Code an agent left unfinished: | No | |
| Names, subpaths and default imports the installed package does not export: | No | |
| APIs the installed package version has removed, which models keep writing from older training data: | No | |
| Assertions that always pass: | No | |
| Test cases with no assertion, which pass whatever the code does. | No | |
| Production code that returns a canned result under a test runner ( | No |
* Enabled at error level in the strict preset.
Agent Safety
Linting checks the code. These check the agent:
Feature | What it does |
One verdict for the current change: lint findings it introduced, weakened tests, and agent-config issues. Pre-existing problems never block. | |
Everything that weakens checks vs a base revision: new suppressions, skipped or removed tests, lowered coverage and TypeScript settings, removed CI steps. | |
A test-focused comparison: focused, skipped, removed or weakened tests, rewritten snapshots, and test commands that can no longer fail. Overlaps with | |
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 ( | |
Scans | |
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 | |
| |
| |
|
Presets
AI Guard exports four official configurations ready for flat config or legacy setups:
Preset | Description | Configuration Focus |
| Default. Balanced adoption preset. Enables 6 high-confidence critical rules at | Production codebases, new teams |
| Enforces all 33 rules at | Strict CI/CD quality gates |
| Focuses on the 14 security-relevant rules (secrets, eval, SQL, client-exposed secrets, invisible Unicode and HTML sinks at | AppSec auditing & security scans |
| 8 high-signal rules at | Claude Code, Cursor, real-time agent loops |
Quick Start & Installation
Try it first, without installing anything or touching your config:
npx eslint-plugin-ai-guard runIt 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.
One command sets up everything:
npx eslint-plugin-ai-guard protectIt 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.
Or install the package yourself as a development dependency:
# npm
npm install --save-dev eslint-plugin-ai-guard
# pnpm
pnpm add -D eslint-plugin-ai-guard
# yarn
yarn add -D eslint-plugin-ai-guard
# bun
bun add -d eslint-plugin-ai-guardOnce AI Guard is installed in a project, its CLI isai-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.
Add a badge to your README
npx eslint-plugin-ai-guard badgeIt scans the project, writes the result to .github/ai-guard-badge.json (a shields.io endpoint 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. Nothing is sent anywhere: shields.io reads the file from your repository.
Requirements
Node.js:
>= 20.0.0ESLint:
>= 8.0.0(Supports both Flat Config and legacy configs)TypeScript (optional):
@typescript-eslint/parser >= 6.0.0for TypeScript AST parsing
ESLint Configuration
1. Flat Config (ESLint 9 and 10: eslint.config.mjs / eslint.config.js)
Each flat/ preset is a complete flat config that registers the plugin itself:
// eslint.config.mjs
import aiGuard from 'eslint-plugin-ai-guard';
export default [aiGuard.configs['flat/recommended']];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:
export default [
aiGuard.configs['flat/recommended'],
{
rules: {
'ai-guard/no-floating-promise': 'error',
},
},
];Spreading the rules into your own config object (plugins: { 'ai-guard': aiGuard }, rules: { ...aiGuard.configs.recommended.rules }) keeps working.
2. Legacy Config (ESLint 8, or ESLint 9 with ESLINT_USE_FLAT_CONFIG=false)
// .eslintrc.js
module.exports = {
plugins: ['ai-guard'],
extends: ['plugin:ai-guard/recommended'],
};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.
CLI Reference
AI Guard includes a full-featured CLI binary (ai-guard) that runs out of the box with zero ESLint configuration files required:
npx ai-guard <command> [options] # AI Guard installed in the project
npx eslint-plugin-ai-guard <command> [options] # not installed (first run, one-off scans)Core Commands
Command | Purpose | Common Options |
| Set up everything in one step: install, agent hooks, pre-commit gate, agent-config check (docs) |
|
| Scan your workspace using AI Guard AST rules |
|
| Fast CI scan — only scans modified files in git |
|
| One verdict for the current change (docs) |
|
| Check npm packages before they are installed (docs) |
|
| Scan agent instructions and MCP config (docs) |
|
| Report code a change copied from elsewhere in the repository (docs) |
|
| Detect changes that weaken checks vs a base revision (docs) |
|
| Automatically detect environment & configure ESLint |
|
| Hooks for Claude Code, Cursor and Codex (docs) |
|
| Pre-commit gate running |
|
| Add AI Guard to |
|
| Generate prompt instruction files for AI coding agents |
|
| Diagnose your ESLint, parser, and plugin environment | (No options needed — prints actionable diagnostic report) |
| Record existing findings, then report only new ones |
|
| Scan and write a README badge with the result (docs) |
|
| Generate an interactive standalone HTML audit report |
|
| Interactively select and switch active preset in config | (Interactive prompt with automatic config patch & backup) |
| Add standard ignore paths ( | (Patches flat config or legacy ignores safely) |
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.
CLI Usage Examples
# 0. Set up hooks, the pre-commit gate and the agent-config check in one step
npx eslint-plugin-ai-guard protect
# 1. Immediate scan of current directory (no install needed)
npx eslint-plugin-ai-guard run
# 2. Strict CI scan failing only on high-confidence issues
npx ai-guard run --strict --fail-on high
# 3. Pull Request scan (diffs against PR target branch)
npx ai-guard changed --pr --sarif --sarif-output results.sarif
# 4. Generate AI agent guardrails for Cursor, Claude Code, and Copilot
npx ai-guard init-context --all
# 5. Generate interactive HTML diagnostic report
npx ai-guard report --output ai-guard-report.html
# 6. Save existing issues as baseline and only fail on new regressions
npx ai-guard baseline create # writes .ai-guard-baseline.json (commit it)
npx ai-guard baseline check # exit 1 if any new finding
npx ai-guard baseline check --fail-on high # fail only on new high-confidence findings
npx ai-guard baseline check --json # machine-readable new findings
# 7. Fail a PR that skips tests, adds eslint-disable, or lowers coverage thresholds
npx ai-guard changed --pr --integrity enforceInline suppressions never hide findings silently
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:
Mode | Effect |
| A covering directive hides the finding from totals and exit codes; it is listed under "Hidden by inline directives" (JSON |
| Only directives with a |
| Directives never hide AI Guard findings (always used by the MCP server) |
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.
AI Agent Integration (init-context)
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:
npx ai-guard init-context --allThis generates three targeted context files:
CLAUDE.md— Automatically loaded by Claude Code.cursorrules— Automatically loaded by Cursor.github/copilot-instructions.md— Automatically loaded by GitHub Copilot
How Shift-Left Works
AI Guard (init-context)
↓
Generates project guardrail files (CLAUDE.md, .cursorrules, copilot-instructions.md)
↓
AI coding assistant reads safety rules before generating code
↓
Model avoids floating promises, empty catches, and hardcoded secrets at prompt time
↓
AI Guard CLI & GitHub Action deterministically verifies the output in CIThis dual-layer defense minimizes review friction and ensures generated code meets your security standard on the first pass.
Claude Code Integration
Using Cursor or Codex too? npx ai-guard init-hooks sets up every agent the project uses; see Agent hooks.
Two ways to use it with Claude Code. Pick one:
In a project (recommended):
npm install --save-dev eslint-plugin-ai-guard, thennpx ai-guard init-claude. This writes the hooks into the project's.claude/settings.json, so everyone on the project gets them.As a Claude Code plugin (adds the MCP tools and the
/ai-guard:verify-changesskill, and works in projects without AI Guard installed):claude plugin marketplace add ai-guard-dev/eslint-plugin-ai-guard, thenclaude plugin install ai-guard@ai-guard-plugins.
AI Guard integrates directly with Claude Code through hooks:
# One-command setup
npx ai-guard init-claudePostToolUse — after each edit, findings from the
agentpreset 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.SessionStart + Stop — before Claude finishes, check integrity 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 lint findings and agent-config issues the session introduced (placeholder code, a canned return under a test runner, a hidden instruction inCLAUDE.md), which also block once. Skip both with--no-stop-hook.PreToolUse (Bash) —
git commit --no-verify/HUSKY=0ask 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.
# Preview before applying
npx ai-guard init-claude --dry-run
# Use per-machine settings (gitignored)
npx ai-guard init-claude --localAgent 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
GitHub Action
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:
# .github/workflows/ai-guard.yml
name: AI Guard
on:
pull_request:
branches: [main, develop]
push:
branches: [main]
jobs:
ai-guard-scan:
name: AI Guard Code Review
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
actions: read
steps:
- name: Checkout Code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Required for git diff comparison
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Run AI Guard
id: aiguard
uses: ai-guard-dev/eslint-plugin-ai-guard@v1
with:
preset: 'recommended'
fail-on: 'high'
changed-only: 'true'
# The Action writes SARIF; this step sends it to Code Scanning.
# if: always() uploads it even when the scan step fails the job.
- name: Upload to GitHub Code Scanning
if: always()
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: ${{ steps.aiguard.outputs.sarif-file }}
category: ai-guardThe Action annotates the pull request and writes the job summary by itself. Alerts in Security → Code scanning need the upload step.
Action Inputs (action.yml)
Input | Description | Default |
| Rule preset: |
|
| Severity threshold to fail CI: |
|
| Scan only files changed in this PR / commit |
|
| Target file or directory to scan |
|
| Always write the SARIF file ( |
|
| Write an execution breakdown to the GitHub Actions Job Summary |
|
| Working directory for scanning (ideal for monorepos) |
|
| Package manager: |
|
| Output filepath for generated SARIF report |
|
| Install project dependencies prior to scanning |
|
| Committed baseline file; with |
|
| Check integrity: |
|
| With |
|
|
|
|
Action Outputs
Output | Description |
| Total number of issues found across scanned files |
| Number of high-confidence issues flagged |
| Number of medium-confidence issues flagged |
| Count of files analyzed during the execution |
| High-confidence check-integrity findings (when |
| Advisory check-integrity findings (when |
| Absolute path to the generated SARIF 2.1.0 artifact |
| Total scan execution duration in milliseconds |
SARIF & GitHub Code Scanning
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:
Inline PR Annotations: Direct comments on the exact source lines where flaws exist.
Security Dashboard: Persistent alerts under your repository's
Security → Code scanningtab.Merge Protection: Block merges automatically when high-confidence security or async bugs are detected.
Visual Previews
Inline Pull Request Annotations
GitHub Advanced Security Summary
Persistent Code Scanning Dashboard
Rule Examples (Before & After)
1. no-floating-promise (Unhandled Promises)
// ❌ BAD: Floating promise. Errors are dropped silently.
async function syncUserProfile(user: User) {
sendTelemetryEvent('user_sync', user.id);
database.save(user);
}
// ✅ GOOD: Awaited, explicitly handled, or marked with void
async function syncUserProfile(user: User) {
await database.save(user);
void sendTelemetryEvent('user_sync', user.id); // Explicitly unhandled
}2. no-hardcoded-secret (Committed Credentials)
// ❌ BAD: Secret committed inline
const client = new PaymentGateway({
apiKey: 'sk-prod-983427598273498273948273',
});
// ✅ GOOD: Read from environment variable (Autofixable!)
const client = new PaymentGateway({
apiKey: process.env.API_KEY,
});3. no-await-in-loop (Sequential Latency Trap)
// ❌ BAD: Consecutive awaits block each iteration sequentially
async function fetchAllUsers(ids: string[]) {
const users = [];
for (const id of ids) {
users.push(await fetchUser(id));
}
return users;
}
// ✅ GOOD: Concurrently fetched with Promise.all (Autofixable!)
async function fetchAllUsers(ids: string[]) {
return await Promise.all(ids.map((id) => fetchUser(id)));
}4. no-empty-catch (Swallowed Errors)
// ❌ BAD: Exception swallowed without trace
try {
parseConfiguration(rawConfig);
} catch (e) {}
// ✅ GOOD: Logged, rethrown, or documented (Autofixable!)
try {
parseConfiguration(rawConfig);
} catch (e) {
logger.error('Configuration parsing failed', { error: e });
throw e;
}5. no-sql-string-concat (SQL Injection)
// ❌ BAD: Dynamic string interpolation in SQL
const query = `SELECT * FROM users WHERE organization_id = '${orgId}' AND role = '${role}'`;
await db.query(query);
// ✅ GOOD: Parameterized query binding
const query = 'SELECT * FROM users WHERE organization_id = $1 AND role = $2';
await db.query(query, [orgId, role]);Automatic Remediation (Autofix)
Rules that have deterministic solutions provide automatic autofix handlers. Run ESLint's native --fix flag to automatically resolve them:
npx eslint . --fixRule | Automatic Fix Behavior |
| Replaces hardcoded string literal with |
| Rewrites straightforward sequential loops to |
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.
Benchmarks & Empirical Evaluation
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.
1. What AI Guard Catches vs. Conventional Linters
Conventional linters either omit AI-specific hazards entirely or require heavyweight TypeScript type-checking (parserOptions.project) that significantly slows down CI:
Pattern | AI Guard Rule | ESLint Core |
|
Floating Promises (unawaited async call) | ❌ None |
| |
Async Array Callbacks ( | ❌ None | Partial: | |
Empty Catch Blocks (swallowed errors) |
| ❌ None | |
Hardcoded Secrets / API Tokens | ❌ None | ❌ None | |
Raw SQL String Concatenation | ❌ None | ❌ None | |
Missing Route Auth Middleware | ❌ None | ❌ None | |
Missing Route Authorization Checks | ❌ None | ❌ None | |
Dynamic |
| ❌ None | |
Unsafe | ❌ None | ❌ None | |
Async Without Await | ❌ None |
| |
Sequential Await in Loop |
| ❌ None | |
Dead Code Branches ( | ❌ None | ❌ None | |
Secrets exposed to the browser ( | ❌ None | ❌ None | |
Trojan Source / hidden Unicode instructions | Partial: | ❌ None | |
Hallucinated / undeclared packages | ❌ None | ❌ None | |
Unsanitized HTML sinks (XSS) | ❌ None | ❌ None | |
Hardcoded secret fallbacks | ❌ None | ❌ None | |
Elided / stubbed code left by agents | Partial: | ❌ None |
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.
2. Runtime Performance
Benchmark: scanning 196 TypeScript / JavaScript files (algorithm-automata-simulator, Windows 11, Node.js 20, median of 3 runs):
Tool / Mode | Scan Time | Configuration Overhead |
| ~1.8s | Zero config (18 AST heuristic rules, no |
| ~2.5s | Core syntax rules only (misses floating promises & secrets) |
| ~8–12s | Requires full TS compiler graph binding (4x–6x slower) |
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.
3. Empirical Bug Detection & Precision Study
Two comprehensive empirical benchmark evaluations were conducted to measure real-world precision and detection yields:
A. Accuracy & False Positive Audit (4 Real-World Repositories, 378 Files)
Category | Findings | True Positives | False Positive Rate |
Security ( | 15 | 15 | 0% |
Reliability ( | 53 | 53 | 0% |
Async Stability ( | 43 | ~40 | ~7% |
AI Patterns (duplicate logic, dead branches) | 58 | 43 | 26% (reduced in v1.2.8+) |
B. Dual-Mode Detection Study (48 Call Sites & Real Production Target)
Audited across a controlled multi-file test corpus (13 files, 48 call sites) and a real-world Express + MongoDB production application (Truvita New):
High Precision: 100% precision on type-aware exclusive findings (26 of 26 verified True Positives; 0 false alarms on synchronous controls).
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.Single-File Actionability: 100% of findings were resolvable locally at the call site (
await,.catch(), orvoid).
For the complete methodology, raw findings, and benchmark harness, see docs/benchmarks.md.
Performance & Philosophy
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.
100% Deterministic: Every finding is derived strictly from Abstract Syntax Tree analysis. No probabilistic drift, no non-deterministic hallucinated findings.
Low False Positives: Built with precision-first design. Context-sensitive rules are configured at
warnoroffin the recommended preset so developers are never blocked by noise.Self-Scanning: AI Guard enforces its own rules on its own codebase in CI using the
strictpreset.
MCP Server (Model Context Protocol)
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).
npx --yes --package eslint-plugin-ai-guard ai-guard-mcpAvailable tools:
Tool | Description |
| Scan a single JS/TS file with structured findings |
| Scan changed files in git diff (including newly created untracked JS/TS files) |
| Scan a bounded workspace directory (at most 500 files; fails instead of truncating) |
| List rules and presets, or look up specific rules ( |
| Report checks weakened by current Git changes (new suppressions, skipped/removed tests, lowered configs, removed CI steps), with |
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.
Claude Code configuration (project-root .mcp.json):
{
"mcpServers": {
"ai-guard": {
"type": "stdio",
"command": "node",
"args": ["/absolute/path/to/ai-guard/dist/mcp/server.js"],
"env": { "AI_GUARD_WORKSPACE": "/absolute/path/to/project" }
}
}
}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.
Learn More & Ecosystem
Visit getaiguard.dev to explore interactive documentation, rule catalogs, benchmarks, and deep-dive engineering articles.
Official Links
Website: https://getaiguard.dev
GitHub Organization: https://github.com/ai-guard-dev
Repository: https://github.com/ai-guard-dev/eslint-plugin-ai-guard
npm Registry: https://www.npmjs.com/package/eslint-plugin-ai-guard
GitHub Action: ai-guard-dev/eslint-plugin-ai-guard@v1
Contributing
We welcome contributions, new rule ideas, bug reports, and false-positive reports!
Check out our Contributing Guide for local setup and testing standards.
Review our Security Policy to report vulnerabilities responsibly.
Check open issues or submit new ones on our Issue Tracker.
License
MIT © AI Guard Authors. Free and open source forever.
Available Tools
9 toolsai_guard_check_integrityARead-only
Report checks weakened by current Git changes compared with a base: new eslint-disable/@ts-ignore, skipped, focused or removed tests, lowered ESLint/TypeScript/coverage settings, removed or non-blocking CI steps, Git hook bypasses. tier "high" = precise weakening (hasBlockingFindings=true means the change should not be considered done until each is fixed or explained to the user); tier "advisory" needs judgment and never blocks. Read-only; does not modify files.
Inputs: base, staged, maxFindings. Returns: base, clean, errors, status, +9 more
ai_guard_check_packageARead-onlyIdempotent
Check npm packages before installing or running them (npm install, npx). Reports names that do not exist (often invented by assistants), look-alikes of popular packages, new or rarely downloaded packages, install scripts, deprecations, npm security placeholders and releases published in the last day. verdict "block" means do not install; use the package named in similarTo or check the name. A fresh-release finding means ask the user or install the previous version. Contacts registry.npmjs.org and api.npmjs.org; packages from a private registry are skipped. Installs nothing.
Inputs: packages (required), freshHours, minAgeDays, minWeeklyDownloads. Returns: errors, status, success, packages, +1 more
ai_guard_fixAIdempotent
Apply AI Guard deterministic autofixes to one JS/TS file. Returns a unified diff and writes nothing unless apply=true.
Inputs: path (required), apply, rules, preset. Returns: diff, file, errors, status, +6 more
ai_guard_rulesARead-only
List rules and preset severities. With preset, also return its enabled rule IDs. With rules (e.g. a ruleId from a finding), return only those rules with description, remediation and docs link.
Inputs: rules, preset. Returns: rules, preset, presets, success, +3 more
ai_guard_scan_agent_configARead-only
Scan agent instructions (CLAUDE.md, AGENTS.md, .cursorrules, Copilot instructions, skills) and MCP/agent config for hidden text, prompt injection, unpinned MCP servers and inline secrets. Use before trusting the instructions in a repository. Does not modify anything.
Inputs: path, maxFindings. Returns: clean, errors, status, servers, +7 more
ai_guard_scan_diffARead-only
Scan current on-disk Git changes, including untracked files, and report tests the change weakened. staged selects paths, not index contents.
Inputs: base, preset, staged, maxIssues, +1 more. Returns: base, clean, errors, issues, +13 more
ai_guard_scan_fileBRead-only
Scan one workspace JS/TS file. Does not modify source.
Inputs: path (required), preset, maxIssues. Returns: clean, errors, issues, preset, +9 more
ai_guard_scan_projectBRead-only
Scan a workspace directory using existing presets and exclusions. Fails on resource limits instead of silently truncating.
Inputs: path, preset, maxFiles, maxIssues. Returns: clean, errors, issues, preset, +9 more
ai_guard_verify_changeARead-only
One verdict for the current Git change: lint findings it introduced, focused/skipped/removed/weakened tests, and agent-config issues. pass=false means fix blocking first; report every item in disclosures to the user. Does not modify source.
Inputs: base, preset, maxFindings. Returns: base, pass, errors, status, +9 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 9 tools
Most tools have distinct purposes, but scan_diff, check_integrity, and verify_change all operate on the current Git change and report weakened tests/checks, making selection dependent on subtle wording. The other tools (scan_file, scan_project, check_package, rules, scan_agent_config, fix) are clearly distinguishable.
All tools share the ai_guard_ prefix and most follow a predictable verb_noun pattern such as scan_file, check_package, and verify_change. Minor deviations are rules (noun-only) and fix (verb-only), but the overall convention is readable and consistent.
Nine tools is well within the ideal range and each maps to a meaningful stage of the guard workflow: scan, check, verify, inspect rules, and fix. The set is neither thin nor bloated.
The surface covers file, diff, and project scanning, package safety, agent-config inspection, rules discovery, change verification, and deterministic autofix. Minor gaps remain around managing baselines/configuration and applying fixes beyond a single file, but core workflows are covered.
Maintenance
Related MCP Connectors
Checks AI-written code for leaked keys and made-up packages, on your machine. Never uploads code.
Lets coding agents check their own code for leaked secrets, risky dependencies and AI-code mistakes
Security scanner for AI agents: prompt injection, leaked secrets, PII, and SSRF-risk URL detection.
Security scanner for AI-written code: SAST, secrets, dependencies, IaC, containers and DAST.
Related MCP Servers
- AlicenseAqualityDmaintenanceAgent-native "safe to ship?" security gate for AI-generated code. Uses real parsers and inter-rocedural taint analysis (JS/TS, Python, Go) to flag the classes AI coding agents get wrong — secrets, SQL injection, SS, SSRF, path traversal, command injection, weak JWT/CORS — and ranks findings by confidence. Exposes a scan tool over MCP.110 npm2MIT
- AlicenseAqualityBmaintenanceLocal-first, zero-egress security scanner for AI-generated / "vibe-coded" JS/TS. Bundles Opengrep, Gitleaks & Trivy behind one CWE-keyed schema and adds AI-code-specific checks (client-side secret exposure, Supabase RLS, prompt-injection & LLM-output XSS sinks). No account, no telemetry.10146 npm51Apache 2.0
- AlicenseNot gradedqualityCmaintenanceEnables AI editors such as Cursor, Claude Code, Windsurf and VS Code to scan a project for common AI-introduced security mistakes — leaked keys, open Supabase/Firebase data, missing auth, unverified Stripe webhooks, SQL injection and more — and return findings with exact fix instructions. It also provides a guided prompt that walks an agent through fixing critical issues one by one and verifying each fix by re-scanning, without ever editing files or rotating keys itself.2MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI coding agents to scan projects or changed files for risky leftovers like hallucinated packages, exposed secrets, truncated code, and unfinished stubs, and to verify that packages exist before installing them.7 npmMIT