ai-rules

fjb040911活跃维护

给 AI 编码助手套上项目规则约束,防止 Cursor、Windsurf、Copilot 乱改架构、UI 库和设计模式,解决 AI 开发中的架构腐化问题。

ai-rules is a governance framework designed to solve "Architectural Decay" in AI-driven development. It forces AI Agents (Cursor, Windsurf, Copilot) to respect your project's boundaries, UI libraries, and design patterns.

暂无版本424star14fork同步于 2026-11-09 05:53 UTC

怎么上手

由 README 提炼,执行前请确认
npm install -g ai-law
ai-law init
ai-law doctor
ai-law audit
硬件要求按 README 说明

README 未说明硬件要求;基础 skill 无需 Node.js,可选 ai-law CLI 需 Node.js 18+

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把团队架构与安全约定变成可复用规则,让 AI 编码代理按规则审查并修复代码

给 AI 编码助手套上项目规则约束,防止 Cursor、Windsurf、Copilot 乱改架构、UI 库和设计模式,解决 AI 开发中的架构腐化问题。

核心能力

  • 用带意图、要求和修复指引的版本化 Markdown 规则约束代理
  • 用 config.json 路径别名把规则映射到真实目录布局
  • 收集本地匹配证据并附文件位置与稳定证据引用
  • 生成带规则 ID、严重级别和报告 schema 的审查提示词
  • 按 issue ID 生成聚焦修复提示词,支持 compact/balanced/full 上下文预算

容易踩的坑

