@aigis-ai/cli 1.0.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/SKILL.md +20 -55
  3. package/bin/aigis.js +446 -59
  4. package/cli-python/LICENSE +21 -0
  5. package/cli-python/README.md +32 -0
  6. package/cli-python/aigis_cli/SKILL.md +70 -0
  7. package/cli-python/aigis_cli/__init__.py +3 -0
  8. package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
  9. package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
  10. package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
  11. package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
  12. package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
  13. package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
  14. package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
  15. package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
  16. package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
  17. package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
  18. package/cli-python/aigis_cli/annotate.py +45 -0
  19. package/cli-python/aigis_cli/auto_verify.py +518 -0
  20. package/cli-python/aigis_cli/build.py +470 -0
  21. package/cli-python/aigis_cli/checksum.py +22 -0
  22. package/cli-python/aigis_cli/classify.py +192 -0
  23. package/cli-python/aigis_cli/cli.py +618 -0
  24. package/cli-python/aigis_cli/content/index/audit-scan.md +217 -0
  25. package/cli-python/aigis_cli/content/index/auto-verify-rules.json +439 -0
  26. package/cli-python/aigis_cli/content/index/context-rules.json +90 -0
  27. package/cli-python/aigis_cli/content/index/frameworks.md +82 -0
  28. package/cli-python/aigis_cli/content/index/guardrails.json +23 -0
  29. package/cli-python/aigis_cli/content/index/taxonomy.md +81 -0
  30. package/cli-python/aigis_cli/content/resolvers/triggers.json +229 -0
  31. package/{content/implement → cli-python/aigis_cli/content/skills/areas}/audit-logging.md +5 -0
  32. package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +200 -0
  33. package/cli-python/aigis_cli/content/skills/areas/input-validation.md +380 -0
  34. package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +189 -0
  35. package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +246 -0
  36. package/cli-python/aigis_cli/content/skills/core.md +62 -0
  37. package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +202 -0
  38. package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +169 -0
  39. package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +167 -0
  40. package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +86 -0
  41. package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +54 -0
  42. package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +39 -0
  43. package/cli-python/aigis_cli/content/templates/risk-characterization.md +34 -0
  44. package/cli-python/aigis_cli/content/templates/third-party-assessment.md +41 -0
  45. package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +13 -0
  46. package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +13 -0
  47. package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +13 -0
  48. package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +12 -0
  49. package/cli-python/aigis_cli/content/verify/checklist-explainability.md +13 -0
  50. package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +13 -0
  51. package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +14 -0
  52. package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +16 -0
  53. package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +13 -0
  54. package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +14 -0
  55. package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +14 -0
  56. package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +13 -0
  57. package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +12 -0
  58. package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +13 -0
  59. package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +13 -0
  60. package/cli-python/aigis_cli/fetch.py +232 -0
  61. package/cli-python/aigis_cli/init_ide.py +159 -0
  62. package/cli-python/aigis_cli/keywords.py +73 -0
  63. package/cli-python/aigis_cli/search.py +69 -0
  64. package/cli-python/aigis_cli.egg-info/PKG-INFO +59 -0
  65. package/cli-python/aigis_cli.egg-info/SOURCES.txt +56 -0
  66. package/cli-python/aigis_cli.egg-info/dependency_links.txt +1 -0
  67. package/cli-python/aigis_cli.egg-info/entry_points.txt +2 -0
  68. package/cli-python/aigis_cli.egg-info/requires.txt +6 -0
  69. package/cli-python/aigis_cli.egg-info/top_level.txt +1 -0
  70. package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
  71. package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
  72. package/cli-python/pyproject.toml +49 -0
  73. package/content/index/audit-scan.md +21 -207
  74. package/content/index/auto-verify-rules.json +439 -0
  75. package/content/index/context-rules.json +90 -0
  76. package/content/resolvers/triggers.json +229 -0
  77. package/content/skills/areas/audit-logging.md +176 -0
  78. package/content/skills/areas/bias-monitoring.md +172 -0
  79. package/content/skills/areas/confidence-scoring.md +180 -0
  80. package/content/skills/areas/data-integrity.md +257 -0
  81. package/content/skills/areas/explainability.md +174 -0
  82. package/content/skills/areas/fallback-patterns.md +200 -0
  83. package/content/skills/areas/human-oversight.md +220 -0
  84. package/content/skills/areas/input-validation.md +380 -0
  85. package/content/skills/areas/monitoring.md +207 -0
  86. package/content/skills/areas/output-sanitization.md +183 -0
  87. package/content/skills/areas/pii-handling.md +189 -0
  88. package/content/skills/areas/prompt-security.md +153 -0
  89. package/content/skills/areas/rag-security.md +230 -0
  90. package/content/skills/areas/rate-limiting.md +246 -0
  91. package/content/skills/areas/supply-chain.md +193 -0
  92. package/content/skills/core.md +62 -0
  93. package/content/skills/infrastructure/logging.md +202 -0
  94. package/content/skills/infrastructure/rate-limiting.md +169 -0
  95. package/content/skills/infrastructure/secrets.md +167 -0
  96. package/content/skills/workflows/fastapi-llm.md +86 -0
  97. package/docs/resolvers.md +114 -0
  98. package/lib/auto-verify.js +378 -0
  99. package/lib/build.js +629 -0
  100. package/lib/checksum.js +39 -0
  101. package/lib/fetch.js +164 -9
  102. package/lib/init.js +141 -93
  103. package/lib/keywords.js +92 -130
  104. package/lib/special-recognizers.js +370 -0
  105. package/package.json +1 -1
  106. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  107. package/scripts/bootstrap-step-6-bench.js +85 -0
  108. package/scripts/check-content-sync.js +91 -0
  109. package/scripts/triggers.schema.json +50 -0
  110. package/scripts/validate-triggers.js +176 -0
  111. package/content/implement/fallback-patterns.md +0 -190
  112. package/content/implement/input-validation.md +0 -212
  113. package/content/implement/pii-handling.md +0 -207
  114. package/content/implement/rate-limiting.md +0 -217
  115. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/bias-monitoring.md +0 -0
  116. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/confidence-scoring.md +0 -0
  117. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/data-integrity.md +0 -0
  118. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/explainability.md +0 -0
  119. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/human-oversight.md +0 -0
  120. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/monitoring.md +0 -0
  121. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/output-sanitization.md +0 -0
  122. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/prompt-security.md +0 -0
  123. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/rag-security.md +0 -0
  124. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/supply-chain.md +0 -0
