@aigis-ai/cli 2.1.1 → 3.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 (50) hide show
  1. package/BENCHMARKS.md +91 -0
  2. package/CHANGELOG.md +55 -0
  3. package/CONTRIBUTING.md +10 -0
  4. package/IMPROVEMENTS.md +41 -0
  5. package/README.md +65 -4
  6. package/SKILL.md +20 -15
  7. package/bin/aigis.js +67 -6
  8. package/content/index/atlas-NOTICE.md +238 -0
  9. package/content/index/atlas-entry-points.json +15 -0
  10. package/content/index/atlas.json +2694 -0
  11. package/content/index/audit-scan.md +6 -0
  12. package/content/index/auto-verify-rules.json +139 -0
  13. package/content/index/taxonomy.md +1 -1
  14. package/content/skills/areas/agent-permissions.md +228 -0
  15. package/content/skills/areas/agent-tool-safety.md +217 -0
  16. package/content/skills/areas/audit-logging.md +1 -0
  17. package/content/skills/areas/bias-monitoring.md +1 -0
  18. package/content/skills/areas/confidence-scoring.md +1 -0
  19. package/content/skills/areas/data-integrity.md +1 -0
  20. package/content/skills/areas/explainability.md +1 -0
  21. package/content/skills/areas/fallback-patterns.md +1 -0
  22. package/content/skills/areas/human-oversight.md +1 -0
  23. package/content/skills/areas/input-validation.md +1 -0
  24. package/content/skills/areas/monitoring.md +1 -0
  25. package/content/skills/areas/output-sanitization.md +1 -0
  26. package/content/skills/areas/pii-handling.md +1 -0
  27. package/content/skills/areas/prompt-security.md +1 -0
  28. package/content/skills/areas/rag-security.md +1 -0
  29. package/content/skills/areas/rate-limiting.md +1 -0
  30. package/content/skills/areas/supply-chain.md +1 -0
  31. package/content/skills/core.md +15 -0
  32. package/content/templates/threat-model.md +80 -0
  33. package/content/verify/checklist-agent-permissions.md +16 -0
  34. package/content/verify/checklist-agent-tool-safety.md +15 -0
  35. package/docs/frontmatter-schema.md +15 -1
  36. package/lib/atlas.js +302 -0
  37. package/lib/auto-verify.js +49 -5
  38. package/lib/build.js +77 -10
  39. package/lib/classify.js +53 -5
  40. package/lib/fetch.js +2 -1
  41. package/lib/report.js +22 -1
  42. package/lib/search.js +6 -2
  43. package/lib/special-recognizers.js +206 -1
  44. package/lib/threats.js +381 -0
  45. package/package.json +4 -1
  46. package/scripts/area-controls-baseline.json +53 -3
  47. package/scripts/area-frontmatter.schema.json +6 -0
  48. package/scripts/build-atlas-index.js +316 -0
  49. package/scripts/test-all.js +61 -0
  50. package/scripts/validate-area-frontmatter.js +58 -2
@@ -6,6 +6,7 @@ controls:
6
6
  nist: [MAP-2.3, MEASURE-2.6]
7
7
  iso42001: [Annex-A.7]
8
8
  eu_ai_act: [Art-10, Art-10(2), Art-10(3), Art-10(4)]
9
+ atlas: [AML.M0007, AML.M0014, AML.M0025]
9
10
  min_risk_tier: all
10
11
  system_traits: [uses-rag, uses-finetuned]
11
12
  ---
@@ -5,6 +5,7 @@ controls:
5
5
  owasp: []
6
6
  nist: [MEASURE-2.8, MEASURE-2.9]
7
7
  iso42001: [Annex-A.8, Clause-7.4]
8
+ atlas: []
8
9
  min_risk_tier: high
9
10
  system_traits: [influences-decisions, handles-health, jurisdiction-eu]
10
11
  ---
@@ -6,6 +6,7 @@ controls:
6
6
  nist: [MEASURE-2.6, MANAGE-2.3, MANAGE-2.4]
7
7
  iso42001: [Clause-8.2]
8
8
  eu_ai_act: [Art-15(4)]
9
+ atlas: []
9
10
  min_risk_tier: all
10
11
  system_traits: [uses-llm, is-agentic, is-high-volume]
11
12
  ---
@@ -6,6 +6,7 @@ controls:
6
6
  nist: [MAP-3.5, MANAGE-1.3, MANAGE-4.1]
7
7
  iso42001: [Annex-A.9, Clause-8.4]
8
8
  eu_ai_act: [Art-14, Art-14(4)]
9
+ atlas: [AML.M0020, AML.M0029, AML.M0036]
9
10
  min_risk_tier: all
10
11
  system_traits: [is-agentic, influences-decisions, handles-minors, generates-code]