audit 前需手动编辑 .ai-rules/config.json 把路径别名映射到仓库真实目录;audit 只生成提示词,需交给 AI 代理审查并把最终 JSON 存为 ai-rule-report.json 才能 validate-report 和 fix;Python、Java、C/C++ 本版本无本地 AST 后端,相关检查仅靠 AI 推理;Claude Code 工作流需在 .claude/settings.local.json 的 permissions.allow 中加入 Bash(ai-law:*) 否则执行被拦截

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    AI-RULES

    Give your AI coding agent project rules it can review and repair against.

    AI-RULES turns your team's architecture and safety conventions into reusable rules, local code evidence, and focused audit and fix prompts. Keep those conventions in your repository and use them across AI coding tools.

    Install the Agent skill directly, or use the optional ai-law CLI (Node.js 18+). MIT licensed.

    English | 简体中文

    Use in agent chat (no Node.js required)

    The standalone ai-rules skill uses the agent's file tools for initialization, project-rule review, and selected repairs. Node.js and the CLI are optional for users; an existing ai-law engine can add AST evidence and deterministic validation.

    Ask a skills-capable agent:

    Install the skills/ai-rules skill from https://github.com/fjb040911/ai-rules
    

    Installation locations and refresh behavior depend on the host. Without an installer, copy the complete skills/ai-rules folder into a supported skill directory. A bare name does not guarantee discovery. Structured question UI is also host-dependent; conversational questions are the fallback.

    Then work in your target project:

    Use ai-rules to initialize this project
    Use ai-rules to initialize automatically with recommended settings
    Use ai-rules to check code
    Use ai-rules to review the current changes
    Use ai-rules to fix ISSUE-001
    

    Initialization preserves existing rules and configuration and adapts aliases to actual paths. Review writes ai-rule-report.json and .ai-rules/cache/skill-review-coverage.json, documenting coverage and limitations without modifying source code. Agent consistency checks are not equivalent to CLI validation.

    Bundled assets provide 14 rendered, flattened templates in English and Simplified Chinese. Maintainers run npm run build:skill after changing source templates; npm pack also rebuilds assets. Build-time Node.js is not a runtime dependency of the basic skill.

    Why AI-RULES

    An AI agent can produce working code that still breaks your project's conventions. A React component makes a network request directly. A Spring controller reaches into a repository. A driver drops an error-path cleanup. A model pipeline silently changes precision.

    Writing those expectations into a project rule set gives each review a concrete starting point. AI-RULES compiles the rules, collects supported local evidence, and builds a prompt with rule IDs, severity, and a report schema.

    What you needWhat AI-RULES provides
    Stop repeating the same review commentsVersioned Markdown rules with intent, requirements, and repair guidance
    Review against your actual directory layoutPath aliases in config.json, with warnings for missing paths
    Investigate findings with concrete evidenceLocal matches with file locations and stable evidence references
    Carry an audit into a focused repairA JSON report that can be validated and used to generate issue-specific fix prompts
    Keep large reviews manageableContext modes, evidence budgets, and review focus by rule or scope

    Start with a built-in template, adapt its paths, and add the conventions your team already uses in review.

    Run your first review

    Install the CLI:

    npm install -g ai-law
    

    Inside the project you want to review:

    ai-law init
    ai-law doctor
    ai-law audit
    

    init lets you select a language and project template. Before auditing, open .ai-rules/config.json and map its paths to your repository. doctor checks configuration, rule references, and installed skills.

    audit prints a generated prompt and attempts to copy it to your clipboard. Give that prompt to your AI coding agent. Ask the agent to review the code and save its final JSON as ai-rule-report.json in the project root.

    Once the report exists:

    ai-law validate-report
    ai-law fix --issueId ISSUE-001
    

    Use an issue ID from your report. fix generates a repair prompt; your AI agent applies the edits. Review the changes and run the project's tests.

    Each finding ties the problem to a rule and gives the next repair step a stable issue ID.

    A fix prompt brings together the selected issue, rule requirements, and available evidence.

    Use it inside your AI coding tool

    Generate reusable workflows with:

    ai-law setup --provider claude-code --write
    

    Replace claude-code with cursor, codex, copilot, or custom for the corresponding layout.

    WorkflowCLI actionReport
    law-auditai-law auditai-rule-report.json
    law-fixai-law fix --issueId <ISSUE_ID>Uses the architecture audit report
    law-logicai-law inspect-logic --profile logicai-logic-report.json
    law-nativeai-law inspect-logic --profile nativeai-native-report.json
    law-modelai-law inspect-logic --profile modelai-model-report.json

    Invoke the generated /law-* workflows where your client supports them. For tools that require explicit skill selection, select the matching skill. Generic workflows can also be followed manually.

    ProviderGenerated files
    claude-code.claude/skills/law-*/SKILL.md
    cursor.cursor/skills/law-*/SKILL.md
    codex$CODEX_HOME/skills/law-*/SKILL.md, defaulting to ~/.codex/skills/
    copilot.github/prompts/law-*.prompt.md
    custom.ai-rules/skills/law-*/SKILL.md

    Re-run setup --write to update managed workflow content. It also removes legacy command files for the selected provider and records the installation in .ai-rules/cache/skill-manifest.json. doctor checks that the recorded files still exist.

    Claude Code workflows use dynamic CLI output injection. Setup adds Bash(ai-law:*) to .claude/settings.local.json under permissions.allow. If execution is blocked, check the client's permissions settings.

    Templates for your stack

    Framework templates inherit their base rules through extends. You can add project rules and tune the enabled set.

    Project familyTemplatesSelected review topics
    Frontendfrontend-base, react-js, react-ts, vueUI/service boundaries, unsafe HTML, dynamic execution, hooks, list keys, Vue props and computed purity
    Desktop and extensionselectron, vscode-extensionDesktop and extension-host conventions built on the frontend foundation
    Node.jsnodejs-base, express, nestjsTransport/service/repository layering, async errors, sensitive logging, outbound timeouts
    Python and AI modelspython-base, python-fastapiException handling, subprocess boundaries, timeouts, input/output contracts, model and checkpoint consistency
    Javajava-base, java-springThin controllers, input validation, security configuration, transaction boundaries, sensitive logging
    C / C++c-cppResource lifetime, critical return values, lock ordering, DMA lifecycles, firmware/protocol validation

    Rules provide both locally detectable patterns and guidance for AI reasoning. A topic listed here does not imply complete automatic detection.

    Frontend AST evidence

    Selected JS, TS, React, and Vue rules use parser-backed local evidence. Current checks include:

    • Direct fetch() or axios.* calls in UI code
    • innerHTML and dangerouslySetInnerHTML usage
    • Dynamic execution with eval() or Function()
    • React and Vue list keys based on loop indexes
    • Vue props mutation in supported .vue script blocks
    • TypeScript any usage in TS/TSX files

    Python, Java, and C/C++ do not have a supported local AST backend in this release. Unsupported AST checks stay AI-guided rather than invoking a frontend parser.

    Review logic, native code, and model pipelines

    Choose a profile for the risks you want to investigate:

    ai-law inspect-logic --profile logic
    ai-law inspect-logic --profile native
    ai-law inspect-logic --profile model
    
    ProfileReview focus
    logicAuthorization, ownership, state transitions, replay/idempotency, tenant isolation, workflow bypasses
    nativeOwnership/lifetime, critical returns, lock protocols, parser boundaries, privileged operations, cleanup and rollback
    modelShape/dtype/device contracts, precision fallback, checkpoint compatibility, train/eval mode, tokenizer and postprocessing consistency

    Without --profile, C/C++ defaults to native, Python templates to model, and other stacks to logic. Use an explicit profile when you need a specific report filename.

    These commands assemble review prompts and report templates. The AI agent investigates the source and writes the report. Logic/native/model reports use a separate risks schema; validate-report and fix currently consume ai-rule-report.json.

    Keep review context small

    Both audit and inspect-logic default to balanced. Rules in the selected review scope retain their requirements, including rules without local matches. Evidence is prioritized by rule severity.

    ModeInitial rule detailEvidence rulesMatches/candidates per ruleSnippet/description characters
    compactRule summaries62160
    balancedSummaries; audit expands rules with selected evidence123240
    fullExpanded rule detailsUnlimited by defaultUnlimited by defaultUnlimited by default
    ai-law audit --context-mode compact
    ai-law audit --rule ARCH-101 --context-mode full
    ai-law audit --scope ui --max-evidence-rules 8 --max-matches-per-rule 2 --max-snippet-chars 180
    ai-law inspect-logic --profile native --context-mode compact
    

    --rule and --scope match exact enabled rule IDs and scope names. You can combine them. Review individual rules in full mode when you need more evidence.

    Budgets affect prompt output. --json and cached artifacts keep the full collected data for validation and fixes. Prompts disclose omitted evidence; omitted matches do not establish that the code is safe. These limits control evidence size rather than enforce a hard token ceiling.

    Generated skills use the prompt first and read source files or detailed rule evidence on demand. Refresh older skills with setup --write. Pasting full cache files alongside the prompt repeats much of the same context.

    Adapt the rules to your repository

    The generated files have separate jobs:

    FilePurpose
    .ai-rules/.ai-rules.mdRule definitions, intent, detection hints, and repair guidance
    .ai-rules/rules-config.jsonEnabled rules, scopes, severity threshold, inheritance, and scan options
    .ai-rules/config.jsonProject-specific overrides, including paths and parser settings
    .ai-rules/cache/Generated context, evidence, validator output, and report templates

    Local config.json overrides the merged rules configuration. Adjust aliases and include/exclude patterns to match the files you want reviewed.

    Directory aliases

    A repository with a small directory structure can map several aliases to the same directory:

    {
      "pathAliases": {
        "@components": "src",
        "@services": "src",
        "@apiClient": "src"
      }
    }
    

    Map each alias used by your chosen template to the corresponding real directory. If you remove an alias, update rules that reference it. doctor and audit warn when configured paths do not exist.

    Aliases resolve in rule context and supported detection paths. context identifies supporting files or directories; it does not define the entire review target. Supported detect.where expressions and scan include/exclude patterns determine local evidence collection.

    Write a project rule

    ### RULE: CUSTOM-101
    severity: FATAL
    scope: ui
    intent: UI components must keep network requests in the service layer.
    detect:
      regex: "fetch[(]|axios[.]"
      where: filePath in @components/**
    fix: Move request logic into a service.
    prompt:
      violation: Direct request logic found in the UI layer.
      requirement: UI components must delegate requests to a service.
      solution: Use a shared client from the service layer.
    context:
      - @services
      - @apiClient
    

    Enable the rule ID and its scope in rules-config.json, then run doctor. Use stable rule IDs so reports and repairs can reference the same convention.

    Configure thresholds and exceptions

    {
      "thresholds": {
        "maxFunctionLines": 80,
        "maxParamsCount": 5
      },
      "exceptions": {
        "ARCH-101": ["src/integrations/**"],
        "SEC-*": ["__mocks__/**", "**/*.stories.tsx"]
      }
    }
    

    Active count rules can reference these thresholds. Exceptions suppress matching files for supported local evidence checks.

    Configure frontend parsing

    {
      "ast": {
        "provider": "babel",
        "target": "react",
        "useProjectConfig": true,
        "parserOptions": {
          "sourceType": "module",
          "plugins": ["jsx", "typescript"]
        }
      }
    }
    

    Parser settings merge in this order: template defaults, detected project configuration such as tsconfig.json or Babel configuration, then local overrides. Keep parser-specific configuration in its existing project files and use config.json for AI-RULES overrides.

    Evidence and report boundaries

    Detection typeCurrent behavior
    regexLocal pattern matches
    import / includeLocal dependency/include evidence
    countLocal function-lines and params-count evidence
    Supported frontend ast checksParser-backed local evidence
    semantic and unsupported ast checksAI-guided review

    The CLI compiles context locally and generates prompts; it does not call a hosted AI model to complete the audit. Your chosen AI tool determines how the supplied project context is processed.

    Local evidence is a review candidate. AI review still needs source inspection and cross-file reasoning. Report validation checks structure and available rule/evidence references; it does not prove a finding is correct. Keep your tests, linters, security tools, and code review in the workflow.

    audit writes these artifacts by default:

    .ai-rules/cache/audit-context.json
    .ai-rules/cache/rule-ir.json
    .ai-rules/cache/rule-validator.json
    .ai-rules/cache/ai-rule-report.template.json
    

    The AI-generated ai-rule-report.json uses schema version 1.1, a project summary, and a violations array. Findings have unique issueId values, rule IDs, severity, locations, repair guidance, and optional evidence references. validate-report normalizes compatible legacy formats and checks required fields, duplicate IDs, and available rule/evidence relationships.

    CLI reference

    ai-law init
    ai-law audit [--locale <code>] [--json] [--summary] [--dry-run] [--dump-context]
    ai-law inspect-logic [--locale <code>] [--profile logic|native|model] [--json] [--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 -h
    

    Prompt options for audit and inspect-logic:

    --context-mode compact|balanced|full
    --rule <rule_id>
    --scope <scope>
    --max-evidence-rules <n>
    --max-matches-per-rule <n>
    --max-snippet-chars <n>
    

    Use audit --summary for coverage counts, audit --dry-run for the local/AI review plan, and audit --json for full structured context. --dump-context explicitly rewrites the cache. doctor --strict treats warnings as failures.

    Languages

    Rule and prompt locales include en, zh-CN, zh-TW, ja, ko, es, and fr. English and Simplified Chinese have complete locale files. The remaining locales are partial; missing strings fall back to English.

    Choose a language during initialization or pass --locale when generating prompts.

    The rules compiler direction

    AI-RULES compiles project-authored Markdown into normalized Rule IR, validator decisions, evidence references, and repair hints. Audit and fix workflows share that rule model.

    The next stages are described in the version evolution plan. The current CLI already produces these artifacts for agents; broader execution and enforcement remain roadmap work.

    Development and design

    npm install
    npm test
    node cli/src/index.js --help