@@ -0,0 +1,86 @@
1
+ ---
2
+ name: workflow-fastapi-llm
3
+ description: Canonical 8-file layout for a FastAPI service that calls an LLM API. Run after `aigis classify` returned a Python/FastAPI system. Maps each governance area to a specific module so wiring is consistent across runs.
4
+ ---
5
+
6
+ # Workflow: FastAPI + LLM
7
+
8
+ This workflow is for: a FastAPI HTTP service that calls a hosted LLM (Anthropic, OpenAI) on user input. If your project is something else (Express, Next.js, agentic loop, RAG service), this workflow does not apply — see `aigis workflow --list` for available workflows.
9
+
10
+ ## Canonical file layout
11
+
12
+ Build into exactly these 8 files.
13
+
14
+ ```
15
+ app/
16
+ ├── main.py # FastAPI routes + minimal orchestration only
17
+ ├── input_validation.py # length limits, sanitize, 3-category injection detection
18
+ ├── pii.py # PII_PATTERNS + redact_pii (5 required classes)
19
+ ├── rate_limit.py # Redis-backed limiter + token budget + Retry-After
20
+ ├── fallback.py # 3-state circuit breaker + per-request kill switch + safe response
21
+ ├── audit.py # trace IDs, structured logs, decision records, fairness fields
22
+ ├── monitoring.py # metrics, drift, incident logging, user feedback endpoint
23
+ └── response.py # response shaping: confidence metadata, explanation, output sanitization
24
+ ```
25
+
26
+ Plus at the project root: `requirements.txt` with pinned `==` versions, `tests/` with at least one smoke test, `docker-compose.yml` (Redis dependency for `rate_limit.py`).
27
+
28
+ ## Area-to-file mapping
29
+
30
+ | Aigis area (run `aigis get <id>` for the procedure) | Lives in |
31
+ |---|---|
32
+ | input-validation | `app/input_validation.py` |
33
+ | pii-handling | `app/pii.py` |
34
+ | rate-limiting | `app/rate_limit.py` |
35
+ | fallback-patterns | `app/fallback.py` |
36
+ | audit-logging | `app/audit.py` |
37
+ | bias-monitoring | `app/audit.py` (fairness fields are part of structured logs) |
38
+ | monitoring | `app/monitoring.py` |
39
+ | confidence-scoring | `app/response.py` |
40
+ | explainability | `app/response.py` |
41
+ | output-sanitization | `app/response.py` |
42
+ | human-oversight | `app/main.py` (decision gate + override surface + action allowlist) |
43
+ | prompt-security | `app/main.py` (`SYSTEM_PROMPT` constant + leakage detection) |
44
+ | supply-chain | `requirements.txt` (pinned versions) + `app/main.py` (`MODEL_VERSION` constant) |
45
+
46
+ If `main.py`'s responsibilities grow past routes + minimal orchestration, pull human-oversight into `app/human_oversight.py` and/or prompt-security into `app/prompt_security.py`. Don't invent other splits — variance hurts maintainability.
47
+
48
+ ## Wiring contracts (cross-file invariants)
49
+
50
+ These are the wiring rules the area-skill verification checkpoints check for. Get them right at build time.
51
+
52
+ 1. **`redact_pii` from `pii.py` is called in two places:**
53
+ - `main.py`, on user input, before passing to the LLM client
54
+ - `audit.py`, on input/output before structured-log emission
55
+ 2. **`call_llm_safely` from `fallback.py` wraps every LLM client call.** Every `client.messages.create` / `client.chat.completions.create` site routes through it. There must be exactly one LLM call site in `main.py` (or in a dedicated `app/llm.py` if you split for clarity); other modules invoke it through the safe wrapper.
56
+ 3. **`ai_system_enabled()` from `fallback.py` is called inside the request handler in `main.py`, on every request.** Not at module load. Not via `@lru_cache`. Not stored on a `settings = Settings()` module-level singleton.
57
+ 4. **The injection guard from `input_validation.py` blocks before the LLM call.** Raises `HTTPException(400)` on detection; the LLM call must come AFTER the guard, never before, never in parallel.
58
+ 5. **`enforce_rate_limit` and `enforce_token_budget` from `rate_limit.py` run in the handler before any sanitize/LLM work.** Cheaper to reject than to sanitize-then-reject.
59
+ 6. **`set_trace_id` middleware from `audit.py` runs on every request.** All log emissions and the `X-Trace-Id` response header use the contextvar.
60
+ 7. **`response.py` shapes the outgoing payload from a parsed model result.** It receives the validated assessment dict and returns the JSON body the client gets — confidence metadata, explanation, sanitized fields, framing. `main.py` calls it at the end of the request handler; `response.py` does not call the LLM and does not log.
61
+
62
+ ## Order of implementation
63
+
64
+ Recommended order (each step ships independently, tests pass at every step):
65
+
66
+ 1. `app/main.py` skeleton with `POST /api/assess-claim` (or your route), `GET /healthz`, no LLM call yet.
67
+ 2. `app/input_validation.py` — `aigis get input-validation` and follow the procedure.
68
+ 3. `app/pii.py` — `aigis get pii-handling` and follow the procedure.
69
+ 4. `app/fallback.py` — `aigis get fallback-patterns` and follow the procedure.
70
+ 5. `app/rate_limit.py` — `aigis get rate-limiting` and follow the procedure.
71
+ 6. Wire the LLM call in `main.py`, routing through `call_llm_safely`.
72
+ 7. `app/audit.py` — `aigis get audit-logging` and `aigis get bias-monitoring`.
73
+ 8. `app/monitoring.py` — `aigis get monitoring`.
74
+ 9. `app/response.py` — `aigis get confidence-scoring`, `aigis get explainability`, `aigis get output-sanitization`. Wire it into `main.py` as the last step before returning.
75
+ 10. Human-oversight + prompt-security work in `main.py` — `aigis get human-oversight`, `aigis get prompt-security`.
76
+ 11. `requirements.txt` and `tests/` — `aigis get supply-chain`.
77
+
78
+ ## Verification per file
79
+
80
+ After building each file, run `aigis verify <area> --auto .`. The scanner returns PASS/FAIL/OVERCLAIM/JUDGMENT for that area's deterministic checks. Fix any FAIL or OVERCLAIM before moving to the next file.
81
+
82
+ ## If your existing codebase uses a different layout
83
+
84
+ Map each responsibility above to your existing modules. The wiring contracts (the numbered list) stay the same — the file names don't. For example, if your codebase already has `services/text_processing.py` for text cleanup, the input-validation procedure can live there; the contract that "an injection guard runs before the LLM call" is what matters, not which file holds it.
85
+
86
+ If the mapping is non-trivial, document it in `docs/aigis-mapping.md` so future contributors and `aigis verify --auto` reviewers can find your modules.
@@ -0,0 +1,114 @@
1
+ # Resolvers
2
+
3
+ Aigis's resolver translates natural-language project descriptions into the trait set classify uses to recommend governance areas. The same source — `content/resolvers/triggers.json` — is consumed by both the CLI (when you run `aigis classify "<description>"`) and embedded in the IDE rules file by `aigis init` (so coding agents apply the same rules in-IDE).
4
+
5
+ ## The two tiers
6
+
7
+ **High-confidence:** the phrase implies the listed traits in essentially every realistic project where it appears. There is no plausible counterexample. Auto-applied — no user prompt.
8
+
9
+ **Low-confidence:** the phrase implies the listed traits only some of the time. There is a realistic project where the phrase appears WITHOUT the trait applying. Requires a confirmation prompt (`yes / no / unsure`); applied only on `yes`.
10
+
11
+ ## Decision rule for new entries
12
+
13
+ If you can describe a real project where the phrase appears but the trait does not apply, the entry is low-confidence. When in doubt, low-confidence — false-positive auto-application is worse than an extra confirmation prompt.
14
+
15
+ ## How the resolver is consumed
16
+
17
+ **CLI flow:**
18
+
19
+ ```
20
+ aigis classify "<plain English description>"
21
+ ```
22
+
23
+ The CLI reads `triggers.json`, scans the description for phrases, and emits:
24
+
25
+ - `high_confidence_matches` — phrases that fired with their traits (auto-applied)
26
+ - `low_confidence_suggestions` — phrases that need confirmation
27
+ - `final_traits` — the resolved trait set after confirmations
28
+
29
+ In a TTY, the CLI prompts interactively for each low-confidence suggestion. With `--json`, with `--confirm <ids>`, with `--reject <ids>`, or in a non-TTY environment (CI, piped), no prompt is shown and low-confidence defaults to rejected unless explicitly confirmed.
30
+
31
+ **Agent flow:**
32
+
33
+ `aigis init <ide>` embeds a checksum-guarded markdown table into the IDE rules file (.cursorrules / SKILL.md / etc.). The agent reads the table inline alongside the user's chat message and applies the same matching rules — auto-apply for high-confidence, ask the user for low-confidence.
34
+
35
+ Both consumers see the exact same table because both load from `triggers.json`. The block in the rules file carries a SHA-256 of the canonical JSON content; running `aigis init` again confirms the block is up to date or surfaces a mismatch.
36
+
37
+ ## Schema
38
+
39
+ ```jsonc
40
+ {
41
+ "version": "1.0",
42
+ "tier_rule": "<the tier rule, inline>",
43
+ "high_confidence": {
44
+ "<phrase>": {
45
+ "traits": ["<trait>", ...],
46
+ "confidence": "high",
47
+ "notes": "<one-line maintainer note>",
48
+ "context_filter": ["web", "agentic"] // OPTIONAL
49
+ }
50
+ },
51
+ "low_confidence": {
52
+ "<phrase>": {
53
+ "traits": ["<trait>", ...],
54
+ "confidence": "low",
55
+ "confirmation_prompt": "<question ending in '(yes / no / unsure)'>",
56
+ "notes": "<one-line maintainer note>",
57
+ "context_filter": ["web"] // OPTIONAL
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ Required fields are enforced by `scripts/validate-triggers.js` (run automatically on PRs touching this file via `.github/workflows/triggers-validation.yml`).
64
+
65
+ - `version`: `N.N` string. Bumped on schema changes, not on entry additions.
66
+ - `tier_rule`: prose, inline at the top so the JSON is self-documenting.
67
+ - `confidence`: redundant with the tier grouping but kept inline so future reorganizations don't restructure entries.
68
+ - `context_filter`: reserved for `aigis get --context` integration; safe to omit.
69
+ - Phrase keys must be sorted case-insensitively within each tier.
70
+
71
+ ## Matching semantics
72
+
73
+ - Case-insensitive substring match against the input description.
74
+ - Multi-word phrases match contiguously.
75
+ - A phrase that appears only inside a longer word does match (e.g., "RAG" matches "RAGgedy"; this is acceptable for the v1.0 ruleset). Submit a high-precision boundary-aware mapping if it bites in practice.
76
+
77
+ ## How to add a mapping
78
+
79
+ 1. Open `content/resolvers/triggers.json`.
80
+ 2. Decide tier per the decision rule above.
81
+ 3. Insert the entry alphabetically within the appropriate tier.
82
+ 4. For low-confidence: write a `confirmation_prompt` that ends with `(yes / no / unsure)` and is answerable in one sentence.
83
+ 5. Run `node scripts/validate-triggers.js` locally before submitting.
84
+ 6. Open a PR using `.github/PULL_REQUEST_TEMPLATE/trigger_mapping.md`.
85
+
86
+ ## The use-case requirement
87
+
88
+ Every trigger PR must include a one-sentence use case: *"I'm building X and I needed this trigger because Y."* This is non-negotiable. We curate based on actual demand, not theoretical taxonomy completeness. PRs without a real use case are closed.
89
+
90
+ ## Curation policy
91
+
92
+ - We accept high-confidence entries only when no plausible counterexample exists.
93
+ - We accept low-confidence entries when the confirmation prompt is answerable yes/no in one sentence.
94
+ - We reject phrases that are too generic to be useful (`AI`, `data`, `users`) — they would fire on every project.
95
+ - We prefer English phrasings with broad reach over jargon.
96
+ - When the same phrase has both a strict and a loose interpretation, low-confidence wins.
97
+
98
+ ## Resolver block in the IDE rules file
99
+
100
+ After `aigis init <ide>`, the rules file (`.cursorrules`, `SKILL.md`, etc.) contains a delimited block:
101
+
102
+ ```
103
+ # --- AIGIS RESOLVER BLOCK START (checksum: <sha256-hex>) ---
104
+ ... rendered table ...
105
+ # --- AIGIS RESOLVER BLOCK END ---
106
+ ```
107
+
108
+ The agent reads this block alongside the user's natural-language description and applies high-confidence matches directly, asking the user for low-confidence matches. The checksum lets `aigis init` detect when the block is stale (after Aigis updates) or has been hand-edited; on mismatch, init refuses unless `--refresh` is passed.
109
+
110
+ The block is regenerated deterministically from `triggers.json`. The rendering algorithm (column widths, ordering) is in `lib/init.js`'s `renderResolverBlock()` function. Two consecutive runs with the same `triggers.json` content produce byte-identical blocks.
111
+
112
+ ## The fixed checksum determinism test
113
+
114
+ `test/checksum-determinism.test.js` pins the SHA-256 of the shipped `triggers.json` as a literal. Any change to the JSON content (even a trailing space) will break the test until the new checksum is committed alongside the JSON change. This catches platform-specific serialization bugs (line endings, BOM) that would otherwise produce silent drift between local and CI builds.
@@ -0,0 +1,378 @@
1
+ /**
2
+ * auto-verify.js — deterministic scanner for `aigis verify <area> --auto <path>`.
3
+ *
4
+ * Philosophy: heuristic regex over the project's source files. Each rule
5
+ * declares patterns; if ANY pattern matches ANY scanned file, the rule is
6
+ * PASS. Some rules are inverse: presence of the pattern = FAIL (anti-pattern
7
+ * detectors, e.g. `eval(`).
8
+ *
9
+ * Out of scope: AST parsing, cross-file flow analysis. Those would raise
10
+ * confidence but also lock the scanner to specific languages. Regex keeps
11
+ * the scanner language-agnostic for Python, JS, TS, and Go without extra
12
+ * infra.
13
+ *
14
+ * Rules live in content/index/auto-verify-rules.json.
15
+ * Special recognizers (overclaim detectors) live in lib/special-recognizers.js.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { REGISTRY: SPECIAL } = require('./special-recognizers');
21
+
22
+ const RULES_PATH = path.join(__dirname, '..', 'content', 'index', 'auto-verify-rules.json');
23
+
24
+ // Default glob: scan typical source files, skip noise.
25
+ const DEFAULT_INCLUDE_EXTS = new Set([
26
+ '.py', '.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.go', '.rb', '.java', '.kt',
27
+ ]);
28
+ const DEFAULT_CONFIG_FILES = new Set([
29
+ 'package.json', 'requirements.txt', 'pyproject.toml', 'Pipfile', 'Pipfile.lock',
30
+ 'poetry.lock', 'go.mod', 'Gemfile', 'Gemfile.lock', 'pom.xml',
31
+ ]);
32
+ const SKIP_DIRS = new Set([
33
+ 'node_modules', '.venv', 'venv', 'env', '__pycache__', '.pytest_cache',
34
+ 'dist', 'build', '.git', '.tox', 'target', 'coverage', '.next', '.nuxt',
35
+ '.cache', '.idea', '.vscode',
36
+ ]);
37
+
38
+ function loadRules() {
39
+ const raw = fs.readFileSync(RULES_PATH, 'utf8');
40
+ const parsed = JSON.parse(raw);
41
+ // Strip _schema_* helper keys so they don't appear as areas
42
+ const cleaned = {};
43
+ for (const [k, v] of Object.entries(parsed)) {
44
+ if (k.startsWith('_schema_')) continue;
45
+ cleaned[k] = v;
46
+ }
47
+ return cleaned;
48
+ }
49
+
50
+ function* walkFiles(rootDir) {
51
+ const stack = [rootDir];
52
+ while (stack.length) {
53
+ const dir = stack.pop();
54
+ let entries;
55
+ try {
56
+ entries = fs.readdirSync(dir, { withFileTypes: true });
57
+ } catch {
58
+ continue;
59
+ }
60
+ for (const entry of entries) {
61
+ const full = path.join(dir, entry.name);
62
+ if (entry.isDirectory()) {
63
+ if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.') && !['', '.'].includes(entry.name)) {
64
+ // Skip hidden and heavy dirs, except allow the root itself
65
+ if (SKIP_DIRS.has(entry.name)) continue;
66
+ if (entry.name.startsWith('.')) continue;
67
+ }
68
+ stack.push(full);
69
+ } else if (entry.isFile()) {
70
+ const ext = path.extname(entry.name);
71
+ if (DEFAULT_INCLUDE_EXTS.has(ext) || DEFAULT_CONFIG_FILES.has(entry.name)) {
72
+ yield full;
73
+ }
74
+ }
75
+ }
76
+ }
77
+ }
78
+
79
+ function loadFiles(rootDir) {
80
+ const files = [];
81
+ for (const p of walkFiles(rootDir)) {
82
+ try {
83
+ const content = fs.readFileSync(p, 'utf8');
84
+ const relPath = path.relative(rootDir, p);
85
+ files.push({ path: relPath, absolutePath: p, content });
86
+ } catch {
87
+ // skip unreadable
88
+ }
89
+ }
90
+ return files;
91
+ }
92
+
93
+ /**
94
+ * Special rule type: exists_path. Returns PASS if any file in the project
95
+ * matches any of the listed path globs. Used for "does a tests/ directory
96
+ * exist" style checks that are filename-based, not content-based.
97
+ */
98
+ function existsPathRule(rule, files) {
99
+ const globs = rule.path_globs || [];
100
+ const evidence = [];
101
+ for (const { path: relPath } of files) {
102
+ for (const g of globs) {
103
+ if (matchesGlob(relPath, g)) {
104
+ evidence.push({ file: relPath, line: 1, snippet: '(path match)', pattern: 0 });
105
+ if (evidence.length >= 5) break;
106
+ }
107
+ }
108
+ if (evidence.length >= 5) break;
109
+ }
110
+ return {
111
+ status: evidence.length > 0 ? 'PASS' : 'FAIL',
112
+ evidence,
113
+ matched_patterns: evidence.length > 0 ? [0] : [],
114
+ total_patterns: 1,
115
+ inverse: false,
116
+ require: 'any',
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Scan files for a rule. Returns { status, evidence, matched } where
122
+ * evidence is an array of { file, line, snippet } for the first handful
123
+ * of matches.
124
+ */
125
+ function scanRule(rule, files) {
126
+ if (rule.type === 'exists_path') {
127
+ return existsPathRule(rule, files);
128
+ }
129
+ // Compile with 'gmi' (case-insensitive) by default. Identifier-level
130
+ // patterns are almost always case-mixed in practice (X-User-Id vs
131
+ // x-user-id; API_KEY vs api_key), and false positives from case-folding
132
+ // on identifier regexes are rare in our use case.
133
+ const flags = rule.case_sensitive ? 'gm' : 'gmi';
134
+ const patterns = (rule.patterns || []).map((p) => {
135
+ try {
136
+ return new RegExp(p, flags);
137
+ } catch {
138
+ return new RegExp(p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), flags);
139
+ }
140
+ });
141
+ const require = rule.require || 'any';
142
+ const inverse = !!rule.inverse;
143
+ const maxEvidence = 5;
144
+
145
+ const matchedPatterns = new Set();
146
+ const evidence = [];
147
+ for (const { path: relPath, content } of files) {
148
+ const lines = content.split('\n');
149
+ for (let i = 0; i < patterns.length; i++) {
150
+ if (matchedPatterns.has(i) && evidence.length >= maxEvidence) continue;
151
+ const re = patterns[i];
152
+ re.lastIndex = 0;
153
+ const matches = content.matchAll(re);
154
+ for (const m of matches) {
155
+ matchedPatterns.add(i);
156
+ if (evidence.length < maxEvidence) {
157
+ // Compute line number from match index
158
+ const before = content.slice(0, m.index);
159
+ const line = (before.match(/\n/g) || []).length + 1;
160
+ const snippet = (lines[line - 1] || '').trim().slice(0, 160);
161
+ evidence.push({ file: relPath, line, snippet, pattern: i });
162
+ }
163
+ if (evidence.length >= maxEvidence) break;
164
+ }
165
+ if (evidence.length >= maxEvidence) break;
166
+ }
167
+ if (evidence.length >= maxEvidence && (require === 'any' || matchedPatterns.size === patterns.length)) break;
168
+ }
169
+
170
+ let passed;
171
+ if (require === 'all') {
172
+ passed = matchedPatterns.size === patterns.length;
173
+ } else {
174
+ passed = matchedPatterns.size >= 1;
175
+ }
176
+ // Inverse rules: presence of pattern = FAIL
177
+ if (inverse) {
178
+ passed = !passed;
179
+ }
180
+
181
+ return {
182
+ status: passed ? 'PASS' : 'FAIL',
183
+ evidence,
184
+ matched_patterns: [...matchedPatterns],
185
+ total_patterns: patterns.length,
186
+ inverse,
187
+ require,
188
+ };
189
+ }
190
+
191
+ function runSpecialRecognizer(name, files, ctx) {
192
+ const fn = SPECIAL[name];
193
+ if (!fn) {
194
+ return {
195
+ flagged: false,
196
+ evidence: [],
197
+ notes: `Unknown recognizer: ${name}`,
198
+ };
199
+ }
200
+ return fn(files, ctx);
201
+ }
202
+
203
+ /**
204
+ * Given a pattern-area id (e.g. 'input-validation') and a project
205
+ * directory, run all AUTO and OVERCLAIM rules and return a structured
206
+ * result the CLI can format.
207
+ */
208
+ function autoVerifyArea(areaId, projectDir) {
209
+ const rules = loadRules();
210
+ const area = rules[areaId];
211
+ if (!area) {
212
+ throw new Error(`No auto-verify rules for pattern area "${areaId}". Known areas: ${Object.keys(rules).join(', ')}`);
213
+ }
214
+
215
+ const files = loadFiles(projectDir);
216
+
217
+ const autoResults = {};
218
+ for (const [checkId, rule] of Object.entries(area.auto || {})) {
219
+ // Optional per-rule file glob override is not implemented here — we scan the
220
+ // default set, then filter by the rule's hint if provided. Simple filter for
221
+ // supply-chain V5 / V3 style where we want e.g. requirements.txt specifically.
222
+ let scanFiles = files;
223
+ if (rule.file_glob) {
224
+ const globs = rule.file_glob.split(',').map((g) => g.trim());
225
+ scanFiles = files.filter((f) => globs.some((g) => matchesGlob(f.path, g)));
226
+ }
227
+ autoResults[checkId] = { ...rule, ...scanRule(rule, scanFiles) };
228
+ }
229
+
230
+ const overclaimResults = {};
231
+ for (const [checkId, entry] of Object.entries(area.overclaim || {})) {
232
+ const recog = runSpecialRecognizer(entry.recognizer, files, {
233
+ rootDir: projectDir, areaId, checkId,
234
+ });
235
+ // An overclaim raises concern only if the corresponding auto rule (also_auto) was PASS.
236
+ const alsoAuto = entry.also_auto;
237
+ let raise = recog.flagged;
238
+ if (alsoAuto && autoResults[alsoAuto] && autoResults[alsoAuto].status !== 'PASS') {
239
+ raise = false; // auto didn't pass, the overclaim question is moot
240
+ }
241
+ overclaimResults[checkId] = {
242
+ desc: entry.desc,
243
+ recognizer: entry.recognizer,
244
+ also_auto: alsoAuto,
245
+ raised: raise,
246
+ flagged: recog.flagged,
247
+ evidence: recog.evidence,
248
+ notes: recog.notes,
249
+ };
250
+ }
251
+
252
+ const judgmentResults = {};
253
+ for (const [checkId, desc] of Object.entries(area.judgment || {})) {
254
+ judgmentResults[checkId] = { desc, status: 'JUDGMENT' };
255
+ }
256
+
257
+ // Summary
258
+ const autoList = Object.entries(autoResults);
259
+ const autoPass = autoList.filter(([, r]) => r.status === 'PASS').length;
260
+ const autoFail = autoList.filter(([, r]) => r.status === 'FAIL').length;
261
+ const overclaimsRaised = Object.values(overclaimResults).filter((r) => r.raised).length;
262
+ const judgmentCount = Object.keys(judgmentResults).length;
263
+
264
+ return {
265
+ area: areaId,
266
+ project_dir: projectDir,
267
+ files_scanned: files.length,
268
+ summary: {
269
+ auto_total: autoList.length,
270
+ auto_pass: autoPass,
271
+ auto_fail: autoFail,
272
+ overclaims_raised: overclaimsRaised,
273
+ judgment_required: judgmentCount,
274
+ },
275
+ auto_checks: autoResults,
276
+ overclaim_checks: overclaimResults,
277
+ judgment_checks: judgmentResults,
278
+ };
279
+ }
280
+
281
+ // Glob matcher supporting `*` and `**`. `**/` at the start matches any number
282
+ // of leading path segments including zero (so `**/foo/**` matches `foo/bar.py`).
283
+ function matchesGlob(filePath, glob) {
284
+ const norm = filePath.replace(/\\/g, '/');
285
+ let pattern = glob.replace(/\\/g, '/');
286
+ // A leading `**/` should optionally match — `**/tests/**` should match both
287
+ // `app/tests/x.py` and `tests/x.py`.
288
+ let reSrc = pattern
289
+ .replace(/[.+^${}()|[\]]/g, '\\$&')
290
+ .replace(/\*\*\//g, '@@GLOBSTAR_SLASH@@')
291
+ .replace(/\*\*/g, '@@GLOBSTAR@@')
292
+ .replace(/\*/g, '[^/]*')
293
+ .replace(/@@GLOBSTAR_SLASH@@/g, '(?:.*/)?')
294
+ .replace(/@@GLOBSTAR@@/g, '.*');
295
+ const re = new RegExp('^' + reSrc + '$');
296
+ return re.test(norm);
297
+ }
298
+
299
+ /**
300
+ * Format a text report for the CLI. Returns a string.
301
+ */
302
+ function formatTextReport(result) {
303
+ const lines = [];
304
+ lines.push(`═══ AUTO-VERIFY: ${result.area} ═══\n`);
305
+ lines.push(`Project: ${result.project_dir}`);
306
+ lines.push(`Files scanned: ${result.files_scanned}`);
307
+ const s = result.summary;
308
+ lines.push(`Auto-verified: ${s.auto_pass}/${s.auto_total} PASS, ${s.auto_fail} FAIL`);
309
+ lines.push(`Overclaim recognizers raised: ${s.overclaims_raised}`);
310
+ lines.push(`Judgment required: ${s.judgment_required} check(s)\n`);
311
+
312
+ // AUTO section
313
+ if (Object.keys(result.auto_checks).length > 0) {
314
+ lines.push('── AUTO CHECKS ──');
315
+ for (const [checkId, r] of Object.entries(result.auto_checks)) {
316
+ const badge = r.status === 'PASS' ? '[PASS]' : '[FAIL]';
317
+ const inv = r.inverse ? ' (inverse: presence of pattern = FAIL)' : '';
318
+ lines.push(`\n${badge} ${checkId}: ${r.desc}${inv}`);
319
+ if (r.evidence.length > 0) {
320
+ for (const e of r.evidence.slice(0, 3)) {
321
+ lines.push(` ${e.file}:${e.line} ${e.snippet}`);
322
+ }
323
+ } else if (r.status === 'FAIL' && !r.inverse) {
324
+ lines.push(` no matches for any of ${r.total_patterns} pattern(s)`);
325
+ } else if (r.status === 'PASS' && r.inverse) {
326
+ lines.push(` no anti-pattern instances found`);
327
+ }
328
+ }
329
+ lines.push('');
330
+ }
331
+
332
+ // OVERCLAIM section
333
+ if (Object.keys(result.overclaim_checks).length > 0) {
334
+ lines.push('── OVERCLAIM RECOGNIZERS ──');
335
+ for (const [checkId, r] of Object.entries(result.overclaim_checks)) {
336
+ const badge = r.raised ? '[OVERCLAIM RAISED]' : '[no signal]';
337
+ lines.push(`\n${badge} ${checkId}: ${r.desc}`);
338
+ lines.push(` recognizer: ${r.recognizer}`);
339
+ lines.push(` ${r.notes}`);
340
+ if (r.evidence.length > 0) {
341
+ for (const e of r.evidence.slice(0, 3)) {
342
+ lines.push(` ${e.file}:${e.line} ${e.snippet}`);
343
+ }
344
+ }
345
+ }
346
+ lines.push('');
347
+ }
348
+
349
+ // JUDGMENT section
350
+ if (Object.keys(result.judgment_checks).length > 0) {
351
+ lines.push('── JUDGMENT REQUIRED (agent must evaluate) ──');
352
+ for (const [checkId, r] of Object.entries(result.judgment_checks)) {
353
+ lines.push(`\n[JUDGMENT] ${checkId}: ${r.desc}`);
354
+ }
355
+ lines.push('');
356
+ }
357
+
358
+ // Footer
359
+ lines.push('═══ SUMMARY ═══');
360
+ lines.push(`Auto-verified: ${s.auto_pass} PASS, ${s.auto_fail} FAIL out of ${s.auto_total} automatic checks`);
361
+ lines.push(`Overclaim flags raised: ${s.overclaims_raised}`);
362
+ lines.push(`Judgment required: ${s.judgment_required} checks`);
363
+ lines.push('');
364
+ lines.push('Interpretation:');
365
+ lines.push(' PASS / FAIL are deterministic based on regex match against project files.');
366
+ lines.push(' Overclaim flags mean the literal checklist wording is satisfied but a stricter');
367
+ lines.push(' operational bar may not be. Mark PARTIAL rather than PASS unless you can');
368
+ lines.push(' rebut the flag with evidence.');
369
+ lines.push(' JUDGMENT checks are not auto-gradable. The agent must evaluate them.');
370
+
371
+ return lines.join('\n');
372
+ }
373
+
374
+ module.exports = {
375
+ autoVerifyArea,
376
+ formatTextReport,
377
+ loadRules,
378
+ };