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

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.
@@ -534,6 +534,10 @@ async function main() {
534
534
  };
535
535
  process.once('SIGINT', shutdown);
536
536
  process.once('SIGTERM', shutdown);
537
+ // Closing the terminal sends SIGHUP (the kernel to the foreground group, and the
538
+ // launcher forwards it). Without a handler Node exits at once, skipping cleanup and
539
+ // leaving the detached monitor group (monitor, compaction proxy, app-server) running.
540
+ process.once('SIGHUP', shutdown);
537
541
 
538
542
  initialGeneration = spawnMonitor();
539
543
 
@@ -16,7 +16,7 @@ export const MAX_LOG_FILES = 3;
16
16
  const LOCK_WAIT_MS = 250;
17
17
  const LOCK_STALE_MS = 30_000;
18
18
  const ADMISSION_MS = 60 * 60 * 1000;
19
- export const ADAPTER_VERSION = '0.4.0-beta.30';
19
+ export const ADAPTER_VERSION = '0.4.0-beta.32';
20
20
  const MAX_DIAGNOSTIC_COUNT = 10_000_000;
21
21
  const MAX_DIAGNOSTIC_BYTES = 128 * 1024 * 1024;
22
22
  const CHECKPOINT_BACKENDS = new Set(['native_store', 'private_file']);
package/dist/cli.mjs CHANGED
@@ -34,7 +34,13 @@ import {
34
34
  tokenFailureGuide,
35
35
  tokenPromptGuide,
36
36
  } from './token-guide.mjs';
37
- import { codexPolicyJson, makePolicy, publicPolicy, isProfile } from './policy.mjs';
37
+ import {
38
+ codexPolicyJson,
39
+ disclosureAnswerAccepted,
40
+ makePolicy,
41
+ publicPolicy,
42
+ isProfile,
43
+ } from './policy.mjs';
38
44
  import { readDiagnostics } from './claude-observation.mjs';
39
45
  import { readCodexDiagnostics } from './codex-diagnostics.mjs';
40
46
  import { checkEngineeringLicense, licenseLine, unavailableLicense } from './engineering.mjs';
@@ -87,15 +93,18 @@ import { anyFormatter } from './guardrails/format.mjs';
87
93
  import { readCodexGuardrails } from './guardrails-plugin.mjs';
88
94
  import { codexHooksStatus, supportsCodexHooks } from './codex-hooks.mjs';
89
95
  import { managerDoctorLine, managerDoctorSection, takeRoleFlags } from './manager/launch-role.mjs';
96
+ import { resourcesDoctorLine, resourcesDoctorSection, runResources } from './resources.mjs';
90
97
  import { WORKERS_USAGE, workersCommand } from './manager/workers-cli.mjs';
91
98
  import {
99
+ describeClientNotConfigured,
100
+ describeMissingSetupClient,
92
101
  describePermissionError,
93
102
  describeRoleError,
94
103
  launchFeedbackLocale,
95
104
  } from './launch-feedback.mjs';
96
105
  import { parseCodexLaunchArgs } from './codex-permissions.mjs';
97
106
 
98
- const VERSION = '0.4.0-beta.30';
107
+ const VERSION = '0.4.0-beta.32';
99
108
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
100
109
  const COMMAND = 'aisac';
101
110
  /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
@@ -106,7 +115,7 @@ const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
106
115
 
