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

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 (60) hide show
  1. package/README.md +146 -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 +846 -14
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +12 -1
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +641 -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 +276 -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 +390 -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 +1557 -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 +403 -47
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/manager/bus.mjs +1921 -0
  35. package/dist/manager/delegation.mjs +354 -0
  36. package/dist/manager/hooks.mjs +918 -0
  37. package/dist/manager/launch-role.mjs +476 -0
  38. package/dist/manager/mcp-stdio.mjs +463 -0
  39. package/dist/manager/messages.mjs +791 -0
  40. package/dist/manager/reserve.mjs +2166 -0
  41. package/dist/manager/room.mjs +106 -0
  42. package/dist/manager/server.mjs +1792 -0
  43. package/dist/manager/status.mjs +118 -0
  44. package/dist/manager/watch.mjs +87 -0
  45. package/dist/manager/worker.mjs +2793 -0
  46. package/dist/manager/workers-cli.mjs +1403 -0
  47. package/dist/mcp-servers.mjs +192 -0
  48. package/dist/mcp.mjs +10 -2
  49. package/dist/monitor.mjs +76 -1
  50. package/dist/package.json +1 -1
  51. package/dist/platform.mjs +78 -29
  52. package/dist/release-manifest-public-keys.json +10 -0
  53. package/dist/release-manifest.json +328 -0
  54. package/dist/release-manifest.mjs +817 -0
  55. package/dist/release-settings.mjs +210 -0
  56. package/dist/self-update.mjs +1036 -0
  57. package/dist/state.mjs +25 -1
  58. package/dist/token-guide.mjs +132 -0
  59. package/dist/update-actions.mjs +442 -0
  60. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -25,6 +25,7 @@ import { launchClaude, launchCodex } from './launch.mjs';
25
25
  import { claudeCompatibilityError, resolveClaudeCompatibility } from './claude-compatibility.mjs';
26
26
  import { codexCompatibilityError, resolveCodexCompatibility } from './codex-compatibility.mjs';
27
27
  import { providerFreeProbe } from './mcp.mjs';
28
+ import { setupFailureHint, tokenFailureGuide, tokenPromptGuide } from './token-guide.mjs';
28
29
  import { codexPolicyJson, makePolicy, publicPolicy, isProfile } from './policy.mjs';
29
30
  import { readDiagnostics } from './claude-observation.mjs';
30
31
  import { readCodexDiagnostics } from './codex-diagnostics.mjs';
@@ -36,17 +37,54 @@ import {
36
37
  resolvePackLocale,
37
38
  writeStoredLocale,
38
39
  } from './engineering-pack.mjs';
40
+ import { initCommand } from './engineering-init.mjs';
41
+ import { manifestDoctorSection, resolveReleaseManifest } from './release-manifest.mjs';
42
+ import {
43
+ isChannel,
44
+ isHostMode,
45
+ isUpdateMode,
46
+ readReleaseSettings,
47
+ writeReleaseSettings,
48
+ } from './release-settings.mjs';
49
+ import {
50
+ askReleaseConsent,
51
+ recordReleaseConsent,
52
+ releaseDisclosure,
53
+ releaseUpdateLock,
54
+ selfUpdateAtLaunch,
55
+ updateCommand,
56
+ updateDoctorSection,
57
+ } from './self-update.mjs';
58
+ import {
59
+ describeManagedHost,
60
+ hostFallbackLine,
61
+ resolveHostExecutable,
62
+ takeHostFlag,
63
+ } from './managed-host.mjs';
64
+ import { scanCommand, scanToolAvailability } from './engineering-scan.mjs';
65
+ import { extensionsSummary, hooksCommand, mcpCommand } from './extensions-cli.mjs';
66
+ import { sessionServers } from './mcp-servers.mjs';
67
+ import { anyFormatter } from './guardrails/format.mjs';
68
+ import { readCodexGuardrails } from './guardrails-plugin.mjs';
69
+ import { codexHooksStatus, supportsCodexHooks } from './codex-hooks.mjs';
70
+ import { managerDoctorLine, managerDoctorSection, takeRoleFlags } from './manager/launch-role.mjs';
71
+ import { WORKERS_USAGE, workersCommand } from './manager/workers-cli.mjs';
39
72
 
40
- const VERSION = '0.4.0-beta.2';
73
+ const VERSION = '0.4.0-beta.22';
41
74
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
42
75
  const COMMAND = 'aisac';
76
+ /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
77
+ const SCAN_CANNOT_RUN_EXIT_CODE = 3;
43
78
  const ENDPOINT = 'https://mcp.ai-brain.aisac.cloud/mcp';
44
79
  const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
45
80
  const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
46
81
 
