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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +146 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +846 -14
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +12 -1
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +641 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +276 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +390 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +1557 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +403 -47
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/manager/bus.mjs +1921 -0
  35. package/dist/manager/delegation.mjs +354 -0
  36. package/dist/manager/hooks.mjs +918 -0
  37. package/dist/manager/launch-role.mjs +476 -0
  38. package/dist/manager/mcp-stdio.mjs +463 -0
  39. package/dist/manager/messages.mjs +791 -0
  40. package/dist/manager/reserve.mjs +2166 -0
  41. package/dist/manager/room.mjs +106 -0
  42. package/dist/manager/server.mjs +1792 -0
  43. package/dist/manager/status.mjs +118 -0
  44. package/dist/manager/watch.mjs +87 -0
  45. package/dist/manager/worker.mjs +2793 -0
  46. package/dist/manager/workers-cli.mjs +1403 -0
  47. package/dist/mcp-servers.mjs +192 -0
  48. package/dist/mcp.mjs +10 -2
  49. package/dist/monitor.mjs +76 -1
  50. package/dist/package.json +1 -1
  51. package/dist/platform.mjs +78 -29
  52. package/dist/release-manifest-public-keys.json +10 -0
  53. package/dist/release-manifest.json +328 -0
  54. package/dist/release-manifest.mjs +817 -0
  55. package/dist/release-settings.mjs +210 -0
  56. package/dist/self-update.mjs +1036 -0
  57. package/dist/state.mjs +25 -1
  58. package/dist/token-guide.mjs +132 -0
  59. package/dist/update-actions.mjs +442 -0
  60. package/package.json +1 -1
package/dist/launch.mjs CHANGED
@@ -14,10 +14,51 @@ import {
14
14
  } from './state.mjs';
15
15
  import { codexPolicyJson, makePolicy } from './policy.mjs';
16
16
  import {
17
+ liveLaunchHosts,
17
18
  prepareEngineeringPack,
19
+ readStoredLocale,
20
+ resolvePackLocale,
18
21
  sweepStaleLaunches,
19
22
  writeLaunchMarker,
20
23
  } from './engineering-pack.mjs';
