archsutra-ai 0.1.5 → 0.2.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 (113) hide show
  1. package/CHANGELOG.md +47 -6
  2. package/README.md +83 -11
  3. package/dist/audit.js +125 -44
  4. package/dist/cli.js +184 -96
  5. package/dist/drift.js +29 -15
  6. package/dist/fsutil.js +117 -20
  7. package/dist/history.js +40 -0
  8. package/dist/html.js +10 -8
  9. package/dist/map.js +26 -5
  10. package/dist/mcp.js +70 -55
  11. package/dist/redact.js +24 -11
  12. package/dist/report.js +69 -19
  13. package/dist/rules-extra.js +59 -0
  14. package/dist/secret-patterns.js +69 -0
  15. package/dist/suppress.js +31 -19
  16. package/dist/verify.js +2 -2
  17. package/dist/write.js +71 -0
  18. package/docs/architecture/overview.html +29 -12
  19. package/docs/architecture/overview.md +2 -2
  20. package/docs/architecture/threat-model.html +28 -11
  21. package/docs/assets/charts/coverage-dark.svg +11 -0
  22. package/docs/assets/charts/coverage.svg +11 -0
  23. package/docs/assets/charts/finding-anatomy-dark.svg +20 -0
  24. package/docs/assets/charts/finding-anatomy.svg +20 -0
  25. package/docs/assets/charts/pipeline-dark.svg +13 -0
  26. package/docs/assets/charts/pipeline.svg +13 -0
  27. package/docs/assets/charts/precision-by-batch-dark.svg +12 -0
  28. package/docs/assets/charts/precision-by-batch.svg +12 -0
  29. package/docs/assets/charts/precision-by-rule-dark.svg +12 -0
  30. package/docs/assets/charts/precision-by-rule.svg +12 -0
  31. package/docs/assets/charts/sample-findings-by-severity-dark.svg +11 -0
  32. package/docs/assets/charts/sample-findings-by-severity.svg +11 -0
  33. package/docs/assets/charts/scan-time-dark.svg +11 -0
  34. package/docs/assets/charts/scan-time.svg +11 -0
  35. package/docs/assets/site.css +259 -138
  36. package/docs/assets/site.js +92 -6
  37. package/docs/community/good-first-issues.html +28 -11
  38. package/docs/compatibility/matrix.html +28 -11
  39. package/docs/compatibility/smoke-tests/index.html +28 -11
  40. package/docs/decisions/ADR-0001-deterministic-cli-plus-ide-skills.html +28 -11
  41. package/docs/guides/cheat-sheet.html +100 -0
  42. package/docs/guides/cheat-sheet.md +146 -0
  43. package/docs/guides/ci-recipes.html +170 -0
  44. package/docs/guides/ci-recipes.md +176 -0
  45. package/docs/guides/evidence-at-a-glance.html +93 -0
  46. package/docs/guides/evidence-at-a-glance.md +65 -0
  47. package/docs/guides/getting-started.html +151 -0
  48. package/docs/guides/getting-started.md +160 -0
  49. package/docs/guides/how-it-works.html +161 -0
  50. package/docs/guides/how-it-works.md +148 -0
  51. package/docs/guides/mcp-server.html +99 -0
  52. package/docs/guides/mcp-server.md +81 -0
  53. package/docs/guides/reading-a-report.html +119 -0
  54. package/docs/guides/reading-a-report.md +111 -0
  55. package/docs/guides/real-world-scenarios.html +287 -0
  56. package/docs/guides/real-world-scenarios.md +377 -0
  57. package/docs/handbook/01-executive-summary.html +30 -13
  58. package/docs/handbook/01-executive-summary.md +2 -2
  59. package/docs/handbook/02-functional-specification.html +30 -13
  60. package/docs/handbook/02-functional-specification.md +3 -3
  61. package/docs/handbook/03-technical-specification.html +31 -14
  62. package/docs/handbook/03-technical-specification.md +3 -3
  63. package/docs/handbook/04-architecture.html +29 -12
  64. package/docs/handbook/04-architecture.md +1 -1
  65. package/docs/handbook/05-user-guide.html +33 -15
  66. package/docs/handbook/05-user-guide.md +5 -4
  67. package/docs/handbook/06-cli-reference.html +52 -16
  68. package/docs/handbook/06-cli-reference.md +47 -4
  69. package/docs/handbook/07-security-privacy-legal.html +31 -12
  70. package/docs/handbook/07-security-privacy-legal.md +4 -0
  71. package/docs/handbook/08-testing-and-proof.html +32 -15
  72. package/docs/handbook/08-testing-and-proof.md +4 -4
  73. package/docs/handbook/09-compatibility-and-roadmap.html +29 -12
  74. package/docs/handbook/09-compatibility-and-roadmap.md +2 -1
  75. package/docs/handbook/10-contributor-guide.html +29 -12
  76. package/docs/handbook/10-contributor-guide.md +1 -1
  77. package/docs/handbook/11-glossary-and-faq.html +34 -13
  78. package/docs/handbook/11-glossary-and-faq.md +7 -1
  79. package/docs/handbook/12-rule-catalog.html +59 -19
  80. package/docs/handbook/12-rule-catalog.md +62 -5
  81. package/docs/handbook/13-trust-and-assurance.html +29 -12
  82. package/docs/handbook/13-trust-and-assurance.md +1 -1
  83. package/docs/handbook/14-real-world-evaluation.html +28 -11
  84. package/docs/handbook/15-supply-chain-and-release.html +28 -11
  85. package/docs/handbook/16-performance-and-quality-metrics.html +28 -11
  86. package/docs/handbook/16-performance-and-quality-metrics.md +1 -1
  87. package/docs/handbook/README.md +4 -2
  88. package/docs/handbook/index.html +31 -13
  89. package/docs/index.html +101 -51
  90. package/docs/legal/legal-review-brief.html +28 -11
  91. package/docs/legal/trademark-and-name-clearance.html +28 -11
  92. package/docs/proof/accessibility.html +28 -11
  93. package/docs/proof/benchmarks.json +9 -9
  94. package/docs/proof/benchmarks.md +4 -4
  95. package/docs/proof/test-results.txt +56 -40
  96. package/docs/rfc/0001-archsutra-v0.1.html +28 -11
  97. package/docs/sample-report/architecture-register.json +46 -0
  98. package/docs/sample-report/audit-report.html +123 -0
  99. package/docs/sample-report/audit-report.md +314 -0
  100. package/docs/sample-report/current-state.html +77 -0
  101. package/docs/sample-report/current-state.md +51 -0
  102. package/docs/sample-report/findings.json +478 -0
  103. package/docs/sample-report/findings.sarif +754 -0
  104. package/docs/sample-report/index.html +57 -0
  105. package/docs/sample-report/overview.md +11 -0
  106. package/docs/search-index.json +1 -0
  107. package/docs/sitemap.xml +39 -28
  108. package/llms.txt +11 -2
  109. package/package.json +3 -2
  110. package/schemas/findings.schema.json +4 -3
  111. package/skills/architecture-audit/SKILL.md +2 -2
  112. package/skills/architecture-audit/references/report-template.md +1 -1
  113. package/skills/architecture-verification/references/fitness-functions.md +1 -1