11
12
  ---
@@ -6,6 +6,7 @@ controls:
6
6
  nist: [MEASURE-2.7, MANAGE-1.3]
7
7
  iso42001: [Clause-8.2, Annex-A.6]
8
8
  eu_ai_act: [Art-15(5)]
9
+ atlas: [AML.M0020, AML.M0036]
9
10
  min_risk_tier: all
10
11
  system_traits: [uses-llm, accepts-user-input]
11
12
  ---
@@ -6,6 +6,7 @@ controls:
6
6
  nist: [MEASURE-2.4, MEASURE-3.1, MANAGE-4.1, MANAGE-4.2]
7
7
  iso42001: [Clause-9.1, Clause-10]
8
8
  eu_ai_act: [Art-72, Art-72(1), Art-72(2), Art-72(3), Art-72(4)]
9
+ atlas: [AML.M0024]
9
10
  min_risk_tier: medium
10
11
  system_traits: [uses-llm, is-high-volume, multi-model-pipeline]
11
12
  ---
@@ -5,6 +5,7 @@ controls:
5
5
  owasp: [LLM05]
6
6
  nist: [MEASURE-2.6, MEASURE-2.7]
7
7
  iso42001: [Clause-8.2]
8
+ atlas: [AML.M0020, AML.M0032]
8
9
  min_risk_tier: all
9
10
  system_traits: [uses-llm]
10
11
  ---
@@ -5,6 +5,7 @@ controls:
5
5
  owasp: [LLM02]
6
6
  nist: [MAP-2.1, MEASURE-2.10]
7
7
  iso42001: [Annex-A.7, Annex-A.4]
8
+ atlas: [AML.M0020, AML.M0024]
8
9
  min_risk_tier: all
9
10
  system_traits: [processes-pii, handles-financial, handles-health, handles-minors]
10
11
  ---
@@ -6,6 +6,7 @@ controls:
6
6
  nist: [MEASURE-2.7, MEASURE-2.8]
7
7
  iso42001: [Clause-8.2]
8
8
  eu_ai_act: [Art-15(5)]
9
+ atlas: [AML.M0020, AML.M0021]
9
10
  min_risk_tier: all
10
11
  system_traits: [uses-llm, handles-proprietary]
11
12
  ---
@@ -5,6 +5,7 @@ controls:
5
5
  owasp: [LLM08]
6
6
  nist: [MEASURE-2.7]
7
7
  iso42001: [Clause-8.2, Annex-A.7]
8
+ atlas: [AML.M0019, AML.M0020, AML.M0024]
8
9
  min_risk_tier: all
9
10
  system_traits: [uses-rag]
10
11
  ---
@@ -5,6 +5,7 @@ controls:
5
5
  owasp: [LLM10]
6
6
  nist: [MEASURE-2.6, MANAGE-2.4]
7
7
  iso42001: [Clause-8.2]
8
+ atlas: [AML.M0004, AML.M0036]
8
9
  min_risk_tier: all
9
10
  system_traits: [is-external, is-high-volume, uses-llm]
10
11
  ---
@@ -5,6 +5,7 @@ controls:
5
5
  owasp: [LLM03]
6
6
  nist: [GOVERN-6.1, GOVERN-6.2, MANAGE-3.1, MANAGE-3.2]
7
7
  iso42001: [Annex-A.10]
8
+ atlas: [AML.M0008]
8
9
  min_risk_tier: all
9
10
  system_traits: [uses-thirdparty-api, uses-finetuned]
10
11
  ---
@@ -7,6 +7,8 @@ description: AI governance for coding agents. Use before building any LLM featur
7
7
 
8
8
  Aigis ships governance patterns mapped to NIST AI RMF, OWASP Top 10 for LLMs, and ISO/IEC 42001. This file orients you. Detailed procedures (per-area + per-workflow) load on demand.
9
9
 
10
+ Areas also map to MITRE ATLAS mitigations. MITRE ATLAS is a threat catalog, not a standard. Nobody is "ATLAS compliant". It does not score risk, and it does not cover bias or fairness.
11
+
10
12
  ## When to use
11
13
 
12
14
  When building a new AI/LLM feature, or auditing one. Do this BEFORE writing the LLM call, not after.
@@ -20,6 +22,7 @@ When building a new AI/LLM feature, or auditing one. Do this BEFORE writing the
20
22
  - Implement the procedure step by step. Honor each "verification checkpoint."
21
23
  - `aigis verify <area-id> --auto .` — run the deterministic scanner against your project. Fix any FAIL or OVERCLAIM before moving on.
22
24
  4. **Generate compliance docs** when all areas pass: `aigis template <id>` for each template the classify output named.
25
+ 5. **Threat model.** Follow "Threat modeling (MITRE ATLAS)" below.
23
26
 
