ai-law
v0.6.4
Published
AI-RULES CLI for architecture-aware AI coding governance
Readme
AI-RULES
AI-RULES is a rule-aware CLI for AI-assisted coding governance. It turns project rules in Markdown into structured rule metadata, lightweight local evidence, and deterministic audit/fix prompts so AI coding agents follow your architecture, design patterns, and UI standards more consistently.
Why AI-RULES
AI coding agents are powerful, but they often write "generally correct" code instead of code that fits your repository's real architecture. They may call data layers from UI components, bypass service boundaries, ignore project-specific directories, leak secrets in logs, or return audit reports in shapes that downstream repair flows cannot reliably consume.
AI-RULES gives those agents a project-local operating contract before code reaches review, CI, or merge gates. It packages your engineering standards into .ai-rules.md, rules-config.json, and config.json, then turns them into rule-aware audit and fix prompts with enabled rules, severity thresholds, local evidence, path aliases, exceptions, and repair guidance.
The practical benefits are:
- AI-generated code is more likely to follow your architecture and layering rules from the start.
- Reviews become faster because repeated violations are encoded once instead of explained every time.
- Prompts become more deterministic because rules, paths, severity, and report schema are structured.
- Non-standard repository layouts are handled through
config.jsonpath aliases instead of editing every rule. - Audit and repair workflows become more stable across Codex, Cursor, Claude Code, or any prompt-driven coding setup.
In short: repository governance tools protect the merge boundary; AI-RULES guides the AI while it is still writing and repairing code.
What It Does
- Initializes reusable rule templates for different stacks
- Parses
.ai-rules/.ai-rules.mdandrules-config.json - Merges
extendschains for rules and config - Collects lightweight local evidence for
regexandimport/includestyle rules - Collects lightweight local evidence for minimal
countrules such asfunction-linesandparams-count - Supports config-level
thresholdsfor active parameterized rule behavior - Supports config-level
exceptionsto suppress known-safe files per rule pattern - Generates rule-aware audit prompts instead of static prompt text
- Normalizes and validates
ai-rule-report.json - Generates stronger fix prompts using both the report and local rule metadata
High-Value Built-In Coverage
Current templates already cover a first batch of high-priority engineering rules in addition to the original architecture baseline.
Frontend / React / Vue
- UI code must not call network or data layers directly
- Raw HTML injection via
innerHTML/dangerouslySetInnerHTMLis flagged - Semantic XSS flows from untrusted rich content into DOM sinks are called out
- Dynamic execution via
eval()/Function()is flagged - Hardcoded frontend secrets / API keys are flagged
- Third-party HTML script tags without SRI are flagged
- Hooks must follow React hook call rules
- React lists should not use array index as
key - React effect-driven remote requests should use stable dependency control
- Vue
computedmust stay pure - Vue props must not be mutated directly
- Vue lists should not use loop index as
:key - Direct DOM access in Vue components is discouraged
Python Base / FastAPI
- Bare
exceptand broad swallowed exceptions are discouraged - Mutable default arguments are flagged
- Weak password hashing algorithms such as MD5/SHA1 are flagged
- Logging patterns that may leak sensitive values are flagged
- External HTTP calls should define explicit timeouts
- Python functions should stay below configured line-count thresholds
- Python function signatures should stay below configured parameter-count thresholds
- FastAPI routes should not access repositories or DB sessions directly
- SQL built through interpolation/concatenation in FastAPI code is flagged
- FastAPI request logging must avoid tokens, cookies, auth headers, and raw credentials
- FastAPI endpoints should use Pydantic input models
- FastAPI endpoints should declare explicit
response_model - List-style FastAPI endpoints should enforce pagination or limit bounds
- Async paths should avoid blocking HTTP clients and
time.sleep
Java / Spring
- Controllers should not depend on repositories directly
- Controllers should stay thin and avoid business branching/orchestration
@Validshould guard@RequestBodyinputs- Overly permissive CORS is flagged
- Exception handlers that may leak stack traces are flagged
- Logging patterns that may expose credentials are flagged
- Sensitive Spring endpoints should have explicit authn/authz coverage
- Overly permissive Spring Security config such as broad
permitAll()or global protection disablement is flagged - Write paths should define transaction boundaries
@Transactionalshould not live on controllers- Write-oriented service logic should keep explicit transaction semantics
- Loops should not perform unbounded remote calls without batching, timeouts, and concurrency control
- Business exceptions should stay distinct from system/infrastructure failures
Current Scope
AI-RULES is not a full static analysis engine yet.
regexandimport/includedetection can collect local evidence- minimal
countdetection can collect local evidence forfunction-linesandparams-count astandsemanticrules are still AI-guided and treated asai-only- The CLI helps structure context and outputs, while the AI still makes the final audit decision
Language Support
Built-in locale files are available for:
zh-CN: Simplified Chinese, completeen: English, completezh-TW: Traditional Chinese, partial, falls back to Englishja: Japanese, partial, falls back to Englishko: Korean, partial, falls back to Englishes: Spanish, partial, falls back to Englishfr: French, partial, falls back to English
The partial locales currently translate the core template names and prompt instructions. Missing rule-level text automatically falls back to English so new languages remain usable while translations are expanded over time.
Installation
Requires Node.js >=18.
Install globally:
npm install -g ai-lawOr for local development in this repository:
npm install
npm testQuick Start
cd your-project
# 1. Initialize rules in the current project
ai-law init
# 2. Check that rules/config are valid
ai-law doctor
# 3. Generate a rule-aware audit prompt
ai-law audit
# 4. `audit` also writes local helper files by default
# - .ai-rules/cache/audit-context.json
# - .ai-rules/cache/ai-rule-report.template.json
# 5. Or inspect the structured audit context directly
ai-law audit --json
# 6. Optionally force a fresh context dump
ai-law audit --dump-context
# 7. After your AI tool produces ai-rule-report.json, validate it
ai-law validate-report
# 8. Generate a fix prompt for one issue
ai-law fix --issueId ISSUE-001
# 9. Or generate a grouped fix prompt for the whole report
ai-law fix --all --group-by-ruleWorkflow
1. Initialize
ai-law init creates a .ai-rules/ directory in your project and materializes the selected template.
Example layout:
.ai-rules/
├── .ai-rules.md
├── rules-config.json
├── config.json
├── base/
│ ├── .ai-rules.md
│ ├── rules-config.json
│ └── config.json
└── cache/
├── audit-context.json
└── ai-rule-report.template.json2. Validate Local Rule Setup
ai-law doctor validates:
.ai-rules/existsrules-config.jsoncan be loaded and merged throughextends- the rules file can be parsed
enabledRuleIdspoint to real rules- rule scopes match config scopes
- required rule fields exist
Use ai-law doctor --strict to treat warnings as failures.
3. Generate Audit Context
ai-law audit now reads the current project rules and builds a prompt from:
- merged config
- parsed rules
- enabled rule IDs
- local evidence candidates
- strict report schema requirements
Useful variants:
ai-law audit --locale zh-CN
ai-law audit --json
ai-law audit --summary
ai-law audit --dry-run
ai-law audit --dump-context--json prints the structured audit context instead of a prompt.
By default, ai-law audit writes:
.ai-rules/cache/audit-context.json.ai-rules/cache/ai-rule-report.template.json
Use the generated prompt with your AI tool, then save the AI result as ai-rule-report.json in the project root.
--dump-context forces a fresh write of .ai-rules/cache/audit-context.json.
--summary prints enabled-rule counts, local-vs-AI coverage, suppressed files, and configured thresholds.
--dry-run prints include/exclude patterns, rule IDs that can run locally, AI-only rule IDs, and active exception patterns.
4. Validate The AI Report
After your AI tool returns ai-rule-report.json, run:
ai-law validate-reportThis command normalizes legacy or drifted report shapes into a stable structure and checks for issues like:
- missing
issueId - missing
ruleId - duplicate
issueId - invalid
severity
You can inspect the normalized report with:
ai-law validate-report --json5. Generate Fix Prompts
ai-law fix now combines:
- normalized report data
- local rule metadata from
.ai-rules - rule intent / requirement / fix guidance
- context assets
- report evidence and snippets when present
Examples:
ai-law fix --issueId ISSUE-001
ai-law fix --id ARCH-101
ai-law fix --all
ai-law fix --all --group-by-ruleRule Model
Rules are defined in .ai-rules.md using RULE blocks. The CLI currently parses fields such as:
RULEseverityscopeintentfixdetectpromptcontextextends
Example:
### RULE: ARCH-101
severity: FATAL
scope: ui
intent: UI components must not initiate network requests directly.
detect:
regex: "fetch\\(|axios\\."
where: filePath in src/components/**
fix: Move request logic into a service layer.
prompt:
violation: Detected direct request logic in UI layer.
requirement: UI components must not contain request logic.
solution: Move requests to a service and reuse shared clients.
context:
- src/services/
- src/api/client.tsProject Path Config
Templates can provide an optional .ai-rules/config.json file for user-specific project layout overrides. This file is merged on top of rules-config.json, so users can adjust directory conventions without editing every rule.
Example:
{
"pathAliases": {
"@controller": "app/controllers",
"@service": "app/services",
"@repository": "app/repositories",
"@config": "app/config"
}
}Rules can reference those aliases in context, detect.where, detect.import, and detect.include:
detect:
include: "@repository/**"
where: filePath in @controller/**
context:
- @serviceAt audit/fix time, the CLI resolves aliases before collecting evidence or building prompts.
ai-law doctor and ai-law audit warn prominently when a configured alias points to a path that does not exist. If this happens, open .ai-rules/config.json and adjust pathAliases to match your repository layout.
Detection Support
Current support in the CLI:
detect.regex: local evidence collection supporteddetect.import: local evidence collection supporteddetect.include: local evidence collection supporteddetect.ast: AI-only for nowdetect.semantic: AI-only for now
This means the CLI can attach concrete local evidence for some rules, while still allowing AI-guided review for higher-level semantic constraints.
The current templates intentionally mix:
- fast local rules for obvious anti-patterns
- semantic AI-guided rules for higher-level architectural or transactional reasoning
Config Extensions
The config model now supports two rule-aware extensions:
thresholds
Used for configurable numeric limits that active local count rules can reference.
Example:
{
"thresholds": {
"maxFunctionLines": 80,
"maxParamsCount": 5,
"maxListLimit": 100
}
}exceptions
Used to suppress known-safe files for matching rule IDs or rule ID patterns during local evidence collection.
Example:
{
"exceptions": {
"ARCH-101": [
"src/integrations/**"
],
"SEC-*": [
"__mocks__/**",
"**/*.stories.tsx"
]
}
}These exceptions currently affect local evidence collection for supported local detect modes.
Report Shape
The audit prompt requests strict JSON with a normalized structure like:
{
"version": "1.1",
"generatedAt": "2026-03-30T12:00:00Z",
"project": {
"cwd": ".",
"stack": "react-ts"
},
"summary": {
"total": 1,
"fatal": 0,
"warn": 1,
"info": 0
},
"violations": [
{
"issueId": "ISSUE-001",
"ruleId": "ARCH-101",
"severity": "WARN",
"confidence": 0.82,
"file": "src/pages/Home.tsx",
"line": 12,
"snippet": "const data = fetch('/api')",
"description": "Direct network request found in UI layer.",
"fixSuggestion": "Move request logic into services.",
"repairPrompt": "Provide a minimal patch...",
"evidence": {
"source": "local-regex",
"matchedBy": "detect.regex"
},
"context": [
"src/services/"
]
}
]
}Templates
Current templates:
frontend-basereact-jsreact-tsvue
python-basepython-fastapi
java-basejava-spring
c-cpp
Branch templates inherit from base templates through extends.
CLI Commands
ai-law init
ai-law audit [--locale <code>] [--json] [--summary] [--dry-run] [--dump-context]
ai-law fix --issueId <issue_id>
ai-law fix --id <rule_id>
ai-law fix --all [--group-by-rule]
ai-law doctor [--strict]
ai-law validate-report [--json] [--path <file>]
ai-law setup [--locale <code>] [--provider <name>] [--write]
ai-law -v
ai-law -hDevelopment Notes
Current implementation layers:
cli/src/core/config: config loading andextendsmergecli/src/core/rules: rule parsing and validationcli/src/core/evidence: local evidence collectioncli/src/core/prompt: audit prompt assemblycli/src/core/report: report normalization and schema
Run tests:
npm testDocs
- English design spec: design/design-spec-en.md
- 中文设计文档: design/design-spec-zh.md
