@brunobracaioli/aibrain 0.4.0-beta.3 → 0.4.0-beta.30

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 (70) hide show
  1. package/README.md +199 -13
  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 +939 -13
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +34 -5
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +1084 -44
  11. package/dist/codex-compatibility.mjs +67 -5
  12. package/dist/codex-hooks.mjs +411 -0
  13. package/dist/codex-permissions.mjs +242 -51
  14. package/dist/codex-protocol-fingerprint.json +12 -13
  15. package/dist/device-login.mjs +511 -0
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +191 -14
  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/engineering.mjs +43 -5
  23. package/dist/extensions-catalog.mjs +390 -0
  24. package/dist/extensions-cli.mjs +524 -0
  25. package/dist/extensions-preferences.mjs +151 -0
  26. package/dist/guardrails/continuity.mjs +239 -0
  27. package/dist/guardrails/format.mjs +111 -0
  28. package/dist/guardrails/guards.mjs +1560 -0
  29. package/dist/guardrails/patch.mjs +33 -0
  30. package/dist/guardrails/run.mjs +286 -0
  31. package/dist/guardrails/shell-words.mjs +206 -0
  32. package/dist/guardrails-plugin.mjs +216 -0
  33. package/dist/launch-banner-art.json +40 -0
  34. package/dist/launch-banner.mjs +533 -0
  35. package/dist/launch-feedback.mjs +286 -0
  36. package/dist/launch.mjs +744 -64
  37. package/dist/managed-host.mjs +1276 -0
  38. package/dist/manager/adapter.mjs +304 -0
  39. package/dist/manager/bus.mjs +2222 -0
  40. package/dist/manager/claude-bus-worker.mjs +1355 -0
  41. package/dist/manager/delegation.mjs +354 -0
  42. package/dist/manager/hooks.mjs +918 -0
  43. package/dist/manager/launch-role.mjs +733 -0
  44. package/dist/manager/mcp-stdio.mjs +463 -0
  45. package/dist/manager/messages.mjs +861 -0
  46. package/dist/manager/native-worker.mjs +338 -0
  47. package/dist/manager/reserve.mjs +2170 -0
  48. package/dist/manager/room.mjs +106 -0
  49. package/dist/manager/send-grant.mjs +147 -0
  50. package/dist/manager/server.mjs +2010 -0
  51. package/dist/manager/status.mjs +119 -0
  52. package/dist/manager/wake-state.mjs +93 -0
  53. package/dist/manager/watch.mjs +87 -0
  54. package/dist/manager/worker.mjs +2977 -0
  55. package/dist/manager/workers-cli.mjs +1880 -0
  56. package/dist/mcp-servers.mjs +192 -0
  57. package/dist/mcp.mjs +10 -2
  58. package/dist/monitor.mjs +179 -2
  59. package/dist/package.json +1 -1
  60. package/dist/platform.mjs +78 -29
  61. package/dist/release-manifest-public-keys.json +10 -0
  62. package/dist/release-manifest.json +334 -0
  63. package/dist/release-manifest.mjs +817 -0
  64. package/dist/release-settings.mjs +335 -0
  65. package/dist/self-update.mjs +1047 -0
  66. package/dist/setup-login-state.mjs +19 -0
  67. package/dist/state.mjs +25 -1
  68. package/dist/token-guide.mjs +201 -0
  69. package/dist/update-actions.mjs +442 -0
  70. package/package.json +2 -2
package/dist/cli.mjs CHANGED
@@ -2,6 +2,8 @@
2
2
  import { dirname } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { stdin, stdout } from 'node:process';
5
+ import { deviceLogin, isLoginNotStarted, openVerificationPage } from './device-login.mjs';
6
+ import { configAfterDeviceLogin } from './setup-login-state.mjs';
5
7
  import { createInterface } from 'node:readline/promises';
6
8
  import {
7
9
  DISCLOSURE_VERSION,
@@ -25,6 +27,13 @@ import { launchClaude, launchCodex } from './launch.mjs';
25
27
  import { claudeCompatibilityError, resolveClaudeCompatibility } from './claude-compatibility.mjs';
26
28
  import { codexCompatibilityError, resolveCodexCompatibility } from './codex-compatibility.mjs';
27
29
  import { providerFreeProbe } from './mcp.mjs';
30
+ import {
31
+ deviceLoginConnectedLine,
32
+ deviceLoginFallbackLine,
33
+ setupFailureHint,
34
+ tokenFailureGuide,
35
+ tokenPromptGuide,
36
+ } from './token-guide.mjs';
28
37
  import { codexPolicyJson, makePolicy, publicPolicy, isProfile } from './policy.mjs';
29
38
  import { readDiagnostics } from './claude-observation.mjs';
30
39
  import { readCodexDiagnostics } from './codex-diagnostics.mjs';
@@ -36,17 +45,74 @@ import {
36
45
  resolvePackLocale,
37
46
  writeStoredLocale,
38
47
  } from './engineering-pack.mjs';
48
+ import { initCommand } from './engineering-init.mjs';
49
+ import {
50
+ installedClientVersion,
51
+ manifestDoctorSection,
52
+ resolveReleaseManifest,
53
+ } from './release-manifest.mjs';
54
+ import {
55
+ HOST_MODE_ENV,
56
+ isChannel,
57
+ isHostMode,
58
+ isUpdateMode,
59
+ readReleaseSettings,
60
+ recordHostSelection,
61
+ writeReleaseSettings,
62
+ } from './release-settings.mjs';
63
+ import {
64
+ askReleaseConsent,
65
+ recordReleaseConsent,
66
+ releaseDisclosure,
67
+ releaseUpdateLock,
68
+ selfUpdateAtLaunch,
69
+ updateCommand,
70
+ updateDoctorSection,
71
+ } from './self-update.mjs';
72
+ import {
73
+ describeManagedHost,
74
+ hostFallbackLine,
75
+ hostRecoveryLine,
76
+ resolveHostExecutable,
77
+ setupHostAnswerAccepted,
78
+ setupHostOffer,
79
+ setupHostQuestion,
80
+ setupHostRecoveryLine,
81
+ takeHostFlag,
82
+ } from './managed-host.mjs';
83
+ import { scanCommand, scanToolAvailability } from './engineering-scan.mjs';
84
+ import { extensionsSummary, hooksCommand, mcpCommand } from './extensions-cli.mjs';
85
+ import { sessionServers } from './mcp-servers.mjs';
86
+ import { anyFormatter } from './guardrails/format.mjs';
87
+ import { readCodexGuardrails } from './guardrails-plugin.mjs';
88
+ import { codexHooksStatus, supportsCodexHooks } from './codex-hooks.mjs';
89
+ import { managerDoctorLine, managerDoctorSection, takeRoleFlags } from './manager/launch-role.mjs';
90
+ import { WORKERS_USAGE, workersCommand } from './manager/workers-cli.mjs';
91
+ import {
92
+ describePermissionError,
93
+ describeRoleError,
94
+ launchFeedbackLocale,
95
+ } from './launch-feedback.mjs';
96
+ import { parseCodexLaunchArgs } from './codex-permissions.mjs';
39
97
 
40
- const VERSION = '0.4.0-beta.3';
98
+ const VERSION = '0.4.0-beta.30';
41
99
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
42
100
  const COMMAND = 'aisac';
101
+ /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
102
+ const SCAN_CANNOT_RUN_EXIT_CODE = 3;
43
103
  const ENDPOINT = 'https://mcp.ai-brain.aisac.cloud/mcp';
44
104
  const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
45
105
  const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
46
106
 
47
107
  function usage() {
48
108
  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.`,
109
+ `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--paste-token | --token-file PATH]\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 [--host-codex managed|system]\n ${COMMAND} setup --login\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 | --worker <name> [--bus]] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--manager | --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.`,
110
+ );
111
+ console.log(
112
+ '`aisac setup` signs in through the browser at a terminal; use `--paste-token` for the manual prompt, `--token-file` for automation, or `aisac setup --login` to replace an existing login.',
113
+ );
114
+ console.log(
115
+ 'Clients: setup without --client configures the clients installed on PATH (Claude Code, Codex, or both).',
50
116
  );
51
117
  console.log(
52
118
  'Telemetry: setup --telemetry on|off (omitted preserves the stored choice; fresh defaults off).',
@@ -55,10 +121,64 @@ function usage() {
55
121
  'Claude shadow: setup --claude-shadow on|off and --claude-diagnostics on|off (preview stays applied=false).',
56
122
  );
57
123
  console.log(
58
- 'AISAC Engineering: `aisac claude` and `aisac codex` (Codex 0.164+) load 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`.',
124
+ '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`.',
125
+ );
126
+ console.log(
127
+ '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.',
128
+ );
129
+ console.log(
130
+ '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.',
131
+ );
132
+ console.log(
133
+ '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.',
134
+ );
135
+ console.log(
136
+ '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.',
137
+ );
138
+ console.log(
139
+ '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.',
140
+ );
141
+ console.log(
142
+ 'Managed hosts: `aisac setup --host-claude managed` or `--host-codex managed` selects the signed Claude Code or Codex pin under the aisac state directory; `aisac claude --host managed` and `aisac codex --host managed` select it for one session. Installs use scripts off and never replace your global CLI, shell profile or host configuration. The managed copy shares your existing host login. `system` keeps the global binary; AISAC_HOST_MODE=system forces that choice for one launch. Doctor reports the selected mode and compatibility under `hosts`.',
143
+ );
144
+ console.log(
145
+ "Manager and workers (licensed accounts): `aisac claude --manager` or `aisac codex --manager` coordinates Codex sessions started with `aisac codex --worker <name>` and opt-in Claude Code bus sessions started with `aisac claude --worker <name> --bus` in the same repository (or `--room <name>`): each manager_* send starts one worker turn under that worker's sandbox and approval policy, and the reply is read as untrusted output. A Codex manager receives content-free wake notices on its idle terminal; Claude Code workers on the native session-messaging channel remain unreachable from Codex. A Claude manager reaches native Claude Code workers through Claude Code's own session messaging. `aisac workers` lists the room. `aisac workers allow-sends [--for 8h]` must be confirmed in your own terminal before a Codex manager can send or cancel to bus workers; it expires after 10 minutes to 24 hours and `--off` revokes it. `aisac workers delegate [<name>...] [--for 8h]` remains a separate terminal grant for a manager to answer Codex worker approval prompts, except the fixed reserve; Claude Code approvals stay with the user. `aisac workers delegate --off` ends the grant and `aisac workers decisions` shows what was decided. Messages are local files under the aisac state directory, deleted when read; message and reply text reaches the involved model providers like anything typed in their sessions.",
146
+ );
147
+ console.log(
148
+ 'Claude Code bus workers are opt-in and require all live room participants to use an AISAC client with Claude bus support; update and restart room sessions before starting `aisac claude --worker <name> --bus`.',
59
149
  );