24
27
  ## The workflow (audit an existing project)
25
28
 
@@ -27,6 +30,7 @@ When building a new AI/LLM feature, or auditing one. Do this BEFORE writing the
27
30
  2. `aigis audit --traits <detected> --json` — scoped checklist with the deterministic denominator.
28
31
  3. For each area, run `aigis verify <id> --auto .` to surface PASS/FAIL/OVERCLAIM/JUDGMENT.
29
32
  4. Implement fixes using `aigis get <id>` for the procedure.
33
+ 5. Threat model the project: follow "Threat modeling (MITRE ATLAS)" below.
30
34
 
31
35
  ## How to read `aigis verify <area> --auto` output
32
36
 
@@ -37,6 +41,16 @@ When building a new AI/LLM feature, or auditing one. Do this BEFORE writing the
37
41
 
38
42
  When an OVERCLAIM is raised, the area is not complete — fix the anti-pattern before marking done.
39
43
 
44
+ ## Threat modeling (MITRE ATLAS)
45
+
46
+ Run this yourself, without being asked, when you: build a new AI feature; add tools, write access, memory or a new data source; prepare a launch; audit an existing project; respond to an incident.
47
+
48
+ 1. Derive the traits from the codebase and the user's request (the same traits you give classify).
49
+ 2. `aigis threats --traits <traits>`. It lists attacker techniques for this system's entry points (Realized first), the mitigations MITRE links to each, the Aigis areas that help implement each one (in part), and gaps. If you cannot name traits, fall back to `aigis threats "<description>"`.
50
+ 3. For every area it names: `aigis get <area>`, implement it, then `aigis verify <area> --auto .`.
51
+ 4. For every gap (a mitigation with no mapped Aigis area): tell the user it is not covered and propose a control. Never report a gap as handled.
52
+ 5. Rerun when tools, permissions, memory or data sources change.
53
+
40
54
  ## How to pick traits
41
55
 
42
56
  Two ways to figure out which traits apply:
@@ -55,6 +69,7 @@ Default to NO on low-confidence questions when the user is unsure — false-posi
55
69
  - `aigis verify <area-id> [--auto <path>]` — checklist or deterministic scan
56
70
  - `aigis template <id>` — compliance documentation template
57
71
  - `aigis audit --scan | --traits <list>` — audit existing code
72
+ - `aigis threats --traits <list>` (or `"<description>"`): ATLAS threat model: techniques, MITRE mitigations, gaps (`--json` for scripts)
58
73
  - `aigis infra <area>` — fetch infrastructure setup content (rate-limiting, secrets, logging). Use after the area procedure references it.
59
74
 
60
75
  ## What loads on demand vs always
