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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +115 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +243 -5
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +6 -0
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +584 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +259 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +373 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +449 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +278 -34
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/mcp-servers.mjs +192 -0
  35. package/dist/mcp.mjs +10 -2
  36. package/dist/monitor.mjs +76 -1
  37. package/dist/package.json +1 -1
  38. package/dist/platform.mjs +78 -29
  39. package/dist/release-manifest-public-keys.json +10 -0
  40. package/dist/release-manifest.json +328 -0
  41. package/dist/release-manifest.mjs +817 -0
  42. package/dist/release-settings.mjs +210 -0
  43. package/dist/self-update.mjs +1036 -0
  44. package/dist/state.mjs +25 -1
  45. package/dist/token-guide.mjs +132 -0
  46. package/dist/update-actions.mjs +442 -0
  47. package/package.json +1 -1
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,52 @@ 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';
39
70
 
40
- const VERSION = '0.4.0-beta.2';
71
+ const VERSION = '0.4.0-beta.21';
41
72
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
42
73
  const COMMAND = 'aisac';
74
+ /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
75
+ const SCAN_CANNOT_RUN_EXIT_CODE = 3;
43
76
  const ENDPOINT = 'https://mcp.ai-brain.aisac.cloud/mcp';
44
77
  const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
45
78
  const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
46
79
 
47
80
  function usage() {
48
81
  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.`,
82
+ `${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] [-- native-args...]\n ${COMMAND} codex [-- native-args...]\n ${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.`,
83
+ );
84
+ console.log(
85
+ 'Clients: setup without --client configures the clients installed on PATH (Claude Code, Codex, or both).',
50
86
  );
51
87
  console.log(
52
88
  'Telemetry: setup --telemetry on|off (omitted preserves the stored choice; fresh defaults off).',
@@ -55,7 +91,25 @@ function usage() {
55
91
  'Claude shadow: setup --claude-shadow on|off and --claude-diagnostics on|off (preview stays applied=false).',
56
92
  );
57
93
  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`.',
94
+ '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`.',
95
+ );
96
+ console.log(
97
+ '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.',
98
+ );
99
+ console.log(
100
+ '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.',
101
+ );
102
+ console.log(
103
+ '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.',
104
+ );
105
+ console.log(
106
+ '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.',
107
+ );
108
+ console.log(
109
+ '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.',
110
+ );
111
+ console.log(
112
+ '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.',
59
113
  );
60
114
  }
61
115
 
@@ -106,6 +160,18 @@ async function maskedPrompt() {
106
160
  }
107
161
  }
108
162
 
163
+ /**
164
+ * A setup error that carries the PAT step-by-step guide when the failure means
165
+ * the subscriber needs a (different) token.
166
+ * @param {string} code @param {'pt-BR' | 'en'} locale @param {string} endpoint
167
+ */
168
+ function setupTokenError(code, locale, endpoint) {
169
+ const error = new Error(code);
170
+ const guide = tokenFailureGuide(code, locale, endpoint) ?? setupFailureHint(code, locale);
171
+ if (guide !== null) Object.defineProperty(error, 'guide', { value: guide });
172
+ return error;
173
+ }
174
+
109
175
  /** @param {string[]} args @param {string} name */