60
150
  }
61
151
 
152
+ /**
153
+ * `aisac workers` (spec aisac-engineering-manager FR1, FR9, FR13): local state
154
+ * only, so it needs no setup and no license.
155
+ * @param {string[]} args
156
+ */
157
+ async function workers(args) {
158
+ const root = stateRoot();
159
+ const locale = resolvePackLocale(await readStoredLocale(root), process.env);
160
+ return workersCommand(args, {
161
+ stateRoot: root,
162
+ cwd: process.cwd(),
163
+ env: process.env,
164
+ locale,
165
+ out: (text) => stdout.write(`${text}\n`),
166
+ err: (text) => process.stderr.write(`${text}\n`),
167
+ terminal: {
168
+ // A delegation is typed by a person: standard input must be a terminal (FR13).
169
+ isTTY: stdin.isTTY === true,
170
+ question: async (prompt) => {
171
+ const reader = createInterface({ input: stdin, output: stdout });
172
+ try {
173
+ return await reader.question(prompt);
174
+ } finally {
175
+ reader.close();
176
+ }
177
+ },
178
+ },
179
+ });
180
+ }
181
+
62
182
  // Telemetry is opt-in; setup omits the flag to preserve the stored choice.
63
183
  function version() {
64
184
  console.log(`${COMMAND} ${VERSION}`);
@@ -106,6 +226,106 @@ async function maskedPrompt() {
106
226
  }
107
227
  }
108
228
 
229
+ /**
230
+ * A setup error that carries the PAT step-by-step guide when the failure means
231
+ * the subscriber needs a (different) token.
232
+ * @param {string} code @param {'pt-BR' | 'en'} locale @param {string} endpoint
233
+ */
234
+ function setupTokenError(code, locale, endpoint) {
235
+ const error = new Error(code);
236
+ const guide = tokenFailureGuide(code, locale, endpoint) ?? setupFailureHint(code, locale);
237
+ if (guide !== null) Object.defineProperty(error, 'guide', { value: guide });
238
+ return error;
239
+ }
240
+
241
+ /**
242
+ * Run device login while converting Ctrl-C into a clean exit status and stable
243
+ * user-facing errors. Browser opener failures remain silent in the login module.
244
+ * When the browser flow never started (the server has it off, is rate limiting or
245
+ * is unreachable), fall back to the masked token prompt instead of failing setup.
246
+ * @param {string} endpoint
247
+ * @param {'claude' | 'codex' | 'both'} agent
248
+ * @param {'pt-BR' | 'en'} locale
249
+ * @returns {Promise<{ token: string, accountHint: string | null }>}
250
+ */
251
+ async function runDeviceLogin(endpoint, agent, locale) {
252
+ if (!stdin.isTTY || !stdout.isTTY)
253
+ throw setupTokenError('token_file_required_in_noninteractive_mode', locale, endpoint);
254
+ const controller = new AbortController();
255
+ const onInterrupt = () => {
256
+ stdout.write('\n');
257
+ controller.abort();
258
+ };
259
+ process.on('SIGINT', onInterrupt);
260
+ try {
261
+ return await deviceLogin({
262
+ endpoint,
263
+ agent,
264
+ clientVersion: VERSION,
265
+ locale,
266
+ signal: controller.signal,
267
+ openBrowser: async (url, signal) => {
268
+ await openVerificationPage(url, signal === undefined ? {} : { signal });
269
+ },
270
+ writeLine: (line) => stdout.write(`${line}\n`),
271
+ });
272
+ } catch (error) {
273
+ const code = errorMessage(error);
274
+ if (code === 'login_cancelled') {
275
+ const cancelled = new Error('login_cancelled');
276
+ Object.defineProperty(cancelled, 'exitCode', { value: 130 });
277
+ throw cancelled;
278
+ }
279
+ if (!isLoginNotStarted(error)) throw setupTokenError(code, locale, endpoint);
280
+ } finally {
281
+ process.off('SIGINT', onInterrupt);
282
+ }
283
+ stdout.write(`${deviceLoginFallbackLine(locale)}\n\n${tokenPromptGuide(locale, endpoint)}\n\n`);
284
+ return { token: await maskedPrompt(), accountHint: null };
285
+ }
286
+
287
+ /** @param {Awaited<ReturnType<typeof readConfig>>} previous */
288
+ async function replaceSetupToken(previous) {
289
+ const locale = resolvePackLocale(await readStoredLocale(stateRoot()));
290
+ if (previous === null)
291
+ throw setupTokenError('setup_login_requires_existing_setup', locale, ENDPOINT);
292
+ if (!stdin.isTTY || !stdout.isTTY)
293
+ throw setupTokenError('token_file_required_in_noninteractive_mode', locale, previous.endpoint);
294
+ const endpoint = previous.endpoint;
295
+ validateEndpoint(endpoint);
296
+ const { token, accountHint } = await runDeviceLogin(endpoint, previous.clientSelection, locale);
297
+ try {
298
+ if (previous.schemaVersion === 2)
299
+ await providerFreeProbe(
300
+ endpoint,
301
+ token,
302
+ previous.context ?? makePolicy('conservative'),
303
+ previous.clientSelection,
304
+ );
305
+ else await providerFreeProbe(endpoint, token);
306
+ } catch (error) {
307
+ throw setupTokenError(`provider_free_probe_failed:${errorMessage(error)}`, locale, endpoint);
308
+ }
309
+ const tokenSha256 = await tokenDigest(token);
310
+ const current = await readConfig();
311
+ let configWithToken;
312
+ try {
313
+ configWithToken = configAfterDeviceLogin(
314
+ /** @type {Record<string, unknown>} */ (previous),
315
+ /** @type {Record<string, unknown> | null} */ (current),
316
+ token,
317
+ tokenSha256,
318
+ );
319
+ } catch (error) {
320
+ throw setupTokenError(errorMessage(error), locale, endpoint);
321
+ }
322
+ if (!isValidConfig(configWithToken)) throw new Error('config_validation_failed');
323
+ const root = stateRoot();
324
+ await atomicJson(`${root}/config.json`, configWithToken);
325
+ if (accountHint !== null) console.log(deviceLoginConnectedLine(locale, accountHint));
326
+ console.log(`Updated the AI Brain login in ${root}; the rest of the setup was preserved.`);
327
+ }
328
+
109
329
  /** @param {string[]} args @param {string} name */