package/dist/cli.js CHANGED
@@ -3,7 +3,10 @@ import { promises as fs } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { HOSTS, detectHosts, doctor, install, packageRoot, planInstall, uninstall } from './adapters.js';
5
5
  import { runAudit } from './audit.js';
6
- import { exists } from './fsutil.js';
6
+ import { exists, walk } from './fsutil.js';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { UsageError, mark, writeReports } from './write.js';
9
+ import { isExpired, readSuppressions } from './suppress.js';
7
10
  import { buildMap } from './map.js';
8
11
  import { markdownTitle, renderAuditHtml, renderCurrentStateHtml, renderMarkdownHtml, renderOverviewHtml } from './html.js';
9
12
  import { findingsJson, registerJson, renderAuditReport, renderCurrentState, renderOverview, renderSarif } from './report.js';
@@ -11,7 +14,7 @@ import { diffFindings, renderDrift } from './drift.js';
11
14
  import { serveMcp } from './mcp.js';
12
15
  import { renderCost, renderDesign, renderModernize, renderReview, renderThreatModel } from './scaffold.js';
13
16
  import { verifyProject } from './verify.js';
14
- const EXIT = { ok: 0, findings: 1, usage: 2, needsModel: 3, verifyFailed: 4, error: 5 };
17
+ const EXIT = { ok: 0, findings: 1, usage: 2, needsModel: 3, verifyFailed: 4, error: 5, incomplete: 6 };
15
18
  const HELP = `ArchSutra AI - Design. Audit. Evolve.
16
19
 
17
20
  Usage: archsutra <command> [path] [options]
@@ -28,10 +31,12 @@ Deterministic commands (no AI, no network, read-only unless noted):
28
31
  cost [path] states that cost is not assessed
29
32
  drift diff two findings.json files, or a project against --baseline
30
33
  compare same diff as drift, for two ArchSutra snapshots
34
+ baseline <create|update> [path] record today's findings in .archsutra/baseline.json
35
+ suppressions [path] list suppressions and show which have expired
31
36
  verify [path] validate skills, agents, links, diagrams, findings.json
32
37
  export [path] write every report as Markdown and HTML (use --output)
33
38
  html <file.md> write a readable HTML page next to a Markdown report
34
- mcp MCP server on stdio (tools: audit, map, drift)
39
+ mcp MCP server on stdio (tools: audit, map, drift); limited to --root
35
40
  install install skills/agents into a project (--host, --target)
36
41
  uninstall remove files ArchSutra installed (--host, --target)
37
42
  hosts list adapters and their support level
@@ -44,45 +49,113 @@ Options:
44
49
  --format <md|html> stdout format for audit and map when not writing files (default md)
45
50
  --dry-run show what would change; write nothing
46
51
  --output <dir> directory for audit, map, export, and the starter commands
47
- --baseline <file> findings.json to diff against (drift, compare)
52
+ --baseline <file> findings.json to diff against (drift, compare, audit --fail-on-new, baseline)
48
53
  --host <id> claude | cursor | codex | copilot | gemini
49
54
  --target <dir> project to install into (default .)
50
- --force overwrite modified files (backups kept)
55
+ --force overwrite modified or foreign files (backups kept)
51
56
  --fail-on <sev> audit, review, and drift exit 1 at or above this severity
57
+ --strict audit and review exit 6 when nothing was scanned or the scan was cut short
58
+ --fail-on-new audit: exit 1 only for locations that are not in the baseline (at --fail-on or above)
59
+ --no-score leave the scorecard out
60
+ --history also look for secrets in local git history
61
+ --history-limit <n> commits read by --history (default 1000)
62
+ --include <globs> scan only matching paths (comma separated)
63
+ --exclude <globs> skip matching paths; .archsutraignore works too
64
+ --respect-gitignore skip what git ignores
65
+ --max-files <n> scan limit (default 5000)
66
+ --max-bytes <n> total bytes limit (default 125829120)
67
+ --time-budget <s> walk time limit in seconds (default 15)
68
+ --root <dir> mcp: only paths inside this directory (default: current directory)
52
69
  --verbose extra detail
53
70
  --version, --help
71
+
72
+ Exit codes: 0 ok, 1 findings at or above --fail-on (also doctor/install problems),
73
+ 2 usage error, 4 verify failed, 5 internal error, 6 incomplete scan (--strict).
54
74
  `;