@@ -0,0 +1,80 @@
1
+ ---
2
+ id: threat-model
3
+ title: Threat Model Worksheet (MITRE ATLAS)
4
+ framework: MITRE ATLAS v2026.10 (threat catalog)
5
+ required_when: not required by classify; fill it in when you design, extend, launch or investigate an AI system
6
+ ---
7
+
8
+ # Threat model
9
+
10
+ > The agent fills in each section for the system being built, then reviews it with the user. Keep it next to the code and update it when the system changes.
11
+
12
+ MITRE ATLAS is a threat catalog, not a standard. Nobody is "ATLAS compliant". It does not score risk, and it does not cover bias or fairness.
13
+
14
+ ## 1. Draw the system
15
+
16
+ List every place text gets in and everything the AI can do. Attacks start at these entry points.
17
+
18
+ | Where text gets in | Source (users, emails, documents, tickets, tool outputs, retrieved content) | Trusted? | Reaches the model how |
19
+ |---|---|---|---|
20
+ | [entry point] | [source] | [yes / no] | [prompt, system prompt, retrieval, tool result] |
21
+
22
+ | What the AI can do | Kind (tools, write access, memory, data source, who sees output) | Needs approval? | Worst case if misused |
23
+ |---|---|---|---|
24
+ | [capability] | [kind] | [yes / no] | [what an attacker gains] |
25
+
26
+ ## 2. Walk the tactics
27
+
28
+ For each tactic, ask: could an attacker do this here? Answer yes, no or unsure, with one line of reasoning tied to an entry point or capability from step 1.
29
+
30
+ | # | Tactic | Could an attacker do this here? | Why |
31
+ |---|---|---|---|
32
+ | 1 | Reconnaissance | | |
33
+ | 2 | Resource Development | | |
34
+ | 3 | AI Attack Adaptation | | |
35
+ | 4 | Initial Access | | |
36
+ | 5 | AI Model Access | | |
37
+ | 6 | Execution | | |
38
+ | 7 | Persistence | | |
39
+ | 8 | Privilege Escalation | | |
40
+ | 9 | Defense Evasion | | |
41
+ | 10 | Credential Access | | |
42
+ | 11 | Discovery | | |
43
+ | 12 | Lateral Movement | | |
44
+ | 13 | Collection | | |
45
+ | 14 | Command and Control | | |
46
+ | 15 | Exfiltration | | |
47
+ | 16 | Impact | | |
48
+
49
+ ## 3. Prioritize
50
+
51
+ Run `aigis threats --traits <traits>` for this system. It lists the techniques for your entry points with Realized ones first (seen in real attacks), then Demonstrated, then Feasible. Order your work the same way, then by how bad the outcome would be for this system. ATLAS gives no number for this; the ordering is a judgment you write down.
52
+
53
+ | Priority | Technique (from `aigis threats`) | Entry point | Why it matters here |
54
+ |---|---|---|---|
55
+ | 1 | | | |
56
+
57
+ ## 4. Pick defenses and record gaps
58
+
59
+ For each priority technique, list the mitigations MITRE links to it and the Aigis areas that help implement each one (in part). A gap is a mitigation with no mapped Aigis area. Never mark a gap as handled.
60
+
61
+ | Mitigation | Aigis area | Status (implemented, partial, gap) | Accepted or planned (owner, date) |
62
+ |---|---|---|---|
63
+ | | | | |
64
+
65
+ ## 5. Red-team
66
+
67
+ Write one test case per top technique from `aigis threats`. Run it against the real system and record the result.
68
+
69
+ | Technique | Entry point | Attempt | Expected defense | Pass criteria | Result | Date |
70
+ |---|---|---|---|---|---|---|
71
+ | | | | | | | |
72
+
73
+ ## Rerun when
74
+
75
+ - You add new tools
76
+ - You add write access
77
+ - You add memory
78
+ - You add a new data source
79
+ - Before launch
80
+ - After an incident
@@ -0,0 +1,16 @@
1
+ ---
2
+ id: checklist-agent-permissions
3
+ implements: agent-permissions
4
+ ---
5
+ # Verification: Agent identity, tool permissions and authority limits
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is every agent listed in one identity map as `service` or `delegated`, read when a run starts so that an unlisted agent is denied? | S1 | [ ] | |
10
+ | V2 | Is each service agent bound to an explicit map of authorized workflows (operations and allowed initiators), checked when a run starts so that an unlisted workflow or initiator is denied? | S2 | [ ] | |
11
+ | V3 | Does a delegated run get its operations from `effective_permissions`, the intersection of the user's permissions and the task scope in trusted config? | S3 | [ ] | |
12
+ | V4 | Does a per-caller function (`authorize_tool_call`) take the caller (agent, user, tenant) and decide each tool call, with no wildcard grant of every tool, scope or permission? | S4 | [ ] | |
13
+ | V5 | Is a maximum authority declared per agent before the run and applied when the run starts, with self-granting operations (new credentials, keys, roles, service accounts, own scopes) removed? | S5 | [ ] | |
14
+ | V6 | Does every resource the agent creates go through `register_agent_resource` with an owner and expiry, and does a sweep outside the agent revoke it at run end or expiry? | S6 | [ ] | |
15
+ | V7 | Do negative tests call the real dispatcher and assert a denial, and that the tool did not run, for each case in Step 7, plus one allowed call? | S7 | [ ] | |
16
+ | V8 | Does authorization run in the tool layer or gateway on every tool call, with the caller taken from the authenticated session, and never in prompt text? | S4 | [ ] | |
@@ -0,0 +1,15 @@
1
+ ---
2
+ id: checklist-agent-tool-safety
3
+ implements: agent-tool-safety
4
+ ---
5
+ # Verification: Tool invocation safety, tool input and output validation, scope drift
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is every item added to the model context recorded with a `trust_level`, and does one untrusted item taint the context for as long as the item stays in it, across turns? | S1 | [ ] | |
10
+ | V2 | While untrusted data is in context, does a gate (`gate_tool_call`) deny side-effect tools or hold them for human approval, rather than only logging? | S2 | [ ] | |
11
+ | V3 | Are tool arguments checked against a schema by `validate_tool_args` before the tool runs, with the call rejected on failure? | S3 | [ ] | |
12
+ | V4 | Are tool results and retrieved data passed through `sanitize_tool_output` (or `validate_tool_output`), which rejects or cleans them before they re-enter the context? | S4 | [ ] | |
13
+ | V5 | Is each planned action checked by `check_scope_drift` against the authorized objective, with drift stopping the call? | S5 | [ ] | |
14
+ | V6 | If the agent keeps persistent memory: are writes attributed (source, trust label, tenant, user), stored as facts rather than instructions, and are recalls filtered by tenant and user? Not applicable without persistent memory. | S6 | [ ] | |
15
+ | V7 | Do injection and drift tests use the real dispatcher, and does each fail when its control is removed? | S7 | [ ] | |
@@ -15,6 +15,7 @@ controls: # REQUIRED — at least three fr
15
15
  nist: [MAP-2.1, ...] # REQUIRED key, array (may be empty)