110
330
  function option(args, name) {
111
331
  const index = args.indexOf(name);
@@ -165,8 +385,11 @@ function policyOverrides(args) {
165
385
  return values;
166
386
  }
167
387
 
168
- /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
169
- function selectedPolicy(args, previous) {
388
+ /**
389
+ * @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous
390
+ * @param {'claude' | 'codex' | 'both'} clients
391
+ */
392
+ function selectedPolicy(args, previous, clients) {
170
393
  const explicitProfile = option(args, '--context-profile');
171
394
  const explicitV2 =
172
395
  explicitProfile !== undefined ||
@@ -205,7 +428,6 @@ function selectedPolicy(args, previous) {
205
428
  if (option(args, '--goal') === undefined && inherited.goal !== undefined)
206
429
  overrides.goal = inherited.goal;
207
430
  }
208
- const clients = option(args, '--client') ?? 'both';
209
431
  if (
210
432
  clients === 'codex' &&
211
433
  args.some(
@@ -394,6 +616,218 @@ async function disclosureAccepted(
394
616
  }
395
617
  }
396
618
 
619
+ /**
620
+ * Client selection when `--client` is omitted: the native clients found on PATH. Codex
621
+ * also needs `node`, the same pair the explicit `--client codex` path checks.
622
+ * @returns {'claude' | 'codex' | 'both' | null}
623
+ */
624
+ function detectedClients(managedCodex = false) {
625
+ const hasClaude = resolveNative('claude') !== null;
626
+ const hasCodex =
627
+ (managedCodex || resolveNative('codex') !== null) && resolveNative('node') !== null;
628
+ if (hasClaude && hasCodex) return 'both';
629
+ if (hasClaude) return 'claude';
630
+ return hasCodex ? 'codex' : null;
631
+ }
632
+
633
+ /** @param {string | undefined} requested @param {boolean} [managedCodex] @returns {'claude' | 'codex' | 'both'} */
634
+ function setupClients(requested, managedCodex = false) {
635
+ if (requested !== undefined) {
636
+ if (requested !== 'claude' && requested !== 'codex' && requested !== 'both')
637
+ throw new Error('invalid_client');
638
+ return requested;
639
+ }
640
+ const detected = detectedClients(managedCodex);
641
+ if (detected === null) throw new Error('no_native_client_found');
642
+ console.log(`Clients detected on PATH: ${detected} (pass --client to choose).`);
643
+ return detected;
644
+ }
645
+
646
+ /**
647
+ * The release disclosure and its answer (spec aisac-release-manifest FR7, D8),
648
+ * recorded in `<state>/release.json`, never in `config.json`: `--update-mode`
649
+ * answers without a question, a terminal gets the one yes/no question, and
650
+ * without either nothing is recorded: the next interactive launch asks and the
651
+ * client keeps notifying meanwhile (FR7). A `--channel` alone is still recorded.
652
+ * @param {string} root @param {'pt-BR' | 'en'} locale
653
+ * @param {{ mode: import('./release-settings.mjs').UpdateMode | undefined,
654
+ * channel: import('./release-settings.mjs').Channel | undefined,
655
+ * hostClaude: import('./release-settings.mjs').HostMode | undefined,
656
+ * hostCodex: import('./release-settings.mjs').HostMode | undefined }} requested
657
+ */
658
+ async function recordSetupConsent(root, locale, requested) {
659
+ const settings = await readReleaseSettings(root);
660
+ let mode = requested.mode;
661
+ if (mode === undefined && stdin.isTTY && stdout.isTTY) {
662
+ mode = (await askReleaseConsent(locale)) ?? undefined;
663
+ } else {
664
+ console.log(`\n${releaseDisclosure(locale)}`);
665
+ }
666
+ const channel = requested.channel ?? settings.update.channel;
667
+ const hosts =
668
+ requested.hostClaude === undefined && requested.hostCodex === undefined
669
+ ? settings.hosts
670
+ : {
671
+ ...settings.hosts,
672
+ ...(requested.hostClaude === undefined ? {} : { claude: requested.hostClaude }),
673
+ ...(requested.hostCodex === undefined ? {} : { codex: requested.hostCodex }),
674
+ };
675
+ if (mode !== undefined) {
676
+ await recordReleaseConsent(root, settings, mode, {
677
+ ...(requested.channel === undefined ? {} : { channel: requested.channel }),
678
+ hosts,
679
+ });
680
+ await recordHostSelection(root, settings, { ...settings, status: 'valid', hosts }, [
681
+ ...(requested.hostClaude === undefined ? [] : ['claude']),
682
+ ...(requested.hostCodex === undefined ? [] : ['codex']),
683
+ ]);
684
+ console.log(`Self-update ${mode} on channel ${channel}; recorded in ${root}/release.json.`);
685
+ } else {
686
+ if (
687
+ requested.channel !== undefined ||
688
+ requested.hostClaude !== undefined ||
689
+ requested.hostCodex !== undefined
690
+ )
691
+ await writeReleaseSettings(
692
+ { consent: settings.consent, update: { ...settings.update, channel }, hosts },
693
+ root,
694
+ );
695
+ if (
696
+ requested.channel !== undefined ||
697
+ requested.hostClaude !== undefined ||
698
+ requested.hostCodex !== undefined
699
+ )
700
+ await recordHostSelection(root, settings, { ...settings, status: 'valid', hosts }, [
701
+ ...(requested.hostClaude === undefined ? [] : ['claude']),
702
+ ...(requested.hostCodex === undefined ? [] : ['codex']),
703
+ ]);
704
+ console.log(
705
+ settings.consent === null
706
+ ? `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).`
707
+ : `Self-update ${settings.update.mode} on channel ${channel}; recorded earlier in ${root}/release.json.`,
708
+ );
709
+ }
710
+ if (requested.hostClaude !== undefined)
711
+ console.log(`Claude Code host ${requested.hostClaude}; recorded in ${root}/release.json.`);
712
+ if (requested.hostCodex !== undefined)
713
+ console.log(`Codex host ${requested.hostCodex}; recorded in ${root}/release.json.`);
714
+ }
715
+
716
+ /** @param {string[]} args */
717
+ function requestedReleaseSettings(args) {
718
+ const mode = option(args, '--update-mode');
719
+ if (mode !== undefined && !isUpdateMode(mode)) throw new Error('invalid_update_mode');
720
+ const channel = option(args, '--channel');
721
+ if (channel !== undefined && !isChannel(channel)) throw new Error('invalid_channel');
722
+ const hostClaude = option(args, '--host-claude');
723
+ if (hostClaude !== undefined && !isHostMode(hostClaude)) throw new Error('invalid_host_mode');
724
+ const hostCodex = option(args, '--host-codex');
725
+ if (hostCodex !== undefined && !isHostMode(hostCodex)) throw new Error('invalid_host_mode');
726
+ return { mode, channel, hostClaude, hostCodex };
727
+ }
728
+
729
+ /**
730
+ * @param {ReturnType<typeof requestedReleaseSettings>} release @param {'claude' | 'codex'} host
731
+ * @returns {ReturnType<typeof requestedReleaseSettings>}
732
+ */
733
+ function withManagedHost(release, host) {
734
+ /** @type {import('./release-settings.mjs').HostMode} */
735
+ const managed = 'managed';
736
+ return host === 'claude'
737
+ ? { ...release, hostClaude: managed }
738
+ : { ...release, hostCodex: managed };
739
+ }
740
+
741
+ /**
742
+ * The one question offering the signed private copy of an incompatible host (C8).
743
+ * @param {'claude' | 'codex'} host @param {{ version: string | null, reason: string }} compatibility
744
+ * @param {'pt-BR' | 'en'} locale
745
+ */
746
+ async function askSetupHost(host, compatibility, locale) {
747
+ const rl = createInterface({ input: stdin, output: stdout });
748
+ try {
749
+ const question = setupHostQuestion(host, compatibility.version, compatibility.reason, locale);
750
+ return setupHostAnswerAccepted(await rl.question(question));
751
+ } catch {
752
+ return false;
753
+ } finally {
754
+ rl.close();
755
+ }
756
+ }
757
+
758
+ /**
759
+ * Setup's check of each selected system host, before the disclosure and the token
760
+ * (spec aisac-host-upgrade-resilience C7, C8). A stored managed choice counts as the
761
+ * flag. An incompatible host is offered the signed private copy at a terminal; if not
762
+ * asked or the user says no, setup stops with the commands that fix it. Local only:
763
+ * nothing is downloaded or written here, and a compatible result is reused later.
764
+ * @param {'claude' | 'codex' | 'both'} clients
765
+ * @param {ReturnType<typeof requestedReleaseSettings>} requested
766
+ * @param {'pt-BR' | 'en'} locale
767
+ */
768
+ async function preflightSetupHosts(clients, requested, locale) {
769
+ const settings = await readReleaseSettings(stateRoot());
770
+ let release = requested;
771
+ /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility | null} */
772
+ let claude = null;
773
+ /** @type {Awaited<ReturnType<typeof resolveCodexCompatibility>> | null} */
774
+ let codex = null;
775
+ for (const host of /** @type {const} */ (['claude', 'codex'])) {
776
+ if (clients !== host && clients !== 'both') continue;
777
+ const flag = host === 'claude' ? release.hostClaude : release.hostCodex;
778
+ if (flag === undefined && settings.status === 'valid' && settings.hosts[host] === 'managed')
779
+ release = withManagedHost(release, host);
780
+ if ((host === 'claude' ? release.hostClaude : release.hostCodex) === 'managed') continue;
781
+ const executable = resolveNative(host);
782
+ // A missing host keeps its own error later in setup (`claude_not_found`, ...).
783
+ if (executable === null || (host === 'codex' && resolveNative('node') === null)) continue;
784
+ const compatibility =
785
+ host === 'claude'
786
+ ? await resolveClaudeCompatibility(executable, PACKAGE_ROOT)
787
+ : await resolveCodexCompatibility(executable);
788
+ if (compatibility.status !== 'rejected') {
789
+ if (host === 'claude')
790
+ claude = /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility} */ (
791
+ compatibility
792
+ );
793
+ else
794
+ codex = /** @type {Awaited<ReturnType<typeof resolveCodexCompatibility>>} */ (
795
+ compatibility
796
+ );
797
+ continue;
798
+ }
799
+ const offer = setupHostOffer({
800
+ host,
801
+ flag: flag ?? null,
802
+ env: process.env,
803
+ settings,
804
+ interactive: Boolean(stdin.isTTY && stdout.isTTY),
805
+ });
806
+ if (offer === 'ask' && (await askSetupHost(host, compatibility, locale))) {
807
+ release = withManagedHost(release, host);
808
+ continue;
809
+ }
810
+ const message =
811
+ host === 'claude'
812
+ ? claudeCompatibilityError(
813
+ /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility} */ (compatibility),
814
+ )
815
+ : codexCompatibilityError(
816
+ /** @type {Awaited<ReturnType<typeof resolveCodexCompatibility>>} */ (compatibility),
817
+ );
818
+ throw Object.assign(new Error(message), {
819
+ guide: setupHostRecoveryLine(
820
+ host,
821
+ compatibility.version,
822
+ compatibility.reason,
823
+ locale,
824
+ process.env[HOST_MODE_ENV] === 'system',
825
+ ),
826
+ });
827
+ }
828
+ return { release, claude, codex };
829
+ }
830
+
397
831
  /** @param {string[]} args */
398
832
  async function setup(args) {
399
833
  if (args.includes('--yes')) throw new Error('explicit_disclosure_flag_required');
@@ -402,6 +836,8 @@ async function setup(args) {
402
836
  new Set([
403
837
  '--client',
404
838
  '--token-file',
839
+ '--paste-token',
840
+ '--login',
405
841
  '--accept-disclosure',
406
842
  '--endpoint',
407
843
  '--yes',
@@ -413,6 +849,10 @@ async function setup(args) {
413
849
  '--claude-shadow',
414
850
  '--claude-diagnostics',
415
851
  '--lang',
852
+ '--update-mode',
853
+ '--channel',
854
+ '--host-claude',
855
+ '--host-codex',
416
856
  ]),
417
857
  new Set([
418
858
  '--client',
@@ -425,14 +865,78 @@ async function setup(args) {
425
865
  '--claude-shadow',
426
866
  '--claude-diagnostics',
427
867
  '--lang',
868
+ '--update-mode',
869
+ '--channel',
870
+ '--host-claude',
871
+ '--host-codex',
428
872
  ]),
429
873
  );
874
+ if (args.includes('--login')) {
875
+ if (args.length !== 1) throw new Error('setup_login_cannot_have_options');
876
+ return replaceSetupToken(await readConfig());
877
+ }
878
+ if (args.includes('--paste-token') && args.includes('--token-file'))
879
+ throw new Error('setup_token_sources_conflict');
430
880
  if (args.includes('--undo') && args.length !== 1)
431
881
  throw new Error('setup_undo_cannot_have_options');
432
882
  const lang = option(args, '--lang');
433
883
  if (lang !== undefined && !isPackLocale(lang)) throw new Error('invalid_lang');
434
- if (lang !== undefined && args.length === 2) return setPackLocale(lang);
884
+ let release = requestedReleaseSettings(args);
435
885
  const previous = await readConfig();
886
+ // `--lang` alone only switches the language of an existing setup. Before the first
887
+ // setup it runs the full setup (token included) and stores the language at the end.
888
+ if (lang !== undefined && args.length === 2 && previous !== null) return setPackLocale(lang);
889
+ // `--update-mode`, `--channel` and host flags alone change the release settings
890
+ // of an existing setup, offline (FR7, FR5); an explicit update flag is the answer to
891
+ // the disclosure, the host flag alone leaves the consent as it is. The managed copy
892
+ // is installed by the next launch, not here.
893
+ const releaseFlags = ['--update-mode', '--channel', '--host-claude', '--host-codex'];
894
+ const releaseOnly =
895
+ (release.mode !== undefined ||
896
+ release.channel !== undefined ||
897
+ release.hostClaude !== undefined ||
898
+ release.hostCodex !== undefined) &&
899
+ args.every((argument, index) =>
900
+ [...releaseFlags, '--accept-disclosure'].includes(argument)
901
+ ? true
902
+ : index > 0 && releaseFlags.includes(args[index - 1] ?? ''),
903
+ );
904
+ if (releaseOnly && previous !== null) {
905
+ const root = await ensureStateRoot();
906
+ const settings = await readReleaseSettings(root);
907
+ const hosts = {
908
+ ...settings.hosts,
909
+ ...(release.hostClaude === undefined ? {} : { claude: release.hostClaude }),
910
+ ...(release.hostCodex === undefined ? {} : { codex: release.hostCodex }),
911
+ };
912
+ if (release.mode !== undefined || release.channel !== undefined) {
913
+ await recordReleaseConsent(root, settings, release.mode ?? settings.update.mode, {
914
+ ...(release.channel === undefined ? {} : { channel: release.channel }),
915
+ hosts,
916
+ });
917
+ console.log(
918
+ `Self-update ${release.mode ?? settings.update.mode} on channel ${release.channel ?? settings.update.channel}; recorded in ${root}/release.json. No network call was made.`,
919
+ );
920
+ } else {
921
+ await writeReleaseSettings(
922
+ { consent: settings.consent, update: settings.update, hosts },
923
+ root,
924
+ );
925
+ }
926
+ await recordHostSelection(root, settings, { ...settings, status: 'valid', hosts }, [
927
+ ...(release.hostClaude === undefined ? [] : ['claude']),
928
+ ...(release.hostCodex === undefined ? [] : ['codex']),
929
+ ]);
930
+ if (release.hostClaude !== undefined)
931
+ console.log(
932
+ `Claude Code host ${release.hostClaude}; recorded in ${root}/release.json. No network call was made.`,
933
+ );
934
+ if (release.hostCodex !== undefined)
935
+ console.log(
936
+ `Codex host ${release.hostCodex}; recorded in ${root}/release.json. No network call was made.`,
937
+ );
938
+ return;
939
+ }
436
940
  if (await updateLocalOptOut(previous, args)) return;
437
941
  const localOptOut =
438
942
  option(args, '--telemetry') === 'off' &&
@@ -440,17 +944,25 @@ async function setup(args) {
440
944
  if (localOptOut) return disableTelemetryLocally(previous);
441
945
  const platform = platformCheck();
442
946
  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');
947
+ const clients = setupClients(option(args, '--client'), release.hostCodex === 'managed');
445
948
  if (
446
949
  clients === 'codex' &&
447
950
  (option(args, '--claude-shadow') !== undefined ||
448
951
  option(args, '--claude-diagnostics') !== undefined)
449
952
  )
450
953
  throw new Error('claude_observation_requires_claude_client');
954
+ if (clients === 'codex' && release.hostClaude !== undefined)
955
+ throw new Error('host_claude_requires_claude_client');
956
+ if (clients === 'claude' && release.hostCodex !== undefined)
957
+ throw new Error('host_codex_requires_codex_client');
958
+ const locale = resolvePackLocale(lang ?? (await readStoredLocale(stateRoot())));
959
+ // The hosts are checked before the disclosure and the token (spec
960
+ // aisac-host-upgrade-resilience C7, C8): an incompatible host costs the user neither.
961
+ const preflight = await preflightSetupHosts(clients, release, locale);
962
+ release = preflight.release;
451
963
  const endpoint = option(args, '--endpoint') ?? ENDPOINT;
452
964
  validateEndpoint(endpoint);
453
- const selection = selectedPolicy(args, previous);
965
+ const selection = selectedPolicy(args, previous, clients);
454
966
  const telemetry = telemetrySelection(args, previous);
455
967
  const claudeObservation = claudeObservationSelection(args, previous);
456
968
  const policy = selection.policy;
@@ -473,25 +985,113 @@ async function setup(args) {
473
985
  throw new Error('disclosure_not_accepted');
474
986
  const root = await ensureStateRoot();
475
987
  const tokenPath = option(args, '--token-file');
476
- let token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
988
+ const pasteToken = args.includes('--paste-token');
989
+ if (!tokenPath && pasteToken && stdin.isTTY && stdout.isTTY)
990
+ console.log(`\n${tokenPromptGuide(locale, endpoint)}\n`);
991
+ let token;
992
+ /** @type {string | null} */
993
+ let accountHint = null;
994
+ try {
995
+ if (tokenPath) token = await readPrivateToken(tokenPath);
996
+ else if (pasteToken) token = await maskedPrompt();
997
+ else {
998
+ const login = await runDeviceLogin(endpoint, clients, locale);
999
+ token = login.token;
1000
+ accountHint = login.accountHint;
1001
+ }
1002
+ } catch (error) {
1003
+ if (errorMessage(error) === 'login_cancelled') {
1004
+ const cancelled = new Error('login_cancelled');
1005
+ Object.defineProperty(cancelled, 'exitCode', { value: 130 });
1006
+ throw cancelled;
1007
+ }
1008
+ const code = errorMessage(error);
1009
+ throw error instanceof Error && 'guide' in error
1010
+ ? error
1011
+ : setupTokenError(code, locale, endpoint);
1012
+ }
477
1013
  token = token.trim();
478
- if (!token) throw new Error('empty_token');
479
- const claude = resolveNative('claude');
480
- const codex = resolveNative('codex');
1014
+ if (!token) throw setupTokenError('empty_token', locale, endpoint);
1015
+ let codex = resolveNative('codex');
481
1016
  const node = resolveNative('node');
1017
+ let claude = resolveNative('claude');
1018
+ /** @type {Awaited<ReturnType<typeof resolveCodexCompatibility>> | null} */
1019
+ let codexCompatibility = preflight.codex;
1020
+ /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility | null} */
1021
+ let claudeCompatibility = preflight.claude;
1022
+ // A managed Claude host asked for at setup (ADR-0056 R4, FR5): the pinned copy is
1023
+ // installed and probed in place of the user's binary, which may then be absent;
1024
+ // when it cannot be, setup goes on with the user's binary and says why.
1025
+ if ((clients === 'claude' || clients === 'both') && release.hostClaude === 'managed') {
1026
+ const releaseSettings = await readReleaseSettings(root);
1027
+ const manifest = await resolveReleaseManifest({
1028
+ root,
1029
+ packageRoot: PACKAGE_ROOT,
1030
+ endpoint,
1031
+ token,
1032
+ host: 'claude',
1033
+ }).catch(() => null);
1034
+ const managed = await resolveHostExecutable({
1035
+ host: 'claude',
1036
+ root,
1037
+ packageRoot: PACKAGE_ROOT,
1038
+ manifest,
1039
+ settings: { ...releaseSettings, hosts: { ...releaseSettings.hosts, claude: 'managed' } },
1040
+ env: process.env,
1041
+ flag: 'managed',
1042
+ clientVersion: VERSION,
1043
+ locale,
1044
+ progress: (line) => console.error(line),
1045
+ });
1046
+ if (managed.mode === 'managed') {
1047
+ claude = managed.executable;
1048
+ claudeCompatibility =
1049
+ /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility | null} */ (
1050
+ managed.compatibility
1051
+ );
1052
+ } else console.error(hostFallbackLine('claude', managed, locale));
1053
+ }
1054
+ if ((clients === 'codex' || clients === 'both') && release.hostCodex === 'managed') {
1055
+ const releaseSettings = await readReleaseSettings(root);
1056
+ const manifest = await resolveReleaseManifest({
1057
+ root,
1058
+ packageRoot: PACKAGE_ROOT,
1059
+ endpoint,
1060
+ token,
1061
+ host: 'codex',
1062
+ }).catch(() => null);
1063
+ const managed = await resolveHostExecutable({
1064
+ host: 'codex',
1065
+ root,
1066
+ packageRoot: PACKAGE_ROOT,
1067
+ manifest,
1068
+ settings: { ...releaseSettings, hosts: { ...releaseSettings.hosts, codex: 'managed' } },
1069
+ env: process.env,
1070
+ flag: 'managed',
1071
+ clientVersion: VERSION,
1072
+ locale,
1073
+ progress: (line) => console.error(line),
1074
+ });
1075
+ codex = managed.executable;
1076
+ codexCompatibility = managed.compatibility;
1077
+ if (managed.mode !== 'managed') console.error(hostFallbackLine('codex', managed, locale));
1078
+ }
482
1079
  if ((clients === 'claude' || clients === 'both') && !claude) throw new Error('claude_not_found');
483
- if ((clients === 'codex' || clients === 'both') && (!codex || !node))
1080
+ if ((clients === 'codex' || clients === 'both') && !node)
484
1081
  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;
1082
+ if ((clients === 'codex' || clients === 'both') && !codex)
1083
+ throw new Error('codex_or_node_not_found');
1084
+ if (
1085
+ claudeCompatibility === null &&
1086
+ (clients === 'claude' || clients === 'both') &&
1087
+ claude !== null
1088
+ )
1089
+ claudeCompatibility = await resolveClaudeCompatibility(claude, PACKAGE_ROOT);
489
1090
  if (claudeCompatibility?.status === 'rejected')
490
1091
  throw new Error(claudeCompatibilityError(claudeCompatibility));
491
1092
  const claudeVersion = claudeCompatibility?.version ?? (claude ? nativeVersion(claude) : null);
492
- let codexCompatibility = null;
493
1093
  if (clients === 'codex' || clients === 'both') {
494
- codexCompatibility = codex ? await resolveCodexCompatibility(codex) : null;
1094
+ codexCompatibility ??= codex ? await resolveCodexCompatibility(codex) : null;
495
1095
  if (codexCompatibility?.status === 'rejected')
496
1096
  throw new Error(codexCompatibilityError(codexCompatibility));
497
1097
  }
@@ -521,7 +1121,7 @@ async function setup(args) {
521
1121
  ? await providerFreeProbe(endpoint, token, policy, clients)
522
1122
  : await providerFreeProbe(endpoint, token);
523
1123
  } catch (error) {
524
- throw new Error(`provider_free_probe_failed:${errorMessage(error)}`);
1124
+ throw setupTokenError(`provider_free_probe_failed:${errorMessage(error)}`, locale, endpoint);
525
1125
  }
526
1126
  try {
527
1127
  const configWithToken = { ...config, token, tokenSha256: await tokenDigest(token), probe };
@@ -530,15 +1130,104 @@ async function setup(args) {
530
1130
  } catch (error) {
531
1131
  throw new Error(`state_write_failed:${errorMessage(error)}`);
532
1132
  }
1133
+ if (accountHint !== null) console.log(deviceLoginConnectedLine(locale, accountHint));
533
1134
  console.log(
534
1135
  `Configured ${clients} in ${root}. Provider-free access verified; no provider batch was used.`,
535
1136
  );
1137
+ await recordSetupConsent(root, locale, release);
536
1138
  if (lang !== undefined) await setPackLocale(lang);
537
1139
  // Display only: the server decides again on every pack request (ADR-0047).
538
1140
  const line = licenseLine(await checkEngineeringLicense(endpoint, token));
539
1141
  if (line !== null) console.log(line);
540
1142
  }
541
1143
 
1144
+ /**
1145
+ * Whether Codex runs the AISAC hooks the user has on, from Codex's own
1146
+ * `hooks/list` in this folder (FR6, FR8, E6b). No session starts, and Codex
1147
+ * writes no config or trust record. Codex is not asked when the last launch had
1148
+ * no license, because the launcher then hands Codex no hook.
1149
+ * @param {{ executable: string | null, version: string | null | undefined, licensed: boolean }} codex
1150
+ */
1151
+ async function doctorCodexHooks({ executable, version, licensed }) {
1152
+ if (executable === null) return { status: 'codex_not_found' };
1153
+ if (!supportsCodexHooks(version)) return { status: 'codex_version_unsupported' };
1154
+ if (!licensed) return { status: 'not_licensed' };
1155
+ const read = await readCodexGuardrails({
1156
+ root: stateRoot(),
1157
+ packageRoot: PACKAGE_ROOT,
1158
+ executable,
1159
+ cwd: process.cwd(),
1160
+ profile: undefined,
1161
+ environment: process.env,
1162
+ }).catch(() => undefined);
1163
+ if (read === undefined) return { status: 'list_failed' };
1164
+ if (read === null) return { status: 'none_enabled' };
1165
+ const { summary } = read;
1166
+ if (summary === null) return { status: 'list_failed' };
1167
+ const status = codexHooksStatus(summary);
1168
+ return {
1169
+ status,
1170
+ handlers: summary.handlers,
1171
+ review: summary.review,
1172
+ off: summary.off,
1173
+ missing: summary.missing,
1174
+ ...(summary.review.length > 0
1175
+ ? { remedy: 'Run aisac codex, open /hooks and approve the AISAC hooks.' }
1176
+ : {}),
1177
+ };
1178
+ }
1179
+
1180
+ /**
1181
+ * Extension state plus whether `format-on-edit` has a formatter in this folder,
1182
+ * and whether Codex runs the hooks (FR8).
1183
+ * @param {{ executable: string | null, version: string | null | undefined }} codex
1184
+ */
1185
+ async function doctorExtensions(codex) {
1186
+ const summary = await extensionsSummary(stateRoot());
1187
+ // A token server is skipped at launch when its variable is unset (names only).
1188
+ const mcpMissingEnv = sessionServers(summary.mcp, 'claude', process.env).missingEnv.map(
1189
+ (skipped) => skipped.id,
1190
+ );
1191
+ const formatOnEdit = !summary.hooks.includes('format-on-edit')
1192
+ ? 'off'
1193
+ : (await anyFormatter(process.cwd()))
1194
+ ? 'ready'
1195
+ : 'no_formatter_found';
1196
+ const licensed = (await readLastLaunch(stateRoot()))?.state === 'loaded';
1197
+ const codexHooks = await doctorCodexHooks({ ...codex, licensed });
1198
+ return { ...summary, formatOnEdit, mcpMissingEnv, codexHooks };
1199
+ }
1200
+
1201
+ /**
1202
+ * The text doctor's `scan` line: `kind=mode`, a binary's version, then the reason, for
1203
+ * example `sca=binary 2.7.1, iac=skipped (tool_unavailable)`.
1204
+ * @param {Awaited<ReturnType<typeof scanToolAvailability>>} entries
1205
+ */
1206
+ function scanLine(entries) {
1207
+ return entries
1208
+ .map(({ kind, mode, version, reason }) => {
1209
+ const detail = mode === 'binary' && version !== null ? ` ${version}` : '';
1210
+ return `${kind}=${mode}${detail}${reason === null ? '' : ` (${reason})`}`;
1211
+ })
1212
+ .join(', ');
1213
+ }
1214
+
1215
+ /**
1216
+ * What `aisac scan` would run, per kind (scan spec FR9): in `--json` the entries of
1217
+ * `scan --check-tools --json`, in text one line. No pull, no scan, no pack, no license.
1218
+ * Optional capability: a failure (only a bad pins file) is its message and never changes
1219
+ * doctor's exit code.
1220
+ * @param {boolean} json
1221
+ */
1222
+ async function doctorScan(json) {
1223
+ try {
1224
+ const entries = await scanToolAvailability({ packageRoot: PACKAGE_ROOT, env: process.env });
1225
+ return json ? entries : scanLine(entries);
1226
+ } catch (error) {
1227
+ return errorMessage(error);
1228
+ }
1229
+ }
1230
+
542
1231
  /** @param {boolean} json */
543
1232
  async function doctor(json) {
544
1233
  const platform = platformCheck();
@@ -564,13 +1253,41 @@ async function doctor(json) {
564
1253
  codex: resolveNative('codex'),
565
1254
  node: resolveNative('node'),
566
1255
  };
1256
+ // Release manifest (ADR-0056 R2): fetched at most every six hours when a setup
1257
+ // exists, bundled copy otherwise; never the exit code.
1258
+ const releaseManifest = await resolveReleaseManifest({
1259
+ root: stateRoot(),
1260
+ packageRoot: PACKAGE_ROOT,
1261
+ endpoint: config?.endpoint ?? null,
1262
+ token: config?.token ?? null,
1263
+ }).catch(() => null);
1264
+ const releaseSettings = await readReleaseSettings(stateRoot());
1265
+ // Managed hosts (ADR-0056 R4/R5, FR8): the host a launch would run and the state of
1266
+ // the pinned copy; doctor installs nothing. A ready managed copy is the binary the
1267
+ // compatibility fields describe, since it is the one `aisac claude` or `aisac codex` runs.
1268
+ /** @param {'claude' | 'codex'} host */
1269
+ const describeHost = (host) =>
1270
+ describeManagedHost({
1271
+ host,
1272
+ root: stateRoot(),
1273
+ packageRoot: PACKAGE_ROOT,
1274
+ manifest: releaseManifest,
1275
+ settings: releaseSettings,
1276
+ env: process.env,
1277
+ clientVersion: VERSION,
1278
+ }).catch(() => null);
1279
+ const managedHosts = { claude: await describeHost('claude'), codex: await describeHost('codex') };
1280
+ const claudeExecutable = managedHosts.claude?.executable ?? native.claude;
1281
+ const codexExecutable = managedHosts.codex?.executable ?? native.codex;
567
1282
  const claudeCompatibility =
568
- native.claude !== null ? await resolveClaudeCompatibility(native.claude, PACKAGE_ROOT) : null;
1283
+ claudeExecutable !== null
1284
+ ? await resolveClaudeCompatibility(claudeExecutable, PACKAGE_ROOT)
1285
+ : null;
569
1286
  const codexCompatibility =
570
- native.codex !== null ? await resolveCodexCompatibility(native.codex) : null;
1287
+ codexExecutable !== null ? await resolveCodexCompatibility(codexExecutable) : null;
571
1288
  const rawNativeVersions = {
572
1289
  claude: claudeCompatibility?.version ?? '',
573
- codex: native.codex ? nativeVersion(native.codex) : '',
1290
+ codex: codexCompatibility?.version ?? (codexExecutable ? nativeVersion(codexExecutable) : ''),
574
1291
  };
575
1292
  const nativeVersions = {
576
1293
  ...rawNativeVersions,
@@ -585,11 +1302,11 @@ async function doctor(json) {
585
1302
  const captureLockPlatform = needsCodex ? captureLockPlatformCheck() : null;
586
1303
  const nativeReady =
587
1304
  (!needsClaude ||
588
- (native.claude !== null &&
1305
+ (claudeExecutable !== null &&
589
1306
  (claudeCompatibility?.status === 'qualified' ||
590
1307
  claudeCompatibility?.status === 'host_checked'))) &&
591
1308
  (!needsCodex ||
592
- (native.codex !== null &&
1309
+ (codexExecutable !== null &&
593
1310
  native.node !== null &&
594
1311
  captureLockPlatform?.ok === true &&
595
1312
  (codexCompatibility?.status === 'qualified' ||
@@ -633,6 +1350,41 @@ async function doctor(json) {
633
1350
  },
634
1351
  engineering,
635
1352
  engineeringPack: await engineeringPackState(),
1353
+ manifest: releaseManifest === null ? null : manifestDoctorSection(releaseManifest),
1354
+ // Self-update (ADR-0056 R3, FR8): the decision this launch would take, no action.
1355
+ update: await updateDoctorSection({
1356
+ root: stateRoot(),
1357
+ packageRoot: PACKAGE_ROOT,
1358
+ version: VERSION,
1359
+ env: process.env,
1360
+ manifest: releaseManifest,
1361
+ }).catch(() => null),
1362
+ // Managed hosts (ADR-0056 R4/R5, FR8): the decision and the pinned copy, no path.
1363
+ hosts: {
1364
+ managed: {
1365
+ claude: hostDoctorSection(managedHosts.claude),
1366
+ codex: hostDoctorSection(managedHosts.codex),
1367
+ },
1368
+ },
1369
+ extensions: await doctorExtensions({
1370
+ executable: codexExecutable,
1371
+ version: codexCompatibility?.version,
1372
+ }),
1373
+ scan: await doctorScan(json),
1374
+ // Manager and workers (ADR-0058, FR11): role support and the live rooms, no path.
1375
+ manager: await managerDoctorSection({
1376
+ root: stateRoot(),
1377
+ claude: claudeExecutable !== null,
1378
+ claudeVersion: claudeCompatibility?.version ?? null,
1379
+ claudeAccepted:
1380
+ claudeCompatibility?.status === 'qualified' ||
1381
+ claudeCompatibility?.status === 'host_checked',
1382
+ codexVersion: codexExecutable === null ? null : (codexCompatibility?.version ?? null),
1383
+ // The worker role needs a Codex this client runs (D14); a refused one never has it.
1384
+ codexAccepted:
1385
+ codexCompatibility?.status === 'qualified' ||
1386
+ codexCompatibility?.status === 'protocol_match',
1387
+ }).catch(() => null),
636
1388
  paidOrPilot: probe?.ok
637
1389
  ? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
638
1390
  : config
@@ -640,13 +1392,101 @@ async function doctor(json) {
640
1392
  : 'not_configured',
641
1393
  };
642
1394
  if (json) console.log(JSON.stringify(result));
643
- else console.log(result);
1395
+ else {
1396
+ console.log(result);
1397
+ for (const line of releaseDoctorLines(result)) console.log(line);
1398
+ console.log(managerDoctorLine(result.manager));
1399
+ }
644
1400
  if (!platform.ok || !config || !probe?.ok || !nativeReady) process.exitCode = 1;
645
1401
  }
646
1402
 
1403
+ /**
1404
+ * The `hosts.managed.<host>` section (FR8): everything `describeManagedHost`
1405
+ * found but the binary's path.
1406
+ * @param {Awaited<ReturnType<typeof describeManagedHost>> | null} described
1407
+ */
1408
+ function hostDoctorSection(described) {
1409
+ if (described === null) return null;
1410
+ return {
1411
+ mode: described.mode,
1412
+ reason: described.reason,
1413
+ selection_source: described.selection_source,
1414
+ pinned: described.pinned,
1415
+ platform: described.platform,
1416
+ installed: described.installed,
1417
+ on_disk: described.on_disk,
1418
+ pin_check: described.pin_check,
1419
+ resolver: described.resolver,
1420
+ resolver_reason: described.resolver_reason,
1421
+ install_failure: described.install_failure,
1422
+ };
1423
+ }
1424
+
1425
+ /**
1426
+ * One line per release section after the text doctor output (FR8, R4).
1427
+ * @param {{ manifest: ReturnType<typeof manifestDoctorSection> | null,
1428
+ * update: Awaited<ReturnType<typeof updateDoctorSection>> | null,
1429
+ * hosts: { managed: Record<'claude' | 'codex', ReturnType<typeof hostDoctorSection>> } }} result
1430
+ */
1431
+ function releaseDoctorLines(result) {
1432
+ const manifest =
1433
+ result.manifest === null
1434
+ ? 'unavailable'
1435
+ : `sequence ${result.manifest.sequence} (${result.manifest.source}), ${result.manifest.state}`;
1436
+ const update =
1437
+ result.update === null
1438
+ ? 'unavailable'
1439
+ : `${result.update.mode} on ${result.update.channel}; ${
1440
+ result.update.action === 'none' ? 'up to date' : result.update.action
1441
+ }${result.update.reason === null ? '' : ` (${result.update.reason})`}`;
1442
+ /** @param {'claude' | 'codex'} name @param {ReturnType<typeof hostDoctorSection>} section */
1443
+ const host = (name, section) =>
1444
+ section === null
1445
+ ? `${name} unknown`
1446
+ : `${name} ${section.mode}${section.pinned === null ? '' : `, pinned ${section.pinned}`}${
1447
+ section.mode === 'managed' ? (section.installed ? ', installed' : ', not installed') : ''
1448
+ }${section.selection_source === 'unknown' ? ', selection source unknown' : ''}${
1449
+ section.reason === null ? '' : ` (${section.reason})`
1450
+ }`;
1451
+ return [
1452
+ `manifest: ${manifest}`,
1453
+ `update: ${update}`,
1454
+ `hosts: ${host('claude', result.hosts.managed.claude)}; ${host('codex', result.hosts.managed.codex)}`,
1455
+ ];
1456
+ }
1457
+
1458
+ /**
1459
+ * `aisac scan`. An error the engine did not classify still means it could not scan as
1460
+ * asked: exit 3, never 1, which a CI step reads as findings (scan review F3). Usage
1461
+ * errors keep their 2.
1462
+ * @param {string[]} args
1463
+ */
1464
+ async function scan(args) {
1465
+ try {
1466
+ return await scanCommand(args, {
1467
+ packageRoot: PACKAGE_ROOT,
1468
+ readConfig,
1469
+ stateRoot,
1470
+ cwd: process.cwd(),
1471
+ env: process.env,
1472
+ });
1473
+ } catch (error) {
1474
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1475
+ if (typeof exitCode === 'number') throw error;
1476
+ const classified = error instanceof Error ? error : new Error(errorMessage(error));
1477
+ throw Object.assign(classified, { exitCode: SCAN_CANNOT_RUN_EXIT_CODE });
1478
+ }
1479
+ }
1480
+
647
1481
  /** @param {boolean} json */
648
1482
  async function status(json) {
649
1483
  const config = await readConfig();
1484
+ // Offline: the cached or bundled manifest, never a fetch (FR8).
1485
+ const releaseManifest = await resolveReleaseManifest({
1486
+ root: stateRoot(),
1487
+ packageRoot: PACKAGE_ROOT,
1488
+ }).catch(() => null);
1489
+ const releaseSettings = await readReleaseSettings(stateRoot());
650
1490
  const policy =
651
1491
  config?.schemaVersion === 2 && config.context !== undefined
652
1492
  ? config.context
@@ -669,6 +1509,22 @@ async function status(json) {
669
1509
  config?.claudeObservation?.disclosedAt !== undefined,
670
1510
  },
671
1511
  engineeringPack: await engineeringPackState(),
1512
+ manifest:
1513
+ releaseManifest === null
1514
+ ? null
1515
+ : {
1516
+ sequence: releaseManifest.sequence,
1517
+ source: releaseManifest.source,
1518
+ state: releaseManifest.state,
1519
+ },
1520
+ update: {
1521
+ mode: releaseSettings.update.mode,
1522
+ channel: releaseSettings.update.channel,
1523
+ consent: releaseSettings.consent !== null,
1524
+ },
1525
+ // Host modes as stored (FR8); whether the managed copy is installed is doctor's.
1526
+ hosts: { claude: releaseSettings.hosts.claude, codex: releaseSettings.hosts.codex },
1527
+ extensions: await extensionsSummary(stateRoot()),
672
1528
  monitoredSession: null,
673
1529
  monitoringStatus: 'not_observed',
674
1530
  };
@@ -717,13 +1573,115 @@ async function main(argv) {
717
1573
  else console.log(records);
718
1574
  return;
719
1575
  }
1576
+ if (command === 'hooks') return hooksCommand(rest);
1577
+ if (command === 'mcp') {
1578
+ if (rest[0] !== 'login') return mcpCommand(rest);
1579
+ return mcpCommand(rest, {
1580
+ resolveCodex: async () => {
1581
+ const root = stateRoot();
1582
+ const config = await readConfig();
1583
+ const locale = resolvePackLocale(await readStoredLocale(root), process.env);
1584
+ const manifest = await resolveReleaseManifest({
1585
+ root,
1586
+ packageRoot: PACKAGE_ROOT,
1587
+ endpoint: config?.endpoint ?? null,
1588
+ token: config?.token ?? null,
1589
+ host: 'codex',
1590
+ }).catch(() => null);
1591
+ const host = await resolveHostExecutable({
1592
+ host: 'codex',
1593
+ root,
1594
+ packageRoot: PACKAGE_ROOT,
1595
+ manifest,
1596
+ settings: await readReleaseSettings(root),
1597
+ env: process.env,
1598
+ flag: null,
1599
+ clientVersion: await installedClientVersion(PACKAGE_ROOT),
1600
+ locale,
1601
+ progress: (line) => process.stderr.write(`${line}\n`),
1602
+ });
1603
+ if (host.fallback !== null && host.compatibility?.status !== 'rejected')
1604
+ process.stderr.write(`${hostFallbackLine('codex', host, locale)}\n`);
1605
+ if (host.executable === null) {
1606
+ const error = new Error('codex_or_node_not_found');
1607
+ Object.assign(error, {
1608
+ guide: hostRecoveryLine(
1609
+ 'codex',
1610
+ host.pinned,
1611
+ host.reason ?? 'codex_not_found',
1612
+ locale,
1613
+ host.reason === 'host_mode_env',
1614
+ ),
1615
+ });
1616
+ throw error;
1617
+ }
1618
+ const compatibility =
1619
+ host.compatibility ?? (await resolveCodexCompatibility(host.executable));
1620
+ if (compatibility.status === 'rejected') {
1621
+ const message =
1622
+ host.fallback === null
1623
+ ? codexCompatibilityError(compatibility)
1624
+ : `${codexCompatibilityError(compatibility)}; managed recovery failed (${host.fallback})`;
1625
+ const error = new Error(message);
1626
+ Object.assign(error, {
1627
+ guide: hostRecoveryLine(
1628
+ 'codex',
1629
+ compatibility.version,
1630
+ compatibility.reason,
1631
+ locale,
1632
+ host.reason === 'host_mode_env',
1633
+ ),
1634
+ });
1635
+ throw error;
1636
+ }
1637
+ return {
1638
+ executable: host.executable,
1639
+ managed: host.mode === 'managed',
1640
+ directory: host.directory,
1641
+ };
1642
+ },
1643
+ });
1644
+ }
1645
+ if (command === 'init')
1646
+ return initCommand(rest, {
1647
+ packageRoot: PACKAGE_ROOT,
1648
+ readConfig,
1649
+ stateRoot,
1650
+ cwd: process.cwd(),
1651
+ env: process.env,
1652
+ });
1653
+ if (command === 'scan') {
1654
+ process.exitCode = await scan(rest);
1655
+ return;
1656
+ }
1657
+ if (command === 'workers') {
1658
+ process.exitCode = await workers(rest);
1659
+ return;
1660
+ }
1661
+ if (command === 'update') {
1662
+ process.exitCode = await updateCommand(rest, {
1663
+ root: stateRoot(),
1664
+ packageRoot: PACKAGE_ROOT,
1665
+ version: VERSION,
1666
+ env: process.env,
1667
+ readConfig: async () => {
1668
+ const config = await readConfig();
1669
+ return config === null ? null : { endpoint: config.endpoint, token: config.token };
1670
+ },
1671
+ interactive: stdin.isTTY === true && stdout.isTTY === true,
1672
+ });
1673
+ return;
1674
+ }
720
1675
  if (command === 'disable') {
721
1676
  if (rest.length > 0) throw new Error('disable_does_not_accept_options');
722
1677
  return removeOwnedSetup();
723
1678
  }
724
1679
  if (command === 'claude' || command === 'codex') {
725
1680
  const config = await readConfig();
726
- if (!config || config.disclosedAt === undefined) throw new Error('setup_required');
1681
+ if (!config || config.disclosedAt === undefined) {
1682
+ const locale = resolvePackLocale(await readStoredLocale(stateRoot()), process.env);
1683
+ throw setupTokenError('setup_required', locale, ENDPOINT);
1684
+ }
727
1685
  if (config.schemaVersion === 2 && config.disclosureVersion !== DISCLOSURE_VERSION)
728
1686
  throw new Error('disclosure_outdated');
729
1687
  if (config.clientSelection !== command && config.clientSelection !== 'both')
@@ -732,20 +1690,89 @@ async function main(argv) {
732
1690
  // metadata only, so patch updates do not block a fresh compatibility check.
733
1691
  if (command === 'codex' && typeof config.codexVersion !== 'string')
734
1692
  throw new Error('codex_version_unverified');
1693
+ // `--host managed|system` belongs to the launcher, not the host (ADR-0056 R5).
735
1694
  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;
1695
+ const locale = launchFeedbackLocale(await readStoredLocale(root));
1696
+ let launch;
1697
+ try {
1698
+ launch = takeHostFlag(rest);
1699
+ } catch (error) {
1700
+ const guide = describePermissionError(error, rest, locale);
1701
+ if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1702
+ throw error;
1703
+ }
1704
+ // `--manager`, `--worker <name>` and `--room <name>` belong to the launcher as
1705
+ // well (spec aisac-engineering-manager D2): a manager is a Claude Code session,
1706
+ // a worker a Codex session.
1707
+ let role;
1708
+ try {
1709
+ role = takeRoleFlags(launch.args, command);
1710
+ } catch (error) {
1711
+ const code = error instanceof Error ? error.message : String(error);
1712
+ const guide =
1713
+ describeRoleError(code, launch.args, command, locale) ??
1714
+ describePermissionError(error, launch.args, locale);
1715
+ if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1716
+ throw error;
1717
+ }
1718
+ const nativeArgs = role.args[0] === '--' ? role.args.slice(1) : role.args;
1719
+ if (command === 'codex') {
1720
+ try {
1721
+ // Permission arguments are validated before self-update or any host
1722
+ // probe so a bad root cannot start or change anything.
1723
+ await parseCodexLaunchArgs(nativeArgs, process.cwd(), locale);
1724
+ } catch (error) {
1725
+ const guide = describePermissionError(error, nativeArgs, locale);
1726
+ if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1727
+ throw error;
1728
+ }
1729
+ }
1730
+ try {
1731
+ // Self-update (ADR-0056 R3, FR6) before any host work: the one-time consent
1732
+ // question on a terminal, then install + re-exec in `auto` mode, one line in
1733
+ // `notify`, and a refusal to launch a host below the manifest's minimum.
1734
+ const update = await selfUpdateAtLaunch({
1735
+ root,
1736
+ packageRoot: PACKAGE_ROOT,
1737
+ version: VERSION,
1738
+ config: { endpoint: config.endpoint, token: config.token },
1739
+ host: command,
1740
+ argv,
1741
+ env: process.env,
1742
+ interactive: stdin.isTTY === true && stdout.isTTY === true,
1743
+ });
1744
+ if (update.kind === 'reexec') {
1745
+ process.exitCode = update.exitCode;
1746
+ return;
1747
+ }
1748
+ if (update.kind === 'blocked')
1749
+ throw Object.assign(new Error(update.reason), { guide: update.line });
1750
+ if (update.kind === 'continue')
1751
+ for (const line of update.lines) process.stderr.write(`${line}\n`);
1752
+ const result = await (command === 'claude'
1753
+ ? launchClaude(
1754
+ { ...config, packageRoot: PACKAGE_ROOT },
1755
+ root,
1756
+ nativeArgs,
1757
+ {},
1758
+ {
1759
+ hostMode: launch.hostMode,
1760
+ role: role.request,
1761
+ },
1762
+ )
1763
+ : launchCodex(
1764
+ { ...config, packageRoot: PACKAGE_ROOT },
1765
+ root,
1766
+ nativeArgs,
1767
+ {},
1768
+ { hostMode: launch.hostMode, role: role.request },
1769
+ ));
1770
+ process.exitCode = result;
1771
+ return;
1772
+ } finally {
1773
+ // The update lock, when this launch still holds it (no host started).
1774
+ await releaseUpdateLock(root).catch(() => undefined);
1775
+ }
749
1776
  }
750
1777
  throw new Error('unknown_command');
751
1778
  }
@@ -765,7 +1792,20 @@ main(cliArgs).catch((error) => {
765
1792
  }),
766
1793
  );
767
1794
  } else {
768
- console.error(`${COMMAND}: ${errorMessage(error)}`);
1795
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1796
+ if (exitCode !== 130) console.error(`${COMMAND}: ${errorMessage(error)}`);
1797
+ const guide = /** @type {{ guide?: unknown }} */ (error ?? {}).guide;
1798
+ if (exitCode !== 130 && typeof guide === 'string') console.error(`\n${guide}`);
769
1799
  }
770
- process.exitCode = 1;
1800
+ // Usage errors exit 2 (init spec FR3, scan spec FR1). `aisac scan` exits 3
1801
+ // when it cannot scan as asked (scan spec D6: no scanner, a tool failure, no
1802
+ // license or pack), so a CI step never reads that as findings; everything
1803
+ // else exits 1.
1804
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1805
+ process.exitCode =
1806
+ typeof exitCode === 'number' &&
1807
+ Number.isInteger(exitCode) &&
1808
+ ((exitCode >= 1 && exitCode <= 3) || exitCode === 130)
1809
+ ? exitCode
1810
+ : 1;
771
1811
  });