55
75
  function parse(argv) {
56
76
  const flags = {};
57
77
  const pos = [];
58
- const withValue = new Set(['output', 'host', 'target', 'fail-on', 'format', 'baseline']);
78
+ const withValue = ['output', 'host', 'target', 'fail-on', 'format', 'baseline', 'root', 'max-files', 'max-bytes', 'time-budget', 'include', 'exclude', 'history-limit'];
79
+ const switches = ['json', 'dry-run', 'force', 'verbose', 'version', 'help', 'strict', 'fail-on-new', 'no-score', 'history', 'respect-gitignore'];
59
80
  for (let i = 0; i < argv.length; i++) {
60
81
  const a = argv[i];
61
- if (a.startsWith('--')) {
62
- const key = a.slice(2);
63
- if (withValue.has(key))
64
- flags[key] = argv[++i] ?? '';
65
- else
82
+ if (a === '-h')
83
+ flags.help = true;
84
+ else if (a === '-v')
85
+ flags.version = true;
86
+ else if (a.startsWith('-') && a.length > 1) {
87
+ const eq = a.indexOf('=');
88
+ const key = a.slice(2, eq < 0 ? undefined : eq);
89
+ if (a.startsWith('--') && withValue.includes(key)) {
90
+ const value = eq < 0 ? argv[++i] : a.slice(eq + 1);
91
+ if (!value || (eq < 0 && value.startsWith('--')))
92
+ throw new UsageError(`--${key} needs a value.`);
93
+ flags[key] = value;
94
+ }
95
+ else if (a.startsWith('--') && switches.includes(key) && eq < 0)
66
96
  flags[key] = true;
97
+ else {
98
+ const near = [...withValue, ...switches].map((k) => ({ k, d: distance(key, k) })).sort((x, y) => x.d - y.d)[0];
99
+ throw new UsageError(`Unknown option "${a}".${near.d <= 3 ? ` Did you mean --${near.k}?` : ''} See archsutra --help.`);
100
+ }
67
101
  }
68
102
  else
69
103
  pos.push(a);
70
104
  }
71
105
  return { cmd: pos.shift(), pos, flags };
72
106
  }
107
+ /** Levenshtein distance, for "did you mean". */
108
+ function distance(a, b) {
109
+ let row = Array.from({ length: b.length + 1 }, (_, j) => j);
110
+ for (let i = 1; i <= a.length; i++) {
111
+ const next = [i];
112
+ for (let j = 1; j <= b.length; j++)
113
+ next[j] = Math.min(next[j - 1] + 1, row[j] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
114
+ row = next;
115
+ }
116
+ return row[b.length];
117
+ }
118
+ function limitsFrom(flags) {
119
+ const num = (key, scale = 1) => {
120
+ if (flags[key] === undefined)
121
+ return undefined;
122
+ const n = Number(flags[key]);
123
+ if (!Number.isFinite(n) || n <= 0)
124
+ throw new UsageError(`--${key} must be a positive number.`);
125
+ return n * scale;
126
+ };
127
+ const list = (key) => (flags[key] === undefined ? undefined : String(flags[key]).split(',').map((g) => g.trim()).filter(Boolean));
128
+ return { maxFiles: num('max-files'), maxTotalBytes: num('max-bytes'), timeBudgetMs: num('time-budget', 1000), include: list('include'), exclude: list('exclude'), respectGitignore: Boolean(flags['respect-gitignore']) };
129
+ }
130
+ async function requireDir(dir) {
131
+ const st = await fs.stat(dir).catch(() => undefined);
132
+ if (!st?.isDirectory())
133
+ throw new UsageError(`Path not found or not a directory: ${dir}`);
134
+ }
135
+ function strictExit(flags, res) {
136
+ if (!flags.strict)
137
+ return undefined;
138
+ const c = res.map.coverage;
139
+ if (c.filesScanned > 0 && !c.truncated)
140
+ return undefined;
141
+ process.stderr.write(c.filesScanned === 0 ? 'Incomplete: 0 files scanned.\n' : 'Incomplete: scan stopped at a limit (raise --max-files, --max-bytes or --time-budget).\n');
142
+ return EXIT.incomplete;
143
+ }
73
144
  function out(json, data, text) {
74
145
  process.stdout.write(json ? `${JSON.stringify(data, null, 2)}\n` : `${text}\n`);
75
146
  }
76
- function insideProject(target, outputFlag) {
147
+ function insideProject(target, outputFlag, force = false) {
77
148
  const outDir = path.resolve(target, outputFlag);
78
149
  const rel = path.relative(target, outDir);
79
150
  if (rel.startsWith('..') || path.isAbsolute(rel))
80
- return undefined;
151
+ throw new UsageError('--output must stay inside the project directory.');
152
+ if (!rel && !force)
153
+ throw new UsageError('--output is the project root. Choose a sub-directory, or add --force.');
81
154
  return outDir;
82
155
  }
83
156
  function reportBundle(res) {
84
157
  const files = [
85
- { path: 'README.md', content: renderOverview(res) },
158
+ { path: 'overview.md', content: renderOverview(res) },
86
159
  { path: 'index.html', content: renderOverviewHtml(res) },
87
160
  { path: 'current-state.md', content: renderCurrentState(res.map) },
88
161
  { path: 'current-state.html', content: renderCurrentStateHtml(res.map) },
@@ -91,18 +164,13 @@ function reportBundle(res) {
91
164
  { path: 'findings.json', content: JSON.stringify(findingsJson(res), null, 2) },
92
165
  { path: 'findings.sarif', content: JSON.stringify(renderSarif(res), null, 2) },
93
166
  ];
94
- files.push({ path: 'architecture-register.json', content: JSON.stringify(registerJson(files), null, 2) });
95
- return files;
96
- }
97
- async function writeReportFiles(outDir, files, dry) {
98
- if (dry)
99
- return;
100
- await fs.mkdir(outDir, { recursive: true });
101
- for (const f of files)
102
- await fs.writeFile(path.join(outDir, f.path), f.content, 'utf8');
167
+ const marked = mark(files);
168
+ marked.push({ path: 'architecture-register.json', content: JSON.stringify(registerJson(marked), null, 2) });
169
+ return marked;
103
170
  }
104
171
  function wroteLine(dry, outDir, files, hint) {
105
- return `${dry ? 'Would write' : 'Wrote'} ${files.length} files to ${outDir}\n${files.map((f) => ` ${f.path}`).join('\n')}\n${hint}`;
172
+ const index = files.find((f) => f.path === 'index.html');
173
+ return `${dry ? 'Would write' : 'Wrote'} ${files.length} files to ${outDir}\n${files.map((f) => ` ${f.path}`).join('\n')}\n${hint}${index && !dry ? `\n${pathToFileURL(path.join(outDir, index.path)).href}` : ''}`;
106
174
  }
107
175
  async function readFindings(file) {
108
176
  const raw = JSON.parse(await fs.readFile(file, 'utf8'));
@@ -116,8 +184,6 @@ function severityExit(findings, th) {
116
184
  return undefined;
117
185
  const order = ['critical', 'high', 'medium', 'low', 'info'];
118
186
  const i = order.indexOf(th);
119
- if (i < 0)
120
- return EXIT.usage;
121
187
  return findings.some((f) => order.indexOf(f.severity) <= i) ? EXIT.findings : EXIT.ok;
122
188
  }
123
189
  async function main() {
@@ -135,6 +201,21 @@ async function main() {
135
201
  return args.cmd || args.flags.help ? EXIT.ok : EXIT.usage;
136
202
  }
137
203
  const target = path.resolve(args.pos[0] ?? '.');
204
+ const force = Boolean(args.flags.force);
205
+ const limits = limitsFrom(args.flags);
206
+ const th = args.flags['fail-on'];
207
+ if (th && !['critical', 'high', 'medium', 'low', 'info'].includes(th))
208
+ throw new UsageError(`Invalid --fail-on "${th}" (critical, high, medium, low, info).`);
209
+ if (['init', 'doctor', 'map', 'audit', 'verify', 'export', 'review', 'design', 'threat-model', 'modernize', 'cost', 'suppressions'].includes(args.cmd) || (['drift', 'compare'].includes(args.cmd) && args.flags.baseline))
210
+ await requireDir(target);
211
+ const historyLimit = args.flags['history-limit'] === undefined ? undefined : Number(args.flags['history-limit']);
212
+ if (historyLimit !== undefined && !(Number.isInteger(historyLimit) && historyLimit > 0))
213
+ throw new UsageError('--history-limit must be a positive whole number.');
214
+ if (args.flags['fail-on-new'] && args.cmd !== 'audit')
215
+ throw new UsageError('--fail-on-new works with audit. For two snapshots use drift --fail-on.');
216
+ const scan = async (dir) => runAudit(dir, await walk(dir, limits), { history: Boolean(args.flags.history), historyLimit, noScore: Boolean(args.flags['no-score']) });
217
+ const baselineOf = (dir) => path.resolve(String(args.flags.baseline ?? path.join(dir, '.archsutra', 'baseline.json')));
218
+ const save = (root, outDir, files) => writeReports(outDir, files, { dry, force, backupDir: path.join(root, '.archsutra', 'backup', new Date().toISOString().replace(/[:.]/g, '-')) });
138
219
  switch (args.cmd) {
139
220
  case 'hosts': {
140
221
  out(json, HOSTS, HOSTS.map((h) => `${h.id.padEnd(8)} ${h.support.padEnd(13)} ${h.label} - ${h.notes}`).join('\n'));
@@ -162,23 +243,19 @@ async function main() {
162
243
  return res.every((r) => r.ok) ? EXIT.ok : EXIT.findings;
163
244
  }
164
245
  case 'map': {
165
- const map = await buildMap(target);
246
+ const map = await buildMap(target, await walk(target, limits));
166
247
  const fmt = String(args.flags.format ?? 'md');
167
248
  if (args.flags.format && !['md', 'html'].includes(fmt)) {
168
249
  process.stderr.write(`Invalid --format "${fmt}" (use md or html)\n`);
169
250
  return EXIT.usage;
170
251
  }
171
252
  if ('output' in args.flags) {
172
- const outDir = insideProject(target, String(args.flags.output || 'docs/architecture'));
173
- if (!outDir) {
174
- process.stderr.write('--output must stay inside the project directory.\n');
175
- return EXIT.usage;
176
- }
177
- const files = [
253
+ const outDir = insideProject(target, String(args.flags.output), force);
254
+ const files = mark([
178
255
  { path: 'current-state.md', content: renderCurrentState(map) },
179
256
  { path: 'current-state.html', content: renderCurrentStateHtml(map) },
180
- ];
181
- await writeReportFiles(outDir, files, dry);
257
+ ]);
258
+ await save(target, outDir, files);
182
259
  out(json, { dryRun: dry, outDir, files: files.map((f) => f.path) }, wroteLine(dry, outDir, files, 'Open current-state.html in a browser. current-state.md is the same report in Markdown.'));
183
260
  return EXIT.ok;
184
261
  }
@@ -186,36 +263,62 @@ async function main() {
186
263
  return EXIT.ok;
187
264
  }
188
265
  case 'audit': {
189
- const res = await runAudit(target);
266
+ const res = await scan(target);
190
267
  const fmt = String(args.flags.format ?? 'md');
191
268
  if (args.flags.format && !['md', 'html'].includes(fmt)) {
192
269
  process.stderr.write(`Invalid --format "${fmt}" (use md or html)\n`);
193
270
  return EXIT.usage;
194
271
  }
272
+ let gate = severityExit(res.findings, th);
273
+ let fresh;
274
+ if (args.flags['fail-on-new']) {
275
+ const file = baselineOf(target);
276
+ if (!(await exists(file)))
277
+ throw new UsageError(`No baseline at ${file}. Create one with: archsutra baseline create`);
278
+ const diff = diffFindings(await readFindings(file), res.findings);
279
+ const rows = [...diff.added, ...diff.changed].map((x) => ({ severity: (x.after ?? 'info') }));
280
+ fresh = rows.length;
281
+ gate = severityExit(rows, th ?? 'info');
282
+ }
283
+ const strict = strictExit(args.flags, res);
284
+ const code = gate === EXIT.findings ? gate : strict ?? EXIT.ok;
285
+ const exitReason = code === EXIT.findings ? (args.flags['fail-on-new'] ? 'new-findings' : 'findings') : code === EXIT.incomplete ? 'incomplete' : 'ok';
195
286
  if ('output' in args.flags) {
196
- const outDir = insideProject(target, String(args.flags.output || 'docs/architecture'));
197
- if (!outDir) {
198
- process.stderr.write('--output must stay inside the project directory.\n');
199
- return EXIT.usage;
200
- }
287
+ const outDir = insideProject(target, String(args.flags.output), force);
201
288
  const files = reportBundle(res);
202
- await writeReportFiles(outDir, files, dry);
203
- out(json, { dryRun: dry, outDir, files: files.map((f) => f.path) }, wroteLine(dry, outDir, files, 'Open index.html in a browser. Each report also has a Markdown file beside it.'));
289
+ await save(target, outDir, files);
290
+ out(json, { dryRun: dry, outDir, files: files.map((f) => f.path), exitReason }, wroteLine(dry, outDir, files, 'Open index.html in a browser. Each report also has a Markdown file beside it.'));
204
291
  }
205
292
  else {
206
- out(json, findingsJson(res), fmt === 'html' ? renderAuditHtml(res) : renderAuditReport(res));
293
+ out(json, { ...findingsJson(res), exitReason, ...(fresh === undefined ? {} : { newLocations: fresh }) }, fmt === 'html' ? renderAuditHtml(res) : renderAuditReport(res));
207
294
  }
208
- const order = ['critical', 'high', 'medium', 'low', 'info'];
209
- const th = args.flags['fail-on'];
210
- if (th) {
211
- const i = order.indexOf(th);
212
- if (i < 0) {
213
- process.stderr.write(`Invalid --fail-on "${th}"\n`);
214
- return EXIT.usage;
215
- }
216
- if (res.findings.some((f) => order.indexOf(f.severity) <= i))
217
- return EXIT.findings;
295
+ if (fresh !== undefined && !json)
296
+ process.stderr.write(`${fresh} location(s) not in the baseline.\n`);
297
+ return code;
298
+ }
299
+ case 'baseline': {
300
+ const action = args.pos[0];
301
+ if (action !== 'create' && action !== 'update')
302
+ throw new UsageError('Use: archsutra baseline create [path] or archsutra baseline update [path]');
303
+ const dir = path.resolve(args.pos[1] ?? '.');
304
+ await requireDir(dir);
305
+ const file = baselineOf(dir);
306
+ if (action === 'create' && !force && (await exists(file)))
307
+ throw new UsageError(`A baseline already exists at ${file}. Use baseline update.`);
308
+ if (action === 'update' && !(await exists(file)))
309
+ throw new UsageError(`No baseline at ${file}. Use baseline create.`);
310
+ const res = await scan(dir);
311
+ const count = res.findings.reduce((n, f) => n + f.evidence.length, 0);
312
+ if (!dry) {
313
+ await fs.mkdir(path.dirname(file), { recursive: true });
314
+ await fs.writeFile(file, `${JSON.stringify(findingsJson(res), null, 2)}\n`, 'utf8');
218
315
  }
316
+ out(json, { dryRun: dry, file, locations: count }, `${dry ? 'Would write' : 'Wrote'} ${file} (${count} location(s)). Commit it, then gate with: archsutra audit . --fail-on-new`);
317
+ return strictExit(args.flags, res) ?? EXIT.ok;
318
+ }
319
+ case 'suppressions': {
320
+ const rows = (await readSuppressions(target)).map((s) => ({ ...s, expired: isExpired(s) }));
321
+ out(json, rows, rows.length ? rows.map((s) => `${s.expired ? 'EXPIRED' : 'active '} ${s.rule ?? '(any rule)'} ${s.fingerprint ?? s.path ?? '(all locations)'}${s.owner ? ` owner=${s.owner}` : ''}${s.expires ? ` expires=${s.expires}` : ''} - ${s.reason}`).join('\n') : 'No suppressions.');
219
322
  return EXIT.ok;
220
323
  }
221
324
  case 'html': {
@@ -233,10 +336,7 @@ async function main() {
233
336
  }
234
337
  const title = markdownTitle(md, path.basename(src, path.extname(src)));
235
338
  const html = renderMarkdownHtml(md, title);
236
- if (!dry) {
237
- await fs.mkdir(path.dirname(dest), { recursive: true });
238
- await fs.writeFile(dest, html, 'utf8');
239
- }
339
+ await save(path.dirname(src), path.dirname(dest), [{ path: path.basename(dest), content: html }]);
240
340
  out(json, { dryRun: dry, source: src, output: dest }, `${dry ? 'Would write' : 'Wrote'} ${dest}\nOpen it in a browser. The Markdown file stays beside it.`);
241
341
  return EXIT.ok;
242
342
  }
@@ -246,14 +346,10 @@ async function main() {
246
346
  return checks.every((c) => c.ok) ? EXIT.ok : EXIT.verifyFailed;
247
347
  }
248
348
  case 'export': {
249
- const outDir = insideProject(target, String(args.flags.output || 'docs/architecture'));
250
- if (!outDir) {
251
- process.stderr.write('--output must stay inside the project directory.\n');
252
- return EXIT.usage;
253
- }
254
- const res = await runAudit(target);
349
+ const outDir = insideProject(target, String(args.flags.output ?? 'docs/architecture'), force);
350
+ const res = await scan(target);
255
351
  const files = reportBundle(res);
256
- await writeReportFiles(outDir, files, dry);
352
+ await save(target, outDir, files);
257
353
  out(json, { dryRun: dry, outDir, files: files.map((f) => f.path) }, wroteLine(dry, outDir, files, 'Open index.html in a browser. Each report also has a Markdown file beside it.'));
258
354
  return EXIT.ok;
259
355
  }
@@ -289,7 +385,9 @@ async function main() {
289
385
  return EXIT.ok;
290
386
  }
291
387
  case 'mcp': {
292
- await serveMcp();
388
+ const root = path.resolve(String(args.flags.root ?? '.'));
389
+ await requireDir(root);
390
+ await serveMcp(root);
293
391
  return EXIT.ok;
294
392
  }
295
393
  case 'drift':
@@ -298,7 +396,7 @@ async function main() {
298
396
  let after;
299
397
  if (args.flags.baseline) {
300
398
  before = await readFindings(path.resolve(String(args.flags.baseline)));
301
- after = (await runAudit(target)).findings;
399
+ after = (await scan(target)).findings;
302
400
  }
303
401
  else if (args.pos.length >= 2) {
304
402
  before = await readFindings(path.resolve(args.pos[0]));
@@ -313,60 +411,46 @@ async function main() {
313
411
  const note = args.cmd === 'compare' ? '\nSemgrep overlap is scripts/compare.mjs (needs semgrep on PATH). Not run by this command.\n' : '';
314
412
  const md = `${renderDrift(report, title)}${note}`;
315
413
  if ('output' in args.flags) {
316
- const outDir = insideProject(path.resolve(args.pos[0] ?? '.'), String(args.flags.output || 'docs/architecture'));
317
- if (!outDir) {
318
- process.stderr.write('--output must stay inside the project directory.\n');
319
- return EXIT.usage;
320
- }
321
- const files = [
414
+ const root = args.flags.baseline ? target : process.cwd();
415
+ const outDir = insideProject(root, String(args.flags.output), force);
416
+ const files = mark([
322
417
  { path: `${args.cmd}.md`, content: md },
323
418
  { path: `${args.cmd}.html`, content: renderMarkdownHtml(md, title) },
324
- ];
325
- await writeReportFiles(outDir, files, dry);
419
+ ]);
420
+ await save(root, outDir, files);
326
421
  }
327
422
  out(json, report, md);
328
423
  const added = report.added.map((r) => ({ severity: (r.after ?? 'info') }));
329
- const gate = severityExit(added, args.flags['fail-on']);
330
- if (gate === EXIT.usage) {
331
- process.stderr.write(`Invalid --fail-on "${args.flags['fail-on']}"\n`);
332
- return EXIT.usage;
333
- }
334
- return gate ?? EXIT.ok;
424
+ return severityExit(added, th) ?? EXIT.ok;
335
425
  }
336
426
  case 'review':
337
427
  case 'design':
338
428
  case 'threat-model':
339
429
  case 'modernize':
340
430
  case 'cost': {
341
- const res = await runAudit(target);
431
+ const res = await scan(target);
342
432
  const md = args.cmd === 'review' ? renderReview(res)
343
433
  : args.cmd === 'design' ? renderDesign(res)
344
434
  : args.cmd === 'threat-model' ? renderThreatModel(res)
345
435
  : args.cmd === 'modernize' ? renderModernize(res)
346
436
  : renderCost(res);
347
437
  if ('output' in args.flags) {
348
- const outDir = insideProject(target, String(args.flags.output || 'docs/architecture'));
349
- if (!outDir) {
350
- process.stderr.write('--output must stay inside the project directory.\n');
351
- return EXIT.usage;
352
- }
353
- const files = [
438
+ const outDir = insideProject(target, String(args.flags.output), force);
439
+ const files = mark([
354
440
  { path: `${args.cmd}.md`, content: md },
355
441
  { path: `${args.cmd}.html`, content: renderMarkdownHtml(md, args.cmd) },
356
- ];
357
- await writeReportFiles(outDir, files, dry);
442
+ ]);
443
+ await save(target, outDir, files);
358
444
  out(json, { dryRun: dry, command: args.cmd }, wroteLine(dry, outDir, files, 'Unknown sections stay unknown. The IDE skill fills those.'));
359
445
  }
360
446
  else {
361
447
  out(json, { command: args.cmd, markdown: md }, md);
362
448
  }
363
449
  if (args.cmd === 'review') {
364
- const gate = severityExit(res.findings, args.flags['fail-on']);
365
- if (gate === EXIT.usage) {
366
- process.stderr.write(`Invalid --fail-on "${args.flags['fail-on']}"\n`);
367
- return EXIT.usage;
368
- }
369
- return gate ?? EXIT.ok;
450
+ const gate = severityExit(res.findings, th);
451
+ if (gate === EXIT.findings)
452
+ return gate;
453
+ return strictExit(args.flags, res) ?? EXIT.ok;
370
454
  }
371
455
  return EXIT.ok;
372
456
  }
@@ -380,6 +464,10 @@ main().then((code) => {
380
464
  process.exitCode = code;
381
465
  }, async (e) => {
382
466
  process.stderr.write(`archsutra: ${e.message}\n`);
467
+ if (e instanceof UsageError) {
468
+ process.exitCode = EXIT.usage;
469
+ return;
470
+ }
383
471
  if (process.argv.includes('--verbose'))
384
472
  process.stderr.write(`${e.stack}\n`);
385
473
  if (!(await exists(process.cwd())))
package/dist/drift.js CHANGED
@@ -1,20 +1,34 @@
1
- function keyOf(f) {
2
- const paths = [...new Set(f.evidence.map((e) => e.path))].sort();
3
- const path = paths[0] ?? '.';
4
- return { key: `${f.rule}@${paths.join('|') || '.'}`, path };
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * One identity per location: rule, path and code text, plus a counter for identical lines.
4
+ * Line numbers are left out so moving code does not create a "new" problem.
5
+ */
6
+ export function fingerprints(rule, evidence) {
7
+ const seen = new Map();
8
+ return evidence.map((e) => {
9
+ let text = (e.excerpt ?? '').replace(/\s+/g, ' ').trim();
10
+ if (rule === 'AS-ARC-003')
11
+ text = ''; // the excerpt is a line count that changes on every edit
12
+ const base = `${rule}\n${e.path}\n${text}`;
13
+ const n = seen.get(base) ?? 0;
14
+ seen.set(base, n + 1);
15
+ return createHash('sha256').update(`${base}\n${n}`).digest('hex').slice(0, 32);
16
+ });
5
17
  }
6
- /** Diff two findings lists. Identity is rule plus evidence paths, not the generated sequence id. */
7
- export function diffFindings(before, after) {
8
- const prev = new Map();
9
- const next = new Map();
10
- for (const f of before) {
11
- const k = keyOf(f);
12
- prev.set(k.key, { sev: f.severity, path: k.path, rule: f.rule });
13
- }
14
- for (const f of after) {
15
- const k = keyOf(f);
16
- next.set(k.key, { sev: f.severity, path: k.path, rule: f.rule });
18
+ function index(list) {
19
+ const rows = new Map();
20
+ for (const f of list) {
21
+ const evidence = f.evidence.length ? f.evidence : [{ path: '.', kind: 'observed' }];
22
+ // Schema 1.0.0 files carry no fingerprint; it is computed the same way for them.
23
+ const computed = fingerprints(f.rule, evidence);
24
+ evidence.map((e, i) => e.fingerprint ?? computed[i]).forEach((print, i) => rows.set(`${f.rule}@${evidence[i].path}#${print}`, { sev: f.severity, path: evidence[i].path, rule: f.rule }));
17
25
  }
26
+ return rows;
27
+ }
28
+ /** Diff two findings lists. Identity is one location of one rule, not the generated sequence id. */
29
+ export function diffFindings(before, after) {
30
+ const prev = index(before);
31
+ const next = index(after);
18
32
  const added = [];
19
33
  const removed = [];
20
34
  const changed = [];