16
16
  iso42001: [Annex-A.7, ...] # REQUIRED key, array (may be empty)
17
17
  eu_ai_act: [Art-50, Art-13(1)(b)] # OPTIONAL — list of EU AI Act article references
18
+ atlas: [AML.M0020, AML.M0036] # OPTIONAL: MITRE ATLAS mitigation ids this area helps implement (in part) (may be empty)
18
19
  min_risk_tier: all # REQUIRED — one of: low | medium | high | all
19
20
  system_traits: [processes-pii, ...] # REQUIRED — non-empty array of trait identifiers
20
21
  jurisdiction: [eu] # OPTIONAL — list of jurisdictions where this area applies
@@ -42,9 +43,22 @@ Maps the area's verification checkpoints to external framework controls. Used by
42
43
  | `nist` | yes (may be empty) | `<FUNCTION>-N.N` | `MAP-2.1`, `MEASURE-2.10`, `GOVERN-6.1` |
43
44
  | `iso42001` | yes (may be empty) | `Clause-N` or `Annex-X[.N]` | `Clause-9.1`, `Annex-A.7`, `Annex-C` |
44
45
  | `eu_ai_act` | no | `Art-N[(N)(letter)]` or `Annex-X[(N)]` | `Art-9`, `Art-10(2)(g)`, `Art-14(4)(c)`, `Annex-IV` |
46
+ | `atlas` | no (may be empty) | `AML.M####`, a mitigation in the pinned ATLAS catalog | `AML.M0020`, `AML.M0036` |
45
47
 
46
48
  The `eu_ai_act` field is the v2.1 addition. It is optional on existing areas; new EU-specific areas declare it.
47
49
 
50
+ ### `controls.atlas` (optional, v3.0 addition)
51
+
52
+ Lists the MITRE ATLAS mitigation ids that this area's procedure helps implement (in part). Written as one flow-style line, last key of `controls`, ids in ascending order. An empty list (`atlas: []`) means no approved link: the area helps no ATLAS mitigation in a way Aigis is willing to claim.
53
+
54
+ - **"Helps implement (in part)", never "implements" or "satisfies".** Following an area's procedure helps with the listed mitigation; it does not mean the mitigation is fully in place in your system. MITRE ATLAS is a threat catalog, not a standard, so there is nothing to comply with.
55
+ - **Mitigations, not techniques.** Every value matches `^AML\.M\d{4}$` and must exist in the vendored catalog `content/index/atlas.json` (ATLAS 2026.10). Technique ids (`AML.T####`) are rejected here. The techniques an area helps against are derived at runtime from MITRE's own `mitigates` links in the catalog (`lib/atlas.js`); they are never stored in frontmatter.
56
+ - **Never jurisdiction-gated.** ATLAS citations apply everywhere, so an area that declares `jurisdiction:` must not declare `atlas`. The four `eu-ai-act-*` areas carry no `atlas` key.
57
+ - **How a mapping change is approved.** The values come from the approved gold file `build/atlas/gold/area-mitigations.json` (rows with `decision: include`). Adding, removing or changing a link means editing that gold file and getting the project owner's (Nayan's) approval recorded in `build/atlas/gold/APPROVAL.md`, then updating the area frontmatter and `scripts/area-controls-baseline.json` in the same commit. The validator's no-deletion check protects `atlas` like the other framework arrays.
58
+ - If `content/index/atlas.json` is missing or is not the pinned release, `scripts/validate-area-frontmatter.js` fails (exit 1) with a message naming the catalog.
59
+
60
+ Raw file fetches (`aigis get`, `aigis search`) print the `atlas:` line verbatim as part of the stored frontmatter.
61
+
48
62
  ### `min_risk_tier` (required)
49
63
 
50
64
  The minimum risk tier at which this area should be recommended. Values:
@@ -72,4 +86,4 @@ Gates which framework controls render in the brief, **not** which areas appear (
72
86
 
73
87
  ## Backward compatibility
74
88
 
75
- All v2.0 area files satisfy this schema unchanged — `eu_ai_act` and `jurisdiction` are pure additions. The validator runs against the full `content/skills/areas/` directory in CI; any existing file that fails is a regression.
89
+ All v2.0 area files satisfy this schema unchanged — `eu_ai_act`, `jurisdiction` and `atlas` are pure additions. The validator runs against the full `content/skills/areas/` directory in CI; any existing file that fails is a regression.
package/lib/atlas.js ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * v2.2 — MITRE ATLAS lookups over the vendored catalog.
3
+ *
4
+ * Aigis owns two small judgments (D1): area -> ATLAS mitigations
5
+ * (`controls.atlas` in area frontmatter) and trait -> entry-point
6
+ * techniques (`content/index/atlas-entry-points.json`). Everything else
7
+ * (names, maturity, tactics, mitigation -> technique links, case-study
8
+ * counts) is read from `content/index/atlas.json`.
9
+ *
10
+ * Rules:
11
+ * - Only MITRE's direct `mitigates` links are used (D6). A sub-technique
12
+ * does not inherit its parent's mitigations, and a parent does not
13
+ * inherit its children's.
14
+ * - Ordering is maturity, then MITRE case-study count descending, then
15
+ * id (D7). ATLAS does not rank threats and this module adds no ranking.
16
+ * - Pure, synchronous, cached per path. No network, no clock, no
17
+ * randomness. Every returned array or object is a fresh copy.
18
+ * - Load failures throw AtlasCatalogError; callers that must keep
19
+ * working without ATLAS wrap their ATLAS code in withAtlas (D12).
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const matter = require('gray-matter');
25
+
26
+ const ROOT = path.join(__dirname, '..');
27
+ const CATALOG_PATH = path.join(ROOT, 'content', 'index', 'atlas.json');
28
+ const ENTRY_POINTS_PATH = path.join(ROOT, 'content', 'index', 'atlas-entry-points.json');
29
+ const AREAS_DIR = path.join(ROOT, 'content', 'skills', 'areas');
30
+
31
+ const PINNED = Object.freeze({
32
+ version: '2026.10',
33
+ sha256: 'ac41ee9f99a47084ba5fdfc77ae83a28687e12390240fffeb37df7914ffe142d',
34
+ });
35
+
36
+ // The only place this sentence is typed in runtime code (S0, AC14).
37
+ const DISCLAIMER = 'MITRE ATLAS is a threat catalog, not a standard. Nobody is "ATLAS compliant". It does not score risk, and it does not cover bias or fairness.';
38
+
39
+ const MATURITY_RANK = Object.freeze({ Realized: 0, Demonstrated: 1, Feasible: 2 });
40
+ const CATALOG_KEYS = ['source', 'counts', 'tactics', 'techniques', 'mitigations'];
41
+
42
+ class AtlasCatalogError extends Error {
43
+ constructor(message, file, code) {
44
+ super(message);
45
+ this.name = 'AtlasCatalogError';
46
+ this.file = file;
47
+ this.code = code;
48
+ }
49
+ }
50
+
51
+ // ── Loading ─────────────────────────────────────────────────────────────
52
+
53
+ const catalogCache = new Map();
54
+ const entryPointCache = new Map();
55
+ const indexCache = new WeakMap();
56
+ const areaCache = new Map();
57
+
58
+ function isObject(value) {
59
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
60
+ }
61
+
62
+ function readJson(filepath, file) {
63
+ let raw;
64
+ try {
65
+ raw = fs.readFileSync(filepath, 'utf8');
66
+ } catch (err) {
67
+ const code = err && (err.code === 'ENOENT' || err.code === 'ENOTDIR') ? 'missing' : 'corrupt';
68
+ throw new AtlasCatalogError(`Cannot read ATLAS ${file} at ${filepath}`, file, code);
69
+ }
70
+ try {
71
+ return JSON.parse(raw);
72
+ } catch (_) {
73
+ throw new AtlasCatalogError(`ATLAS ${file} at ${filepath} is not valid JSON`, file, 'corrupt');
74
+ }
75
+ }
76
+
77
+ function loadCatalog(opts = {}) {
78
+ const filepath = path.resolve(opts.path || CATALOG_PATH);
79
+ if (catalogCache.has(filepath)) return catalogCache.get(filepath);
80
+
81
+ const data = readJson(filepath, 'catalog');
82
+ const shapeOk = isObject(data)
83
+ && CATALOG_KEYS.every((k) => Object.hasOwn(data, k))
84
+ && isObject(data.source) && isObject(data.counts) && Array.isArray(data.tactics)
85
+ && isObject(data.techniques) && isObject(data.mitigations);
86
+ if (!shapeOk) {
87
+ throw new AtlasCatalogError(`ATLAS catalog at ${filepath} is missing top-level keys`, 'catalog', 'corrupt');
88
+ }
89
+ if (data.source.version !== PINNED.version || data.source.sha256 !== PINNED.sha256) {
90
+ throw new AtlasCatalogError(
91
+ `ATLAS catalog at ${filepath} is not the pinned release ${PINNED.version}`, 'catalog', 'pin-mismatch');
92
+ }
93
+ catalogCache.set(filepath, data);
94
+ return data;
95
+ }
96
+
97
+ function loadEntryPoints(opts = {}) {
98
+ const filepath = path.resolve(opts.path || ENTRY_POINTS_PATH);
99
+ if (entryPointCache.has(filepath)) return entryPointCache.get(filepath);
100
+
101
+ const data = readJson(filepath, 'entry-points');
102
+ const corrupt = (why) => new AtlasCatalogError(`ATLAS entry points at ${filepath}: ${why}`, 'entry-points', 'corrupt');
103
+ if (!isObject(data) || !isObject(data.entry_points)) throw corrupt('missing entry_points');
104
+
105
+ // Lazy require: classify may itself depend on this module (S4.1).
106
+ const { ALL_TRAITS } = require('./classify');
107
+ const catalog = loadCatalog();
108
+ for (const [trait, entry] of Object.entries(data.entry_points)) {
109
+ if (!ALL_TRAITS.includes(trait)) throw corrupt(`unknown trait ${trait}`);
110
+ if (!isObject(entry) || !Array.isArray(entry.techniques)) throw corrupt(`trait ${trait} has no techniques list`);
111
+ for (const id of entry.techniques) {
112
+ if (typeof id !== 'string' || !Object.hasOwn(catalog.techniques, id)) {
113
+ throw corrupt(`trait ${trait} names unknown technique ${id}`);
114
+ }
115
+ }
116
+ }
117
+ if (data.atlas_version !== PINNED.version) {
118
+ throw new AtlasCatalogError(
119
+ `ATLAS entry points at ${filepath} target ${data.atlas_version}, not ${PINNED.version}`, 'entry-points', 'pin-mismatch');
120
+ }
121
+ entryPointCache.set(filepath, data);
122
+ return data;
123
+ }
124
+
125
+ // Reverse index technique -> direct mitigation ids, built once per catalog.
126
+ function mitigationIndex(catalog) {
127
+ if (indexCache.has(catalog)) return indexCache.get(catalog);
128
+ const index = new Map();
129
+ for (const mid of Object.keys(catalog.mitigations).sort()) {
130
+ for (const tid of catalog.mitigations[mid].techniques || []) {
131
+ if (!index.has(tid)) index.set(tid, []);
132
+ index.get(tid).push(mid);
133
+ }
134
+ }
135
+ indexCache.set(catalog, index);
136
+ return index;
137
+ }
138
+
139
+ // ── Catalog lookups ─────────────────────────────────────────────────────
140
+
141
+ function technique(id) {
142
+ const catalog = loadCatalog();
143
+ if (typeof id !== 'string' || !Object.hasOwn(catalog.techniques, id)) return null;
144
+ const t = catalog.techniques[id];
145
+ const parent = t.parent || null;
146
+ const parentEntry = parent && Object.hasOwn(catalog.techniques, parent) ? catalog.techniques[parent] : null;
147
+ const tacticNames = new Map(catalog.tactics.map((x) => [x.id, x.name]));
148
+ return {
149
+ id,
150
+ name: t.name,
151
+ display_name: parentEntry ? `${parentEntry.name}: ${t.name}` : t.name,
152
+ maturity: t.maturity,
153
+ tactics: (t.tactics || []).map((tid) => ({ id: tid, name: tacticNames.has(tid) ? tacticNames.get(tid) : tid })),
154
+ parent,
155
+ case_studies: t.case_studies || 0,
156
+ };
157
+ }
158
+
159
+ function mitigation(id) {
160
+ const catalog = loadCatalog();
161
+ if (typeof id !== 'string' || !Object.hasOwn(catalog.mitigations, id)) return null;
162
+ const m = catalog.mitigations[id];
163
+ return { id, name: m.name, techniques: [...(m.techniques || [])] };
164
+ }
165
+
166
+ function mitigationsForTechnique(id) {
167
+ const catalog = loadCatalog();
168
+ const mids = mitigationIndex(catalog).get(id) || [];
169
+ return mids.map((mid) => ({ id: mid, name: catalog.mitigations[mid].name }));
170
+ }
171
+
172
+ function compareTechniques(a, b) {
173
+ const rank = (t) => (Object.hasOwn(MATURITY_RANK, t.maturity) ? MATURITY_RANK[t.maturity] : 3);
174
+ const byMaturity = rank(a) - rank(b);
175
+ if (byMaturity) return byMaturity;
176
+ const byCases = (b.case_studies || 0) - (a.case_studies || 0);
177
+ if (byCases) return byCases;
178
+ if (a.id < b.id) return -1;
179
+ if (a.id > b.id) return 1;
180
+ return 0;
181
+ }
182
+
183
+ function techniquesForMitigations(ids) {
184
+ const catalog = loadCatalog();
185
+ const seen = new Set();
186
+ for (const mid of ids || []) {
187
+ if (typeof mid !== 'string' || !Object.hasOwn(catalog.mitigations, mid)) continue;
188
+ for (const tid of catalog.mitigations[mid].techniques || []) {
189
+ if (Object.hasOwn(catalog.techniques, tid)) seen.add(tid);
190
+ }
191
+ }
192
+ return [...seen].map(technique).sort(compareTechniques).map((t) => t.id);
193
+ }
194
+
195
+ // ── Area labels (frontmatter controls.atlas) ────────────────────────────
196
+
197
+ function areasDirOf(opts) {
198
+ return path.resolve((opts && opts.areasDir) || AREAS_DIR);
199
+ }
200
+
201
+ // Map<areaId, sorted mitigation ids> for every area file in the directory.
202
+ function areaLabels(dir) {
203
+ if (areaCache.has(dir)) return areaCache.get(dir);
204
+ const labels = new Map();
205
+ let files = [];
206
+ try {
207
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
208
+ } catch (_) {
209
+ files = [];
210
+ }
211
+ for (const file of files) {
212
+ let ids = [];
213
+ try {
214
+ const fm = matter(fs.readFileSync(path.join(dir, file), 'utf8')).data;
215
+ const atlas = fm && fm.controls && fm.controls.atlas;
216
+ if (Array.isArray(atlas)) ids = [...new Set(atlas.filter((x) => typeof x === 'string'))].sort();
217
+ } catch (_) {
218
+ ids = [];
219
+ }
220
+ labels.set(file.slice(0, -'.md'.length), ids);
221
+ }
222
+ areaCache.set(dir, labels);
223
+ return labels;
224
+ }
225
+
226
+ function areaMitigations(areaId, opts) {
227
+ const ids = areaLabels(areasDirOf(opts)).get(areaId);
228
+ return ids ? [...ids] : [];
229
+ }
230
+
231
+ function mitigationAreas(opts) {
232
+ const reverse = {};
233
+ for (const [areaId, mids] of areaLabels(areasDirOf(opts))) {
234
+ for (const mid of mids) (reverse[mid] ||= []).push(areaId);
235
+ }
236
+ const out = {};
237
+ for (const mid of Object.keys(reverse).sort()) out[mid] = reverse[mid].sort();
238
+ return out;
239
+ }
240
+
241
+ function summarizeAreas(areaIds, opts) {
242
+ const catalog = loadCatalog();
243
+ const mids = new Set();
244
+ for (const areaId of areaIds || []) {
245
+ for (const mid of areaMitigations(areaId, opts)) {
246
+ if (Object.hasOwn(catalog.mitigations, mid)) mids.add(mid);
247
+ }
248
+ }
249
+ const sortedMids = [...mids].sort();
250
+ const techniques = techniquesForMitigations(sortedMids).map(technique);
251
+ const count = (m) => techniques.filter((t) => t.maturity === m).length;
252
+ return {
253
+ version: PINNED.version,
254
+ disclaimer: DISCLAIMER,
255
+ mitigations: sortedMids.map((id) => ({ id, name: catalog.mitigations[id].name })),
256
+ techniques_addressed: {
257
+ total: techniques.length,
258
+ realized: count('Realized'),
259
+ demonstrated: count('Demonstrated'),
260
+ feasible: count('Feasible'),
261
+ },
262
+ top_techniques: techniques.slice(0, 2).map((t) => ({ id: t.id, name: t.display_name, maturity: t.maturity })),
263
+ };
264
+ }
265
+
266
+ // ── Fail-soft wrapper (D12) ─────────────────────────────────────────────
267
+
268
+ let warnedDefault = false;
269
+
270
+ function defaultWarn(message) {
271
+ if (warnedDefault) return;
272
+ warnedDefault = true;
273
+ process.stderr.write(`${message}\n`);
274
+ }
275
+
276
+ function withAtlas(fn, fallback, warn = defaultWarn) {
277
+ try {
278
+ return fn();
279
+ } catch (err) {
280
+ if (!(err instanceof AtlasCatalogError)) throw err;
281
+ warn(`aigis: ATLAS catalog unavailable (${err.file} ${err.code}); ATLAS output omitted`);
282
+ return fallback;
283
+ }
284
+ }
285
+
286
+ module.exports = {
287
+ PINNED,
288
+ DISCLAIMER,
289
+ MATURITY_RANK,
290
+ AtlasCatalogError,
291
+ loadCatalog,
292
+ loadEntryPoints,
293
+ technique,
294
+ mitigation,
295
+ mitigationsForTechnique,
296
+ techniquesForMitigations,
297
+ compareTechniques,
298
+ areaMitigations,
299
+ mitigationAreas,
300
+ summarizeAreas,
301
+ withAtlas,
302
+ };