110
176
  function option(args, name) {
111
177
  const index = args.indexOf(name);
@@ -165,8 +231,11 @@ function policyOverrides(args) {
165
231
  return values;
166
232
  }
167
233
 
168
- /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
169
- function selectedPolicy(args, previous) {
234
+ /**
235
+ * @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous
236
+ * @param {'claude' | 'codex' | 'both'} clients
237
+ */
238
+ function selectedPolicy(args, previous, clients) {
170
239
  const explicitProfile = option(args, '--context-profile');
171
240
  const explicitV2 =
172
241
  explicitProfile !== undefined ||
@@ -205,7 +274,6 @@ function selectedPolicy(args, previous) {
205
274
  if (option(args, '--goal') === undefined && inherited.goal !== undefined)
206
275
  overrides.goal = inherited.goal;
207
276
  }
208
- const clients = option(args, '--client') ?? 'both';
209
277
  if (
210
278
  clients === 'codex' &&
211
279
  args.some(
@@ -394,6 +462,89 @@ async function disclosureAccepted(
394
462
  }
395
463
  }
396
464
 
465
+ /**
466
+ * Client selection when `--client` is omitted: the native clients found on PATH. Codex
467
+ * also needs `node`, the same pair the explicit `--client codex` path checks.
468
+ * @returns {'claude' | 'codex' | 'both' | null}
469
+ */
470
+ function detectedClients() {
471
+ const hasClaude = resolveNative('claude') !== null;
472
+ const hasCodex = resolveNative('codex') !== null && resolveNative('node') !== null;
473
+ if (hasClaude && hasCodex) return 'both';
474
+ if (hasClaude) return 'claude';
475
+ return hasCodex ? 'codex' : null;
476
+ }
477
+
478
+ /** @param {string | undefined} requested @returns {'claude' | 'codex' | 'both'} */
479
+ function setupClients(requested) {
480
+ if (requested !== undefined) {
481
+ if (requested !== 'claude' && requested !== 'codex' && requested !== 'both')
482
+ throw new Error('invalid_client');
483
+ return requested;
484
+ }
485
+ const detected = detectedClients();
486
+ if (detected === null) throw new Error('no_native_client_found');
487
+ console.log(`Clients detected on PATH: ${detected} (pass --client to choose).`);
488
+ return detected;
489
+ }
490
+
491
+ /**
492
+ * The release disclosure and its answer (spec aisac-release-manifest FR7, D8),
493
+ * recorded in `<state>/release.json`, never in `config.json`: `--update-mode`
494
+ * answers without a question, a terminal gets the one yes/no question, and
495
+ * without either nothing is recorded: the next interactive launch asks and the
496
+ * client keeps notifying meanwhile (FR7). A `--channel` alone is still recorded.
497
+ * @param {string} root @param {'pt-BR' | 'en'} locale
498
+ * @param {{ mode: import('./release-settings.mjs').UpdateMode | undefined,
499
+ * channel: import('./release-settings.mjs').Channel | undefined,
500
+ * hostClaude: import('./release-settings.mjs').HostMode | undefined }} requested
501
+ */
502
+ async function recordSetupConsent(root, locale, requested) {
503
+ const settings = await readReleaseSettings(root);
504
+ let mode = requested.mode;
505
+ if (mode === undefined && stdin.isTTY && stdout.isTTY) {
506
+ mode = (await askReleaseConsent(locale)) ?? undefined;
507
+ } else {
508
+ console.log(`\n${releaseDisclosure(locale)}`);
509
+ }
510
+ const channel = requested.channel ?? settings.update.channel;
511
+ const hosts =
512
+ requested.hostClaude === undefined
513
+ ? settings.hosts
514
+ : { ...settings.hosts, claude: requested.hostClaude };
515
+ if (mode !== undefined) {
516
+ await recordReleaseConsent(root, settings, mode, {
517
+ ...(requested.channel === undefined ? {} : { channel: requested.channel }),
518
+ hosts,
519
+ });
520
+ console.log(`Self-update ${mode} on channel ${channel}; recorded in ${root}/release.json.`);
521
+ } else {
522
+ if (requested.channel !== undefined || requested.hostClaude !== undefined)
523
+ await writeReleaseSettings(
524
+ { consent: settings.consent, update: { ...settings.update, channel }, hosts },
525
+ root,
526
+ );
527
+ console.log(
528
+ settings.consent === null
529
+ ? `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).`
530
+ : `Self-update ${settings.update.mode} on channel ${channel}; recorded earlier in ${root}/release.json.`,
531
+ );
532
+ }
533
+ if (requested.hostClaude !== undefined)
534
+ console.log(`Claude Code host ${requested.hostClaude}; recorded in ${root}/release.json.`);
535
+ }
536
+
537
+ /** @param {string[]} args */
538
+ function requestedReleaseSettings(args) {
539
+ const mode = option(args, '--update-mode');
540
+ if (mode !== undefined && !isUpdateMode(mode)) throw new Error('invalid_update_mode');
541
+ const channel = option(args, '--channel');
542
+ if (channel !== undefined && !isChannel(channel)) throw new Error('invalid_channel');
543
+ const hostClaude = option(args, '--host-claude');
544
+ if (hostClaude !== undefined && !isHostMode(hostClaude)) throw new Error('invalid_host_mode');
545
+ return { mode, channel, hostClaude };
546
+ }
547
+
397
548
  /** @param {string[]} args */
398
549
  async function setup(args) {
399
550
  if (args.includes('--yes')) throw new Error('explicit_disclosure_flag_required');
@@ -413,6 +564,9 @@ async function setup(args) {
413
564
  '--claude-shadow',
414
565
  '--claude-diagnostics',
415
566
  '--lang',
567
+ '--update-mode',
568
+ '--channel',
569
+ '--host-claude',
416
570
  ]),
417
571
  new Set([
418
572
  '--client',
@@ -425,14 +579,61 @@ async function setup(args) {
425
579
  '--claude-shadow',
426
580
  '--claude-diagnostics',
427
581
  '--lang',
582
+ '--update-mode',
583
+ '--channel',
584
+ '--host-claude',
428
585
  ]),
429
586
  );
430
587
  if (args.includes('--undo') && args.length !== 1)
431
588
  throw new Error('setup_undo_cannot_have_options');
432
589
  const lang = option(args, '--lang');
433
590
  if (lang !== undefined && !isPackLocale(lang)) throw new Error('invalid_lang');
434
- if (lang !== undefined && args.length === 2) return setPackLocale(lang);
591
+ const release = requestedReleaseSettings(args);
435
592
  const previous = await readConfig();
593
+ // `--lang` alone only switches the language of an existing setup. Before the first
594
+ // setup it runs the full setup (token included) and stores the language at the end.
595
+ if (lang !== undefined && args.length === 2 && previous !== null) return setPackLocale(lang);
596
+ // `--update-mode`, `--channel` and `--host-claude` alone change the release settings
597
+ // of an existing setup, offline (FR7, FR5); an explicit update flag is the answer to
598
+ // the disclosure, the host flag alone leaves the consent as it is. The managed copy
599
+ // is installed by the next launch, not here.
600
+ const releaseFlags = ['--update-mode', '--channel', '--host-claude'];
601
+ const releaseOnly =
602
+ (release.mode !== undefined ||
603
+ release.channel !== undefined ||
604
+ release.hostClaude !== undefined) &&
605
+ args.every((argument, index) =>
606
+ [...releaseFlags, '--accept-disclosure'].includes(argument)
607
+ ? true
608
+ : index > 0 && releaseFlags.includes(args[index - 1] ?? ''),
609
+ );
610
+ if (releaseOnly && previous !== null) {
611
+ const root = await ensureStateRoot();
612
+ const settings = await readReleaseSettings(root);
613
+ const hosts =
614
+ release.hostClaude === undefined
615
+ ? settings.hosts
616
+ : { ...settings.hosts, claude: release.hostClaude };
617
+ if (release.mode !== undefined || release.channel !== undefined) {
618
+ await recordReleaseConsent(root, settings, release.mode ?? settings.update.mode, {
619
+ ...(release.channel === undefined ? {} : { channel: release.channel }),
620
+ hosts,
621
+ });
622
+ console.log(
623
+ `Self-update ${release.mode ?? settings.update.mode} on channel ${release.channel ?? settings.update.channel}; recorded in ${root}/release.json. No network call was made.`,
624
+ );
625
+ } else {
626
+ await writeReleaseSettings(
627
+ { consent: settings.consent, update: settings.update, hosts },
628
+ root,
629
+ );
630
+ }
631
+ if (release.hostClaude !== undefined)
632
+ console.log(
633
+ `Claude Code host ${release.hostClaude}; recorded in ${root}/release.json. No network call was made.`,
634
+ );
635
+ return;
636
+ }
436
637
  if (await updateLocalOptOut(previous, args)) return;
437
638
  const localOptOut =
438
639
  option(args, '--telemetry') === 'off' &&
@@ -440,17 +641,18 @@ async function setup(args) {
440
641
  if (localOptOut) return disableTelemetryLocally(previous);
441
642
  const platform = platformCheck();
442
643
  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');
644
+ const clients = setupClients(option(args, '--client'));
445
645
  if (
446
646
  clients === 'codex' &&
447
647
  (option(args, '--claude-shadow') !== undefined ||
448
648
  option(args, '--claude-diagnostics') !== undefined)
449
649
  )
450
650
  throw new Error('claude_observation_requires_claude_client');
651
+ if (clients === 'codex' && release.hostClaude !== undefined)
652
+ throw new Error('host_claude_requires_claude_client');
451
653
  const endpoint = option(args, '--endpoint') ?? ENDPOINT;
452
654
  validateEndpoint(endpoint);
453
- const selection = selectedPolicy(args, previous);
655
+ const selection = selectedPolicy(args, previous, clients);
454
656
  const telemetry = telemetrySelection(args, previous);
455
657
  const claudeObservation = claudeObservationSelection(args, previous);
456
658
  const policy = selection.policy;
@@ -472,20 +674,61 @@ async function setup(args) {
472
674
  )
473
675
  throw new Error('disclosure_not_accepted');
474
676
  const root = await ensureStateRoot();
677
+ const locale = resolvePackLocale(lang ?? (await readStoredLocale(root)));
475
678
  const tokenPath = option(args, '--token-file');
476
- let token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
679
+ if (!tokenPath && stdin.isTTY && stdout.isTTY)
680
+ console.log(`\n${tokenPromptGuide(locale, endpoint)}\n`);
681
+ let token;
682
+ try {
683
+ token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
684
+ } catch (error) {
685
+ throw setupTokenError(errorMessage(error), locale, endpoint);
686
+ }
477
687
  token = token.trim();
478
- if (!token) throw new Error('empty_token');
479
- const claude = resolveNative('claude');
688
+ if (!token) throw setupTokenError('empty_token', locale, endpoint);
480
689
  const codex = resolveNative('codex');
481
690
  const node = resolveNative('node');
691
+ let claude = resolveNative('claude');
692
+ /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility | null} */
693
+ let claudeCompatibility = null;
694
+ // A managed Claude host asked for at setup (ADR-0056 R4, FR5): the pinned copy is
695
+ // installed and probed in place of the user's binary, which may then be absent;
696
+ // when it cannot be, setup goes on with the user's binary and says why.
697
+ if ((clients === 'claude' || clients === 'both') && release.hostClaude === 'managed') {
698
+ const releaseSettings = await readReleaseSettings(root);
699
+ const manifest = await resolveReleaseManifest({
700
+ root,
701
+ packageRoot: PACKAGE_ROOT,
702
+ endpoint,
703
+ token,
704
+ host: 'claude',
705
+ }).catch(() => null);
706
+ const managed = await resolveHostExecutable({
707
+ host: 'claude',
708
+ root,
709
+ packageRoot: PACKAGE_ROOT,
710
+ manifest,
711
+ settings: { ...releaseSettings, hosts: { ...releaseSettings.hosts, claude: 'managed' } },
712
+ env: process.env,
713
+ flag: 'managed',
714
+ clientVersion: VERSION,
715
+ locale,
716
+ progress: (line) => console.error(line),
717
+ });
718
+ if (managed.mode === 'managed') {
719
+ claude = managed.executable;
720
+ claudeCompatibility = managed.compatibility;
721
+ } else console.error(hostFallbackLine('claude', managed, locale));
722
+ }
482
723
  if ((clients === 'claude' || clients === 'both') && !claude) throw new Error('claude_not_found');
483
724
  if ((clients === 'codex' || clients === 'both') && (!codex || !node))
484
725
  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;
726
+ if (
727
+ claudeCompatibility === null &&
728
+ (clients === 'claude' || clients === 'both') &&
729
+ claude !== null
730
+ )
731
+ claudeCompatibility = await resolveClaudeCompatibility(claude, PACKAGE_ROOT);
489
732
  if (claudeCompatibility?.status === 'rejected')
490
733
  throw new Error(claudeCompatibilityError(claudeCompatibility));
491
734
  const claudeVersion = claudeCompatibility?.version ?? (claude ? nativeVersion(claude) : null);
@@ -521,7 +764,7 @@ async function setup(args) {
521
764
  ? await providerFreeProbe(endpoint, token, policy, clients)
522
765
  : await providerFreeProbe(endpoint, token);
523
766
  } catch (error) {
524
- throw new Error(`provider_free_probe_failed:${errorMessage(error)}`);
767
+ throw setupTokenError(`provider_free_probe_failed:${errorMessage(error)}`, locale, endpoint);
525
768
  }
526
769
  try {
527
770
  const configWithToken = { ...config, token, tokenSha256: await tokenDigest(token), probe };
@@ -533,12 +776,100 @@ async function setup(args) {
533
776
  console.log(
534
777
  `Configured ${clients} in ${root}. Provider-free access verified; no provider batch was used.`,
535
778
  );
779
+ await recordSetupConsent(root, locale, release);
536
780
  if (lang !== undefined) await setPackLocale(lang);
537
781
  // Display only: the server decides again on every pack request (ADR-0047).
538
782
  const line = licenseLine(await checkEngineeringLicense(endpoint, token));
539
783
  if (line !== null) console.log(line);
540
784
  }
541
785
 
786
+ /**
787
+ * Whether Codex runs the AISAC hooks the user has on, from Codex's own
788
+ * `hooks/list` in this folder (FR6, FR8, E6b). No session starts, and Codex
789
+ * writes no config or trust record. Codex is not asked when the last launch had
790
+ * no license, because the launcher then hands Codex no hook.
791
+ * @param {{ executable: string | null, version: string | null | undefined, licensed: boolean }} codex
792
+ */
793
+ async function doctorCodexHooks({ executable, version, licensed }) {
794
+ if (executable === null) return { status: 'codex_not_found' };
795
+ if (!supportsCodexHooks(version)) return { status: 'codex_version_unsupported' };
796
+ if (!licensed) return { status: 'not_licensed' };
797
+ const read = await readCodexGuardrails({
798
+ root: stateRoot(),
799
+ packageRoot: PACKAGE_ROOT,
800
+ executable,
801
+ cwd: process.cwd(),
802
+ profile: undefined,
803
+ environment: process.env,
804
+ }).catch(() => undefined);
805
+ if (read === undefined) return { status: 'list_failed' };
806
+ if (read === null) return { status: 'none_enabled' };
807
+ const { summary } = read;
808
+ if (summary === null) return { status: 'list_failed' };
809
+ const status = codexHooksStatus(summary);
810
+ return {
811
+ status,
812
+ handlers: summary.handlers,
813
+ review: summary.review,
814
+ off: summary.off,
815
+ missing: summary.missing,
816
+ ...(summary.review.length > 0
817
+ ? { remedy: 'Run aisac codex, open /hooks and approve the AISAC hooks.' }
818
+ : {}),
819
+ };
820
+ }
821
+
822
+ /**
823
+ * Extension state plus whether `format-on-edit` has a formatter in this folder,
824
+ * and whether Codex runs the hooks (FR8).
825
+ * @param {{ executable: string | null, version: string | null | undefined }} codex
826
+ */
827
+ async function doctorExtensions(codex) {
828
+ const summary = await extensionsSummary(stateRoot());
829
+ // A token server is skipped at launch when its variable is unset (names only).
830
+ const mcpMissingEnv = sessionServers(summary.mcp, 'claude', process.env).missingEnv.map(
831
+ (skipped) => skipped.id,
832
+ );
833
+ const formatOnEdit = !summary.hooks.includes('format-on-edit')
834
+ ? 'off'
835
+ : (await anyFormatter(process.cwd()))
836
+ ? 'ready'
837
+ : 'no_formatter_found';
838
+ const licensed = (await readLastLaunch(stateRoot()))?.state === 'loaded';
839
+ const codexHooks = await doctorCodexHooks({ ...codex, licensed });
840
+ return { ...summary, formatOnEdit, mcpMissingEnv, codexHooks };
841
+ }
842
+
843
+ /**
844
+ * The text doctor's `scan` line: `kind=mode`, a binary's version, then the reason, for
845
+ * example `sca=binary 2.7.1, iac=skipped (tool_unavailable)`.
846
+ * @param {Awaited<ReturnType<typeof scanToolAvailability>>} entries
847
+ */
848
+ function scanLine(entries) {
849
+ return entries
850
+ .map(({ kind, mode, version, reason }) => {
851
+ const detail = mode === 'binary' && version !== null ? ` ${version}` : '';
852
+ return `${kind}=${mode}${detail}${reason === null ? '' : ` (${reason})`}`;
853
+ })
854
+ .join(', ');
855
+ }
856
+
857
+ /**
858
+ * What `aisac scan` would run, per kind (scan spec FR9): in `--json` the entries of
859
+ * `scan --check-tools --json`, in text one line. No pull, no scan, no pack, no license.
860
+ * Optional capability: a failure (only a bad pins file) is its message and never changes
861
+ * doctor's exit code.
862
+ * @param {boolean} json
863
+ */
864
+ async function doctorScan(json) {
865
+ try {
866
+ const entries = await scanToolAvailability({ packageRoot: PACKAGE_ROOT, env: process.env });
867
+ return json ? entries : scanLine(entries);
868
+ } catch (error) {
869
+ return errorMessage(error);
870
+ }
871
+ }
872
+
542
873
  /** @param {boolean} json */
543
874
  async function doctor(json) {
544
875
  const platform = platformCheck();
@@ -564,8 +895,35 @@ async function doctor(json) {
564
895
  codex: resolveNative('codex'),
565
896
  node: resolveNative('node'),
566
897
  };
898
+ // Release manifest (ADR-0056 R2): fetched at most every six hours when a setup
899
+ // exists, bundled copy otherwise; never the exit code.
900
+ const releaseManifest = await resolveReleaseManifest({
901
+ root: stateRoot(),
902
+ packageRoot: PACKAGE_ROOT,
903
+ endpoint: config?.endpoint ?? null,
904
+ token: config?.token ?? null,
905
+ }).catch(() => null);
906
+ const releaseSettings = await readReleaseSettings(stateRoot());
907
+ // Managed hosts (ADR-0056 R4, FR8): the host a launch would run and the state of
908
+ // the pinned copy; doctor installs nothing. A ready managed copy is the binary the
909
+ // compatibility fields describe, since it is the one `aisac claude` runs.
910
+ /** @param {'claude' | 'codex'} host */
911
+ const describeHost = (host) =>
912
+ describeManagedHost({
913
+ host,
914
+ root: stateRoot(),
915
+ packageRoot: PACKAGE_ROOT,
916
+ manifest: releaseManifest,
917
+ settings: releaseSettings,
918
+ env: process.env,
919
+ clientVersion: VERSION,
920
+ }).catch(() => null);
921
+ const managedHosts = { claude: await describeHost('claude'), codex: await describeHost('codex') };
922
+ const claudeExecutable = managedHosts.claude?.executable ?? native.claude;
567
923
  const claudeCompatibility =
568
- native.claude !== null ? await resolveClaudeCompatibility(native.claude, PACKAGE_ROOT) : null;
924
+ claudeExecutable !== null
925
+ ? await resolveClaudeCompatibility(claudeExecutable, PACKAGE_ROOT)
926
+ : null;
569
927
  const codexCompatibility =
570
928
  native.codex !== null ? await resolveCodexCompatibility(native.codex) : null;
571
929
  const rawNativeVersions = {
@@ -585,7 +943,7 @@ async function doctor(json) {
585
943
  const captureLockPlatform = needsCodex ? captureLockPlatformCheck() : null;
586
944
  const nativeReady =
587
945
  (!needsClaude ||
588
- (native.claude !== null &&
946
+ (claudeExecutable !== null &&
589
947
  (claudeCompatibility?.status === 'qualified' ||
590
948
  claudeCompatibility?.status === 'host_checked'))) &&
591
949
  (!needsCodex ||
@@ -633,6 +991,27 @@ async function doctor(json) {
633
991
  },
634
992
  engineering,
635
993
  engineeringPack: await engineeringPackState(),
994
+ manifest: releaseManifest === null ? null : manifestDoctorSection(releaseManifest),
995
+ // Self-update (ADR-0056 R3, FR8): the decision this launch would take, no action.
996
+ update: await updateDoctorSection({
997
+ root: stateRoot(),
998
+ packageRoot: PACKAGE_ROOT,
999
+ version: VERSION,
1000
+ env: process.env,
1001
+ manifest: releaseManifest,
1002
+ }).catch(() => null),
1003
+ // Managed hosts (ADR-0056 R4, FR8): the decision and the pinned copy, no path.
1004
+ hosts: {
1005
+ managed: {
1006
+ claude: hostDoctorSection(managedHosts.claude),
1007
+ codex: hostDoctorSection(managedHosts.codex),
1008
+ },
1009
+ },
1010
+ extensions: await doctorExtensions({
1011
+ executable: native.codex,
1012
+ version: codexCompatibility?.version,
1013
+ }),
1014
+ scan: await doctorScan(json),
636
1015
  paidOrPilot: probe?.ok
637
1016
  ? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
638
1017
  : config
@@ -640,13 +1019,97 @@ async function doctor(json) {
640
1019
  : 'not_configured',
641
1020
  };
642
1021
  if (json) console.log(JSON.stringify(result));
643
- else console.log(result);
1022
+ else {
1023
+ console.log(result);
1024
+ for (const line of releaseDoctorLines(result)) console.log(line);
1025
+ }
644
1026
  if (!platform.ok || !config || !probe?.ok || !nativeReady) process.exitCode = 1;
645
1027
  }
646
1028
 
1029
+ /**
1030
+ * The `hosts.managed.<host>` section (FR8): everything `describeManagedHost`
1031
+ * found but the binary's path.
1032
+ * @param {Awaited<ReturnType<typeof describeManagedHost>> | null} described
1033
+ */
1034
+ function hostDoctorSection(described) {
1035
+ if (described === null) return null;
1036
+ return {
1037
+ mode: described.mode,
1038
+ reason: described.reason,
1039
+ pinned: described.pinned,
1040
+ platform: described.platform,
1041
+ installed: described.installed,
1042
+ on_disk: described.on_disk,
1043
+ pin_check: described.pin_check,
1044
+ resolver: described.resolver,
1045
+ resolver_reason: described.resolver_reason,
1046
+ install_failure: described.install_failure,
1047
+ };
1048
+ }
1049
+
1050
+ /**
1051
+ * One line per release section after the text doctor output (FR8, R4).
1052
+ * @param {{ manifest: ReturnType<typeof manifestDoctorSection> | null,
1053
+ * update: Awaited<ReturnType<typeof updateDoctorSection>> | null,
1054
+ * hosts: { managed: Record<'claude' | 'codex', ReturnType<typeof hostDoctorSection>> } }} result
1055
+ */
1056
+ function releaseDoctorLines(result) {
1057
+ const manifest =
1058
+ result.manifest === null
1059
+ ? 'unavailable'
1060
+ : `sequence ${result.manifest.sequence} (${result.manifest.source}), ${result.manifest.state}`;
1061
+ const update =
1062
+ result.update === null
1063
+ ? 'unavailable'
1064
+ : `${result.update.mode} on ${result.update.channel}; ${
1065
+ result.update.action === 'none' ? 'up to date' : result.update.action
1066
+ }${result.update.reason === null ? '' : ` (${result.update.reason})`}`;
1067
+ /** @param {'claude' | 'codex'} name @param {ReturnType<typeof hostDoctorSection>} section */
1068
+ const host = (name, section) =>
1069
+ section === null
1070
+ ? `${name} unknown`
1071
+ : `${name} ${section.mode}${section.pinned === null ? '' : `, pinned ${section.pinned}`}${
1072
+ section.mode === 'managed' ? (section.installed ? ', installed' : ', not installed') : ''
1073
+ }${section.reason === null ? '' : ` (${section.reason})`}`;
1074
+ return [
1075
+ `manifest: ${manifest}`,
1076
+ `update: ${update}`,
1077
+ `hosts: ${host('claude', result.hosts.managed.claude)}; ${host('codex', result.hosts.managed.codex)}`,
1078
+ ];
1079
+ }
1080
+
1081
+ /**
1082
+ * `aisac scan`. An error the engine did not classify still means it could not scan as
1083
+ * asked: exit 3, never 1, which a CI step reads as findings (scan review F3). Usage
1084
+ * errors keep their 2.
1085
+ * @param {string[]} args
1086
+ */
1087
+ async function scan(args) {
1088
+ try {
1089
+ return await scanCommand(args, {
1090
+ packageRoot: PACKAGE_ROOT,
1091
+ readConfig,
1092
+ stateRoot,
1093
+ cwd: process.cwd(),
1094
+ env: process.env,
1095
+ });
1096
+ } catch (error) {
1097
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1098
+ if (typeof exitCode === 'number') throw error;
1099
+ const classified = error instanceof Error ? error : new Error(errorMessage(error));
1100
+ throw Object.assign(classified, { exitCode: SCAN_CANNOT_RUN_EXIT_CODE });
1101
+ }
1102
+ }
1103
+
647
1104
  /** @param {boolean} json */
648
1105
  async function status(json) {
649
1106
  const config = await readConfig();
1107
+ // Offline: the cached or bundled manifest, never a fetch (FR8).
1108
+ const releaseManifest = await resolveReleaseManifest({
1109
+ root: stateRoot(),
1110
+ packageRoot: PACKAGE_ROOT,
1111
+ }).catch(() => null);
1112
+ const releaseSettings = await readReleaseSettings(stateRoot());
650
1113
  const policy =
651
1114
  config?.schemaVersion === 2 && config.context !== undefined
652
1115
  ? config.context
@@ -669,6 +1132,22 @@ async function status(json) {
669
1132
  config?.claudeObservation?.disclosedAt !== undefined,
670
1133
  },
671
1134
  engineeringPack: await engineeringPackState(),
1135
+ manifest:
1136
+ releaseManifest === null
1137
+ ? null
1138
+ : {
1139
+ sequence: releaseManifest.sequence,
1140
+ source: releaseManifest.source,
1141
+ state: releaseManifest.state,
1142
+ },
1143
+ update: {
1144
+ mode: releaseSettings.update.mode,
1145
+ channel: releaseSettings.update.channel,
1146
+ consent: releaseSettings.consent !== null,
1147
+ },
1148
+ // Host modes as stored (FR8); whether the managed copy is installed is doctor's.
1149
+ hosts: { claude: releaseSettings.hosts.claude, codex: releaseSettings.hosts.codex },
1150
+ extensions: await extensionsSummary(stateRoot()),
672
1151
  monitoredSession: null,
673
1152
  monitoringStatus: 'not_observed',
674
1153
  };
@@ -717,6 +1196,34 @@ async function main(argv) {
717
1196
  else console.log(records);
718
1197
  return;
719
1198
  }
1199
+ if (command === 'hooks') return hooksCommand(rest);
1200
+ if (command === 'mcp') return mcpCommand(rest);
1201
+ if (command === 'init')
1202
+ return initCommand(rest, {
1203
+ packageRoot: PACKAGE_ROOT,
1204
+ readConfig,
1205
+ stateRoot,
1206
+ cwd: process.cwd(),
1207
+ env: process.env,
1208
+ });
1209
+ if (command === 'scan') {
1210
+ process.exitCode = await scan(rest);
1211
+ return;
1212
+ }
1213
+ if (command === 'update') {
1214
+ process.exitCode = await updateCommand(rest, {
1215
+ root: stateRoot(),
1216
+ packageRoot: PACKAGE_ROOT,
1217
+ version: VERSION,
1218
+ env: process.env,
1219
+ readConfig: async () => {
1220
+ const config = await readConfig();
1221
+ return config === null ? null : { endpoint: config.endpoint, token: config.token };
1222
+ },
1223
+ interactive: stdin.isTTY === true && stdout.isTTY === true,
1224
+ });
1225
+ return;
1226
+ }
720
1227
  if (command === 'disable') {
721
1228
  if (rest.length > 0) throw new Error('disable_does_not_accept_options');
722
1229
  return removeOwnedSetup();
@@ -732,20 +1239,52 @@ async function main(argv) {
732
1239
  // metadata only, so patch updates do not block a fresh compatibility check.
733
1240
  if (command === 'codex' && typeof config.codexVersion !== 'string')
734
1241
  throw new Error('codex_version_unverified');
1242
+ // `--host managed|system` belongs to the launcher, not the host (ADR-0056 R4,
1243
+ // FR5); a managed Codex arrives with R5.
1244
+ const launch = takeHostFlag(rest);
1245
+ if (command === 'codex' && launch.hostMode === 'managed')
1246
+ throw new Error('host_mode_unsupported');
1247
+ const nativeArgs = launch.args[0] === '--' ? launch.args.slice(1) : launch.args;
735
1248
  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;
1249
+ try {
1250
+ // Self-update (ADR-0056 R3, FR6) before any host work: the one-time consent
1251
+ // question on a terminal, then install + re-exec in `auto` mode, one line in
1252
+ // `notify`, and a refusal to launch a host below the manifest's minimum.
1253
+ const update = await selfUpdateAtLaunch({
1254
+ root,
1255
+ packageRoot: PACKAGE_ROOT,
1256
+ version: VERSION,
1257
+ config: { endpoint: config.endpoint, token: config.token },
1258
+ host: command,
1259
+ argv,
1260
+ env: process.env,
1261
+ interactive: stdin.isTTY === true && stdout.isTTY === true,
1262
+ });
1263
+ if (update.kind === 'reexec') {
1264
+ process.exitCode = update.exitCode;
1265
+ return;
1266
+ }
1267
+ if (update.kind === 'blocked')
1268
+ throw Object.assign(new Error(update.reason), { guide: update.line });
1269
+ if (update.kind === 'continue')
1270
+ for (const line of update.lines) process.stderr.write(`${line}\n`);
1271
+ const result = await (command === 'claude'
1272
+ ? launchClaude(
1273
+ { ...config, packageRoot: PACKAGE_ROOT },
1274
+ root,
1275
+ nativeArgs,
1276
+ {},
1277
+ {
1278
+ hostMode: launch.hostMode,
1279
+ },
1280
+ )
1281
+ : launchCodex({ ...config, packageRoot: PACKAGE_ROOT }, root, nativeArgs));
1282
+ process.exitCode = result;
1283
+ return;
1284
+ } finally {
1285
+ // The update lock, when this launch still holds it (no host started).
1286
+ await releaseUpdateLock(root).catch(() => undefined);
1287
+ }
749
1288
  }
750
1289
  throw new Error('unknown_command');
751
1290
  }
@@ -766,6 +1305,16 @@ main(cliArgs).catch((error) => {
766
1305
  );
767
1306
  } else {
768
1307
  console.error(`${COMMAND}: ${errorMessage(error)}`);
1308
+ const guide = /** @type {{ guide?: unknown }} */ (error ?? {}).guide;
1309
+ if (typeof guide === 'string') console.error(`\n${guide}`);
769
1310
  }
770
- process.exitCode = 1;
1311
+ // Usage errors exit 2 (init spec FR3, scan spec FR1). `aisac scan` exits 3
1312
+ // when it cannot scan as asked (scan spec D6: no scanner, a tool failure, no
1313
+ // license or pack), so a CI step never reads that as findings; everything
1314
+ // else exits 1.
1315
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1316
+ process.exitCode =
1317
+ typeof exitCode === 'number' && Number.isInteger(exitCode) && exitCode >= 1 && exitCode <= 3
1318
+ ? exitCode
1319
+ : 1;
771
1320
  });