107
116
  function usage() {
108
117
  console.log(
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.`,
118
+ `${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} resources [--json] [--sizes]\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
119
  );
111
120
  console.log(
112
121
  '`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.',
@@ -610,28 +619,41 @@ async function disclosureAccepted(
610
619
  const rl = createInterface({ input: stdin, output: stdout });
611
620
  try {
612
621
  const answer = await rl.question(`${disclosure} Type ACCEPT to continue: `);
613
- return answer.trim() === 'ACCEPT';
622
+ return disclosureAnswerAccepted(answer);
614
623
  } finally {
615
624
  rl.close();
616
625
  }
617
626
  }
618
627
 
619
628
  /**
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.
629
+ * Whether a native client is usable from PATH. Codex also needs `node`, the same pair
630
+ * the explicit `--client codex` path checks; a managed Codex needs only `node`.
631
+ * @param {'claude' | 'codex'} host @param {boolean} [managedCodex]
632
+ */
633
+ function nativeClientFound(host, managedCodex = false) {
634
+ if (host === 'claude') return resolveNative('claude') !== null;
635
+ return (managedCodex || resolveNative('codex') !== null) && resolveNative('node') !== null;
636
+ }
637
+
638
+ /**
639
+ * Client selection when `--client` is omitted: the native clients found on PATH.
622
640
  * @returns {'claude' | 'codex' | 'both' | null}
623
641
  */
624
642
  function detectedClients(managedCodex = false) {
625
- const hasClaude = resolveNative('claude') !== null;
626
- const hasCodex =
627
- (managedCodex || resolveNative('codex') !== null) && resolveNative('node') !== null;
643
+ const hasClaude = nativeClientFound('claude');
644
+ const hasCodex = nativeClientFound('codex', managedCodex);
628
645
  if (hasClaude && hasCodex) return 'both';
629
646
  if (hasClaude) return 'claude';
630
647
  return hasCodex ? 'codex' : null;
631
648
  }
632
649
 
633
- /** @param {string | undefined} requested @param {boolean} [managedCodex] @returns {'claude' | 'codex' | 'both'} */
634
- function setupClients(requested, managedCodex = false) {
650
+ /**
651
+ * When setup found only one client, it says which one it left out and how to add it
652
+ * later (spec aisac-host-upgrade-resilience, contract 10).
653
+ * @param {string | undefined} requested @param {boolean} managedCodex @param {'pt-BR' | 'en'} locale
654
+ * @returns {'claude' | 'codex' | 'both'}
655
+ */
656
+ function setupClients(requested, managedCodex, locale) {
635
657
  if (requested !== undefined) {
636
658
  if (requested !== 'claude' && requested !== 'codex' && requested !== 'both')
637
659
  throw new Error('invalid_client');
@@ -640,6 +662,7 @@ function setupClients(requested, managedCodex = false) {
640
662
  const detected = detectedClients(managedCodex);
641
663
  if (detected === null) throw new Error('no_native_client_found');
642
664
  console.log(`Clients detected on PATH: ${detected} (pass --client to choose).`);
665
+ if (detected !== 'both') console.log(describeMissingSetupClient(detected, locale));
643
666
  return detected;
644
667
  }
645
668
 
@@ -944,7 +967,8 @@ async function setup(args) {
944
967
  if (localOptOut) return disableTelemetryLocally(previous);
945
968
  const platform = platformCheck();
946
969
  if (!platform.ok) throw new Error(`${platform.code}:${platform.message}`);
947
- const clients = setupClients(option(args, '--client'), release.hostCodex === 'managed');
970
+ const locale = resolvePackLocale(lang ?? (await readStoredLocale(stateRoot())));
971
+ const clients = setupClients(option(args, '--client'), release.hostCodex === 'managed', locale);
948
972
  if (
949
973
  clients === 'codex' &&
950
974
  (option(args, '--claude-shadow') !== undefined ||
@@ -955,7 +979,6 @@ async function setup(args) {
955
979
  throw new Error('host_claude_requires_claude_client');
956
980
  if (clients === 'claude' && release.hostCodex !== undefined)
957
981
  throw new Error('host_codex_requires_codex_client');
958
- const locale = resolvePackLocale(lang ?? (await readStoredLocale(stateRoot())));
959
982
  // The hosts are checked before the disclosure and the token (spec
960
983
  // aisac-host-upgrade-resilience C7, C8): an incompatible host costs the user neither.
961
984
  const preflight = await preflightSetupHosts(clients, release, locale);
@@ -1385,6 +1408,8 @@ async function doctor(json) {
1385
1408
  codexCompatibility?.status === 'qualified' ||
1386
1409
  codexCompatibility?.status === 'protocol_match',
1387
1410
  }).catch(() => null),
1411
+ // Machine resources (spec aisac-engineering-resources FR1): counts only, no worktree work.
1412
+ resources: await resourcesDoctorSection({ root: stateRoot() }).catch(() => null),
1388
1413
  paidOrPilot: probe?.ok
1389
1414
  ? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
1390
1415
  : config
@@ -1396,6 +1421,7 @@ async function doctor(json) {
1396
1421
  console.log(result);
1397
1422
  for (const line of releaseDoctorLines(result)) console.log(line);
1398
1423
  console.log(managerDoctorLine(result.manager));
1424
+ console.log(resourcesDoctorLine(result.resources));
1399
1425
  }
1400
1426
  if (!platform.ok || !config || !probe?.ok || !nativeReady) process.exitCode = 1;
1401
1427
  }
@@ -1548,6 +1574,15 @@ async function main(argv) {
1548
1574
  validateOptions(rest, new Set(['--json']), new Set());
1549
1575
  return doctor(rest.includes('--json'));
1550
1576
  }
1577
+ if (command === 'resources') {
1578
+ const root = stateRoot();
1579
+ return runResources(rest, {
1580
+ root,
1581
+ cwd: process.cwd(),
1582
+ locale: resolvePackLocale(await readStoredLocale(root), process.env),
1583
+ write: (line) => console.log(line),
1584
+ });
1585
+ }
1551
1586
  if (command === 'status') {
1552
1587
  validateOptions(rest, new Set(['--json']), new Set());
1553
1588
  return status(rest.includes('--json'));
@@ -1684,8 +1719,12 @@ async function main(argv) {
1684
1719
  }
1685
1720
  if (config.schemaVersion === 2 && config.disclosureVersion !== DISCLOSURE_VERSION)
1686
1721
  throw new Error('disclosure_outdated');
1687
- if (config.clientSelection !== command && config.clientSelection !== 'both')
1688
- throw new Error('client_not_configured');
1722
+ if (config.clientSelection !== command && config.clientSelection !== 'both') {
1723
+ const locale = resolvePackLocale(await readStoredLocale(stateRoot()), process.env);
1724
+ throw Object.assign(new Error('client_not_configured'), {
1725
+ guide: describeClientNotConfigured(command, nativeClientFound(command), locale),
1726
+ });
1727
+ }
1689
1728
  // The native executable is authoritative. The stored setup version is
1690
1729
  // metadata only, so patch updates do not block a fresh compatibility check.
1691
1730
  if (command === 'codex' && typeof config.codexVersion !== 'string')
@@ -14,7 +14,7 @@
14
14
  * launch or treat a failure as licensed.
15
15
  */
16
16
 
17
- import { createHash, createPublicKey, verify } from 'node:crypto';
17
+ import { createHash, createPublicKey, randomBytes, verify } from 'node:crypto';
18
18
  import { constants } from 'node:fs';
19
19
  import {
20
20
  lstat,
@@ -37,6 +37,13 @@ import {
37
37
  unavailableReasonFor,
38
38
  } from './engineering.mjs';
39
39
  import { atomicJson } from './state.mjs';
40
+ import {
41
+ createStartLookup,
42
+ currentProcessStart,
43
+ isLaunchRunning,
44
+ readDescendantSnapshot,
45
+ snapshotHasLiveMember,
46
+ } from './process-snapshot.mjs';
40
47
  import {
41
48
  AGENT_NAME,
42
49
  CODEX_AGENTS_DIRECTORY,
@@ -876,26 +883,138 @@ export async function prepareEngineeringPack(input) {
876
883
  * skip while one is live, so the version it is about to run is never removed.
877
884
  */
878
885
 
886
+ /**
887
+ * What `launch.json` records about one launch (spec
888
+ * aisac-engineering-resources FR2). A schema 1 record has `role: 'unknown'`
889
+ * and no session id.
890
+ * @typedef {object} LaunchRecord
891
+ * @property {1} schemaVersion kept at 1: the previous client skips any other value, and its garbage collection would then miss a launch in use after a rollback
892
+ * @property {number} launcherPid
893
+ * @property {number | null} childPid
894
+ * @property {LaunchHost | null} host
895
+ * @property {string | null} sessionId 128-bit random, hex
896
+ * @property {'solo' | 'manager' | 'worker' | 'unknown'} role
897
+ * @property {string | null} roomId
898
+ * @property {string | null} roomLabel the repository folder or room name, never a path
899
+ * @property {string | null} cwd
900
+ * @property {string | null} launcherStartTime pid start token, read as the bus reads liveness
901
+ * @property {string | null} childStartTime
902
+ * @property {string | null} startedAt
903
+ */
904
+ const SESSION_ID_PATTERN = /^[0-9a-f]{32}$/u;
905
+ const ROOM_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
906
+ const LAUNCH_ROLES = Object.freeze(['solo', 'manager', 'worker']);
907
+ const LAUNCH_CWD_MAX = 1024;
908
+ const START_TIME_MAX = 80;
909
+ const ROOM_LABEL_MAX = 64;
910
+
911
+ /** @param {unknown} value @param {number} limit @returns {string | null} */
912
+ function boundedString(value, limit) {
913
+ return typeof value === 'string' && value.length > 0 && value.length <= limit ? value : null;
914
+ }
915
+
916
+ /**
917
+ * Parse a launch marker (schema 1; the extended fields are optional); null when it is not one. An extended
918
+ * field that is malformed reads as absent: the record still counts as a launch.
919
+ * @param {unknown} value
920
+ * @returns {LaunchRecord | null}
921
+ */
922
+ export function parseLaunchRecord(value) {
923
+ if (!isRecord(value) || value.schemaVersion !== 1) return null;
924
+ if (!isPid(value.launcherPid)) return null;
925
+ if (value.childPid !== null && !isPid(value.childPid)) return null;
926
+ // The extended form is told by its session id; a record without one is a plain
927
+ // launch marker whose extra fields, if any, are not read.
928
+ const sessionId =
929
+ typeof value.sessionId === 'string' && SESSION_ID_PATTERN.test(value.sessionId)
930
+ ? value.sessionId
931
+ : null;
932
+ const extended = sessionId !== null;
933
+ const role =
934
+ extended && LAUNCH_ROLES.includes(/** @type {string} */ (value.role))
935
+ ? /** @type {'solo' | 'manager' | 'worker'} */ (value.role)
936
+ : 'unknown';
937
+ return {
938
+ schemaVersion: 1,
939
+ launcherPid: /** @type {number} */ (value.launcherPid),
940
+ childPid: /** @type {number | null} */ (value.childPid),
941
+ host: launchHostOf(value.host),
942
+ sessionId,
943
+ role,
944
+ roomId:
945
+ extended && typeof value.roomId === 'string' && ROOM_ID_PATTERN.test(value.roomId)
946
+ ? value.roomId
947
+ : null,
948
+ roomLabel: extended ? boundedString(value.roomLabel, ROOM_LABEL_MAX) : null,
949
+ cwd: extended ? boundedString(value.cwd, LAUNCH_CWD_MAX) : null,
950
+ launcherStartTime: extended ? boundedString(value.launcherStartTime, START_TIME_MAX) : null,
951
+ childStartTime: extended ? boundedString(value.childStartTime, START_TIME_MAX) : null,
952
+ startedAt: boundedString(value.startedAt, 40),
953
+ };
954
+ }
955
+
956
+ /** The working directory, or null when it was removed under the process. */
957
+ function currentDirectory() {
958
+ try {
959
+ return process.cwd();
960
+ } catch {
961
+ return null;
962
+ }
963
+ }
964
+
965
+ /** @type {string | null | undefined} */
966
+ let ownStartTime;
967
+
879
968
  /**
880
969
  * Record who owns a launch directory, so a later launch can sweep it once
881
- * both processes are gone (spec FR4 step 7), and which host it runs.
970
+ * both processes are gone (spec FR4 step 7), which host it runs, and the
971
+ * session identity: a random id, the role, the room, the working directory
972
+ * and the start times of the launcher and the host. Each write keeps the id,
973
+ * role, room and start of the previous one unless the caller names a new value.
882
974
  * @param {string} directory
883
- * @param {{ launcherPid: number, childPid: number | null, host?: LaunchHost }} owners
975
+ * @param {{ launcherPid: number, childPid: number | null, host?: LaunchHost, role?: 'solo' | 'manager' | 'worker', roomId?: string | null, roomLabel?: string | null, cwd?: string }} owners
976
+ * @returns {Promise<LaunchRecord>} what was written
884
977
  */
885
978
  export async function writeLaunchMarker(directory, owners) {
886
979
  const path = join(directory, LAUNCH_MARKER_FILE);
887
980
  const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
981
+ const previous = parseLaunchRecord(await readSmallStateJson(path));
982
+ if (owners.launcherPid === process.pid && ownStartTime === undefined)
983
+ ownStartTime = currentProcessStart(process.pid);
984
+ const cwd = boundedString(owners.cwd ?? previous?.cwd ?? currentDirectory(), LAUNCH_CWD_MAX);
985
+ const written = {
986
+ schemaVersion: 1,
987
+ launcherPid: owners.launcherPid,
988
+ childPid: owners.childPid,
989
+ ...(owners.host === undefined && previous?.host == null
990
+ ? {}
991
+ : { host: owners.host ?? previous?.host }),
992
+ sessionId: previous?.sessionId ?? randomBytes(16).toString('hex'),
993
+ role:
994
+ owners.role ?? (previous === null || previous.role === 'unknown' ? 'solo' : previous.role),
995
+ roomId: owners.roomId === undefined ? (previous?.roomId ?? null) : owners.roomId,
996
+ roomLabel:
997
+ owners.roomLabel === undefined
998
+ ? (previous?.roomLabel ?? null)
999
+ : boundedString(owners.roomLabel, ROOM_LABEL_MAX),
1000
+ cwd,
1001
+ launcherStartTime:
1002
+ owners.launcherPid === process.pid
1003
+ ? (ownStartTime ?? null)
1004
+ : currentProcessStart(owners.launcherPid),
1005
+ childStartTime: owners.childPid === null ? null : currentProcessStart(owners.childPid),
1006
+ startedAt: previous?.startedAt ?? new Date().toISOString(),
1007
+ };
888
1008
  try {
889
- await writeFile(
890
- temp,
891
- `${JSON.stringify({ schemaVersion: 1, ...owners, startedAt: new Date().toISOString() })}\n`,
892
- { mode: 0o600, flag: 'wx' },
893
- );
1009
+ await writeFile(temp, `${JSON.stringify(written)}\n`, { mode: 0o600, flag: 'wx' });
894
1010
  await rename(temp, path);
895
1011
  } catch (error) {
896
1012
  await unlink(temp).catch(() => undefined);
897
1013
  throw error;
898
1014
  }
1015
+ const record = parseLaunchRecord(written);
1016
+ if (record === null) throw new Error('launch_marker_invalid');
1017
+ return record;
899
1018
  }
900
1019
 
901
1020
  /** @param {number} pid */
@@ -913,14 +1032,37 @@ function isPid(value) {
913
1032
  return Number.isSafeInteger(value) && /** @type {number} */ (value) > 0;
914
1033
  }
915
1034
 
1035
+ /**
1036
+ * Which of a launch's two processes still run (`isLaunchRunning`: pid, and the
1037
+ * start time where the record has one).
1038
+ * @param {LaunchRecord} record
1039
+ * @param {(pid: number) => boolean} alive
1040
+ * @param {import('./process-snapshot.mjs').StartLookup} startOf
1041
+ */
1042
+ async function launchRunning(record, alive, startOf) {
1043
+ const launcher = await isLaunchRunning(
1044
+ record.launcherPid,
1045
+ record.launcherStartTime,
1046
+ alive,
1047
+ startOf,
1048
+ );
1049
+ const child = await isLaunchRunning(record.childPid, record.childStartTime, alive, startOf);
1050
+ return { launcher, child, any: launcher || child };
1051
+ }
1052
+
916
1053
  /**
917
1054
  * Remove launch directories left by crashed launches: only directories with
918
1055
  * a marker whose launcher and child are both gone. Never throws.
919
1056
  * @param {string} root
920
1057
  * @param {(pid: number) => boolean} [alive]
1058
+ * @param {import('./process-snapshot.mjs').StartLookup} [startOf] the start token of a live pid
921
1059
  * @returns {Promise<number>} directories removed
922
1060
  */
923
- export async function sweepStaleLaunches(root, alive = processAlive) {
1061
+ export async function sweepStaleLaunches(
1062
+ root,
1063
+ alive = processAlive,
1064
+ startOf = createStartLookup(),
1065
+ ) {
924
1066
  const runtime = join(root, 'runtime');
925
1067
  let entries;
926
1068
  try {
@@ -932,12 +1074,12 @@ export async function sweepStaleLaunches(root, alive = processAlive) {
932
1074
  for (const entry of entries) {
933
1075
  if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
934
1076
  const directory = join(runtime, entry.name);
935
- const marker = await readSmallStateJson(join(directory, LAUNCH_MARKER_FILE));
936
- if (!isRecord(marker) || marker.schemaVersion !== 1 || !isPid(marker.launcherPid)) continue;
937
- const launcherPid = /** @type {number} */ (marker.launcherPid);
938
- if (marker.childPid !== null && !isPid(marker.childPid)) continue;
939
- const childPid = /** @type {number | null} */ (marker.childPid);
940
- if (alive(launcherPid) || (childPid !== null && alive(childPid))) continue;
1077
+ const record = parseLaunchRecord(await readSmallStateJson(join(directory, LAUNCH_MARKER_FILE)));
1078
+ if (record === null) continue;
1079
+ if ((await launchRunning(record, alive, startOf)).any) continue;
1080
+ // A process the launch's snapshot lists is still running: keep the record, so
1081
+ // a later cleanup can attribute it (FR2).
1082
+ if (await snapshotHasLiveMember(directory, alive, startOf)) continue;
941
1083
  try {
942
1084
  await rm(directory, { recursive: true, force: true });
943
1085
  removed += 1;
@@ -957,7 +1099,8 @@ export async function sweepStaleLaunches(root, alive = processAlive) {
957
1099
  * @returns {Promise<number>}
958
1100
  */
959
1101
  export async function liveLaunchCount(root, alive = processAlive) {
960
- await sweepStaleLaunches(root, alive);
1102
+ const startOf = createStartLookup();
1103
+ await sweepStaleLaunches(root, alive, startOf);
961
1104
  const runtime = join(root, 'runtime');
962
1105
  let entries;
963
1106
  try {
@@ -968,11 +1111,11 @@ export async function liveLaunchCount(root, alive = processAlive) {
968
1111
  let live = 0;
969
1112
  for (const entry of entries) {
970
1113
  if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
971
- const marker = await readSmallStateJson(join(runtime, entry.name, LAUNCH_MARKER_FILE));
972
- if (!isRecord(marker) || marker.schemaVersion !== 1 || !isPid(marker.launcherPid)) continue;
973
- const childPid = isPid(marker.childPid) ? /** @type {number} */ (marker.childPid) : null;
974
- if (alive(/** @type {number} */ (marker.launcherPid)) || (childPid !== null && alive(childPid)))
975
- live += 1;
1114
+ const record = parseLaunchRecord(
1115
+ await readSmallStateJson(join(runtime, entry.name, LAUNCH_MARKER_FILE)),
1116
+ );
1117
+ if (record === null) continue;
1118
+ if ((await launchRunning(record, alive, startOf)).any) live += 1;
976
1119
  }
977
1120
  return live;
978
1121
  }
@@ -995,7 +1138,8 @@ function launchHostOf(value) {
995
1138
  * @returns {Promise<LaunchHost[]>}
996
1139
  */
997
1140
  export async function liveLaunchHosts(root, alive = processAlive) {
998
- await sweepStaleLaunches(root, alive);
1141
+ const startOf = createStartLookup();
1142
+ await sweepStaleLaunches(root, alive, startOf);
999
1143
  const runtime = join(root, 'runtime');
1000
1144
  let entries;
1001
1145
  try {
@@ -1007,16 +1151,62 @@ export async function liveLaunchHosts(root, alive = processAlive) {
1007
1151
  const hosts = [];
1008
1152
  for (const entry of entries) {
1009
1153
  if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
1010
- const marker = await readSmallStateJson(join(runtime, entry.name, LAUNCH_MARKER_FILE));
1011
- if (!isRecord(marker) || marker.schemaVersion !== 1 || !isPid(marker.launcherPid)) continue;
1012
- const childPid = isPid(marker.childPid) ? /** @type {number} */ (marker.childPid) : null;
1013
- if (
1014
- !alive(/** @type {number} */ (marker.launcherPid)) &&
1015
- (childPid === null || !alive(childPid))
1016
- )
1017
- continue;
1018
- const host = launchHostOf(marker.host);
1154
+ const record = parseLaunchRecord(
1155
+ await readSmallStateJson(join(runtime, entry.name, LAUNCH_MARKER_FILE)),
1156
+ );
1157
+ if (record === null) continue;
1158
+ if (!(await launchRunning(record, alive, startOf)).any) continue;
1159
+ const host = record.host;
1019
1160
  if (host !== null) hosts.push(host);
1020
1161
  }
1021
1162
  return hosts;
1022
1163
  }
1164
+
1165
+ /**
1166
+ * One launch directory as `aisac resources` reads it (FR1, FR2).
1167
+ * @typedef {object} LaunchEntry
1168
+ * @property {string} name the directory name, `claude-` or `codex-` and six characters
1169
+ * @property {string} directory
1170
+ * @property {LaunchRecord} record
1171
+ * @property {boolean} live the launcher or the host still runs (pid and start time)
1172
+ * @property {boolean} launcherRunning
1173
+ * @property {boolean} childRunning
1174
+ * @property {import('./process-snapshot.mjs').SnapshotMember[]} members the snapshot's members
1175
+ */
1176
+
1177
+ /**
1178
+ * Every launch directory with a readable marker, live or not, and its snapshot.
1179
+ * Read-only: nothing is swept. Never throws.
1180
+ * @param {string} root
1181
+ * @param {(pid: number) => boolean} [alive]
1182
+ * @param {import('./process-snapshot.mjs').StartLookup} [startOf]
1183
+ * @returns {Promise<LaunchEntry[]>}
1184
+ */
1185
+ export async function listLaunches(root, alive = processAlive, startOf = createStartLookup()) {
1186
+ const runtime = join(root, 'runtime');
1187
+ let entries;
1188
+ try {
1189
+ entries = await readdir(runtime, { withFileTypes: true });
1190
+ } catch {
1191
+ return [];
1192
+ }
1193
+ /** @type {LaunchEntry[]} */
1194
+ const launches = [];
1195
+ for (const entry of entries) {
1196
+ if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
1197
+ const directory = join(runtime, entry.name);
1198
+ const record = parseLaunchRecord(await readSmallStateJson(join(directory, LAUNCH_MARKER_FILE)));
1199
+ if (record === null) continue;
1200
+ const running = await launchRunning(record, alive, startOf);
1201
+ launches.push({
1202
+ name: entry.name,
1203
+ directory,
1204
+ record,
1205
+ live: running.any,
1206
+ launcherRunning: running.launcher,
1207
+ childRunning: running.child,
1208
+ members: await readDescendantSnapshot(directory),
1209
+ });
1210
+ }
1211
+ return launches;
1212
+ }
@@ -361,10 +361,13 @@ export const MCP_CATALOG = Object.freeze([
361
361
  'pt-BR':
362
362
  'As chaves dos provedores são gerenciadas só na página de chaves do Studio (https://studio.aisac.agency/?studio=keys): uma chave digitada numa chamada de ferramenta ficaria no transcript da sessão.',
363
363
  },
364
+ // Since mcp-creatives ADR-0053 (2026-12-01) the consent page approves with the
365
+ // Studio session of the browser the host opens; a personal token stays as the
366
+ // fallback. Without a session there, the login cannot finish.
364
367
  loginNote: {
365
- en: 'The Studio login needs an account with access (it comes with the AISAC Engineering purchase). Register your provider keys on the Studio keys page before the first generation; the server never takes a key as an argument.',
368
+ en: 'Before you log in, open the Studio in your default browser: from the AISAC Mothership, or with the e-mail of an account with access (it comes with the AISAC Engineering purchase). When the host opens the authorization page, click “Aprovar”: no token to paste. Register your provider keys on the Studio keys page before the first generation; the server never takes a key as an argument.',
366
369
  'pt-BR':
367
- 'O login do Studio exige uma conta com acesso (vem com a compra do AISAC Engineering). Registre as chaves dos seus provedores na página de chaves do Studio antes da primeira geração; o servidor nunca recebe uma chave como argumento.',
370
+ 'Antes do login, abra o Studio no seu navegador padrão: pela AISAC Mothership, ou com o e-mail de uma conta com acesso (vem com a compra do AISAC Engineering). Quando o host abrir a página de autorização, clique em “Aprovar”: não há token para colar. Registre as chaves dos seus provedores na página de chaves do Studio antes da primeira geração; o servidor nunca recebe uma chave como argumento.',
368
371
  },
369
372
  description: {
370
373
  en: 'The AISAC Creatives Studio: images, narration and video generated with your own provider keys, plus voices, influencer profiles and reel productions.',
@@ -275,6 +275,66 @@ export function describePermissionError(error, args, locale) {
275
275
  return null;
276
276
  }
277
277
 
278
+ /** @param {'claude' | 'codex'} host */
279
+ function hostName(host) {
280
+ return host === 'claude' ? 'Claude Code' : 'Codex';
281
+ }
282
+
283
+ /** @param {'claude' | 'codex'} host */
284
+ function otherHost(host) {
285
+ return host === 'claude' ? 'codex' : 'claude';
286
+ }
287
+
288
+ /**
289
+ * Guide for `aisac claude|codex` when the setup covers only the other host
290
+ * (spec aisac-host-upgrade-resilience, contract 11).
291
+ * @param {'claude' | 'codex'} host the host the user asked to launch
292
+ * @param {boolean} hostFound whether that host is on PATH now
293
+ * @param {FeedbackLocale} locale
294
+ */
295
+ export function describeClientNotConfigured(host, hostFound, locale) {
296
+ const name = hostName(host);
297
+ const configured = hostName(otherHost(host));
298
+ const managed = `aisac setup --client both --host-${host} managed`;
299
+ if (locale === 'pt-BR') {
300
+ const first = `O \`aisac setup\` deste computador configurou só o ${configured}, por isso o \`aisac ${host}\` não foi iniciado.`;
301
+ const again = 'O setup pede o ACCEPT e o login de novo.';
302
+ return hostFound
303
+ ? [
304
+ first,
305
+ `Isso acontece quando o ${name} é instalado depois do setup. Rode \`aisac setup --client both\` para adicionar o ${name} e manter o ${configured}. ${again}`,
306
+ ].join('\n')
307
+ : [
308
+ first,
309
+ `O ${name} não foi encontrado no PATH. Instale-o e rode \`aisac setup --client both\`, ou deixe o setup instalar a cópia privada do aisac com \`${managed}\`. ${again}`,
310
+ ].join('\n');
311
+ }
312
+ const first = `This computer's \`aisac setup\` covers ${configured} only, so \`aisac ${host}\` was not started.`;
313
+ const again = 'Setup asks for ACCEPT and a login again.';
314
+ return hostFound
315
+ ? [
316
+ first,
317
+ `This happens when ${name} is installed after setup. Run \`aisac setup --client both\` to add ${name} and keep ${configured}. ${again}`,
318
+ ].join('\n')
319
+ : [
320
+ first,
321
+ `${name} was not found on PATH. Install it and run \`aisac setup --client both\`, or let setup install aisac's private copy with \`${managed}\`. ${again}`,
322
+ ].join('\n');
323
+ }
324
+
325
+ /**
326
+ * Setup's line when it selected the clients itself and found only one
327
+ * (spec aisac-host-upgrade-resilience, contract 10).
328
+ * @param {'claude' | 'codex'} found the host setup is about to configure
329
+ * @param {FeedbackLocale} locale
330
+ */
331
+ export function describeMissingSetupClient(found, locale) {
332
+ const missing = otherHost(found);
333
+ return locale === 'pt-BR'
334
+ ? `O ${hostName(missing)} não foi encontrado no PATH, então este setup configura só o ${hostName(found)}. Para usar o \`aisac ${missing}\` depois, instale o ${hostName(missing)} e rode \`aisac setup --client both\`.`
335
+ : `${hostName(missing)} was not found on PATH, so this setup covers ${hostName(found)} only. To use \`aisac ${missing}\` later, install ${hostName(missing)} and run \`aisac setup --client both\`.`;
336
+ }
337
+
278
338
  /**
279
339
  * The launch-feedback locale follows the saved pack choice. An unset choice
280
340
  * uses English as required for command-line errors.