@aisac/cli 0.4.0-beta.2 → 0.4.0-beta.21

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 (47) hide show
  1. package/README.md +115 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +243 -5
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +6 -0
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +584 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +259 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +373 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +449 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +278 -34
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/mcp-servers.mjs +192 -0
  35. package/dist/mcp.mjs +10 -2
  36. package/dist/monitor.mjs +76 -1
  37. package/dist/package.json +1 -1
  38. package/dist/platform.mjs +78 -29
  39. package/dist/release-manifest-public-keys.json +10 -0
  40. package/dist/release-manifest.json +328 -0
  41. package/dist/release-manifest.mjs +817 -0
  42. package/dist/release-settings.mjs +210 -0
  43. package/dist/self-update.mjs +1036 -0
  44. package/dist/state.mjs +25 -1
  45. package/dist/token-guide.mjs +132 -0
  46. package/dist/update-actions.mjs +442 -0
  47. package/package.json +1 -1
@@ -0,0 +1,1265 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * `aisac scan` (spec aisac-engineering-scan, ADR-0055, wave S2): a
5
+ * deterministic security scan of the user's own working tree with pinned
6
+ * scanners, normalized into `.security-reports/aisac-scan/<UTC>/`.
7
+ *
8
+ * The command makes no model call and uploads nothing. It checks the
9
+ * arguments and the target, fetches the licensed pack with the launch code
10
+ * path before any tool runs (FR7), then runs secrets, SAST, SCA and IaC in
11
+ * that order, each from its image by digest or an allowlisted binary. The
12
+ * only writes in the project are the run directory (`0700`, files `0600`)
13
+ * and `latest.json` next to it; tool output lands in a private temporary
14
+ * directory first and reaches the project only as a sanitized copy.
15
+ */
16
+
17
+ import { spawn as nodeSpawn } from 'node:child_process';
18
+ import { randomBytes } from 'node:crypto';
19
+ import { constants, rmSync } from 'node:fs';
20
+ import {
21
+ access,
22
+ lstat,
23
+ mkdir,
24
+ mkdtemp,
25
+ readdir,
26
+ readlink,
27
+ realpath,
28
+ rename,
29
+ rm,
30
+ stat,
31
+ } from 'node:fs/promises';
32
+ import { tmpdir } from 'node:os';
33
+ import { dirname, join, relative, resolve, sep } from 'node:path';
34
+ import {
35
+ isPackLocale,
36
+ obtainPack,
37
+ packNotice,
38
+ readStoredLocale,
39
+ resolvePackLocale,
40
+ } from './engineering-pack.mjs';
41
+ import { isRecord } from './engineering.mjs';
42
+ import {
43
+ EXCLUDED_DIRECTORIES,
44
+ HISTORY_OUTPUT_FILE,
45
+ OSV_LOCKFILE_NAMES,
46
+ OUTPUT_FILE,
47
+ SCAN_KINDS,
48
+ SCANNER_CONFIG_NAMES,
49
+ TOOL_OF_KIND,
50
+ ensureImage,
51
+ executeTool,
52
+ imageReference,
53
+ loadAisacRules,
54
+ loadScanPins,
55
+ needsContainer,
56
+ prepareSemgrepRules,
57
+ probeBinary,
58
+ probeDocker,
59
+ readBoundedFile,
60
+ runProcess,
61
+ usesNetwork,
62
+ writeClientConfigs,
63
+ writePrivateFile,
64
+ } from './engineering-scan-tools.mjs';
65
+ import {
66
+ FAIL_ON_LEVELS,
67
+ PARSERS,
68
+ availabilityLines,
69
+ buildSummary,
70
+ findingPath,
71
+ mergeSecretPasses,
72
+ renderSummaryMarkdown,
73
+ scanReportLines,
74
+ summaryJson,
75
+ } from './engineering-scan-report.mjs';
76
+ import { resolveNative } from './platform.mjs';
77
+
78
+ export { SCAN_KINDS } from './engineering-scan-tools.mjs';
79
+
80
+ /** @typedef {import('./engineering-scan-tools.mjs').ScanKind} ScanKind */
81
+ /** @typedef {import('./engineering-scan-tools.mjs').ScanTool} ScanTool */
82
+ /** @typedef {import('./engineering-scan-tools.mjs').ToolPin} ToolPin */
83
+ /** @typedef {import('./engineering-scan-tools.mjs').Runner} Runner */
84
+ /** @typedef {import('./engineering-scan-tools.mjs').SpawnFunction} SpawnFunction */
85
+ /** @typedef {import('./engineering-scan-tools.mjs').RulesetRecord} RulesetRecord */
86
+ /** @typedef {import('./engineering-scan-tools.mjs').AisacRules} AisacRules */
87
+ /** @typedef {import('./engineering-scan-report.mjs').FailOn} FailOn */
88
+ /** @typedef {import('./engineering-scan-report.mjs').Finding} Finding */
89
+ /** @typedef {import('./engineering-scan-report.mjs').ParsedOutput} ParsedOutput */
90
+ /** @typedef {import('./engineering-scan-report.mjs').ToolRecord} ToolRecord */
91
+ /** @typedef {import('./engineering-scan-report.mjs').NetworkUse} NetworkUse */
92
+ /** @typedef {import('./engineering-scan-report.mjs').AvailabilityEntry} AvailabilityEntry */
93
+ /** @typedef {import('./engineering-pack.mjs').PackLocale} PackLocale */
94
+ /** @typedef {import('./engineering-pack.mjs').VerifiedPack} VerifiedPack */
95
+
96
+ const USAGE_EXIT_CODE = 2;
97
+ const CANNOT_SCAN_EXIT_CODE = 3;
98
+ /** @type {FailOn} */
99
+ const DEFAULT_FAIL_ON = 'high';
100
+ const DEFAULT_TIMEOUT_SECONDS = 600;
101
+ const MAX_TIMEOUT_SECONDS = 3600;
102
+ const MILLISECONDS_PER_SECOND = 1000;
103
+ const TIMEOUT_DIGITS = /^[1-9]\d{0,3}$/u;
104
+ const REPORTS_DIRECTORY = '.security-reports';
105
+ const SCAN_DIRECTORY = 'aisac-scan';
106
+ const LATEST_FILE = 'latest.json';
107
+ const SUMMARY_FILE = 'summary.json';
108
+ const SUMMARY_MARKDOWN_FILE = 'summary.md';
109
+ const PRIVATE_DIRECTORY_MODE = 0o700;
110
+ const MAX_RUN_DIRECTORY_ATTEMPTS = 100;
111
+ const TEMPORARY_SUFFIX_BYTES = 6;
112
+ const MAX_WALK_ENTRIES = 200_000;
113
+ const MAX_SKIPPED_PATHS = 1000;
114
+ const GIT_TIMEOUT_MS = 15_000;
115
+ const GIT_IGNORED_EXIT_CODE = 0;
116
+ const GIT_NOT_IGNORED_EXIT_CODE = 1;
117
+ const GIT_ENV_KEYS = ['PATH', 'HOME', 'XDG_CONFIG_HOME', 'LANG', 'LC_ALL'];
118
+ const CONTAINER_SOURCE_PREFIX = '/src/';
119
+ const CONTAINER_DEFERRED = 'container_not_in_s2';
120
+ const TOOL_NEEDS_CONTAINER = 'tool_needs_container';
121
+ const INTERRUPTED = 'interrupted';
122
+ const GIT_DIRECTORY = '.git';
123
+ const GITLEAKS_IGNORE_FILE = '.gitleaksignore';
124
+ /** Scanner configs listed one by one; the rest are counted (scan review F2). */
125
+ const MAX_SCANNER_CONFIG_WARNINGS = 20;
126
+ const WORKSPACE_PREFIX = 'aisac-scan-';
127
+ /** Written in each workspace with the run's pid; nothing without it is ever swept. */
128
+ const WORKSPACE_MARKER = '.aisac-scan-workspace';
129
+ const STALE_WORKSPACE_MS = 24 * 60 * 60 * 1000;
130
+ const MAX_MARKER_BYTES = 32;
131
+ const UNKNOWN_CLIENT_VERSION = 'unknown';
132
+ const CLIENT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
133
+ const MAX_PACKAGE_JSON_BYTES = 64 * 1024;
134
+ const PACKAGE_JSON = 'package.json';
135
+ const WALK_EXCLUDED = new Set(EXCLUDED_DIRECTORIES);
136
+ const FLAG_OPTIONS = new Set(['--history', '--json', '--check-tools', '--no-docker']);
137
+ const VALUE_OPTIONS = new Set(['--fail-on', '--only', '--skip', '--lang', '--timeout']);
138
+ const DAST_OPTION = '--target';
139
+
140
+ /**
141
+ * @typedef {{
142
+ * dir: string | undefined,
143
+ * failOn: FailOn,
144
+ * only: ScanKind[] | undefined,
145
+ * skip: ScanKind[] | undefined,
146
+ * history: boolean,
147
+ * docker: boolean,
148
+ * lang: PackLocale | undefined,
149
+ * json: boolean,
150
+ * checkTools: boolean,
151
+ * timeoutSeconds: number
152
+ * }} ScanArguments
153
+ */
154
+ /**
155
+ * @typedef {{
156
+ * packageRoot: string,
157
+ * readConfig: () => Promise<unknown>,
158
+ * stateRoot: () => string,
159
+ * cwd?: string,
160
+ * env?: NodeJS.ProcessEnv,
161
+ * fetchImpl?: typeof fetch,
162
+ * log?: (line: string) => void,
163
+ * warn?: (line: string) => void,
164
+ * spawn?: SpawnFunction,
165
+ * now?: () => Date,
166
+ * tmpRoot?: string,
167
+ * signal?: AbortSignal
168
+ * }} ScanDependencies
169
+ */
170
+ /** @typedef {{ runner: Runner, pullRequired: boolean } | { skipped: string }} Resolution */
171
+
172
+ /**
173
+ * An error that carries its exit code: 2 for usage (FR1), 3 when the scan
174
+ * cannot run (D6), so a CI step never reads it as "findings" (exit 1).
175
+ * @param {string} code
176
+ * @param {number} exitCode
177
+ */
178
+ function exitError(code, exitCode) {
179
+ const error = new Error(code);
180
+ Object.defineProperty(error, 'exitCode', { value: exitCode });
181
+ return error;
182
+ }
183
+
184
+ /** @param {string} code */
185
+ function usageError(code) {
186
+ return exitError(code, USAGE_EXIT_CODE);
187
+ }
188
+
189
+ /** @param {string} code */
190
+ function cannotScan(code) {
191
+ return exitError(code, CANNOT_SCAN_EXIT_CODE);
192
+ }
193
+
194
+ /**
195
+ * An error the engine did not classify still means it could not scan as
196
+ * asked: exit 3, never 1, which a CI step reads as findings (scan review F3).
197
+ * Classified errors (usage 2, cannot scan 3) pass through.
198
+ * @param {unknown} error
199
+ */
200
+ function classified(error) {
201
+ if (isRecord(error) && typeof error.exitCode === 'number') return error;
202
+ const wrapped = error instanceof Error ? error : new Error(String(error));
203
+ Object.defineProperty(wrapped, 'exitCode', { value: CANNOT_SCAN_EXIT_CODE });
204
+ return wrapped;
205
+ }
206
+
207
+ /** @param {unknown} value @returns {value is ScanKind} */
208
+ function isScanKind(value) {
209
+ return typeof value === 'string' && SCAN_KINDS.includes(/** @type {ScanKind} */ (value));
210
+ }
211
+
212
+ /** @param {unknown} value @returns {value is FailOn} */
213
+ function isFailOn(value) {
214
+ return typeof value === 'string' && FAIL_ON_LEVELS.includes(/** @type {FailOn} */ (value));
215
+ }
216
+
217
+ /** @param {string} value @returns {ScanKind[]} */
218
+ function parseKinds(value) {
219
+ const kinds = value.split(',');
220
+ if (!kinds.every(isScanKind) || new Set(kinds).size !== kinds.length)
221
+ throw usageError('invalid_kinds');
222
+ return kinds;
223
+ }
224
+
225
+ /** @param {string} value */
226
+ function parseTimeout(value) {
227
+ const seconds = TIMEOUT_DIGITS.test(value) ? Number(value) : Number.NaN;
228
+ if (!Number.isSafeInteger(seconds) || seconds > MAX_TIMEOUT_SECONDS)
229
+ throw usageError('invalid_timeout');
230
+ return seconds;
231
+ }
232
+
233
+ /**
234
+ * @param {ScanArguments} parsed
235
+ * @param {string} option
236
+ * @param {string} value
237
+ */
238
+ function applyValue(parsed, option, value) {
239
+ switch (option) {
240
+ case '--fail-on':
241
+ if (!isFailOn(value)) throw usageError('invalid_fail_on');
242
+ parsed.failOn = value;
243
+ return;
244
+ case '--only':
245
+ parsed.only = parseKinds(value);
246
+ return;
247
+ case '--skip':
248
+ parsed.skip = parseKinds(value);
249
+ return;
250
+ case '--lang':
251
+ if (!isPackLocale(value)) throw usageError('invalid_lang');
252
+ parsed.lang = value;
253
+ return;
254
+ default:
255
+ parsed.timeoutSeconds = parseTimeout(value);
256
+ }
257
+ }
258
+
259
+ /** @param {ScanArguments} parsed @param {string} flag */
260
+ function applyFlag(parsed, flag) {
261
+ if (flag === '--history') parsed.history = true;
262
+ else if (flag === '--json') parsed.json = true;
263
+ else if (flag === '--check-tools') parsed.checkTools = true;
264
+ else parsed.docker = false;
265
+ }
266
+
267
+ /**
268
+ * `aisac scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]
269
+ * [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]
270
+ * [--check-tools] [--timeout <seconds>]` (FR1). Usage errors exit 2;
271
+ * `--target` is reserved for S3 (D11).
272
+ * @param {readonly string[]} args
273
+ * @returns {ScanArguments}
274
+ */
275
+ export function parseScanArguments(args) {
276
+ /** @type {ScanArguments} */
277
+ const parsed = {
278
+ dir: undefined,
279
+ failOn: DEFAULT_FAIL_ON,
280
+ only: undefined,
281
+ skip: undefined,
282
+ history: false,
283
+ docker: true,
284
+ lang: undefined,
285
+ json: false,
286
+ checkTools: false,
287
+ timeoutSeconds: DEFAULT_TIMEOUT_SECONDS,
288
+ };
289
+ const seen = new Set();
290
+ for (let index = 0; index < args.length; index += 1) {
291
+ const argument = /** @type {string} */ (args[index]);
292
+ if (argument === DAST_OPTION || argument.startsWith(`${DAST_OPTION}=`))
293
+ throw usageError('dast_not_available');
294
+ if (FLAG_OPTIONS.has(argument) || VALUE_OPTIONS.has(argument)) {
295
+ if (seen.has(argument)) throw usageError(`duplicate_option:${argument}`);
296
+ seen.add(argument);
297
+ }
298
+ if (FLAG_OPTIONS.has(argument)) {
299
+ applyFlag(parsed, argument);
300
+ } else if (VALUE_OPTIONS.has(argument)) {
301
+ const value = args[index + 1];
302
+ if (value === undefined || value.startsWith('-'))
303
+ throw usageError(`option_value_required:${argument}`);
304
+ applyValue(parsed, argument, value);
305
+ index += 1;
306
+ } else if (argument.startsWith('-') || parsed.dir !== undefined) {
307
+ throw usageError('unknown_option');
308
+ } else {
309
+ parsed.dir = argument;
310
+ }
311
+ }
312
+ if (parsed.only !== undefined && parsed.skip !== undefined) throw usageError('only_with_skip');
313
+ return parsed;
314
+ }
315
+
316
+ /** @param {ScanArguments} options @returns {Set<ScanKind>} */
317
+ function selectedKinds(options) {
318
+ if (options.only !== undefined) return new Set(options.only);
319
+ const skipped = new Set(options.skip ?? []);
320
+ return new Set(SCAN_KINDS.filter((kind) => !skipped.has(kind)));
321
+ }
322
+
323
+ /** @param {unknown} error */
324
+ function errorCodeOf(error) {
325
+ return isRecord(error) && typeof error.code === 'string' ? error.code : 'unknown';
326
+ }
327
+
328
+ /**
329
+ * The target's real path (FR2): it exists, is a directory, is not under a
330
+ * `.git/` and can be read. Resolved once; every tool gets this path.
331
+ * @param {string} base
332
+ * @param {string | undefined} dir
333
+ */
334
+ async function resolveTarget(base, dir) {
335
+ let real;
336
+ try {
337
+ real = await realpath(resolve(base, dir ?? '.'));
338
+ } catch (error) {
339
+ if (errorCodeOf(error) === 'EACCES') throw cannotScan('dir_unreadable');
340
+ throw usageError('dir_not_found');
341
+ }
342
+ if (!(await stat(real)).isDirectory()) throw usageError('dir_not_directory');
343
+ if (real.split(sep).some((segment) => segment.toLowerCase() === '.git'))
344
+ throw usageError('dir_inside_git');
345
+ try {
346
+ await access(real, constants.R_OK | constants.X_OK);
347
+ } catch {
348
+ throw cannotScan('dir_unreadable');
349
+ }
350
+ return real;
351
+ }
352
+
353
+ /**
354
+ * `--history` reads the repository's own history (scan review F1): the
355
+ * target must be its top level, with `.git` a directory. A worktree's `.git`
356
+ * file or a link is refused before the license and before any tool.
357
+ * @param {string} target
358
+ */
359
+ async function checkHistoryTarget(target) {
360
+ const entry = await lstat(join(target, GIT_DIRECTORY)).catch(() => null);
361
+ if (entry === null || !entry.isDirectory()) throw cannotScan('history_not_a_repository');
362
+ }
363
+
364
+ /** @param {unknown} config @returns {{ endpoint: string, token: string }} */
365
+ function accountOf(config) {
366
+ if (
367
+ !isRecord(config) ||
368
+ typeof config.endpoint !== 'string' ||
369
+ typeof config.token !== 'string' ||
370
+ config.token.length === 0
371
+ )
372
+ throw cannotScan('setup_required');
373
+ return { endpoint: config.endpoint, token: config.token };
374
+ }
375
+
376
+ /**
377
+ * The licensed pack, with the launch's code path and messages (D8, FR7).
378
+ * Every failure stops the command before any tool runs.
379
+ * @param {ScanDependencies} deps
380
+ * @param {PackLocale} locale
381
+ * @param {(line: string) => void} warn
382
+ * @returns {Promise<VerifiedPack>}
383
+ */
384
+ async function licensedPack(deps, locale, warn) {
385
+ const account = accountOf(await deps.readConfig());
386
+ const outcome = await obtainPack({
387
+ endpoint: account.endpoint,
388
+ token: account.token,
389
+ locale,
390
+ packageRoot: deps.packageRoot,
391
+ ...(deps.fetchImpl === undefined ? {} : { fetchImpl: deps.fetchImpl }),
392
+ });
393
+ if (outcome.outcome === 'loaded') return outcome.pack;
394
+ const notice = packNotice(outcome, locale);
395
+ if (notice !== null) warn(notice);
396
+ switch (outcome.outcome) {
397
+ case 'inactive':
398
+ throw cannotScan('license_inactive');
399
+ case 'not_offered':
400
+ throw cannotScan('engineering_not_offered');
401
+ case 'unavailable':
402
+ throw cannotScan(`pack_unavailable:${outcome.reason}`);
403
+ default:
404
+ throw cannotScan(`pack_rejected:${outcome.reason}`);
405
+ }
406
+ }
407
+
408
+ /** `2026-11-12T11:25:28.123Z` → `20261112T112528Z`. @param {Date} date */
409
+ export function runIdOf(date) {
410
+ return date
411
+ .toISOString()
412
+ .replace(/\.\d{3}Z$/u, 'Z')
413
+ .replaceAll(/[-:]/gu, '');
414
+ }
415
+
416
+ /**
417
+ * `<target>/.security-reports/aisac-scan/<UTC>/`, refusing a link or a
418
+ * non-directory on the way; missing levels are created `0700`. Two runs in
419
+ * the same second get `-2`, `-3`, ... (exclusive creation).
420
+ * @param {string} target
421
+ * @param {Date} startedAt
422
+ */
423
+ async function prepareRunDirectory(target, startedAt) {
424
+ let current = target;
425
+ for (const segment of [REPORTS_DIRECTORY, SCAN_DIRECTORY]) {
426
+ current = join(current, segment);
427
+ let entry = await lstat(current).catch(() => null);
428
+ if (entry === null) {
429
+ await mkdir(current, { mode: PRIVATE_DIRECTORY_MODE }).catch((error) => {
430
+ if (errorCodeOf(error) !== 'EEXIST') throw cannotScan('report_directory_unwritable');
431
+ });
432
+ entry = await lstat(current).catch(() => null);
433
+ }
434
+ if (entry === null || entry.isSymbolicLink() || !entry.isDirectory())
435
+ throw cannotScan('report_directory_invalid');
436
+ }
437
+ const base = runIdOf(startedAt);
438
+ for (let attempt = 1; attempt <= MAX_RUN_DIRECTORY_ATTEMPTS; attempt += 1) {
439
+ const runDirectory = join(current, attempt === 1 ? base : `${base}-${attempt}`);
440
+ try {
441
+ await mkdir(runDirectory, { mode: PRIVATE_DIRECTORY_MODE });
442
+ return { scanRoot: current, runDirectory };
443
+ } catch (error) {
444
+ if (errorCodeOf(error) !== 'EEXIST') throw cannotScan('report_directory_unwritable');
445
+ }
446
+ }
447
+ throw cannotScan('report_directory_unwritable');
448
+ }
449
+
450
+ /**
451
+ * `latest.json` is a copy of the newest summary, replaced atomically; a link
452
+ * in its place is replaced, never followed (D5). When the rename fails (a
453
+ * directory planted there), the temporary copy is removed and the run exits 3
454
+ * with `latest_json_unwritable` (scan review F3).
455
+ * @param {string} scanRoot
456
+ * @param {string} content
457
+ */
458
+ async function replaceLatest(scanRoot, content) {
459
+ const temporary = join(
460
+ scanRoot,
461
+ `.${LATEST_FILE}.${randomBytes(TEMPORARY_SUFFIX_BYTES).toString('hex')}.tmp`,
462
+ );
463
+ await writePrivateFile(temporary, content);
464
+ try {
465
+ await rename(temporary, join(scanRoot, LATEST_FILE));
466
+ } catch {
467
+ await rm(temporary, { force: true });
468
+ throw cannotScan('latest_json_unwritable');
469
+ }
470
+ }
471
+
472
+ /** @param {string} link @param {string} root */
473
+ async function pointsOutside(link, root) {
474
+ let resolved;
475
+ try {
476
+ resolved = await realpath(link);
477
+ } catch {
478
+ try {
479
+ resolved = resolve(dirname(link), await readlink(link));
480
+ } catch {
481
+ return false;
482
+ }
483
+ }
484
+ return resolved !== root && !resolved.startsWith(`${root}${sep}`);
485
+ }
486
+
487
+ /** @param {string} target @param {string} full */
488
+ function relativePath(target, full) {
489
+ return relative(target, full).split(sep).join('/');
490
+ }
491
+
492
+ /**
493
+ * @typedef {{
494
+ * paths: string[],
495
+ * truncated: boolean,
496
+ * scannerConfigs: string[],
497
+ * lockfiles: boolean
498
+ * }} TreeWalk
499
+ */
500
+ /**
501
+ * One walk of the tree, the excluded directories not entered (FR2):
502
+ * symbolic links that resolve outside it (skipped paths, never followed),
503
+ * the scanner configs a repository can plant (scan review F2, display-safe
504
+ * and sorted) and whether it holds a file osv-scanner extracts packages from
505
+ * (F6). A walk cut short says `truncated`, and then a lockfile is assumed.
506
+ * @param {string} target
507
+ * @returns {Promise<TreeWalk>}
508
+ */
509
+ async function walkTarget(target) {
510
+ /** @type {string[]} */
511
+ const paths = [];
512
+ /** @type {string[]} */
513
+ const scannerConfigs = [];
514
+ let lockfiles = false;
515
+ let truncated = false;
516
+ const queue = [target];
517
+ let visited = 0;
518
+ for (let next = 0; next < queue.length && !truncated; next += 1) {
519
+ const directory = /** @type {string} */ (queue[next]);
520
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
521
+ for (const entry of entries) {
522
+ visited += 1;
523
+ if (visited > MAX_WALK_ENTRIES) {
524
+ truncated = true;
525
+ break;
526
+ }
527
+ const full = join(directory, entry.name);
528
+ if (entry.isDirectory()) {
529
+ if (!WALK_EXCLUDED.has(entry.name)) queue.push(full);
530
+ continue;
531
+ }
532
+ if (entry.isSymbolicLink() && (await pointsOutside(full, target)))
533
+ paths.push(relativePath(target, full));
534
+ if (SCANNER_CONFIG_NAMES.has(entry.name))
535
+ scannerConfigs.push(findingPath(relativePath(target, full), []));
536
+ if (OSV_LOCKFILE_NAMES.has(entry.name)) lockfiles = true;
537
+ }
538
+ }
539
+ paths.sort();
540
+ return {
541
+ paths: paths.slice(0, MAX_SKIPPED_PATHS),
542
+ truncated: truncated || paths.length > MAX_SKIPPED_PATHS,
543
+ scannerConfigs: scannerConfigs.sort(),
544
+ lockfiles: lockfiles || truncated,
545
+ };
546
+ }
547
+
548
+ /**
549
+ * `repo_scanner_config:<path>` for the first 20, then one
550
+ * `repo_scanner_config_more:<count>` for the rest (scan review F2).
551
+ * @param {readonly string[]} configs
552
+ */
553
+ function scannerConfigWarnings(configs) {
554
+ const listed = configs
555
+ .slice(0, MAX_SCANNER_CONFIG_WARNINGS)
556
+ .map((path) => `repo_scanner_config:${path}`);
557
+ const more = configs.length - listed.length;
558
+ return more > 0 ? [...listed, `repo_scanner_config_more:${more}`] : listed;
559
+ }
560
+
561
+ /**
562
+ * Whether gitleaks would read a `.gitleaksignore` at the target's root: any
563
+ * entry there but a directory (a link is masked where it points).
564
+ * @param {string} target
565
+ */
566
+ async function hasRootGitleaksIgnore(target) {
567
+ const entry = await lstat(join(target, GITLEAKS_IGNORE_FILE)).catch(() => null);
568
+ return entry !== null && !entry.isDirectory();
569
+ }
570
+
571
+ /**
572
+ * Whether git ignores `.security-reports/` in the target (FR2). Without git
573
+ * or outside a repository the answer is unknown and nothing is said. The
574
+ * index and the repository's fsmonitor hook are never used.
575
+ * @param {SpawnFunction} spawnImpl
576
+ * @param {NodeJS.ProcessEnv} env
577
+ * @param {string} target
578
+ * @returns {Promise<'ignored' | 'not_ignored' | 'unknown'>}
579
+ */
580
+ async function reportsIgnored(spawnImpl, env, target) {
581
+ const git = resolveNative('git', env);
582
+ if (git === null) return 'unknown';
583
+ /** @type {NodeJS.ProcessEnv} */
584
+ const gitEnv = {};
585
+ for (const key of GIT_ENV_KEYS) if (typeof env[key] === 'string') gitEnv[key] = env[key];
586
+ const answer = await runProcess(
587
+ spawnImpl,
588
+ git,
589
+ [
590
+ '-c',
591
+ 'core.fsmonitor=false',
592
+ '-C',
593
+ target,
594
+ 'check-ignore',
595
+ '-q',
596
+ '--no-index',
597
+ '--',
598
+ `${REPORTS_DIRECTORY}/`,
599
+ ],
600
+ { timeoutMs: GIT_TIMEOUT_MS, env: { ...gitEnv, GIT_OPTIONAL_LOCKS: '0' } },
601
+ );
602
+ if (answer.code === GIT_IGNORED_EXIT_CODE) return 'ignored';
603
+ return answer.code === GIT_NOT_IGNORED_EXIT_CODE ? 'not_ignored' : 'unknown';
604
+ }
605
+
606
+ /**
607
+ * How one tool would run (FR3): its image when Docker answers (pulled when
608
+ * `pull` is set), else an allowlisted binary, else a skip with the reason.
609
+ * Trivy has no binary fallback (`tool_needs_container`, scan review F5); an
610
+ * abort during the inspect or the pull is `interrupted` (F8).
611
+ * @param {{ spawn: SpawnFunction, env: NodeJS.ProcessEnv, docker: string | null,
612
+ * signal?: AbortSignal }} context
613
+ * @param {ScanTool} tool
614
+ * @param {ToolPin} pin
615
+ * @param {{ pull: boolean, timeoutMs: number }} options
616
+ * @returns {Promise<Resolution>}
617
+ */
618
+ async function resolveTool(context, tool, pin, options) {
619
+ let imageFailed = false;
620
+ if (context.docker !== null) {
621
+ const docker = context.docker;
622
+ const state = await ensureImage(
623
+ {
624
+ spawn: context.spawn,
625
+ env: context.env,
626
+ docker,
627
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
628
+ },
629
+ pin,
630
+ options,
631
+ );
632
+ if (state === 'interrupted') return { skipped: INTERRUPTED };
633
+ if (state !== 'pull_failed')
634
+ return {
635
+ runner: {
636
+ mode: 'image',
637
+ tool,
638
+ pin,
639
+ reference: imageReference(pin),
640
+ version: pin.tag,
641
+ docker,
642
+ },
643
+ pullRequired: state === 'absent',
644
+ };
645
+ imageFailed = true;
646
+ }
647
+ if (needsContainer(tool)) return { skipped: TOOL_NEEDS_CONTAINER };
648
+ const binary = await probeBinary(context.spawn, context.env, pin);
649
+ if (binary.status === 'qualified')
650
+ return {
651
+ runner: { mode: 'binary', tool, pin, reference: binary.path, version: binary.version ?? '' },
652
+ pullRequired: false,
653
+ };
654
+ if (binary.status === 'unqualified') return { skipped: 'tool_version_unqualified' };
655
+ return { skipped: imageFailed ? 'image_unavailable' : 'tool_unavailable' };
656
+ }
657
+
658
+ /**
659
+ * @param {ScanKind} kind
660
+ * @param {Resolution} resolution
661
+ * @returns {AvailabilityEntry}
662
+ */
663
+ function availabilityEntry(kind, resolution) {
664
+ const tool = TOOL_OF_KIND[kind];
665
+ if ('skipped' in resolution)
666
+ return {
667
+ kind,
668
+ tool,
669
+ mode: 'skipped',
670
+ reference: null,
671
+ version: null,
672
+ reason: resolution.skipped,
673
+ };
674
+ return {
675
+ kind,
676
+ tool,
677
+ mode: resolution.runner.mode,
678
+ reference: resolution.runner.reference,
679
+ version: resolution.runner.version,
680
+ reason: resolution.pullRequired ? 'image_pull_required' : null,
681
+ };
682
+ }
683
+
684
+ /**
685
+ * @param {{ packageRoot: string, env?: NodeJS.ProcessEnv, spawn?: SpawnFunction }} deps
686
+ * @param {{ docker?: boolean }} options
687
+ */
688
+ async function availability(deps, options) {
689
+ const pins = await loadScanPins(deps.packageRoot);
690
+ const spawnImpl = deps.spawn ?? nodeSpawn;
691
+ const env = deps.env ?? process.env;
692
+ const docker = options.docker === false ? null : await probeDocker(spawnImpl, env);
693
+ /** @type {Map<ScanTool, Resolution>} */
694
+ const resolved = new Map();
695
+ /** @type {AvailabilityEntry[]} */
696
+ const entries = [];
697
+ for (const kind of SCAN_KINDS) {
698
+ if (kind === 'container') {
699
+ entries.push(availabilityEntry(kind, { skipped: CONTAINER_DEFERRED }));
700
+ continue;
701
+ }
702
+ const tool = TOOL_OF_KIND[kind];
703
+ const resolution =
704
+ resolved.get(tool) ??
705
+ (await resolveTool({ spawn: spawnImpl, env, docker }, tool, pins.tools[tool], {
706
+ pull: false,
707
+ timeoutMs: 0,
708
+ }));
709
+ resolved.set(tool, resolution);
710
+ entries.push(availabilityEntry(kind, resolution));
711
+ }
712
+ /** @type {'available' | 'unavailable' | 'disabled'} */
713
+ const dockerState =
714
+ options.docker === false ? 'disabled' : docker === null ? 'unavailable' : 'available';
715
+ return { docker: dockerState, entries };
716
+ }
717
+
718
+ /**
719
+ * What `aisac scan` would run, per kind (FR1 `--check-tools`, FR9 doctor):
720
+ * no pull, no scan, no pack, no license needed.
721
+ * @param {{ packageRoot: string, env?: NodeJS.ProcessEnv, spawn?: SpawnFunction }} deps
722
+ * @param {{ docker?: boolean }} [options]
723
+ * @returns {Promise<AvailabilityEntry[]>}
724
+ */
725
+ export async function scanToolAvailability(deps, options = {}) {
726
+ return (await availability(deps, options)).entries;
727
+ }
728
+
729
+ /** @param {string} packageRoot */
730
+ async function clientVersion(packageRoot) {
731
+ const read = await readBoundedFile(join(packageRoot, PACKAGE_JSON), MAX_PACKAGE_JSON_BYTES);
732
+ if (!read.ok) return UNKNOWN_CLIENT_VERSION;
733
+ try {
734
+ const value = JSON.parse(read.text);
735
+ return isRecord(value) &&
736
+ typeof value.version === 'string' &&
737
+ CLIENT_VERSION.test(value.version)
738
+ ? value.version
739
+ : UNKNOWN_CLIENT_VERSION;
740
+ } catch {
741
+ return UNKNOWN_CLIENT_VERSION;
742
+ }
743
+ }
744
+
745
+ /**
746
+ * @typedef {{
747
+ * options: ScanArguments,
748
+ * target: string,
749
+ * pack: VerifiedPack,
750
+ * pins: import('./engineering-scan-tools.mjs').ScanPins,
751
+ * spawn: SpawnFunction,
752
+ * env: NodeJS.ProcessEnv,
753
+ * fetchImpl: typeof fetch,
754
+ * now: () => Date,
755
+ * signal: AbortSignal,
756
+ * workspace: { outDir: string, rulesDir: string, home: string },
757
+ * tree: { ignoreOverlay: boolean, lockfiles: boolean }
758
+ * }} RunContext
759
+ */
760
+ /**
761
+ * `sanitized` maps a report file name to its sanitized copy.
762
+ * @typedef {{
763
+ * tools: ToolRecord[],
764
+ * findings: Finding[],
765
+ * sanitized: Map<string, unknown>,
766
+ * rulesets: RulesetRecord[],
767
+ * network: NetworkUse[],
768
+ * warnings: string[],
769
+ * interrupted: boolean
770
+ * }} RunState
771
+ */
772
+
773
+ /**
774
+ * @param {ScanTool} tool
775
+ * @param {ScanKind} kind
776
+ * @param {{ mode: ToolRecord['mode'], reference: string | null, version: string | null,
777
+ * status: ToolRecord['status'], reason: string | null, exitCode: number | null,
778
+ * history: string | null }} outcome
779
+ * @param {Date} started
780
+ * @param {Date} finished
781
+ * @returns {ToolRecord}
782
+ */
783
+ function toolRecord(tool, kind, outcome, started, finished) {
784
+ return {
785
+ tool,
786
+ kind,
787
+ mode: outcome.mode,
788
+ reference: outcome.reference,
789
+ version: outcome.version,
790
+ status: outcome.status,
791
+ reason: outcome.reason,
792
+ startedAt: started.toISOString(),
793
+ finishedAt: finished.toISOString(),
794
+ durationMs: Math.max(0, finished.getTime() - started.getTime()),
795
+ exitCode: outcome.exitCode,
796
+ history: outcome.history,
797
+ };
798
+ }
799
+
800
+ /** @param {string} reason */
801
+ function skippedOutcome(reason) {
802
+ return {
803
+ mode: /** @type {const} */ ('skipped'),
804
+ reference: null,
805
+ version: null,
806
+ status: /** @type {const} */ ('skipped'),
807
+ reason,
808
+ exitCode: null,
809
+ history: null,
810
+ };
811
+ }
812
+
813
+ /**
814
+ * Semgrep step 1 (S2 note on FR4/D9): the rulesets without the source, then
815
+ * the configs the scan step will read from the private rules directory.
816
+ * @param {RunContext} context
817
+ * @param {RunState} state
818
+ * @param {AisacRules} aisacRules
819
+ */
820
+ async function semgrepConfigs(context, state, aisacRules) {
821
+ const prepared = await prepareSemgrepRules({
822
+ rulesDir: context.workspace.rulesDir,
823
+ fetchImpl: context.fetchImpl,
824
+ aisacRules,
825
+ signal: context.signal,
826
+ });
827
+ state.rulesets.push(...prepared.rulesets);
828
+ state.network.push({ tool: 'semgrep', purpose: 'registry_rulesets' });
829
+ if (prepared.rulesets.some((ruleset) => ruleset.status === 'unavailable'))
830
+ state.warnings.push('registry_rulesets_unavailable');
831
+ return prepared.configs;
832
+ }
833
+
834
+ /**
835
+ * @typedef {{
836
+ * status: 'ran' | 'failed' | 'timed_out',
837
+ * reason: string | null,
838
+ * interrupted: boolean,
839
+ * exitCode: number | null,
840
+ * parsed: ParsedOutput | null
841
+ * }} PassOutcome
842
+ */
843
+
844
+ /**
845
+ * One run of a tool and its parsed output; `parsed` is null unless it ran
846
+ * and wrote its own schema (else `output_schema`). `history` is gitleaks'
847
+ * second pass (scan review F1).
848
+ * @param {RunContext} context
849
+ * @param {Runner} runner
850
+ * @param {string[]} configs
851
+ * @param {boolean} history
852
+ * @returns {Promise<PassOutcome>}
853
+ */
854
+ async function runPass(context, runner, configs, history) {
855
+ const run = await executeTool(
856
+ { spawn: context.spawn, env: context.env, signal: context.signal },
857
+ {
858
+ runner,
859
+ target: context.target,
860
+ outDir: context.workspace.outDir,
861
+ rulesDir: context.workspace.rulesDir,
862
+ configs,
863
+ history,
864
+ timeoutMs: context.options.timeoutSeconds * MILLISECONDS_PER_SECOND,
865
+ home: context.workspace.home,
866
+ ignoreOverlay: context.tree.ignoreOverlay,
867
+ lockfiles: context.tree.lockfiles,
868
+ },
869
+ );
870
+ const base = { reason: run.reason, interrupted: false, exitCode: run.exitCode, parsed: null };
871
+ if (run.status === 'interrupted') return { ...base, status: 'failed', interrupted: true };
872
+ if (run.status !== 'ran') return { ...base, status: run.status };
873
+ const prefixes =
874
+ runner.mode === 'image' ? [CONTAINER_SOURCE_PREFIX] : [`${context.target}${sep}`];
875
+ const parsed = PARSERS[runner.tool](run.output, { prefixes });
876
+ return parsed === null
877
+ ? { ...base, status: 'failed', reason: 'output_schema' }
878
+ : { ...base, status: 'ran', parsed };
879
+ }
880
+
881
+ /** `ran`, `timed_out` or `failed(<reason>)` (scan review F1). @param {PassOutcome} pass */
882
+ function historyState(pass) {
883
+ if (pass.status === 'ran') return 'ran';
884
+ if (pass.status === 'timed_out') return 'timed_out';
885
+ return `failed(${pass.reason ?? 'unknown'})`;
886
+ }
887
+
888
+ /**
889
+ * Run one resolved tool and fold its outcome into the run state. With
890
+ * `--history`, gitleaks scans the tree, then the history with the same
891
+ * flags; the findings are merged, one row per secret, the tree's first
892
+ * (`mergeSecretPasses`), and a
893
+ * history pass that does not complete fails the tool (`history_failed`,
894
+ * scan review F1).
895
+ * @param {RunContext} context
896
+ * @param {RunState} state
897
+ * @param {Runner} runner
898
+ * @param {ScanKind} kind
899
+ * @param {string[]} configs
900
+ * @param {Date} started
901
+ */
902
+ async function runResolved(context, state, runner, kind, configs, started) {
903
+ const tool = runner.tool;
904
+ if (usesNetwork(tool)) state.network.push({ tool, purpose: 'advisory_lookup' });
905
+ const tree = await runPass(context, runner, configs, false);
906
+ let { status, reason, interrupted } = tree;
907
+ let findings = tree.parsed?.findings ?? [];
908
+ if (tree.parsed !== null) state.sanitized.set(OUTPUT_FILE[tool], tree.parsed.sanitized);
909
+ /** @type {string | null} */
910
+ let history = null;
911
+ if (tool === 'gitleaks' && context.options.history) {
912
+ if (interrupted || context.signal.aborted) {
913
+ history = `failed(${INTERRUPTED})`;
914
+ interrupted = true;
915
+ } else {
916
+ const past = await runPass(context, runner, configs, true);
917
+ history = historyState(past);
918
+ interrupted = past.interrupted;
919
+ if (past.parsed !== null) {
920
+ findings = mergeSecretPasses(tree.parsed ?? { findings: [], sanitized: [] }, past.parsed);
921
+ state.sanitized.set(HISTORY_OUTPUT_FILE, past.parsed.sanitized);
922
+ }
923
+ }
924
+ if (history !== 'ran' && status === 'ran') {
925
+ status = 'failed';
926
+ reason = 'history_failed';
927
+ }
928
+ }
929
+ if (interrupted) state.interrupted = true;
930
+ state.findings.push(...findings);
931
+ state.tools.push(
932
+ toolRecord(
933
+ tool,
934
+ kind,
935
+ {
936
+ mode: runner.mode,
937
+ reference: runner.reference,
938
+ version: runner.version,
939
+ status,
940
+ reason,
941
+ exitCode: tree.exitCode,
942
+ history,
943
+ },
944
+ started,
945
+ context.now(),
946
+ ),
947
+ );
948
+ }
949
+
950
+ /**
951
+ * The kinds in spec order (FR3); one tool's failure never stops the others.
952
+ * @param {RunContext} context
953
+ * @param {AisacRules} aisacRules
954
+ * @returns {Promise<RunState>}
955
+ */
956
+ async function runKinds(context, aisacRules) {
957
+ /** @type {RunState} */
958
+ const state = {
959
+ tools: [],
960
+ findings: [],
961
+ sanitized: new Map(),
962
+ rulesets: [],
963
+ network: [],
964
+ warnings: [],
965
+ interrupted: false,
966
+ };
967
+ const selected = selectedKinds(context.options);
968
+ const docker = context.options.docker ? await probeDocker(context.spawn, context.env) : null;
969
+ /** @type {Map<ScanTool, Resolution>} */
970
+ const resolved = new Map();
971
+ for (const kind of SCAN_KINDS) {
972
+ const tool = TOOL_OF_KIND[kind];
973
+ const started = context.now();
974
+ /** @param {string} reason */
975
+ const skip = (reason) =>
976
+ state.tools.push(toolRecord(tool, kind, skippedOutcome(reason), started, context.now()));
977
+ if (!selected.has(kind)) {
978
+ skip('not_selected');
979
+ continue;
980
+ }
981
+ if (kind === 'container') {
982
+ skip(CONTAINER_DEFERRED);
983
+ continue;
984
+ }
985
+ if (state.interrupted || context.signal.aborted) {
986
+ state.interrupted = true;
987
+ skip('interrupted');
988
+ continue;
989
+ }
990
+ const resolution =
991
+ resolved.get(tool) ??
992
+ (await resolveTool(
993
+ { spawn: context.spawn, env: context.env, docker, signal: context.signal },
994
+ tool,
995
+ context.pins.tools[tool],
996
+ {
997
+ pull: true,
998
+ timeoutMs: context.options.timeoutSeconds * MILLISECONDS_PER_SECOND,
999
+ },
1000
+ ));
1001
+ resolved.set(tool, resolution);
1002
+ if ('skipped' in resolution) {
1003
+ if (resolution.skipped === INTERRUPTED) state.interrupted = true;
1004
+ skip(resolution.skipped);
1005
+ continue;
1006
+ }
1007
+ const configs = tool === 'semgrep' ? await semgrepConfigs(context, state, aisacRules) : [];
1008
+ if (context.signal.aborted) {
1009
+ state.interrupted = true;
1010
+ skip(INTERRUPTED);
1011
+ continue;
1012
+ }
1013
+ if (tool === 'semgrep' && configs.length === 0) {
1014
+ skip('no_rules');
1015
+ continue;
1016
+ }
1017
+ await runResolved(context, state, resolution.runner, kind, configs, started);
1018
+ }
1019
+ return state;
1020
+ }
1021
+
1022
+ /** @param {AisacRules} rules */
1023
+ function aisacRulesRecord(rules) {
1024
+ return {
1025
+ status: rules.status,
1026
+ reason: rules.status === 'refused' ? rules.reason : null,
1027
+ count: rules.status === 'loaded' ? rules.count : 0,
1028
+ };
1029
+ }
1030
+
1031
+ /**
1032
+ * The private workspace for one run: tool output, Semgrep rules and a home
1033
+ * for binaries, all `0700`, outside the project.
1034
+ * @param {string} root
1035
+ */
1036
+ async function createWorkspace(root) {
1037
+ const base = await mkdtemp(join(root, WORKSPACE_PREFIX));
1038
+ await writePrivateFile(join(base, WORKSPACE_MARKER), `${process.pid}\n`);
1039
+ const workspace = {
1040
+ base,
1041
+ outDir: join(base, 'out'),
1042
+ rulesDir: join(base, 'rules'),
1043
+ home: join(base, 'home'),
1044
+ };
1045
+ for (const directory of [workspace.outDir, workspace.rulesDir, workspace.home])
1046
+ await mkdir(directory, { mode: PRIVATE_DIRECTORY_MODE });
1047
+ return workspace;
1048
+ }
1049
+
1050
+ /** Whether `pid` still runs: only ESRCH says it does not. @param {number} pid */
1051
+ function processAlive(pid) {
1052
+ try {
1053
+ process.kill(pid, 0);
1054
+ return true;
1055
+ } catch (error) {
1056
+ return !(isRecord(error) && error.code === 'ESRCH');
1057
+ }
1058
+ }
1059
+
1060
+ /**
1061
+ * Remove the workspaces that a killed run left behind, raw tool output
1062
+ * included (scan review F8): only directories (never links) named with the
1063
+ * workspace prefix that hold the marker, whose process is gone or whose
1064
+ * marker is older than a day. Returns how many were removed.
1065
+ * @param {string} root
1066
+ */
1067
+ async function sweepStaleWorkspaces(root) {
1068
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
1069
+ let removed = 0;
1070
+ for (const entry of entries) {
1071
+ if (!entry.isDirectory() || !entry.name.startsWith(WORKSPACE_PREFIX)) continue;
1072
+ const marker = join(root, entry.name, WORKSPACE_MARKER);
1073
+ const info = await lstat(marker).catch(() => null);
1074
+ if (info === null || !info.isFile()) continue;
1075
+ const read = await readBoundedFile(marker, MAX_MARKER_BYTES);
1076
+ const pid = read.ok ? Number(read.text.trim()) : Number.NaN;
1077
+ const dead = Number.isSafeInteger(pid) && pid > 0 && !processAlive(pid);
1078
+ if (!dead && Date.now() - info.mtimeMs <= STALE_WORKSPACE_MS) continue;
1079
+ await rm(join(root, entry.name), { recursive: true, force: true });
1080
+ removed += 1;
1081
+ }
1082
+ return removed;
1083
+ }
1084
+
1085
+ /**
1086
+ * Write the sanitized raw outputs, `summary.json`, `summary.md` and
1087
+ * `latest.json` (D5); nothing else is written in the project.
1088
+ * @param {{ runDirectory: string, scanRoot: string }} paths
1089
+ * @param {Map<string, unknown>} sanitized
1090
+ * @param {import('./engineering-scan-report.mjs').ScanSummary} summary
1091
+ * @param {PackLocale} locale
1092
+ */
1093
+ async function writeReports(paths, sanitized, summary, locale) {
1094
+ for (const [file, value] of sanitized)
1095
+ await writePrivateFile(join(paths.runDirectory, file), `${JSON.stringify(value, null, 2)}\n`);
1096
+ const json = summaryJson(summary);
1097
+ await writePrivateFile(join(paths.runDirectory, SUMMARY_FILE), json);
1098
+ await writePrivateFile(
1099
+ join(paths.runDirectory, SUMMARY_MARKDOWN_FILE),
1100
+ renderSummaryMarkdown(summary, locale),
1101
+ );
1102
+ await replaceLatest(paths.scanRoot, json);
1103
+ return json;
1104
+ }
1105
+
1106
+ /**
1107
+ * Stop the running tool on Ctrl-C, SIGTERM or the caller's signal; the
1108
+ * remaining kinds are skipped and the partial summary is still written
1109
+ * (exit 3). A second Ctrl-C keeps its default meaning.
1110
+ * @param {AbortController} controller
1111
+ * @param {AbortSignal | undefined} external
1112
+ */
1113
+ function watchSignals(controller, external) {
1114
+ const onSignal = () => controller.abort();
1115
+ process.once('SIGINT', onSignal);
1116
+ process.once('SIGTERM', onSignal);
1117
+ if (external?.aborted === true) controller.abort();
1118
+ external?.addEventListener('abort', onSignal, { once: true });
1119
+ return () => {
1120
+ process.removeListener('SIGINT', onSignal);
1121
+ process.removeListener('SIGTERM', onSignal);
1122
+ external?.removeEventListener('abort', onSignal);
1123
+ };
1124
+ }
1125
+
1126
+ /**
1127
+ * The scan itself, after the license gate.
1128
+ * @param {Omit<RunContext, 'workspace' | 'signal' | 'tree'>} input
1129
+ * @param {{ tmpRoot: string, locale: PackLocale, json: boolean, packageRoot: string,
1130
+ * log: (line: string) => void, signal: AbortSignal | undefined }} output
1131
+ */
1132
+ async function runScan(input, output) {
1133
+ const startedAt = input.now();
1134
+ const aisacRules = loadAisacRules(input.pack.files);
1135
+ const paths = await prepareRunDirectory(input.target, startedAt);
1136
+ const swept = await sweepStaleWorkspaces(output.tmpRoot);
1137
+ const workspace = await createWorkspace(output.tmpRoot);
1138
+ // Should the process end mid-run (process.exit elsewhere), the private
1139
+ // workspace, which holds raw tool output, goes with it (scan review F8).
1140
+ const removeWorkspace = () => {
1141
+ try {
1142
+ rmSync(workspace.base, { recursive: true, force: true });
1143
+ } catch {
1144
+ // Exiting anyway; the directory is private (0700) and in the temporary root.
1145
+ }
1146
+ };
1147
+ process.on('exit', removeWorkspace);
1148
+ const controller = new AbortController();
1149
+ const unwatch = watchSignals(controller, output.signal);
1150
+ try {
1151
+ await writeClientConfigs(workspace.rulesDir);
1152
+ const walk = await walkTarget(input.target);
1153
+ const ignored = await reportsIgnored(input.spawn, input.env, input.target);
1154
+ const tree = {
1155
+ ignoreOverlay: await hasRootGitleaksIgnore(input.target),
1156
+ lockfiles: walk.lockfiles,
1157
+ };
1158
+ const state = await runKinds(
1159
+ { ...input, workspace, signal: controller.signal, tree },
1160
+ aisacRules,
1161
+ );
1162
+ // A gitleaks binary reads the root .gitleaksignore; only the image masks it.
1163
+ const honoured =
1164
+ tree.ignoreOverlay && state.tools.some((t) => t.tool === 'gitleaks' && t.mode === 'binary');
1165
+ const summary = buildSummary({
1166
+ aisacClient: await clientVersion(output.packageRoot),
1167
+ packVersion: input.pack.packVersion,
1168
+ startedAt: startedAt.toISOString(),
1169
+ finishedAt: input.now().toISOString(),
1170
+ target: input.target,
1171
+ failOn: input.options.failOn,
1172
+ tools: state.tools,
1173
+ rulesets: state.rulesets,
1174
+ aisacRules: aisacRulesRecord(aisacRules),
1175
+ network: state.network,
1176
+ skippedPaths: walk.paths,
1177
+ warnings: [
1178
+ ...(ignored === 'not_ignored' ? ['gitignore_missing'] : []),
1179
+ ...(walk.truncated ? ['skipped_paths_truncated'] : []),
1180
+ ...scannerConfigWarnings(walk.scannerConfigs),
1181
+ ...(honoured ? ['repo_gitleaksignore_honoured'] : []),
1182
+ ...(swept > 0 ? [`stale_workspace_removed:${swept}`] : []),
1183
+ ...(aisacRules.status === 'refused' ? ['aisac_rules_refused'] : []),
1184
+ ...state.warnings,
1185
+ ],
1186
+ findings: state.findings,
1187
+ interrupted: state.interrupted,
1188
+ });
1189
+ const json = await writeReports(paths, state.sanitized, summary, output.locale);
1190
+ if (output.json) output.log(json.trimEnd());
1191
+ else
1192
+ for (const line of scanReportLines(summary, output.locale, paths.runDirectory))
1193
+ output.log(line);
1194
+ return summary.exitCode;
1195
+ } finally {
1196
+ unwatch();
1197
+ process.removeListener('exit', removeWorkspace);
1198
+ await rm(workspace.base, { recursive: true, force: true });
1199
+ }
1200
+ }
1201
+
1202
+ /**
1203
+ * The command (FR1–FR9). Returns the exit code of D6: 0 clean, 1 a finding
1204
+ * reaches `--fail-on`, 3 nothing ran or a tool failed. Throws usage errors
1205
+ * (`exitCode` 2) and the pack and setup errors of `aisac init` (`exitCode`
1206
+ * 3) before any tool runs; any other error is thrown with `exitCode` 3
1207
+ * (scan review F3). It never prompts.
1208
+ * @param {readonly string[]} args
1209
+ * @param {ScanDependencies} deps
1210
+ * @returns {Promise<number>}
1211
+ */
1212
+ export async function scanCommand(args, deps) {
1213
+ try {
1214
+ return await runCommand(args, deps);
1215
+ } catch (error) {
1216
+ throw classified(error);
1217
+ }
1218
+ }
1219
+
1220
+ /**
1221
+ * @param {readonly string[]} args
1222
+ * @param {ScanDependencies} deps
1223
+ * @returns {Promise<number>}
1224
+ */
1225
+ async function runCommand(args, deps) {
1226
+ const log = deps.log ?? ((line) => console.log(line));
1227
+ const warn = deps.warn ?? ((line) => console.error(line));
1228
+ const options = parseScanArguments(args);
1229
+ const env = deps.env ?? process.env;
1230
+ const spawnImpl = deps.spawn ?? nodeSpawn;
1231
+ const locale = options.lang ?? resolvePackLocale(await readStoredLocale(deps.stateRoot()), env);
1232
+ if (options.checkTools) {
1233
+ const view = await availability(
1234
+ { packageRoot: deps.packageRoot, env, spawn: spawnImpl },
1235
+ options,
1236
+ );
1237
+ if (options.json) log(JSON.stringify({ docker: view.docker, tools: view.entries }));
1238
+ else for (const line of availabilityLines(view.entries, locale, view.docker)) log(line);
1239
+ return 0;
1240
+ }
1241
+ const target = await resolveTarget(deps.cwd ?? process.cwd(), options.dir);
1242
+ if (options.history) await checkHistoryTarget(target);
1243
+ const pins = await loadScanPins(deps.packageRoot);
1244
+ const pack = await licensedPack(deps, locale, warn);
1245
+ return runScan(
1246
+ {
1247
+ options,
1248
+ target,
1249
+ pack,
1250
+ pins,
1251
+ spawn: spawnImpl,
1252
+ env,
1253
+ fetchImpl: deps.fetchImpl ?? fetch,
1254
+ now: deps.now ?? (() => new Date()),
1255
+ },
1256
+ {
1257
+ tmpRoot: deps.tmpRoot ?? tmpdir(),
1258
+ locale,
1259
+ json: options.json,
1260
+ packageRoot: deps.packageRoot,
1261
+ log,
1262
+ signal: deps.signal,
1263
+ },
1264
+ );
1265
+ }