24
+ import { prepareCodexGuardrails, prepareGuardrails } from './guardrails-plugin.mjs';
25
+ import { installedClientVersion, refreshReleaseManifest } from './release-manifest.mjs';
26
+ import { readReleaseSettings, updateCommandFor } from './release-settings.mjs';
27
+ import { REEXEC_ENV, releaseUpdateLock } from './update-actions.mjs';
28
+ import {
29
+ collectManagedHosts,
30
+ hostFallbackLine,
31
+ managedHostEnvironment,
32
+ resolveHostExecutable,
33
+ } from './managed-host.mjs';
34
+ import { recordLaunchHost } from './self-update.mjs';
35
+ import { CODEX_HOOKS_ENV, GUARDRAILS_SESSION_ENV, supportsCodexHooks } from './codex-hooks.mjs';
36
+ import {
37
+ CODEX_MCP_ENV,
38
+ claudeDenyRules,
39
+ claudeMcpEntries,
40
+ mcpLaunchLines,
41
+ sessionServers,
42
+ } from './mcp-servers.mjs';
43
+ import { enabledServerIds, readPreferences } from './extensions-preferences.mjs';
44
+ import {
45
+ CODEX_ENGINEERING_ENV,
46
+ CODEX_ENGINEERING_SKILLS_ROOT_ENV,
47
+ supportsCodexEngineering,
48
+ } from './codex-engineering.mjs';
49
+ import {
50
+ MANAGER_SERVER_NAME,
51
+ ROLE_ENVIRONMENT_VARIABLES,
52
+ closeRole,
53
+ managerAllowRules,
54
+ managerMcpEntry,
55
+ prepareRole,
56
+ roleLaunchLine,
57
+ supportsWorkerRole,
58
+ workerEnvironment,
59
+ } from './manager/launch-role.mjs';
60
+ import { MANAGER_ROLE_ENV } from './manager/bus.mjs';
61
+ import { prepareManagerPlugin } from './manager/hooks.mjs';
21
62
  import {
22
63
  CODEX_LAUNCH_ENVELOPE,
23
64
  CODEX_MONITOR_CWD,
@@ -132,6 +173,15 @@ function childEnvironment(root) {
132
173
  delete environment.CODEX_CONTEXT_COMPACT_AT;
133
174
  delete environment[CODEX_LAUNCH_ENVELOPE];
134
175
  delete environment[CODEX_MONITOR_CWD];
176
+ delete environment[CODEX_ENGINEERING_ENV];
177
+ delete environment[CODEX_ENGINEERING_SKILLS_ROOT_ENV];
178
+ delete environment[CODEX_MCP_ENV];
179
+ delete environment[CODEX_HOOKS_ENV];
180
+ delete environment[GUARDRAILS_SESSION_ENV];
181
+ delete environment[REEXEC_ENV];
182
+ // A role is given by this launch alone (spec aisac-engineering-manager D2): one
183
+ // inherited from an outer session, such as a manager's shell, never reaches the host.
184
+ for (const variable of ROLE_ENVIRONMENT_VARIABLES) delete environment[variable];
135
185
  environment.AIBRAIN_STATE_DIR = resolve(root);
136
186
  return environment;
137
187
  }
@@ -368,22 +418,34 @@ async function assertClaudeCheckpointHelper(packageRoot) {
368
418
 
369
419
  /**
370
420
  * A fresh private directory for one launch. Directories left by launches whose
371
- * processes are gone are swept first; this one records its launcher.
421
+ * processes are gone are swept first; this one records its launcher and the
422
+ * host it runs, `pending` until resolved (release-manifest FR5: a managed
423
+ * version a live launch names is never garbage-collected, and nothing is
424
+ * collected while a live launch is still resolving its host).
372
425
  * @param {string} root @param {string} prefix
426
+ * @param {import('./engineering-pack.mjs').LaunchHost} host
373
427
  */
374
- async function launchDirectory(root, prefix) {
428
+ async function launchDirectory(root, prefix, host) {
375
429
  await sweepStaleLaunches(root);
376
430
  const parent = await privateDirectory(join(root, 'runtime'));
377
431
  const directory = await mkdtemp(join(parent, `${prefix}-`));
378
432
  await chmod(directory, 0o700);
379
- await writeLaunchMarker(directory, { launcherPid: process.pid, childPid: null });
433
+ await writeLaunchMarker(directory, { launcherPid: process.pid, childPid: null, host });
434
+ // This launch now counts as live for other launchers, so the update lock the
435
+ // self-update step took can go (release-manifest FR6).
436
+ await releaseUpdateLock(root).catch(() => undefined);
380
437
  return directory;
381
438
  }
382
439
 
383
- /** @param {string} directory @param {number | undefined} childPid */
384
- async function recordChild(directory, childPid) {
440
+ /**
441
+ * @param {string} directory @param {number | undefined} childPid
442
+ * @param {import('./engineering-pack.mjs').LaunchHost} host
443
+ */
444
+ async function recordChild(directory, childPid, host) {
385
445
  if (childPid === undefined) return;
386
- await writeLaunchMarker(directory, { launcherPid: process.pid, childPid }).catch(() => undefined);
446
+ await writeLaunchMarker(directory, { launcherPid: process.pid, childPid, host }).catch(
447
+ () => undefined,
448
+ );
387
449
  }
388
450
 
389
451
  /** @param {import('node:child_process').ChildProcess} child @param {string} directory */
@@ -418,9 +480,33 @@ function waitForChild(child, directory) {
418
480
  });
419
481
  }
420
482
 
483
+ /**
484
+ * The catalog servers that join this session: the user's enabled choices from
485
+ * the preferences file. Called only after the license was confirmed.
486
+ * @param {string} root
487
+ * @param {'claude' | 'codex'} client
488
+ * @param {NodeJS.ProcessEnv} environment
489
+ */
490
+ export async function readSessionServers(root, client, environment) {
491
+ return sessionServers(enabledServerIds(await readPreferences(root)), client, environment);
492
+ }
493
+
421
494
  /**
422
495
  * @typedef {object} LaunchDependencies
423
496
  * @property {typeof prepareEngineeringPack} [preparePack] AISAC Engineering pack loader (E4b)
497
+ * @property {typeof prepareGuardrails} [prepareGuardrails] Guardrail hooks plugin writer (E6a)
498
+ * @property {typeof readSessionServers} [readSessionServers] MCP catalog servers to load (E6c)
499
+ * @property {typeof prepareCodexGuardrails} [prepareCodexGuardrails] Codex guardrail hooks (E6b)
500
+ * @property {typeof refreshReleaseManifest} [refreshReleaseManifest] Release manifest refresh (ADR-0056 R2)
501
+ * @property {typeof resolveHostExecutable} [resolveHost] Managed or system host resolution (ADR-0056 R4)
502
+ * @property {typeof prepareRole} [prepareRole] Manager or worker role registration (ADR-0058)
503
+ * @property {typeof prepareManagerPlugin} [prepareManagerPlugin] Manager hook nudges plugin writer (ADR-0058)
504
+ */
505
+
506
+ /**
507
+ * @typedef {object} LaunchOptions
508
+ * @property {import('./release-settings.mjs').HostMode | null} [hostMode] `--host managed|system` for this launch (FR5)
509
+ * @property {import('./manager/launch-role.mjs').RoleRequest | null} [role] `--manager`, or `--worker <name>`, with `--room` (ADR-0058)
424
510
  */
425
511
 
426
512
  /**
@@ -428,22 +514,30 @@ function waitForChild(child, directory) {
428
514
  * @param {string} root
429
515
  * @param {string[]} args
430
516
  * @param {LaunchDependencies} [dependencies]
517
+ * @param {LaunchOptions} [launchOptions]
431
518
  */
432
- export async function launchClaude(config, root, args, dependencies = {}) {
519
+ export async function launchClaude(config, root, args, dependencies = {}, launchOptions = {}) {
433
520
  const preparePack = dependencies.preparePack ?? prepareEngineeringPack;
521
+ const refreshManifest = dependencies.refreshReleaseManifest ?? refreshReleaseManifest;
522
+ const writeGuardrails = dependencies.prepareGuardrails ?? prepareGuardrails;
523
+ const readServers = dependencies.readSessionServers ?? readSessionServers;
524
+ const resolveHost = dependencies.resolveHost ?? resolveHostExecutable;
525
+ const registerRole = dependencies.prepareRole ?? prepareRole;
526
+ const writeManagerPlugin = dependencies.prepareManagerPlugin ?? prepareManagerPlugin;
434
527
  const validated = assertConfig(config);
435
528
  const launchArgs = await parseClaudeLaunchArgs(args, process.cwd());
436
529
  assertClaudeArgs(launchArgs.args);
437
- const executable = resolveNative('claude');
438
- if (!executable) throw new Error('claude_not_found');
439
- const compatibility = await resolveClaudeCompatibility(executable, validated.packageRoot);
440
- if (compatibility.status === 'rejected') throw new Error(claudeCompatibilityError(compatibility));
441
- const pinnedExecutable = compatibility.executable ?? executable;
442
- if (compatibility.status === 'host_checked')
443
- process.stderr.write(
444
- `aisac: Claude ${compatibility.version ?? 'unknown'} accepted by the local native host contract; end-to-end recovery remains separately qualified.\n`,
445
- );
446
- const currentVersion = compatibility.version ?? nativeVersion(pinnedExecutable);
530
+ // Release manifest (ADR-0056 R2): refreshed at most every six hours, bounded by
531
+ // its own timeout; it never blocks the launch. R4 reads the Claude pin from it.
532
+ const manifest = await refreshManifest({
533
+ root,
534
+ packageRoot: validated.packageRoot,
535
+ endpoint: validated.endpoint,
536
+ token: validated.token,
537
+ host: 'claude',
538
+ });
539
+ // Everything that can fail without the host: the package's own assets, before any
540
+ // launch directory exists.
447
541
  const pluginRoot = await assertClaudeAssets(validated.packageRoot);
448
542
  const telemetryActive =
449
543
  validated.telemetry?.enabled === true && validated.telemetry?.disclosedAt != null;
@@ -463,7 +557,65 @@ export async function launchClaude(config, root, args, dependencies = {}) {
463
557
  const checkpointHelperPath = await assertClaudeCheckpointHelper(validated.packageRoot);
464
558
  const checkpointConfigDigest = claudeCheckpointConfigBinding(validated);
465
559
  const checkpointStateDir = await privateDirectory(join(root, 'claude', 'checkpoints'));
466
- const directory = await launchDirectory(root, 'claude');
560
+ // The launch marker first, its host `pending` (FR5): another launch's garbage
561
+ // collection skips while it exists, so the version this launch is about to run
562
+ // is never removed between its resolution and its spawn.
563
+ const directory = await launchDirectory(root, 'claude', {
564
+ name: 'claude',
565
+ mode: 'pending',
566
+ version: null,
567
+ });
568
+ // Managed or system host (ADR-0056 R4, FR5): the managed copy when the settings
569
+ // or `--host` ask for it and it is installed, pinned and qualified; otherwise the
570
+ // user's own binary, with the reason on stderr when a managed launch fell back.
571
+ const locale = resolvePackLocale(await readStoredLocale(root), process.env);
572
+ const host = await resolveHost({
573
+ host: 'claude',
574
+ root,
575
+ packageRoot: validated.packageRoot,
576
+ manifest,
577
+ settings: await readReleaseSettings(root),
578
+ env: process.env,
579
+ flag: launchOptions.hostMode ?? null,
580
+ clientVersion: await installedClientVersion(validated.packageRoot),
581
+ locale,
582
+ progress: (line) => process.stderr.write(`${line}\n`),
583
+ });
584
+ if (host.fallback !== null) process.stderr.write(`${hostFallbackLine('claude', host, locale)}\n`);
585
+ const executable = host.executable;
586
+ if (!executable) {
587
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
588
+ throw new Error('claude_not_found');
589
+ }
590
+ const compatibility =
591
+ host.compatibility ?? (await resolveClaudeCompatibility(executable, validated.packageRoot));
592
+ if (compatibility.status === 'rejected') {
593
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
594
+ throw new Error(claudeCompatibilityError(compatibility));
595
+ }
596
+ const pinnedExecutable = compatibility.executable ?? executable;
597
+ if (compatibility.status === 'host_checked')
598
+ process.stderr.write(
599
+ `aisac: Claude ${compatibility.version ?? 'unknown'} accepted by the local native host contract; end-to-end recovery remains separately qualified.\n`,
600
+ );
601
+ const currentVersion = compatibility.version ?? nativeVersion(pinnedExecutable);
602
+ /** @type {import('./engineering-pack.mjs').LaunchHost} */
603
+ const launchHost = { name: 'claude', mode: host.mode, version: compatibility.version ?? null };
604
+ await writeLaunchMarker(directory, {
605
+ launcherPid: process.pid,
606
+ childPid: null,
607
+ host: launchHost,
608
+ });
609
+ await recordLaunchHost(
610
+ root,
611
+ {
612
+ name: 'claude',
613
+ mode: host.mode,
614
+ version: launchHost.version,
615
+ reason: host.fallback ?? host.reason,
616
+ },
617
+ manifest === null ? null : { sequence: manifest.sequence, source: manifest.source },
618
+ ).catch(() => undefined);
467
619
  const settingsPath = join(directory, 'settings.json');
468
620
  const mcpPath = join(directory, 'mcp.json');
469
621
  const context = validated.context;
@@ -535,6 +687,14 @@ export async function launchClaude(config, root, args, dependencies = {}) {
535
687
  for (const rule of [...userAllow, ...requiredAllow]) {
536
688
  if (!mergedAllow.includes(rule)) mergedAllow.push(rule);
537
689
  }
690
+ // Catalog tools that spend money stay denied whatever the user allows or the
691
+ // permission mode is (spec aisac-engineering-extensions FR7.2).
692
+ const userDeny = Array.isArray(userPermissions.deny) ? userPermissions.deny : [];
693
+ /** @type {unknown[]} */
694
+ const mergedDeny = [];
695
+ for (const rule of [...userDeny, ...claudeDenyRules()]) {
696
+ if (!mergedDeny.includes(rule)) mergedDeny.push(rule);
697
+ }
538
698
  const settings = {
539
699
  ...(launchArgs.settings?.sandbox === undefined ? {} : { sandbox: launchArgs.settings.sandbox }),
540
700
  pluginConfigs: {
@@ -544,10 +704,88 @@ export async function launchClaude(config, root, args, dependencies = {}) {
544
704
  permissions: {
545
705
  ...userPermissions,
546
706
  allow: mergedAllow,
707
+ deny: mergedDeny,
547
708
  },
548
709
  };
710
+ // The pack never blocks the launch: every failure starts Claude without it.
711
+ const engineering = await preparePack({
712
+ endpoint: validated.endpoint,
713
+ token: validated.token,
714
+ root,
715
+ directory,
716
+ packageRoot: validated.packageRoot,
717
+ updateCommand: await updateCommandFor(root, validated.packageRoot),
718
+ }).catch(() => ({ pluginRoot: null, line: null }));
719
+ if (engineering.line !== null) process.stderr.write(`${engineering.line}\n`);
720
+ // Guardrails need the license this launch confirmed (the pack loaded), and
721
+ // like the pack they never block the launch (spec aisac-engineering-extensions FR5).
722
+ const guardrails =
723
+ engineering.pluginRoot === null
724
+ ? null
725
+ : await writeGuardrails({ directory, root, packageRoot: validated.packageRoot }).catch(
726
+ () => null,
727
+ );
728
+ if (guardrails !== null) process.stderr.write(`${guardrails.line}\n`);
729
+ // Catalog servers need the same confirmed license, and never block the launch.
730
+ const servers =
731
+ engineering.pluginRoot === null
732
+ ? null
733
+ : await readServers(root, 'claude', process.env).catch(() => null);
734
+ for (const line of servers === null ? [] : mcpLaunchLines(servers, 'claude'))
735
+ process.stderr.write(`${line}\n`);
736
+ // The manager role (spec aisac-engineering-manager FR1, FR6-FR8) needs the same
737
+ // confirmed license and never blocks the launch; a second manager of the room
738
+ // stops it here, before any host starts.
739
+ /** @type {Awaited<ReturnType<typeof prepareRole>> | null} */
740
+ let role = null;
741
+ /** @type {{ pluginRoot: string } | null} */
742
+ let managerPlugin = null;
743
+ if (launchOptions.role != null) {
744
+ try {
745
+ role = await registerRole({
746
+ root,
747
+ request: launchOptions.role,
748
+ host: { name: 'claude', version: launchHost.version },
749
+ cwd: process.cwd(),
750
+ locale,
751
+ licensed: engineering.pluginRoot !== null,
752
+ qualified: true,
753
+ });
754
+ } catch (error) {
755
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
756
+ throw error;
757
+ }
758
+ process.stderr.write(`${roleLaunchLine(role, locale)}\n`);
759
+ if (role.active) {
760
+ managerPlugin = await writeManagerPlugin({
761
+ directory,
762
+ packageRoot: validated.packageRoot,
763
+ }).catch(() => null);
764
+ // The read tools and `manager_decide` are pre-allowed; sending and cancelling
765
+ // are left to the host's permission flow (FR8).
766
+ for (const rule of managerAllowRules()) {
767
+ if (!mergedAllow.includes(rule)) mergedAllow.push(rule);
768
+ requiredAllow.push(rule);
769
+ }
770
+ }
771
+ }
772
+ /** Undo what this launch registered and wrote, when no host will run. */
773
+ const abandon = async () => {
774
+ await closeRole(role);
775
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
776
+ };
777
+ try {
778
+ await privateJson(settingsPath, settings);
779
+ } catch (error) {
780
+ await abandon();
781
+ throw error;
782
+ }
549
783
  const mcp = {
550
784
  mcpServers: {
785
+ ...(servers === null ? {} : claudeMcpEntries(servers.ready)),
786
+ ...(role !== null && role.active
787
+ ? { [MANAGER_SERVER_NAME]: managerMcpEntry(role, validated.packageRoot, process.execPath) }
788
+ : {}),
551
789
  [MCP_ALIAS]: {
552
790
  type: 'http',
553
791
  url: validated.endpoint,
@@ -556,23 +794,20 @@ export async function launchClaude(config, root, args, dependencies = {}) {
556
794
  },
557
795
  };
558
796
  try {
559
- await privateJson(settingsPath, settings);
560
797
  await privateJson(mcpPath, mcp);
561
798
  } catch (error) {
562
- await rm(directory, { recursive: true, force: true });
799
+ await abandon();
563
800
  throw error;
564
801
  }
565
- // The pack never blocks the launch: every failure starts Claude without it.
566
- const engineering = await preparePack({
567
- endpoint: validated.endpoint,
568
- token: validated.token,
569
- root,
570
- directory,
571
- packageRoot: validated.packageRoot,
572
- }).catch(() => ({ pluginRoot: null, line: null }));
573
- if (engineering.line !== null) process.stderr.write(`${engineering.line}\n`);
574
- const environment = childEnvironment(root);
802
+ // The managed copy never updates itself (FR5); a system launch keeps the
803
+ // user's environment as it is.
804
+ const environment =
805
+ host.mode === 'managed'
806
+ ? managedHostEnvironment(childEnvironment(root))
807
+ : childEnvironment(root);
575
808
  environment.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = '1';
809
+ // The manager's hooks and `aisac workers --wait` read the room from here (FR9).
810
+ if (role !== null && role.active) environment[MANAGER_ROLE_ENV] = role.environmentValue;
576
811
  /** @type {import('node:child_process').ChildProcess} */
577
812
  let child;
578
813
  try {
@@ -588,22 +823,57 @@ export async function launchClaude(config, root, args, dependencies = {}) {
588
823
  '--plugin-dir',
589
824
  pluginRoot,
590
825
  ...(engineering.pluginRoot === null ? [] : ['--plugin-dir', engineering.pluginRoot]),
826
+ ...(guardrails === null ? [] : ['--plugin-dir', guardrails.pluginRoot]),
827
+ ...(managerPlugin === null ? [] : ['--plugin-dir', managerPlugin.pluginRoot]),
591
828
  ...launchArgs.args,
592
829
  ],
593
830
  { cwd: process.cwd(), env: environment, stdio: 'inherit' },
594
831
  );
595
832
  } catch (error) {
596
- await rm(directory, { recursive: true, force: true }).catch(() => undefined);
833
+ await abandon();
597
834
  throw error;
598
835
  }
599
836
  // Listen for exit before any await, so a child that exits at once is not missed.
600
- const finished = waitForChild(child, directory);
601
- await recordChild(directory, child.pid);
837
+ const finished = waitForChild(child, directory).then(async (code) => {
838
+ await closeRole(role);
839
+ return code;
840
+ });
841
+ await recordChild(directory, child.pid, launchHost);
842
+ // Garbage collection after a successful launch (FR5): the versions the manifest
843
+ // still carries lock sets for stay, as does any version a live launch runs.
844
+ // The live markers are read under the host lock, by the collector; a live launch
845
+ // still resolving its host (`pending`) could run any version and vetoes it.
846
+ if (manifest !== null && manifest.manifest !== null)
847
+ await collectManagedHosts({
848
+ root,
849
+ host: 'claude',
850
+ keep: Object.keys(manifest.manifest.hosts.claude.versions),
851
+ live: async () => {
852
+ const hosts = await liveLaunchHosts(root);
853
+ if (hosts.some((entry) => entry.mode === 'pending')) return null;
854
+ return hosts.flatMap((entry) =>
855
+ entry.name === 'claude' && entry.mode === 'managed' && entry.version !== null
856
+ ? [entry.version]
857
+ : [],
858
+ );
859
+ },
860
+ }).catch(() => undefined);
602
861
  return finished;
603
862
  }
604
863
 
605
- /** @param {LaunchConfig} config @param {string} root @param {string[]} args */
606
- export async function launchCodex(config, root, args) {
864
+ /**
865
+ * @param {LaunchConfig} config
866
+ * @param {string} root
867
+ * @param {string[]} args
868
+ * @param {LaunchDependencies} [dependencies]
869
+ * @param {LaunchOptions} [launchOptions]
870
+ */
871
+ export async function launchCodex(config, root, args, dependencies = {}, launchOptions = {}) {
872
+ const preparePack = dependencies.preparePack ?? prepareEngineeringPack;
873
+ const refreshManifest = dependencies.refreshReleaseManifest ?? refreshReleaseManifest;
874
+ const readServers = dependencies.readSessionServers ?? readSessionServers;
875
+ const writeCodexGuardrails = dependencies.prepareCodexGuardrails ?? prepareCodexGuardrails;
876
+ const registerRole = dependencies.prepareRole ?? prepareRole;
607
877
  const validated = assertConfig(config);
608
878
  assertCodexArgs(args);
609
879
  const captureLockPlatform = captureLockPlatformCheck();
@@ -630,7 +900,9 @@ export async function launchCodex(config, root, args) {
630
900
  ]);
631
901
  const checkpoints = await privateDirectory(join(root, 'codex', 'checkpoints'));
632
902
  const notes = await privateDirectory(join(root, 'codex', 'notes'));
633
- const directory = await launchDirectory(root, 'codex');
903
+ /** @type {import('./engineering-pack.mjs').LaunchHost} */
904
+ const launchHost = { name: 'codex', mode: 'system', version: compatibility.version };
905
+ const directory = await launchDirectory(root, 'codex', launchHost);
634
906
  const environment = childEnvironment(root);
635
907
  try {
636
908
  if (
@@ -654,6 +926,75 @@ export async function launchCodex(config, root, args) {
654
926
  await rm(directory, { recursive: true, force: true });
655
927
  throw error;
656
928
  }
929
+ // Release manifest (ADR-0056 R2): same contract as for Claude.
930
+ await refreshManifest({
931
+ root,
932
+ packageRoot: validated.packageRoot,
933
+ endpoint: validated.endpoint,
934
+ token: validated.token,
935
+ host: 'codex',
936
+ });
937
+ // The pack never blocks the launch: every failure starts Codex without it.
938
+ const engineering = await preparePack({
939
+ endpoint: validated.endpoint,
940
+ token: validated.token,
941
+ root,
942
+ directory,
943
+ packageRoot: validated.packageRoot,
944
+ client: 'codex',
945
+ hostSupported: supportsCodexEngineering(compatibility.version),
946
+ updateCommand: await updateCommandFor(root, validated.packageRoot),
947
+ }).catch(() => ({ pluginRoot: null, codex: null, line: null }));
948
+ if (engineering.line !== null) process.stderr.write(`${engineering.line}\n`);
949
+ if (engineering.codex != null) {
950
+ environment[CODEX_ENGINEERING_ENV] = JSON.stringify(engineering.codex);
951
+ // Catalog servers need the license the pack confirmed (spec extensions FR6).
952
+ const servers = await readServers(root, 'codex', environment).catch(() => null);
953
+ for (const line of servers === null ? [] : mcpLaunchLines(servers, 'codex'))
954
+ process.stderr.write(`${line}\n`);
955
+ if (servers !== null && servers.ready.length > 0)
956
+ environment[CODEX_MCP_ENV] = JSON.stringify(servers.ready.map((entry) => entry.id));
957
+ // Guardrail hooks need the same license and a Codex measured with them
958
+ // (0.166.0+); like the pack they never block the launch (spec extensions FR6).
959
+ const guardrails = supportsCodexHooks(compatibility.version)
960
+ ? await writeCodexGuardrails({
961
+ root,
962
+ packageRoot,
963
+ executable,
964
+ cwd: launchPlan.effectiveCwd,
965
+ profile: launchPlan.profile,
966
+ environment,
967
+ }).catch(() => null)
968
+ : null;
969
+ if (guardrails !== null) {
970
+ environment[CODEX_HOOKS_ENV] = guardrails.value;
971
+ process.stderr.write(`${guardrails.line}\n`);
972
+ }
973
+ }
974
+ // The worker role (spec aisac-engineering-manager FR1, D14) needs the license the
975
+ // pack confirmed and a Codex measured with it; it never blocks the launch. A name
976
+ // another live session of the room has stops it here, before any host starts.
977
+ /** @type {Awaited<ReturnType<typeof prepareRole>> | null} */
978
+ let role = null;
979
+ if (launchOptions.role != null) {
980
+ const locale = resolvePackLocale(await readStoredLocale(root), process.env);
981
+ try {
982
+ role = await registerRole({
983
+ root,
984
+ request: launchOptions.role,
985
+ host: { name: 'codex', version: compatibility.version },
986
+ cwd: launchPlan.effectiveCwd,
987
+ locale,
988
+ licensed: engineering.codex != null,
989
+ qualified: supportsWorkerRole(compatibility.version),
990
+ });
991
+ } catch (error) {
992
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
993
+ throw error;
994
+ }
995
+ process.stderr.write(`${roleLaunchLine(role, locale)}\n`);
996
+ if (role.active) Object.assign(environment, workerEnvironment(role, packageRoot));
997
+ }
657
998
  environment.AI_BRAIN_MCP_SERVER = MCP_ALIAS;
658
999
  environment.CODEX_BIN = executable;
659
1000
  environment.CODEX_MONITOR_COMMAND = monitor;
@@ -671,19 +1012,34 @@ export async function launchCodex(config, root, args) {
671
1012
  environment.CODEX_CONTEXT_TELEMETRY_ENABLED = validated.telemetry?.enabled === true ? '1' : '0';
672
1013
  environment.CODEX_CONTEXT_TELEMETRY_DISCLOSED =
673
1014
  validated.telemetry?.enabled === true && validated.telemetry?.disclosedAt != null ? '1' : '0';
674
- if (validated.schemaVersion === 2 && validated.context !== undefined) {
675
- environment.CODEX_CONTEXT_POLICY_JSON = codexPolicyJson(validated.context);
676
- } else {
677
- delete environment.CODEX_CONTEXT_POLICY_JSON;
1015
+ /** Undo what this launch registered and wrote, when no host will run. */
1016
+ const abandon = async () => {
1017
+ await closeRole(role);
1018
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
1019
+ };
1020
+ /** @type {import('node:child_process').ChildProcess} */
1021
+ let child;
1022
+ try {
1023
+ if (validated.schemaVersion === 2 && validated.context !== undefined) {
1024
+ environment.CODEX_CONTEXT_POLICY_JSON = codexPolicyJson(validated.context);
1025
+ } else {
1026
+ delete environment.CODEX_CONTEXT_POLICY_JSON;
1027
+ }
1028
+ child = spawn(node, [terminal, '--', ...launchPlan.nativeArgs], {
1029
+ cwd: process.cwd(),
1030
+ env: environment,
1031
+ stdio: 'inherit',
1032
+ });
1033
+ } catch (error) {
1034
+ await abandon();
1035
+ throw error;
678
1036
  }
679
- const child = spawn(node, [terminal, '--', ...launchPlan.nativeArgs], {
680
- cwd: process.cwd(),
681
- env: environment,
682
- stdio: 'inherit',
683
- });
684
1037
  // Listen for exit before any await, so a child that exits at once is not missed.
685
- const finished = waitForChild(child, directory);
686
- await recordChild(directory, child.pid);
1038
+ const finished = waitForChild(child, directory).then(async (code) => {
1039
+ await closeRole(role);
1040
+ return code;
1041
+ });
1042
+ await recordChild(directory, child.pid, launchHost);
687
1043
  return finished;
688
1044
  }
689
1045