@aigis-ai/cli 2.1.0 → 3.0.0

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 +89 -0
  2. package/CHANGELOG.md +49 -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
@@ -360,11 +360,216 @@ function rateLimitNoRetryAfter(files, ctx) {
360
360
  return { flagged: flagged || partial, evidence, notes };
361
361
  }
362
362
 
363
+ /**
364
+ * maskNonCode (v3.0, rubric C-11)
365
+ *
366
+ * Returns the file text with everything that is not executable code
367
+ * replaced by spaces: line comments, block comments (including Ruby
368
+ * =begin/=end), Python triple-quoted
369
+ * strings (docstrings and string blocks, assigned or not), JS/Go template
370
+ * literals, and the contents of ordinary string literals that are not a
371
+ * plain token. A plain token is a string made only of letters, digits and
372
+ * `_ : . - / * @` (for example "service", "iam:create_key", "*"); those
373
+ * are kept because rules and recognizers read them as data. Newlines are
374
+ * preserved, so line numbers do not move.
375
+ *
376
+ * Used only by rules that opt in with `"code_only": true` and by the two
377
+ * v3.0 recognizers. A tokenizer, not a parser: unusual syntax may be
378
+ * masked imperfectly, which can only make a check stricter.
379
+ */
380
+ const HASH_COMMENT_EXTS = new Set(['.py', '.rb']);
381
+ const C_COMMENT_EXTS = new Set(['.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.go', '.java', '.kt']);
382
+ const PLAIN_STRING = /^[A-Za-z0-9_:.\-/*@]*$/;
383
+ const REGEX_PREFIX_WORDS = new Set(['return', 'typeof', 'case', 'do', 'else', 'in', 'of', 'new', 'delete', 'void', 'throw', 'yield', 'await']);
384
+
385
+ function maskNonCode(src, filePath) {
386
+ const ext = (String(filePath || '').match(/\.[A-Za-z0-9]+$/) || [''])[0].toLowerCase();
387
+ const hash = HASH_COMMENT_EXTS.has(ext);
388
+ const clike = C_COMMENT_EXTS.has(ext);
389
+ if (!hash && !clike) return src;
390
+ const py = ext === '.py';
391
+ const out = src.split('');
392
+ const n = src.length;
393
+ const blank = (from, to) => { for (let k = from; k < to && k < n; k++) if (out[k] !== '\n') out[k] = ' '; };
394
+ let lastSig = '';
395
+ let lastWord = '';
396
+ let i = 0;
397
+ while (i < n) {
398
+ const c = src[i];
399
+ if (ext === '.rb' && c === '=' && (i === 0 || src[i - 1] === '\n') && /^=begin\b/.test(src.slice(i, i + 7))) {
400
+ const m = /\n=end\b[^\n]*/.exec(src.slice(i));
401
+ const j = m ? i + m.index + m[0].length : n;
402
+ blank(i, j);
403
+ i = j;
404
+ continue;
405
+ }
406
+ if ((hash && c === '#') || (clike && c === '/' && src[i + 1] === '/')) {
407
+ let j = src.indexOf('\n', i);
408
+ if (j < 0) j = n;
409
+ blank(i, j);
410
+ i = j;
411
+ continue;
412
+ }
413
+ if (clike && c === '/' && src[i + 1] === '*') {
414
+ let j = src.indexOf('*/', i + 2);
415
+ j = j < 0 ? n : j + 2;
416
+ blank(i, j);
417
+ i = j;
418
+ continue;
419
+ }
420
+ if (py && (src.startsWith('"""', i) || src.startsWith("'''", i))) {
421
+ const q = src.slice(i, i + 3);
422
+ let j = i + 3;
423
+ while (j < n && !src.startsWith(q, j)) j += src[j] === '\\' ? 2 : 1;
424
+ j = Math.min(n, j + 3);
425
+ blank(i, j);
426
+ i = j;
427
+ lastSig = '"';
428
+ lastWord = '';
429
+ continue;
430
+ }
431
+ if (c === '"' || c === "'" || (clike && c === '`')) {
432
+ let j = i + 1;
433
+ while (j < n && src[j] !== c && (c === '`' || src[j] !== '\n')) j += src[j] === '\\' ? 2 : 1;
434
+ const end = Math.min(n, j + 1);
435
+ const body = src.slice(i + 1, Math.min(j, n));
436
+ if (c === '`' || !PLAIN_STRING.test(body)) blank(i + 1, Math.min(j, n));
437
+ i = end;
438
+ lastSig = c;
439
+ lastWord = '';
440
+ continue;
441
+ }
442
+ if (clike && c === '/' && (lastSig === '' || '(,=:[!&|?{};+-*%<>~^'.includes(lastSig) || REGEX_PREFIX_WORDS.has(lastWord))) {
443
+ // regex literal: skip it unchanged so quotes or slashes inside are not misread
444
+ let j = i + 1;
445
+ let inClass = false;
446
+ while (j < n && src[j] !== '\n') {
447
+ if (src[j] === '\\') { j += 2; continue; }
448
+ if (src[j] === '[') inClass = true;
449
+ else if (src[j] === ']') inClass = false;
450
+ else if (src[j] === '/' && !inClass) break;
451
+ j++;
452
+ }
453
+ i = j + 1;
454
+ lastSig = '/';
455
+ lastWord = '';
456
+ continue;
457
+ }
458
+ if (/[A-Za-z0-9_$]/.test(c)) {
459
+ let j = i;
460
+ while (j < n && /[A-Za-z0-9_$]/.test(src[j])) j++;
461
+ lastWord = src.slice(i, j);
462
+ lastSig = 'a';
463
+ i = j;
464
+ continue;
465
+ }
466
+ if (!/\s/.test(c)) { lastSig = c; lastWord = ''; }
467
+ i++;
468
+ }
469
+ return out.join('');
470
+ }
471
+
472
+ // Lines that are only a comment are skipped by the v3.0 recognizers below,
473
+ // so a note such as `# never grant "*" scope` is not read as code.
474
+ const COMMENT_LINE = /^\s*(?:#|\/\/|\/\*|\*)/;
475
+
476
+ /**
477
+ * wildcard_tool_scope (agent-permissions V4, SPEC S7.3)
478
+ *
479
+ * A per-caller authorization function exists (V4 PASS) but the code also
480
+ * grants everything somewhere: a "*" string literal on a line about scope,
481
+ * tools, allow or permission, or an allow_all flag set to a true value.
482
+ * Evidence: at most 3 { file, line, snippet }.
483
+ */
484
+ function wildcardToolScope(files, ctx) {
485
+ const evidence = [];
486
+ const starLiteral = /(["'])\*\1/;
487
+ const scopeWords = /scope|tool|allow|permission/i;
488
+ const allowAllTrue = /\b(?:allow_all|allowAll|ALLOW_ALL)\b\s*(?::[^=\n]*)?(?:=|:)\s*(?:True|true|1|["']true["'])\b/;
489
+ for (const { path, content } of files) {
490
+ const raw = content.split('\n');
491
+ const lines = maskNonCode(content, path).split('\n');
492
+ for (let i = 0; i < lines.length; i++) {
493
+ const line = lines[i];
494
+ if (COMMENT_LINE.test(line)) continue;
495
+ if ((starLiteral.test(line) && scopeWords.test(line)) || allowAllTrue.test(line)) {
496
+ if (evidence.length < 3) evidence.push({ file: path, line: i + 1, snippet: (raw[i] || '').trim().slice(0, 160) });
497
+ }
498
+ }
499
+ }
500
+ const flagged = evidence.length > 0;
501
+ return {
502
+ flagged,
503
+ evidence,
504
+ notes: flagged
505
+ ? 'A wildcard grant was found ("*" on a scope, tool, allow or permission line, or allow_all set to true). '
506
+ + 'An authorization function exists, but a wildcard lets every caller reach every tool or resource, so the per-caller decision of Step 4 does not hold. '
507
+ + 'Verify manually; if confirmed, mark PARTIAL rather than PASS.'
508
+ : 'No wildcard tool, scope or permission grant found.',
509
+ };
510
+ }
511
+
512
+ /**
513
+ * untrusted_gate_log_only (agent-tool-safety V2, SPEC S7.3, AC30)
514
+ *
515
+ * Modeled on injection_log_only. A conditional that tests the trust label
516
+ * or taint state (trust_level, trustLevel, untrusted, tainted) contains a logging call within the
517
+ * next 8 lines, and within 8 lines after that logging call there is no
518
+ * blocking construct (raise, throw, a return of a denial, require_approval).
519
+ * Logging alone is not a restriction (Step 2).
520
+ */
521
+ function untrustedGateLogOnly(files, ctx) {
522
+ const evidence = [];
523
+ const sites = [];
524
+ const trustTest = /^\s*(?:\}\s*)?(?:if|elif|else\s+if|while|unless)\b.*(?:trust_?level|untrusted|\btaint\w*)/i;
525
+ const logCall = /\b(?:logger|logging|log|console|logs|audit_log|auditLog)\s*\.\s*(?:debug|info|warn|warning|error|critical|exception|log|notice)\s*\(|\bprint\s*\(|\b(?:log|logWarning|log_warning)\s*\(/;
526
+ const blocking = /\braise\b|\bthrow\b|\breturn\s+(?:False|false|None|null|deny\w*|denied\w*|Denied\w*|block\w*|reject\w*|\{[^}\n]*\b(?:allowed|ok|allow)["']?\s*:\s*(?:False|false))|require_approval|requireApproval/;
527
+ for (const { path, content } of files) {
528
+ const raw = content.split('\n');
529
+ const lines = maskNonCode(content, path).split('\n');
530
+ for (let i = 0; i < lines.length; i++) {
531
+ if (COMMENT_LINE.test(lines[i]) || !trustTest.test(lines[i])) continue;
532
+ let logAt = -1;
533
+ for (let j = i; j <= Math.min(i + 8, lines.length - 1); j++) {
534
+ if (!COMMENT_LINE.test(lines[j]) && logCall.test(lines[j])) { logAt = j; break; }
535
+ }
536
+ if (logAt < 0) continue;
537
+ let blocks = false;
538
+ for (let j = logAt; j <= Math.min(logAt + 8, lines.length - 1); j++) {
539
+ if (!COMMENT_LINE.test(lines[j]) && blocking.test(lines[j])) { blocks = true; break; }
540
+ }
541
+ sites.push({ file: path, line: i + 1, blocks });
542
+ if (!blocks && evidence.length < 3) {
543
+ evidence.push({
544
+ file: path,
545
+ line: i + 1,
546
+ snippet: `${(raw[i] || '').trim().slice(0, 120)} // logs at line ${logAt + 1}; no raise/throw/denial/approval within 8 lines`,
547
+ });
548
+ }
549
+ }
550
+ }
551
+ const logOnly = sites.filter((s) => !s.blocks).length;
552
+ const flagged = logOnly > 0;
553
+ let notes;
554
+ if (sites.length === 0) {
555
+ notes = 'No trust-label check that logs was found; nothing to flag.';
556
+ } else if (flagged) {
557
+ notes = `${logOnly} of ${sites.length} trust-label check(s) log the untrusted case without blocking. `
558
+ + 'A gate exists, but logging is not a restriction (Step 2): side-effect tools still run with untrusted data in context. '
559
+ + 'Verify manually; if confirmed, mark PARTIAL rather than PASS.';
560
+ } else {
561
+ notes = 'Every trust-label check that logs also blocks (raise/throw/denial/approval).';
562
+ }
563
+ return { flagged, evidence, notes };
564
+ }
565
+
363
566
  const REGISTRY = {
364
567
  kill_switch_restart_latched: killSwitchRestartLatched,
365
568
  injection_log_only: injectionLogOnly,
366
569
  pii_incomplete_classes: piiIncompleteClasses,
367
570
  rate_limit_no_retry_after: rateLimitNoRetryAfter,
571
+ wildcard_tool_scope: wildcardToolScope,
572
+ untrusted_gate_log_only: untrustedGateLogOnly,
368
573
  };
369
574
 
370
- module.exports = { REGISTRY };
575
+ module.exports = { REGISTRY, maskNonCode };
package/lib/threats.js ADDED
@@ -0,0 +1,381 @@
1
+ /**
2
+ * v3.0: `aigis threats`: a starting threat model for a system's entry
3
+ * points, read from the vendored MITRE ATLAS catalog (SPEC S5).
4
+ *
5
+ * Scope comes from the approved trait -> entry-point map, not from the
6
+ * mitigations the areas already cite (D5), so gaps can appear. Every
7
+ * (technique, mitigation) pair printed is one of MITRE's direct
8
+ * `mitigates` links (D6). Order is maturity, then MITRE case-study count,
9
+ * then id (D7). No color, no timestamp, no network (D11).
10
+ *
11
+ * The CLI (bin/aigis.js) only parses flags, calls these functions, prints
12
+ * and sets the exit code. Input problems throw ThreatsInputError (exit 1);
13
+ * catalog problems throw AtlasCatalogError (exit 2, see catalogErrorLine).
14
+ */
15
+
16
+ const atlas = require('./atlas');
17
+ const { classify, ALL_TRAITS } = require('./classify');
18
+ const { getUserJurisdictions, filterAreasByJurisdiction } = require('./jurisdiction');
19
+ const { normalizeDescription, assignUniqueSlugs, resolveTraits } = require('./build');
20
+ const { detectTraitsFromText } = require('./keywords');
21
+
22
+ const DEFAULT_TOP = 10;
23
+ const MAX_TOP = 25;
24
+ const MAX_MITIGATION_LINES = 4;
25
+ const MAX_GAP_LINES = 8;
26
+ const MAX_REDTEAM = 5;
27
+
28
+ const MISSING_INPUT_LINES = [
29
+ 'Provide --traits, a quoted description, or both.',
30
+ 'Example: aigis threats --traits uses-llm,uses-rag,is-agentic',
31
+ 'Example: aigis threats "customer support agent that answers from our docs and can file tickets"',
32
+ ];
33
+
34
+ class ThreatsInputError extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = 'ThreatsInputError';
38
+ this.exitCode = 1;
39
+ }
40
+ }
41
+
42
+ // ── Input parsing ───────────────────────────────────────────────────────
43
+
44
+ function splitTraits(flag) {
45
+ if (flag === undefined || flag === null || flag === false) return [];
46
+ const list = String(flag).split(',').map((t) => t.trim()).filter(Boolean);
47
+ return [...new Set(list)];
48
+ }
49
+
50
+ /**
51
+ * --top: an integer from 1 to 25, default 10. Throws ThreatsInputError.
52
+ */
53
+ function parseTop(value) {
54
+ if (value === undefined || value === null) return DEFAULT_TOP;
55
+ const text = String(value).trim();
56
+ const n = /^\d+$/.test(text) ? Number(text) : NaN;
57
+ if (!Number.isInteger(n) || n < 1 || n > MAX_TOP) {
58
+ throw new ThreatsInputError('--top must be an integer from 1 to 25. The full catalog is at https://atlas.mitre.org.');
59
+ }
60
+ return n;
61
+ }
62
+
63
+ /**
64
+ * Resolve the final trait set (S5.2). Never prompts.
65
+ * --traits: split, trimmed, unknown -> exit 1.
66
+ * description: detected like `aigis build` (uncertain traits included and marked).
67
+ * Returns { traits, uncertainTraits, description (normalized or null), traitsFlag }.
68
+ */
69
+ function resolveThreatTraits({ description, traitsFlag } = {}) {
70
+ const flagTraits = Array.isArray(traitsFlag) ? [...new Set(traitsFlag)] : splitTraits(traitsFlag);
71
+ const normalized = normalizeDescription(description);
72
+
73
+ if (!flagTraits.length && !normalized) throw new ThreatsInputError(MISSING_INPUT_LINES.join('\n'));
74
+
75
+ const unknown = flagTraits.filter((t) => !ALL_TRAITS.includes(t));
76
+ if (unknown.length) {
77
+ throw new ThreatsInputError(`Unknown traits: ${unknown.join(', ')}. Run "aigis traits" to see available traits.`);
78
+ }
79
+
80
+ let fromDescription = [];
81
+ let uncertain = [];
82
+ if (normalized) {
83
+ const detection = detectTraitsFromText(normalized);
84
+ const withSlugs = { ...detection, low_confidence_matches: assignUniqueSlugs(detection.low_confidence_matches) };
85
+ const resolved = resolveTraits(withSlugs, {}, { uncertainAsIncluded: true });
86
+ fromDescription = resolved.all_traits;
87
+ uncertain = resolved.uncertain_traits;
88
+ }
89
+
90
+ if (!flagTraits.length && !fromDescription.length) {
91
+ throw new ThreatsInputError('No traits resolved from description. Pass --traits <list> (run "aigis traits" to see them).');
92
+ }
93
+
94
+ const flagSet = new Set(flagTraits);
95
+ const traits = [...new Set([...flagTraits, ...fromDescription])].sort();
96
+ const uncertainTraits = uncertain.filter((t) => !flagSet.has(t)).sort();
97
+ return { traits, uncertainTraits, description: normalized || null, traitsFlag: flagTraits };
98
+ }
99
+
100
+ // ── Model ───────────────────────────────────────────────────────────────
101
+
102
+ function recommendedAreasFor(traits) {
103
+ const result = classify(traits);
104
+ return filterAreasByJurisdiction(result.implement_files, getUserJurisdictions(traits));
105
+ }
106
+
107
+ /**
108
+ * Build the threat model (S5.3). Loads the catalog and the entry-point map
109
+ * first, so a broken install fails before any other work (AtlasCatalogError).
110
+ */
111
+ function buildThreatModel({ traits, uncertainTraits = [], description = null, traitsFlag = [], top, redteam = false } = {}) {
112
+ const catalog = atlas.loadCatalog();
113
+ const entryFile = atlas.loadEntryPoints();
114
+ const shownLimit = top === undefined || top === null ? DEFAULT_TOP : parseTop(top);
115
+
116
+ const finalTraits = [...new Set(traits || [])].sort();
117
+ const uncertainSet = new Set(uncertainTraits || []);
118
+ const recommendedAreas = recommendedAreasFor(finalTraits);
119
+ const recommendedSet = new Set(recommendedAreas);
120
+ const areasByMitigation = atlas.mitigationAreas();
121
+
122
+ // Entry points: one per final trait that the map knows, trait ascending.
123
+ const entryPoints = finalTraits
124
+ .filter((t) => Object.hasOwn(entryFile.entry_points, t))
125
+ .map((t) => {
126
+ const e = entryFile.entry_points[t];
127
+ return {
128
+ trait: t,
129
+ surface: typeof e.surface === 'string' && e.surface ? e.surface : t,
130
+ uncertain: uncertainSet.has(t),
131
+ techniques: [...e.techniques],
132
+ };
133
+ });
134
+
135
+ // In-scope techniques: union over entry points, sorted with compareTechniques.
136
+ const entryTraitsById = new Map();
137
+ for (const e of entryPoints) {
138
+ for (const id of e.techniques) {
139
+ if (!entryTraitsById.has(id)) entryTraitsById.set(id, []);
140
+ entryTraitsById.get(id).push(e.trait);
141
+ }
142
+ }
143
+ const scope = [...entryTraitsById.keys()].map((id) => atlas.technique(id)).sort(atlas.compareTechniques);
144
+
145
+ // Mitigations over ALL in-scope techniques (gaps, counts, unmitigated).
146
+ const mitigationToScope = new Map();
147
+ const unmitigated = [];
148
+ for (const t of scope) {
149
+ const mids = atlas.mitigationsForTechnique(t.id);
150
+ if (!mids.length) unmitigated.push(t.id);
151
+ for (const m of mids) {
152
+ if (!mitigationToScope.has(m.id)) mitigationToScope.set(m.id, []);
153
+ mitigationToScope.get(m.id).push(t.id);
154
+ }
155
+ }
156
+ const areasOf = (mid) => areasByMitigation[mid] || [];
157
+ const gaps = [...mitigationToScope.entries()]
158
+ .filter(([mid]) => !areasOf(mid).length)
159
+ .map(([id, tids]) => ({ id, techniques: [...tids].sort() }))
160
+ .sort((a, b) => b.techniques.length - a.techniques.length || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
161
+ const withArea = [...mitigationToScope.keys()].filter((mid) => areasOf(mid).length).length;
162
+
163
+ const shown = scope.slice(0, shownLimit).map((t) => ({
164
+ id: t.id,
165
+ name: t.display_name,
166
+ maturity: t.maturity,
167
+ tactics: t.tactics.map((x) => ({ id: x.id, name: x.name })),
168
+ entry_traits: [...entryTraitsById.get(t.id)].sort(),
169
+ case_studies: t.case_studies,
170
+ mitigations: atlas.mitigationsForTechnique(t.id).map((m) => ({
171
+ id: m.id,
172
+ areas: areasOf(m.id).map((areaId) => ({ id: areaId, recommended: recommendedSet.has(areaId) })),
173
+ })),
174
+ }));
175
+
176
+ const usedMitigations = new Set([...gaps.map((g) => g.id), ...shown.flatMap((t) => t.mitigations.map((m) => m.id))]);
177
+ const mitigationNames = {};
178
+ for (const id of [...usedMitigations].sort()) mitigationNames[id] = catalog.mitigations[id].name;
179
+
180
+ const model = {
181
+ atlas: {
182
+ version: atlas.PINNED.version,
183
+ disclaimer: atlas.DISCLAIMER,
184
+ source_sha256: atlas.PINNED.sha256,
185
+ license: catalog.source.license || 'Apache-2.0',
186
+ },
187
+ input: { description: description || null, traits_flag: [...(traitsFlag || [])] },
188
+ traits: finalTraits,
189
+ uncertain_traits: finalTraits.filter((t) => uncertainSet.has(t)),
190
+ entry_points: entryPoints,
191
+ techniques_in_scope: scope.length,
192
+ techniques_shown: shown.length,
193
+ techniques: shown,
194
+ mitigation_names: mitigationNames,
195
+ gaps,
196
+ unmitigated_techniques: unmitigated,
197
+ mitigation_counts: { in_scope: mitigationToScope.size, with_area: withArea, without_area: gaps.length },
198
+ recommended_areas: recommendedAreas,
199
+ };
200
+ if (redteam) model.redteam = buildRedteam(model);
201
+ return model;
202
+ }
203
+
204
+ // ── Red-team stubs (S5.5, SHOULD) ───────────────────────────────────────
205
+
206
+ function buildRedteam(model) {
207
+ const surfaces = Object.fromEntries(model.entry_points.map((e) => [e.trait, e.surface]));
208
+ return model.techniques.slice(0, MAX_REDTEAM).map((t, i) => {
209
+ const trait = t.entry_traits[0];
210
+ return {
211
+ id: `RT-${String(i + 1).padStart(2, '0')}`,
212
+ technique: t.id,
213
+ name: t.name,
214
+ maturity: t.maturity,
215
+ tactics: t.tactics.map((x) => x.name),
216
+ entry_point: { trait, surface: surfaces[trait] },
217
+ attempt: 'TODO: write the concrete attack input for this system through this entry point.',
218
+ expected_defenses: t.mitigations
219
+ .filter((m) => m.areas.length)
220
+ .map((m) => ({ mitigation: m.id, areas: m.areas.map((a) => a.id) })),
221
+ pass_criteria: 'Blocked or contained, no unauthorized tool call or data leaves the system, and the attempt appears in the audit log.',
222
+ rerun_when: 'Tools, write access, memory, data sources or the model change.',
223
+ };
224
+ });
225
+ }
226
+
227
+ // ── Output ──────────────────────────────────────────────────────────────
228
+
229
+ function plural(n, word) {
230
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
231
+ }
232
+
233
+ function mitigationLine(m, names) {
234
+ if (!m.areas.length) return ` - ${m.id} ${names[m.id]} -> no mapped Aigis area`;
235
+ // `*` marks an area classify did not recommend for these traits (legend in Next).
236
+ const areas = m.areas.map((a) => (a.recommended ? a.id : `${a.id}*`)).join(', ');
237
+ return ` - ${m.id} ${names[m.id]} -> ${areas}`;
238
+ }
239
+
240
+ function formatThreatsText(model) {
241
+ const names = model.mitigation_names;
242
+ const L = [];
243
+ L.push(`# Aigis threat model (MITRE ATLAS v${model.atlas.version})`);
244
+ L.push('');
245
+ L.push(`> ${model.atlas.disclaimer}`);
246
+ L.push('> This is a starting list from your traits, not proof of coverage. Method: `aigis template threat-model`.');
247
+ L.push('> An area named after a mitigation (->) helps implement it, in part.');
248
+ L.push('');
249
+ L.push(`Traits (${model.traits.length}): ${model.traits.join(', ')}`);
250
+ if (model.uncertain_traits.length) {
251
+ L.push(`Uncertain traits (${model.uncertain_traits.length}, marked ⚠): ${model.uncertain_traits.join(', ')}`);
252
+ }
253
+ L.push('Missing a trait? Rerun with --traits (see `aigis traits`).');
254
+ L.push('');
255
+
256
+ L.push(`## Entry points (${model.entry_points.length})`);
257
+ L.push('');
258
+ if (!model.entry_points.length) {
259
+ L.push('No ATLAS entry points are mapped for these traits.');
260
+ } else {
261
+ for (const e of model.entry_points) {
262
+ L.push(`- ${e.uncertain ? '⚠ ' : ''}${e.trait}: ${e.surface} (${plural(e.techniques.length, 'technique')})`);
263
+ }
264
+ }
265
+ L.push('');
266
+
267
+ L.push(`## Techniques (showing ${model.techniques_shown} of ${model.techniques_in_scope}; Realized first, then by number of MITRE case studies)`);
268
+ L.push('');
269
+ if (!model.techniques.length) {
270
+ L.push('- None for these traits.');
271
+ }
272
+ model.techniques.forEach((t, i) => {
273
+ const tactics = t.tactics.map((x) => x.name).join(', ');
274
+ L.push(`${i + 1}. ${t.id} ${t.name} [${t.maturity}] | tactic: ${tactics} | entry: ${t.entry_traits.join(', ')} | case studies: ${t.case_studies}`);
275
+ if (!t.mitigations.length) {
276
+ L.push(' - No mitigation listed by MITRE for this technique.');
277
+ return;
278
+ }
279
+ const ordered = [...t.mitigations.filter((m) => m.areas.length), ...t.mitigations.filter((m) => !m.areas.length)];
280
+ for (const m of ordered.slice(0, MAX_MITIGATION_LINES)) L.push(mitigationLine(m, names));
281
+ if (ordered.length > MAX_MITIGATION_LINES) {
282
+ L.push(` - +${ordered.length - MAX_MITIGATION_LINES} more mitigations (use --json)`);
283
+ }
284
+ });
285
+ L.push('');
286
+
287
+ L.push(`## Gaps: mitigations MITRE links to these techniques with no mapped Aigis area (${model.gaps.length})`);
288
+ L.push('');
289
+ if (!model.gaps.length) {
290
+ L.push('- None for these techniques.');
291
+ } else {
292
+ for (const g of model.gaps.slice(0, MAX_GAP_LINES)) {
293
+ L.push(`- ${g.id} ${names[g.id]} (MITRE links it to ${g.techniques.join(', ')})`);
294
+ }
295
+ if (model.gaps.length > MAX_GAP_LINES) L.push(`- +${model.gaps.length - MAX_GAP_LINES} more (use --json)`);
296
+ }
297
+ L.push('');
298
+
299
+ if (model.redteam && model.redteam.length) {
300
+ L.push(`## Red-team test stubs (${model.redteam.length})`);
301
+ L.push('');
302
+ for (const r of model.redteam) {
303
+ const defenses = r.expected_defenses.length
304
+ ? r.expected_defenses.map((d) => `${d.mitigation} -> ${d.areas.join(', ')}`).join('; ')
305
+ : 'none with a mapped Aigis area (see Gaps)';
306
+ L.push(`${r.id} ${r.technique} ${r.name} [${r.maturity}] | entry: ${r.entry_point.trait} (${r.entry_point.surface})`);
307
+ L.push(` - Attempt: ${r.attempt}`);
308
+ L.push(` - Expected defenses: ${defenses}`);
309
+ L.push(` - Pass: ${r.pass_criteria}`);
310
+ L.push(` - Rerun when: ${r.rerun_when}`);
311
+ }
312
+ L.push('');
313
+ }
314
+
315
+ L.push('## Next');
316
+ L.push('');
317
+ L.push('- Fetch the areas named above with `aigis get <area>`. An area marked * is not in your brief: classify did not recommend it for these traits.');
318
+ L.push('- Fill in the method: `aigis template threat-model`.');
319
+ if (!Object.hasOwn(model, 'redteam')) L.push('- Test-case stubs: rerun with `--redteam`.');
320
+ L.push('- Rerun when you add tools, write access, memory or a data source, before launch, and after an incident.');
321
+ return `${L.join('\n')}\n`;
322
+ }
323
+
324
+ // JSON layout (S5.1 "2-space indent"): every nesting level is indented by two
325
+ // spaces, as JSON.stringify(model, null, 2) does, except that a container
326
+ // holding only scalars (for example `{ "id": "audit-logging", "recommended": true }`
327
+ // or `["AML.T0051.001", "AML.T0070"]`) is written on one line when that line
328
+ // fits in JSON_INLINE_WIDTH columns. Same data, same key order, deterministic;
329
+ // it keeps the default output inside the AC11 size cap.
330
+ const JSON_INLINE_WIDTH = 100;
331
+
332
+ function isContainer(value) {
333
+ return value !== null && typeof value === 'object';
334
+ }
335
+
336
+ function inlineLeaf(value) {
337
+ if (Array.isArray(value)) return value.length ? `[${value.map((v) => JSON.stringify(v)).join(', ')}]` : '[]';
338
+ const keys = Object.keys(value);
339
+ return keys.length ? `{ ${keys.map((k) => `${JSON.stringify(k)}: ${JSON.stringify(value[k])}`).join(', ')} }` : '{}';
340
+ }
341
+
342
+ function layoutJSON(value, indent, prefixLength) {
343
+ if (!isContainer(value)) return JSON.stringify(value);
344
+ const items = Array.isArray(value) ? value : Object.values(value);
345
+ if (!items.some(isContainer)) {
346
+ const inline = inlineLeaf(value);
347
+ if (indent.length + prefixLength + inline.length <= JSON_INLINE_WIDTH || !items.length) return inline;
348
+ }
349
+ const inner = `${indent} `;
350
+ if (Array.isArray(value)) {
351
+ return `[\n${value.map((v) => `${inner}${layoutJSON(v, inner, 0)}`).join(',\n')}\n${indent}]`;
352
+ }
353
+ const lines = Object.keys(value).map((k) => {
354
+ const key = `${JSON.stringify(k)}: `;
355
+ return `${inner}${key}${layoutJSON(value[k], inner, key.length)}`;
356
+ });
357
+ return `{\n${lines.join(',\n')}\n${indent}}`;
358
+ }
359
+
360
+ function formatThreatsJSON(model) {
361
+ // Round-trip first so undefined values and key handling match JSON.stringify.
362
+ return `${layoutJSON(JSON.parse(JSON.stringify(model)), '', 0)}\n`;
363
+ }
364
+
365
+ /** The single stderr line for a catalog or entry-point failure (S5.6, exit 2). */
366
+ function catalogErrorLine(err) {
367
+ return `ATLAS catalog unavailable: ${err.file} ${err.code}. Reinstall the aigis package.`;
368
+ }
369
+
370
+ module.exports = {
371
+ DEFAULT_TOP,
372
+ MAX_TOP,
373
+ ThreatsInputError,
374
+ AtlasCatalogError: atlas.AtlasCatalogError,
375
+ parseTop,
376
+ resolveThreatTraits,
377
+ buildThreatModel,
378
+ formatThreatsText,
379
+ formatThreatsJSON,
380
+ catalogErrorLine,
381
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aigis-ai/cli",
3
- "version": "2.1.0",
3
+ "version": "3.0.0",
4
4
  "description": "AI governance guardrails for coding agents. Framework-aligned security and compliance patterns from NIST AI RMF, OWASP Top 10 for LLMs, and ISO/IEC 42001.",
5
5
  "main": "bin/aigis.js",
6
6
  "bin": {
@@ -35,5 +35,8 @@
35
35
  "commander": "^12.0.0",
36
36
  "chalk": "^4.1.2",
37
37
  "gray-matter": "^4.0.3"
38
+ },
39
+ "scripts": {
40
+ "test": "node scripts/test-all.js"
38
41
  }
39
42
  }