47
82
  function usage() {
48
83
  console.log(
49
- `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [-- native-args...]\n ${COMMAND} codex [-- native-args...]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
84
+ `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager [--room <name>]] [-- native-args...]\n ${COMMAND} codex [--worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
85
+ );
86
+ console.log(
87
+ 'Clients: setup without --client configures the clients installed on PATH (Claude Code, Codex, or both).',
50
88
  );
51
89
  console.log(
52
90
  'Telemetry: setup --telemetry on|off (omitted preserves the stored choice; fresh defaults off).',
@@ -55,10 +93,61 @@ function usage() {
55
93
  'Claude shadow: setup --claude-shadow on|off and --claude-diagnostics on|off (preview stays applied=false).',
56
94
  );
57
95
  console.log(
58
- 'AISAC Engineering: `aisac claude` loads the licensed method; setup --lang pt-BR|en picks its language; setup and doctor report the license; status stays offline. `aibrain` is an alias of `aisac`.',
96
+ 'AISAC Engineering: `aisac claude` and `aisac codex` (Codex 0.164+) load the licensed method; setup --lang pt-BR|en picks its language (before the first setup it runs the full setup); setup and doctor report the license; status stays offline. `aibrain` is an alias of `aisac`.',
97
+ );
98
+ console.log(
99
+ 'Project skeleton: `aisac init [dir]` (licensed accounts) writes the AISAC skeleton from the pack into a new or existing project, only the files that are missing; `--dry-run` lists them, `--stack` picks node|python|none when detection is not enough.',
100
+ );
101
+ console.log(
102
+ 'Security scan: `aisac scan [dir]` (licensed accounts) runs pinned scanners (gitleaks, Semgrep CE, osv-scanner, Trivy) over your own project and writes the report under `.security-reports/aisac-scan/`; findings stay on the machine; `--check-tools` shows what would run (doctor reports it as `scan`); <kinds> is a comma list of secrets, sast, sca, iac, container.',
103
+ );
104
+ console.log(
105
+ 'Guardrails: `aisac hooks` lists them (a checklist on a terminal); `aisac hooks enable|disable <id>...` and `aisac hooks reset` change the next `aisac claude` or `aisac codex` session.',
106
+ );
107
+ console.log(
108
+ 'MCP catalog: `aisac mcp` lists the reviewed servers (GitHub, Supabase, Vercel, Playwright, Context7); `aisac mcp enable|disable <id>...`, `aisac mcp reset`, `aisac mcp info <id>` and `aisac mcp login <id>` (Codex) change or explain the next session.',
109
+ );
110
+ console.log(
111
+ 'Updates: at launch `aisac` reads the signed release manifest and, in `auto` mode, installs the newer listed version into its own npm prefix and restarts; `notify` (the default) prints the command; `off` stays quiet. `aisac update` does it on demand (`--check` only looks, `--rollback` returns to the previous version, `--yes` for scripts); setup --update-mode and --channel record the choice; AISAC_NO_SELF_UPDATE=1 turns it off for one launch.',
112
+ );
113
+ console.log(
114
+ 'Managed host: `aisac setup --host-claude managed` (or `aisac claude --host managed` for one session) runs the Claude Code version the signed manifest pins, installed from the npm registry under the aisac state directory with scripts off; the installer never touches your own `claude`, your `~/.claude` (the managed copy shares your login and settings) or your shell profile. `system` (the default) keeps your binary; AISAC_HOST_MODE=system turns the managed host off for one launch; doctor reports it under `hosts`. After a failed install the launches of the next hour keep your binary without trying again; `aisac claude --host managed` tries at once.',
115
+ );
116
+ console.log(
117
+ "Manager and workers (licensed accounts): `aisac claude --manager` coordinates the Codex sessions started with `aisac codex --worker <name>` in the same repository (or the same `--room <name>`): its manager_* tools send a message to a worker, which runs it as one turn under its own sandbox and approval policy, and read the reply; you can still type in any worker. `aisac workers` lists the room; `aisac workers delegate [<name>...] [--for 8h]`, typed by you on a terminal, lets the manager answer the workers' approval prompts for a limited time, except a fixed reserve that always stays with you; `aisac workers delegate --off` ends it and `aisac workers decisions` shows what was decided. Messages are local files under the aisac state directory, deleted when read; a message becomes part of the other session's conversation, so its text reaches that session's model provider like anything typed there.",
59
118
  );
60
119
  }
61
120
 
121
+ /**
122
+ * `aisac workers` (spec aisac-engineering-manager FR1, FR9, FR13): local state
123
+ * only, so it needs no setup and no license.
124
+ * @param {string[]} args
125
+ */
126
+ async function workers(args) {
127
+ const root = stateRoot();
128
+ const locale = resolvePackLocale(await readStoredLocale(root), process.env);
129
+ return workersCommand(args, {
130
+ stateRoot: root,
131
+ cwd: process.cwd(),
132
+ env: process.env,
133
+ locale,
134
+ out: (text) => stdout.write(`${text}\n`),
135
+ err: (text) => process.stderr.write(`${text}\n`),
136
+ terminal: {
137
+ // A delegation is typed by a person: standard input must be a terminal (FR13).
138
+ isTTY: stdin.isTTY === true,
139
+ question: async (prompt) => {
140
+ const reader = createInterface({ input: stdin, output: stdout });
141
+ try {
142
+ return await reader.question(prompt);
143
+ } finally {
144
+ reader.close();
145
+ }
146
+ },
147
+ },
148
+ });
149
+ }
150
+
62
151
  // Telemetry is opt-in; setup omits the flag to preserve the stored choice.
63
152
  function version() {
64
153
  console.log(`${COMMAND} ${VERSION}`);
@@ -106,6 +195,18 @@ async function maskedPrompt() {
106
195
  }
107
196
  }
108
197
 
198
+ /**
199
+ * A setup error that carries the PAT step-by-step guide when the failure means
200
+ * the subscriber needs a (different) token.
201
+ * @param {string} code @param {'pt-BR' | 'en'} locale @param {string} endpoint
202
+ */
203
+ function setupTokenError(code, locale, endpoint) {
204
+ const error = new Error(code);
205
+ const guide = tokenFailureGuide(code, locale, endpoint) ?? setupFailureHint(code, locale);
206
+ if (guide !== null) Object.defineProperty(error, 'guide', { value: guide });
207
+ return error;
208
+ }
209
+
109
210
  /** @param {string[]} args @param {string} name */
110
211
  function option(args, name) {
111
212
  const index = args.indexOf(name);
@@ -165,8 +266,11 @@ function policyOverrides(args) {
165
266
  return values;
166
267
  }
167
268
 
168
- /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
169
- function selectedPolicy(args, previous) {
269
+ /**
270
+ * @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous
271
+ * @param {'claude' | 'codex' | 'both'} clients
272
+ */
273
+ function selectedPolicy(args, previous, clients) {
170
274
  const explicitProfile = option(args, '--context-profile');
171
275
  const explicitV2 =
172
276
  explicitProfile !== undefined ||
@@ -205,7 +309,6 @@ function selectedPolicy(args, previous) {
205
309
  if (option(args, '--goal') === undefined && inherited.goal !== undefined)
206
310
  overrides.goal = inherited.goal;
207
311
  }
208
- const clients = option(args, '--client') ?? 'both';
209
312
  if (
210
313
  clients === 'codex' &&
211
314
  args.some(
@@ -394,6 +497,89 @@ async function disclosureAccepted(
394
497
  }
395
498
  }
396
499
 
500
+ /**
501
+ * Client selection when `--client` is omitted: the native clients found on PATH. Codex
502
+ * also needs `node`, the same pair the explicit `--client codex` path checks.
503
+ * @returns {'claude' | 'codex' | 'both' | null}
504
+ */
505
+ function detectedClients() {
506
+ const hasClaude = resolveNative('claude') !== null;
507
+ const hasCodex = resolveNative('codex') !== null && resolveNative('node') !== null;
508
+ if (hasClaude && hasCodex) return 'both';
509
+ if (hasClaude) return 'claude';
510
+ return hasCodex ? 'codex' : null;
511
+ }
512
+
513
+ /** @param {string | undefined} requested @returns {'claude' | 'codex' | 'both'} */
514
+ function setupClients(requested) {
515
+ if (requested !== undefined) {
516
+ if (requested !== 'claude' && requested !== 'codex' && requested !== 'both')
517
+ throw new Error('invalid_client');
518
+ return requested;
519
+ }
520
+ const detected = detectedClients();
521
+ if (detected === null) throw new Error('no_native_client_found');
522
+ console.log(`Clients detected on PATH: ${detected} (pass --client to choose).`);
523
+ return detected;
524
+ }
525
+
526
+ /**
527
+ * The release disclosure and its answer (spec aisac-release-manifest FR7, D8),
528
+ * recorded in `<state>/release.json`, never in `config.json`: `--update-mode`
529
+ * answers without a question, a terminal gets the one yes/no question, and
530
+ * without either nothing is recorded: the next interactive launch asks and the
531
+ * client keeps notifying meanwhile (FR7). A `--channel` alone is still recorded.
532
+ * @param {string} root @param {'pt-BR' | 'en'} locale
533
+ * @param {{ mode: import('./release-settings.mjs').UpdateMode | undefined,
534
+ * channel: import('./release-settings.mjs').Channel | undefined,
535
+ * hostClaude: import('./release-settings.mjs').HostMode | undefined }} requested
536
+ */
537
+ async function recordSetupConsent(root, locale, requested) {
538
+ const settings = await readReleaseSettings(root);
539
+ let mode = requested.mode;
540
+ if (mode === undefined && stdin.isTTY && stdout.isTTY) {
541
+ mode = (await askReleaseConsent(locale)) ?? undefined;
542
+ } else {
543
+ console.log(`\n${releaseDisclosure(locale)}`);
544
+ }
545
+ const channel = requested.channel ?? settings.update.channel;
546
+ const hosts =
547
+ requested.hostClaude === undefined
548
+ ? settings.hosts
549
+ : { ...settings.hosts, claude: requested.hostClaude };
550
+ if (mode !== undefined) {
551
+ await recordReleaseConsent(root, settings, mode, {
552
+ ...(requested.channel === undefined ? {} : { channel: requested.channel }),
553
+ hosts,
554
+ });
555
+ console.log(`Self-update ${mode} on channel ${channel}; recorded in ${root}/release.json.`);
556
+ } else {
557
+ if (requested.channel !== undefined || requested.hostClaude !== undefined)
558
+ await writeReleaseSettings(
559
+ { consent: settings.consent, update: { ...settings.update, channel }, hosts },
560
+ root,
561
+ );
562
+ console.log(
563
+ settings.consent === null
564
+ ? `Release disclosure not answered; aisac keeps notifying about updates on channel ${channel} until an interactive launch asks (pass --update-mode auto|notify|off to answer now).`
565
+ : `Self-update ${settings.update.mode} on channel ${channel}; recorded earlier in ${root}/release.json.`,
566
+ );
567
+ }
568
+ if (requested.hostClaude !== undefined)
569
+ console.log(`Claude Code host ${requested.hostClaude}; recorded in ${root}/release.json.`);
570
+ }
571
+
572
+ /** @param {string[]} args */
573
+ function requestedReleaseSettings(args) {
574
+ const mode = option(args, '--update-mode');
575
+ if (mode !== undefined && !isUpdateMode(mode)) throw new Error('invalid_update_mode');
576
+ const channel = option(args, '--channel');
577
+ if (channel !== undefined && !isChannel(channel)) throw new Error('invalid_channel');
578
+ const hostClaude = option(args, '--host-claude');
579
+ if (hostClaude !== undefined && !isHostMode(hostClaude)) throw new Error('invalid_host_mode');
580
+ return { mode, channel, hostClaude };
581
+ }
582
+
397
583
  /** @param {string[]} args */
398
584
  async function setup(args) {
399
585
  if (args.includes('--yes')) throw new Error('explicit_disclosure_flag_required');
@@ -413,6 +599,9 @@ async function setup(args) {
413
599
  '--claude-shadow',
414
600
  '--claude-diagnostics',
415
601
  '--lang',
602
+ '--update-mode',
603
+ '--channel',
604
+ '--host-claude',
416
605
  ]),
417
606
  new Set([
418
607
  '--client',
@@ -425,14 +614,61 @@ async function setup(args) {
425
614
  '--claude-shadow',
426
615
  '--claude-diagnostics',
427
616
  '--lang',
617
+ '--update-mode',
618
+ '--channel',
619
+ '--host-claude',
428
620
  ]),
429
621
  );
430
622
  if (args.includes('--undo') && args.length !== 1)
431
623
  throw new Error('setup_undo_cannot_have_options');
432
624
  const lang = option(args, '--lang');
433
625
  if (lang !== undefined && !isPackLocale(lang)) throw new Error('invalid_lang');
434
- if (lang !== undefined && args.length === 2) return setPackLocale(lang);
626
+ const release = requestedReleaseSettings(args);
435
627
  const previous = await readConfig();
628
+ // `--lang` alone only switches the language of an existing setup. Before the first
629
+ // setup it runs the full setup (token included) and stores the language at the end.
630
+ if (lang !== undefined && args.length === 2 && previous !== null) return setPackLocale(lang);
631
+ // `--update-mode`, `--channel` and `--host-claude` alone change the release settings
632
+ // of an existing setup, offline (FR7, FR5); an explicit update flag is the answer to
633
+ // the disclosure, the host flag alone leaves the consent as it is. The managed copy
634
+ // is installed by the next launch, not here.
635
+ const releaseFlags = ['--update-mode', '--channel', '--host-claude'];
636
+ const releaseOnly =
637
+ (release.mode !== undefined ||
638
+ release.channel !== undefined ||
639
+ release.hostClaude !== undefined) &&
640
+ args.every((argument, index) =>
641
+ [...releaseFlags, '--accept-disclosure'].includes(argument)
642
+ ? true
643
+ : index > 0 && releaseFlags.includes(args[index - 1] ?? ''),
644
+ );
645
+ if (releaseOnly && previous !== null) {
646
+ const root = await ensureStateRoot();
647
+ const settings = await readReleaseSettings(root);
648
+ const hosts =
649
+ release.hostClaude === undefined
650
+ ? settings.hosts
651
+ : { ...settings.hosts, claude: release.hostClaude };
652
+ if (release.mode !== undefined || release.channel !== undefined) {
653
+ await recordReleaseConsent(root, settings, release.mode ?? settings.update.mode, {
654
+ ...(release.channel === undefined ? {} : { channel: release.channel }),
655
+ hosts,
656
+ });
657
+ console.log(
658
+ `Self-update ${release.mode ?? settings.update.mode} on channel ${release.channel ?? settings.update.channel}; recorded in ${root}/release.json. No network call was made.`,
659
+ );
660
+ } else {
661
+ await writeReleaseSettings(
662
+ { consent: settings.consent, update: settings.update, hosts },
663
+ root,
664
+ );
665
+ }
666
+ if (release.hostClaude !== undefined)
667
+ console.log(
668
+ `Claude Code host ${release.hostClaude}; recorded in ${root}/release.json. No network call was made.`,
669
+ );
670
+ return;
671
+ }
436
672
  if (await updateLocalOptOut(previous, args)) return;
437
673
  const localOptOut =
438
674
  option(args, '--telemetry') === 'off' &&
@@ -440,17 +676,18 @@ async function setup(args) {
440
676
  if (localOptOut) return disableTelemetryLocally(previous);
441
677
  const platform = platformCheck();
442
678
  if (!platform.ok) throw new Error(`${platform.code}:${platform.message}`);
443
- const clients = option(args, '--client') ?? 'both';
444
- if (!['claude', 'codex', 'both'].includes(clients)) throw new Error('invalid_client');
679
+ const clients = setupClients(option(args, '--client'));
445
680
  if (
446
681
  clients === 'codex' &&
447
682
  (option(args, '--claude-shadow') !== undefined ||
448
683
  option(args, '--claude-diagnostics') !== undefined)
449
684
  )
450
685
  throw new Error('claude_observation_requires_claude_client');
686
+ if (clients === 'codex' && release.hostClaude !== undefined)
687
+ throw new Error('host_claude_requires_claude_client');
451
688
  const endpoint = option(args, '--endpoint') ?? ENDPOINT;
452
689
  validateEndpoint(endpoint);
453
- const selection = selectedPolicy(args, previous);
690
+ const selection = selectedPolicy(args, previous, clients);
454
691
  const telemetry = telemetrySelection(args, previous);
455
692
  const claudeObservation = claudeObservationSelection(args, previous);
456
693
  const policy = selection.policy;
@@ -472,20 +709,61 @@ async function setup(args) {
472
709
  )
473
710
  throw new Error('disclosure_not_accepted');
474
711
  const root = await ensureStateRoot();
712
+ const locale = resolvePackLocale(lang ?? (await readStoredLocale(root)));
475
713
  const tokenPath = option(args, '--token-file');
476
- let token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
714
+ if (!tokenPath && stdin.isTTY && stdout.isTTY)
715
+ console.log(`\n${tokenPromptGuide(locale, endpoint)}\n`);
716
+ let token;
717
+ try {
718
+ token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
719
+ } catch (error) {
720
+ throw setupTokenError(errorMessage(error), locale, endpoint);
721
+ }
477
722
  token = token.trim();
478
- if (!token) throw new Error('empty_token');
479
- const claude = resolveNative('claude');
723
+ if (!token) throw setupTokenError('empty_token', locale, endpoint);
480
724
  const codex = resolveNative('codex');
481
725
  const node = resolveNative('node');
726
+ let claude = resolveNative('claude');
727
+ /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility | null} */
728
+ let claudeCompatibility = null;
729
+ // A managed Claude host asked for at setup (ADR-0056 R4, FR5): the pinned copy is
730
+ // installed and probed in place of the user's binary, which may then be absent;
731
+ // when it cannot be, setup goes on with the user's binary and says why.
732
+ if ((clients === 'claude' || clients === 'both') && release.hostClaude === 'managed') {
733
+ const releaseSettings = await readReleaseSettings(root);
734
+ const manifest = await resolveReleaseManifest({
735
+ root,
736
+ packageRoot: PACKAGE_ROOT,
737
+ endpoint,
738
+ token,
739
+ host: 'claude',
740
+ }).catch(() => null);
741
+ const managed = await resolveHostExecutable({
742
+ host: 'claude',
743
+ root,
744
+ packageRoot: PACKAGE_ROOT,
745
+ manifest,
746
+ settings: { ...releaseSettings, hosts: { ...releaseSettings.hosts, claude: 'managed' } },
747
+ env: process.env,
748
+ flag: 'managed',
749
+ clientVersion: VERSION,
750
+ locale,
751
+ progress: (line) => console.error(line),
752
+ });
753
+ if (managed.mode === 'managed') {
754
+ claude = managed.executable;
755
+ claudeCompatibility = managed.compatibility;
756
+ } else console.error(hostFallbackLine('claude', managed, locale));
757
+ }
482
758
  if ((clients === 'claude' || clients === 'both') && !claude) throw new Error('claude_not_found');
483
759
  if ((clients === 'codex' || clients === 'both') && (!codex || !node))
484
760
  throw new Error('codex_or_node_not_found');
485
- const claudeCompatibility =
486
- (clients === 'claude' || clients === 'both') && claude !== null
487
- ? await resolveClaudeCompatibility(claude, PACKAGE_ROOT)
488
- : null;
761
+ if (
762
+ claudeCompatibility === null &&
763
+ (clients === 'claude' || clients === 'both') &&
764
+ claude !== null
765
+ )
766
+ claudeCompatibility = await resolveClaudeCompatibility(claude, PACKAGE_ROOT);
489
767
  if (claudeCompatibility?.status === 'rejected')
490
768
  throw new Error(claudeCompatibilityError(claudeCompatibility));
491
769
  const claudeVersion = claudeCompatibility?.version ?? (claude ? nativeVersion(claude) : null);
@@ -521,7 +799,7 @@ async function setup(args) {
521
799
  ? await providerFreeProbe(endpoint, token, policy, clients)
522
800
  : await providerFreeProbe(endpoint, token);
523
801
  } catch (error) {
524
- throw new Error(`provider_free_probe_failed:${errorMessage(error)}`);
802
+ throw setupTokenError(`provider_free_probe_failed:${errorMessage(error)}`, locale, endpoint);
525
803
  }
526
804
  try {
527
805
  const configWithToken = { ...config, token, tokenSha256: await tokenDigest(token), probe };
@@ -533,12 +811,100 @@ async function setup(args) {
533
811
  console.log(
534
812
  `Configured ${clients} in ${root}. Provider-free access verified; no provider batch was used.`,
535
813
  );
814
+ await recordSetupConsent(root, locale, release);
536
815
  if (lang !== undefined) await setPackLocale(lang);
537
816
  // Display only: the server decides again on every pack request (ADR-0047).
538
817
  const line = licenseLine(await checkEngineeringLicense(endpoint, token));
539
818
  if (line !== null) console.log(line);
540
819
  }
541
820
 
821
+ /**
822
+ * Whether Codex runs the AISAC hooks the user has on, from Codex's own
823
+ * `hooks/list` in this folder (FR6, FR8, E6b). No session starts, and Codex
824
+ * writes no config or trust record. Codex is not asked when the last launch had
825
+ * no license, because the launcher then hands Codex no hook.
826
+ * @param {{ executable: string | null, version: string | null | undefined, licensed: boolean }} codex
827
+ */
828
+ async function doctorCodexHooks({ executable, version, licensed }) {
829
+ if (executable === null) return { status: 'codex_not_found' };
830
+ if (!supportsCodexHooks(version)) return { status: 'codex_version_unsupported' };
831
+ if (!licensed) return { status: 'not_licensed' };
832
+ const read = await readCodexGuardrails({
833
+ root: stateRoot(),
834
+ packageRoot: PACKAGE_ROOT,
835
+ executable,
836
+ cwd: process.cwd(),
837
+ profile: undefined,
838
+ environment: process.env,
839
+ }).catch(() => undefined);
840
+ if (read === undefined) return { status: 'list_failed' };
841
+ if (read === null) return { status: 'none_enabled' };
842
+ const { summary } = read;
843
+ if (summary === null) return { status: 'list_failed' };
844
+ const status = codexHooksStatus(summary);
845
+ return {
846
+ status,
847
+ handlers: summary.handlers,
848
+ review: summary.review,
849
+ off: summary.off,
850
+ missing: summary.missing,
851
+ ...(summary.review.length > 0
852
+ ? { remedy: 'Run aisac codex, open /hooks and approve the AISAC hooks.' }
853
+ : {}),
854
+ };
855
+ }
856
+
857
+ /**
858
+ * Extension state plus whether `format-on-edit` has a formatter in this folder,
859
+ * and whether Codex runs the hooks (FR8).
860
+ * @param {{ executable: string | null, version: string | null | undefined }} codex
861
+ */
862
+ async function doctorExtensions(codex) {
863
+ const summary = await extensionsSummary(stateRoot());
864
+ // A token server is skipped at launch when its variable is unset (names only).
865
+ const mcpMissingEnv = sessionServers(summary.mcp, 'claude', process.env).missingEnv.map(
866
+ (skipped) => skipped.id,
867
+ );
868
+ const formatOnEdit = !summary.hooks.includes('format-on-edit')
869
+ ? 'off'
870
+ : (await anyFormatter(process.cwd()))
871
+ ? 'ready'
872
+ : 'no_formatter_found';
873
+ const licensed = (await readLastLaunch(stateRoot()))?.state === 'loaded';
874
+ const codexHooks = await doctorCodexHooks({ ...codex, licensed });
875
+ return { ...summary, formatOnEdit, mcpMissingEnv, codexHooks };
876
+ }
877
+
878
+ /**
879
+ * The text doctor's `scan` line: `kind=mode`, a binary's version, then the reason, for
880
+ * example `sca=binary 2.7.1, iac=skipped (tool_unavailable)`.
881
+ * @param {Awaited<ReturnType<typeof scanToolAvailability>>} entries
882
+ */
883
+ function scanLine(entries) {
884
+ return entries
885
+ .map(({ kind, mode, version, reason }) => {
886
+ const detail = mode === 'binary' && version !== null ? ` ${version}` : '';
887
+ return `${kind}=${mode}${detail}${reason === null ? '' : ` (${reason})`}`;
888
+ })
889
+ .join(', ');
890
+ }
891
+
892
+ /**
893
+ * What `aisac scan` would run, per kind (scan spec FR9): in `--json` the entries of
894
+ * `scan --check-tools --json`, in text one line. No pull, no scan, no pack, no license.
895
+ * Optional capability: a failure (only a bad pins file) is its message and never changes
896
+ * doctor's exit code.
897
+ * @param {boolean} json
898
+ */
899
+ async function doctorScan(json) {
900
+ try {
901
+ const entries = await scanToolAvailability({ packageRoot: PACKAGE_ROOT, env: process.env });
902
+ return json ? entries : scanLine(entries);
903
+ } catch (error) {
904
+ return errorMessage(error);
905
+ }
906
+ }
907
+
542
908
  /** @param {boolean} json */
543
909
  async function doctor(json) {
544
910
  const platform = platformCheck();
@@ -564,8 +930,35 @@ async function doctor(json) {
564
930
  codex: resolveNative('codex'),
565
931
  node: resolveNative('node'),
566
932
  };
933
+ // Release manifest (ADR-0056 R2): fetched at most every six hours when a setup
934
+ // exists, bundled copy otherwise; never the exit code.
935
+ const releaseManifest = await resolveReleaseManifest({
936
+ root: stateRoot(),
937
+ packageRoot: PACKAGE_ROOT,
938
+ endpoint: config?.endpoint ?? null,
939
+ token: config?.token ?? null,
940
+ }).catch(() => null);
941
+ const releaseSettings = await readReleaseSettings(stateRoot());
942
+ // Managed hosts (ADR-0056 R4, FR8): the host a launch would run and the state of
943
+ // the pinned copy; doctor installs nothing. A ready managed copy is the binary the
944
+ // compatibility fields describe, since it is the one `aisac claude` runs.
945
+ /** @param {'claude' | 'codex'} host */
946
+ const describeHost = (host) =>
947
+ describeManagedHost({
948
+ host,
949
+ root: stateRoot(),
950
+ packageRoot: PACKAGE_ROOT,
951
+ manifest: releaseManifest,
952
+ settings: releaseSettings,
953
+ env: process.env,
954
+ clientVersion: VERSION,
955
+ }).catch(() => null);
956
+ const managedHosts = { claude: await describeHost('claude'), codex: await describeHost('codex') };
957
+ const claudeExecutable = managedHosts.claude?.executable ?? native.claude;
567
958
  const claudeCompatibility =
568
- native.claude !== null ? await resolveClaudeCompatibility(native.claude, PACKAGE_ROOT) : null;
959
+ claudeExecutable !== null
960
+ ? await resolveClaudeCompatibility(claudeExecutable, PACKAGE_ROOT)
961
+ : null;
569
962
  const codexCompatibility =
570
963
  native.codex !== null ? await resolveCodexCompatibility(native.codex) : null;
571
964
  const rawNativeVersions = {
@@ -585,7 +978,7 @@ async function doctor(json) {
585
978
  const captureLockPlatform = needsCodex ? captureLockPlatformCheck() : null;
586
979
  const nativeReady =
587
980
  (!needsClaude ||
588
- (native.claude !== null &&
981
+ (claudeExecutable !== null &&
589
982
  (claudeCompatibility?.status === 'qualified' ||
590
983
  claudeCompatibility?.status === 'host_checked'))) &&
591
984
  (!needsCodex ||
@@ -633,6 +1026,33 @@ async function doctor(json) {
633
1026
  },
634
1027
  engineering,
635
1028
  engineeringPack: await engineeringPackState(),
1029
+ manifest: releaseManifest === null ? null : manifestDoctorSection(releaseManifest),
1030
+ // Self-update (ADR-0056 R3, FR8): the decision this launch would take, no action.
1031
+ update: await updateDoctorSection({
1032
+ root: stateRoot(),
1033
+ packageRoot: PACKAGE_ROOT,
1034
+ version: VERSION,
1035
+ env: process.env,
1036
+ manifest: releaseManifest,
1037
+ }).catch(() => null),
1038
+ // Managed hosts (ADR-0056 R4, FR8): the decision and the pinned copy, no path.
1039
+ hosts: {
1040
+ managed: {
1041
+ claude: hostDoctorSection(managedHosts.claude),
1042
+ codex: hostDoctorSection(managedHosts.codex),
1043
+ },
1044
+ },
1045
+ extensions: await doctorExtensions({
1046
+ executable: native.codex,
1047
+ version: codexCompatibility?.version,
1048
+ }),
1049
+ scan: await doctorScan(json),
1050
+ // Manager and workers (ADR-0058, FR11): role support and the live rooms, no path.
1051
+ manager: await managerDoctorSection({
1052
+ root: stateRoot(),
1053
+ claude: native.claude !== null,
1054
+ codexVersion: native.codex === null ? null : (codexCompatibility?.version ?? null),
1055
+ }).catch(() => null),
636
1056
  paidOrPilot: probe?.ok
637
1057
  ? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
638
1058
  : config
@@ -640,13 +1060,98 @@ async function doctor(json) {
640
1060
  : 'not_configured',
641
1061
  };
642
1062
  if (json) console.log(JSON.stringify(result));
643
- else console.log(result);
1063
+ else {
1064
+ console.log(result);
1065
+ for (const line of releaseDoctorLines(result)) console.log(line);
1066
+ console.log(managerDoctorLine(result.manager));
1067
+ }
644
1068
  if (!platform.ok || !config || !probe?.ok || !nativeReady) process.exitCode = 1;
645
1069
  }
646
1070
 
1071
+ /**
1072
+ * The `hosts.managed.<host>` section (FR8): everything `describeManagedHost`
1073
+ * found but the binary's path.
1074
+ * @param {Awaited<ReturnType<typeof describeManagedHost>> | null} described
1075
+ */
1076
+ function hostDoctorSection(described) {
1077
+ if (described === null) return null;
1078
+ return {
1079
+ mode: described.mode,
1080
+ reason: described.reason,
1081
+ pinned: described.pinned,
1082
+ platform: described.platform,
1083
+ installed: described.installed,
1084
+ on_disk: described.on_disk,
1085
+ pin_check: described.pin_check,
1086
+ resolver: described.resolver,
1087
+ resolver_reason: described.resolver_reason,
1088
+ install_failure: described.install_failure,
1089
+ };
1090
+ }
1091
+
1092
+ /**
1093
+ * One line per release section after the text doctor output (FR8, R4).
1094
+ * @param {{ manifest: ReturnType<typeof manifestDoctorSection> | null,
1095
+ * update: Awaited<ReturnType<typeof updateDoctorSection>> | null,
1096
+ * hosts: { managed: Record<'claude' | 'codex', ReturnType<typeof hostDoctorSection>> } }} result
1097
+ */
1098
+ function releaseDoctorLines(result) {
1099
+ const manifest =
1100
+ result.manifest === null
1101
+ ? 'unavailable'
1102
+ : `sequence ${result.manifest.sequence} (${result.manifest.source}), ${result.manifest.state}`;
1103
+ const update =
1104
+ result.update === null
1105
+ ? 'unavailable'
1106
+ : `${result.update.mode} on ${result.update.channel}; ${
1107
+ result.update.action === 'none' ? 'up to date' : result.update.action
1108
+ }${result.update.reason === null ? '' : ` (${result.update.reason})`}`;
1109
+ /** @param {'claude' | 'codex'} name @param {ReturnType<typeof hostDoctorSection>} section */
1110
+ const host = (name, section) =>
1111
+ section === null
1112
+ ? `${name} unknown`
1113
+ : `${name} ${section.mode}${section.pinned === null ? '' : `, pinned ${section.pinned}`}${
1114
+ section.mode === 'managed' ? (section.installed ? ', installed' : ', not installed') : ''
1115
+ }${section.reason === null ? '' : ` (${section.reason})`}`;
1116
+ return [
1117
+ `manifest: ${manifest}`,
1118
+ `update: ${update}`,
1119
+ `hosts: ${host('claude', result.hosts.managed.claude)}; ${host('codex', result.hosts.managed.codex)}`,
1120
+ ];
1121
+ }
1122
+
1123
+ /**
1124
+ * `aisac scan`. An error the engine did not classify still means it could not scan as
1125
+ * asked: exit 3, never 1, which a CI step reads as findings (scan review F3). Usage
1126
+ * errors keep their 2.
1127
+ * @param {string[]} args
1128
+ */
1129
+ async function scan(args) {
1130
+ try {
1131
+ return await scanCommand(args, {
1132
+ packageRoot: PACKAGE_ROOT,
1133
+ readConfig,
1134
+ stateRoot,
1135
+ cwd: process.cwd(),
1136
+ env: process.env,
1137
+ });
1138
+ } catch (error) {
1139
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1140
+ if (typeof exitCode === 'number') throw error;
1141
+ const classified = error instanceof Error ? error : new Error(errorMessage(error));
1142
+ throw Object.assign(classified, { exitCode: SCAN_CANNOT_RUN_EXIT_CODE });
1143
+ }
1144
+ }
1145
+
647
1146
  /** @param {boolean} json */
648
1147
  async function status(json) {
649
1148
  const config = await readConfig();
1149
+ // Offline: the cached or bundled manifest, never a fetch (FR8).
1150
+ const releaseManifest = await resolveReleaseManifest({
1151
+ root: stateRoot(),
1152
+ packageRoot: PACKAGE_ROOT,
1153
+ }).catch(() => null);
1154
+ const releaseSettings = await readReleaseSettings(stateRoot());
650
1155
  const policy =
651
1156
  config?.schemaVersion === 2 && config.context !== undefined
652
1157
  ? config.context
@@ -669,6 +1174,22 @@ async function status(json) {
669
1174
  config?.claudeObservation?.disclosedAt !== undefined,
670
1175
  },
671
1176
  engineeringPack: await engineeringPackState(),
1177
+ manifest:
1178
+ releaseManifest === null
1179
+ ? null
1180
+ : {
1181
+ sequence: releaseManifest.sequence,
1182
+ source: releaseManifest.source,
1183
+ state: releaseManifest.state,
1184
+ },
1185
+ update: {
1186
+ mode: releaseSettings.update.mode,
1187
+ channel: releaseSettings.update.channel,
1188
+ consent: releaseSettings.consent !== null,
1189
+ },
1190
+ // Host modes as stored (FR8); whether the managed copy is installed is doctor's.
1191
+ hosts: { claude: releaseSettings.hosts.claude, codex: releaseSettings.hosts.codex },
1192
+ extensions: await extensionsSummary(stateRoot()),
672
1193
  monitoredSession: null,
673
1194
  monitoringStatus: 'not_observed',
674
1195
  };
@@ -717,6 +1238,38 @@ async function main(argv) {
717
1238
  else console.log(records);
718
1239
  return;
719
1240
  }
1241
+ if (command === 'hooks') return hooksCommand(rest);
1242
+ if (command === 'mcp') return mcpCommand(rest);
1243
+ if (command === 'init')
1244
+ return initCommand(rest, {
1245
+ packageRoot: PACKAGE_ROOT,
1246
+ readConfig,
1247
+ stateRoot,
1248
+ cwd: process.cwd(),
1249
+ env: process.env,
1250
+ });
1251
+ if (command === 'scan') {
1252
+ process.exitCode = await scan(rest);
1253
+ return;
1254
+ }
1255
+ if (command === 'workers') {
1256
+ process.exitCode = await workers(rest);
1257
+ return;
1258
+ }
1259
+ if (command === 'update') {
1260
+ process.exitCode = await updateCommand(rest, {
1261
+ root: stateRoot(),
1262
+ packageRoot: PACKAGE_ROOT,
1263
+ version: VERSION,
1264
+ env: process.env,
1265
+ readConfig: async () => {
1266
+ const config = await readConfig();
1267
+ return config === null ? null : { endpoint: config.endpoint, token: config.token };
1268
+ },
1269
+ interactive: stdin.isTTY === true && stdout.isTTY === true,
1270
+ });
1271
+ return;
1272
+ }
720
1273
  if (command === 'disable') {
721
1274
  if (rest.length > 0) throw new Error('disable_does_not_accept_options');
722
1275
  return removeOwnedSetup();
@@ -732,20 +1285,63 @@ async function main(argv) {
732
1285
  // metadata only, so patch updates do not block a fresh compatibility check.
733
1286
  if (command === 'codex' && typeof config.codexVersion !== 'string')
734
1287
  throw new Error('codex_version_unverified');
1288
+ // `--host managed|system` belongs to the launcher, not the host (ADR-0056 R4,
1289
+ // FR5); a managed Codex arrives with R5.
1290
+ const launch = takeHostFlag(rest);
1291
+ if (command === 'codex' && launch.hostMode === 'managed')
1292
+ throw new Error('host_mode_unsupported');
1293
+ // `--manager`, `--worker <name>` and `--room <name>` belong to the launcher as
1294
+ // well (spec aisac-engineering-manager D2): a manager is a Claude Code session,
1295
+ // a worker a Codex session.
1296
+ const role = takeRoleFlags(launch.args, command);
1297
+ const nativeArgs = role.args[0] === '--' ? role.args.slice(1) : role.args;
735
1298
  const root = stateRoot();
736
- const result = await (command === 'claude'
737
- ? launchClaude(
738
- { ...config, packageRoot: PACKAGE_ROOT },
739
- root,
740
- rest[0] === '--' ? rest.slice(1) : rest,
741
- )
742
- : launchCodex(
743
- { ...config, packageRoot: PACKAGE_ROOT },
744
- root,
745
- rest[0] === '--' ? rest.slice(1) : rest,
746
- ));
747
- process.exitCode = result;
748
- return;
1299
+ try {
1300
+ // Self-update (ADR-0056 R3, FR6) before any host work: the one-time consent
1301
+ // question on a terminal, then install + re-exec in `auto` mode, one line in
1302
+ // `notify`, and a refusal to launch a host below the manifest's minimum.
1303
+ const update = await selfUpdateAtLaunch({
1304
+ root,
1305
+ packageRoot: PACKAGE_ROOT,
1306
+ version: VERSION,
1307
+ config: { endpoint: config.endpoint, token: config.token },
1308
+ host: command,
1309
+ argv,
1310
+ env: process.env,
1311
+ interactive: stdin.isTTY === true && stdout.isTTY === true,
1312
+ });
1313
+ if (update.kind === 'reexec') {
1314
+ process.exitCode = update.exitCode;
1315
+ return;
1316
+ }
1317
+ if (update.kind === 'blocked')
1318
+ throw Object.assign(new Error(update.reason), { guide: update.line });
1319
+ if (update.kind === 'continue')
1320
+ for (const line of update.lines) process.stderr.write(`${line}\n`);
1321
+ const result = await (command === 'claude'
1322
+ ? launchClaude(
1323
+ { ...config, packageRoot: PACKAGE_ROOT },
1324
+ root,
1325
+ nativeArgs,
1326
+ {},
1327
+ {
1328
+ hostMode: launch.hostMode,
1329
+ role: role.request,
1330
+ },
1331
+ )
1332
+ : launchCodex(
1333
+ { ...config, packageRoot: PACKAGE_ROOT },
1334
+ root,
1335
+ nativeArgs,
1336
+ {},
1337
+ { role: role.request },
1338
+ ));
1339
+ process.exitCode = result;
1340
+ return;
1341
+ } finally {
1342
+ // The update lock, when this launch still holds it (no host started).
1343
+ await releaseUpdateLock(root).catch(() => undefined);
1344
+ }
749
1345
  }
750
1346
  throw new Error('unknown_command');
751
1347
  }
@@ -766,6 +1362,16 @@ main(cliArgs).catch((error) => {
766
1362
  );
767
1363
  } else {
768
1364
  console.error(`${COMMAND}: ${errorMessage(error)}`);
1365
+ const guide = /** @type {{ guide?: unknown }} */ (error ?? {}).guide;
1366
+ if (typeof guide === 'string') console.error(`\n${guide}`);
769
1367
  }
770
- process.exitCode = 1;
1368
+ // Usage errors exit 2 (init spec FR3, scan spec FR1). `aisac scan` exits 3
1369
+ // when it cannot scan as asked (scan spec D6: no scanner, a tool failure, no
1370
+ // license or pack), so a CI step never reads that as findings; everything
1371
+ // else exits 1.
1372
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1373
+ process.exitCode =
1374
+ typeof exitCode === 'number' && Number.isInteger(exitCode) && exitCode >= 1 && exitCode <= 3
1375
+ ? exitCode
1376
+ : 1;
771
1377
  });