@awebai/oats 0.52.0 → 0.53.0

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 (98) hide show
  1. package/README.md +2 -1
  2. package/bin/oats.mjs +304 -92
  3. package/docs/capabilities.md +66 -4
  4. package/docs/configuration.md +66 -3
  5. package/docs/desktop-cli-api.md +673 -58
  6. package/docs/desktop-instance-start.md +25 -12
  7. package/docs/execution-targets.md +1 -0
  8. package/docs/implementation.md +175 -11
  9. package/docs/integrations.md +6 -3
  10. package/docs/knowledge.md +2 -2
  11. package/docs/macos-test-runs.md +246 -0
  12. package/docs/official-catalog.md +5 -5
  13. package/docs/packages.md +14 -14
  14. package/docs/release-lane.md +210 -6
  15. package/docs/release-notes/v0.53.0.md +1274 -0
  16. package/docs/schedules.md +7 -1
  17. package/docs/souls-and-instances.md +237 -15
  18. package/docs/tui.md +453 -21
  19. package/docs/upgrading.md +298 -0
  20. package/docs/workspaces.md +3 -3
  21. package/lib/automations.mjs +22 -22
  22. package/lib/claim.mjs +93 -4
  23. package/lib/config-data.mjs +4 -1
  24. package/lib/core.mjs +569 -121
  25. package/lib/instance-events.mjs +19 -1
  26. package/lib/instance-git.mjs +39 -3
  27. package/lib/instance-inspect.mjs +5 -6
  28. package/lib/instance-lifecycle.mjs +145 -18
  29. package/lib/instance-resolution.mjs +59 -6
  30. package/lib/launch-preference.mjs +226 -15
  31. package/lib/local-edit.mjs +118 -0
  32. package/lib/packages.mjs +13 -4
  33. package/lib/pi-bridge.mjs +308 -0
  34. package/lib/refused-text.mjs +11 -0
  35. package/lib/remote.mjs +190 -25
  36. package/lib/resolve.mjs +2 -1
  37. package/lib/retained-after-retire.mjs +2 -2
  38. package/lib/retire-output.mjs +12 -1
  39. package/lib/schedule-host.mjs +6 -35
  40. package/lib/shell-word.mjs +13 -0
  41. package/lib/soul-launch-verbs.mjs +153 -0
  42. package/lib/stable-node.mjs +62 -0
  43. package/lib/teams-verbs.mjs +18 -46
  44. package/lib/workspace.mjs +49 -19
  45. package/package-catalog.json +4 -4
  46. package/package.json +2 -1
  47. package/packages/client/attach-exit.mjs +25 -0
  48. package/packages/client/cli-adapter.mjs +16 -3
  49. package/packages/client/cli-locator.mjs +2 -2
  50. package/packages/client/deployment-contract.mjs +4 -0
  51. package/packages/client/deployment-facts.mjs +71 -10
  52. package/packages/client/deployment-panel.mjs +49 -11
  53. package/packages/client/deployment-read-cli.mjs +7 -3
  54. package/packages/client/display-text.mjs +8 -2
  55. package/packages/client/instance-acts.mjs +46 -10
  56. package/packages/client/instance-events-contract.mjs +4 -2
  57. package/packages/client/instance-presentation.mjs +66 -2
  58. package/packages/client/instance-tree.mjs +23 -14
  59. package/packages/client/kernel-lines.mjs +31 -0
  60. package/packages/client/kernel-made.mjs +23 -0
  61. package/packages/client/launch-prompt-outcome.mjs +51 -16
  62. package/packages/client/lifecycle-contract.mjs +45 -4
  63. package/packages/client/liveness.mjs +14 -1
  64. package/packages/client/own-codes.mjs +31 -0
  65. package/packages/client/panel-views.mjs +18 -11
  66. package/packages/client/readiness-contract.mjs +3 -1
  67. package/packages/client/remote-address.mjs +34 -9
  68. package/packages/client/remote-identity-memory.mjs +94 -0
  69. package/packages/client/remote-roster.mjs +92 -6
  70. package/packages/client/session-attach.mjs +175 -0
  71. package/packages/client/spawn-apply-contract.mjs +16 -4
  72. package/packages/client/spawn-messages.mjs +26 -3
  73. package/packages/client/spawn-preview-cli.mjs +8 -2
  74. package/packages/client/spawn-preview-contract.mjs +5 -1
  75. package/packages/client/terminal-exec.mjs +21 -0
  76. package/packages/client/workspace-choices.mjs +95 -0
  77. package/packages/client/workspace-views.mjs +39 -3
  78. package/packages/record/README.md +21 -0
  79. package/packages/record/bin/setup.mjs +108 -15
  80. package/packages/tui/README.md +30 -12
  81. package/packages/tui/lib/actions.mjs +16 -1
  82. package/packages/tui/lib/client.mjs +32 -1
  83. package/packages/tui/lib/config.mjs +151 -0
  84. package/packages/tui/lib/main.mjs +117 -46
  85. package/packages/tui/lib/model.mjs +392 -0
  86. package/packages/tui/lib/read.mjs +473 -0
  87. package/packages/tui/lib/store.mjs +364 -0
  88. package/packages/tui/lib/term/keys.mjs +44 -0
  89. package/packages/tui/lib/term/screen.mjs +16 -4
  90. package/packages/tui/lib/term/text.mjs +60 -0
  91. package/packages/tui/lib/term/tty.mjs +13 -3
  92. package/packages/tui/lib/views/detail.mjs +46 -0
  93. package/packages/tui/lib/views/frame.mjs +230 -36
  94. package/packages/tui/lib/views/help.mjs +125 -13
  95. package/packages/tui/lib/views/instances.mjs +137 -0
  96. package/packages/tui/lib/views/scroll.mjs +19 -0
  97. package/packages/tui/lib/views/switcher.mjs +97 -0
  98. package/skills/oats-getting-started/SKILL.md +2 -2
package/bin/oats.mjs CHANGED
@@ -31,16 +31,18 @@ import {
31
31
  LAYERS, OATS_VERSION, manifestOperations, upgradeHomeMeta,
32
32
  capabilityManifests, capabilityTrust, capabilityExecutablePath,
33
33
  officialPackageCatalog, officialCatalogFile, officialCapabilityAliases, resolvedFromHome, resolvedFromPrepared, teamEnv, isWorkspaceHome, preWorkspaceHome, isCapturedHome, capturedHomeRefusal, composeInstanceAgentsMd, parseYamlNested, withConfigFile,
34
- findInstanceHome, findInstanceHomes, processScanInformation, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, instanceSoulDir, stableSoulId, preparedSoulIdOf, recordedKernelBin, launchConfigsAt, launchStartNotices, launchReportFor, explicitInstanceName, retireInstance, RETIRE_SELECTED_HOME, RETIRE_UNDER_CLAIM, inspectInstanceSession, inputInstanceSession, attachInstanceSession, startInstanceSession, defaultRepo, RELATIONS, validateLaunchConfig, validateLaunchConfigDefaults, renderLaunchRecipe, describeLaunchCommand, redactLaunchRecipe, withSafeTaskPrompt, LAUNCH_HARNESSES, planLaunch, redactLaunchCommand, restartInstanceSession,
34
+ findInstanceHome, findInstanceHomes, homeLaunchLayers, processScanInformation, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, instanceSoulDir, stableSoulId, preparedSoulIdOf, recordedKernelBin, launchConfigsAt, launchStartNotices, launchReportFor, explicitInstanceName, retireInstance, RETIRE_SELECTED_HOME, RETIRE_UNDER_CLAIM, inspectInstanceSession, inputInstanceSession, attachInstanceSession, startInstanceSession, defaultRepo, RELATIONS, validateLaunchConfig, validateLaunchConfigDefaults, renderLaunchRecipe, describeLaunchCommand, redactLaunchRecipe, withSafeTaskPrompt, LAUNCH_HARNESSES, planLaunch, redactLaunchCommand, restartInstanceSession,
35
35
  FAILED_SPAWN_BRANCH_LEFT, RETIRE_DELETE_BRANCH_REFUSED,
36
36
  } from "../lib/core.mjs";
37
37
  import {
38
38
  writeFileAtomic, LOCK_FILE, canonicalLock, readLock, readLockIfPresent, writeLock, resolvePackages, memoizedRemote,
39
39
  classifyPackageValue, parsePackageRequest } from "../lib/packages.mjs";
40
40
  import { harnessTrust } from "../lib/harness-trust-write.mjs";
41
- import { loadLocal, validateWorkspace, validateLocal, discoverPackageSouls, workspaceWarnings, memberRowByKey } from "../lib/workspace.mjs";
41
+ import { PI_BRIDGE, piBridgeFolders, piBridgeSkewWarnings, planPiBridges, piBridgePlanLines, piBridgeStepProblem, piBridgeFailure, kernelLookup, kernelLookupResult, planCliUpdate, bridgeLookup, bridgeLookupProblem } from "../lib/pi-bridge.mjs";
42
+ import { loadLocal, validateWorkspace, validateLocal, discoverPackageSouls, unlockedPackages, workspaceWarnings, memberRowByKey } from "../lib/workspace.mjs";
42
43
  import { discoveredTeamKeys, isTeamRefusal, localTeamsClosedProblem, recordedTeams, reportRows, soulKeyOf, soulTeams, teamKeyOf, teamModel } from "../lib/teams.mjs";
43
- import { launchLayers } from "../lib/launch-preference.mjs";
44
+ import { LAUNCH_KEY_UNCHECKED, LAUNCH_PREFERENCE_UNMATCHED, launchKeyQuoted, launchKeysUnmatched, launchLayers, soulLaunchCommand, unmatchedKeyMessage } from "../lib/launch-preference.mjs";
45
+ import { soulsOffered } from "../lib/instance-resolution.mjs";
44
46
  import { parseConfigData } from "../lib/config-data.mjs";
45
47
  import * as remoteModule from "../lib/remote.mjs";
46
48
  import { activateLocalInputs, localRevision } from "../lib/local-inputs.mjs";
@@ -51,11 +53,12 @@ import { tickTriggers } from "../lib/triggers.mjs";
51
53
  import * as A from "../lib/automations.mjs";
52
54
  import { parseEnvelopeText, unresolvedScheduleAttempts, scheduleScopeOf, listSchedules, describe as describeSchedule, testSchedule, addSchedule, updateSchedule, updateScheduleDescription, setEnabled as setScheduleEnabled, removeSchedule, runNow as runScheduleNow, reconcile as reconcileSchedule, tickHost, tickWorkspace, scopeAutomations, scheduleKind, registerWorkspace, unregisterWorkspace, readRegistry, schedulerStatus, saveWakeForHome, removeWakeForHome, wakeFromFlags, withHostLock, scheduleError, SCHEDULE_API } from "../lib/schedule.mjs";
53
55
  import { hostUnitFiles, hostUnitStatus, installHostUnit, uninstallHostUnit } from "../lib/schedule-host.mjs";
56
+ import { kernelNode, stableNode } from "../lib/stable-node.mjs";
54
57
  import { receiveAttachment, uploadAttachment, readStreamBounded, MAX_ATTACHMENT_BYTES } from "../lib/attachments.mjs";
55
58
 
56
59
  import { observeInstanceGit, diffInstanceFile } from "../lib/instance-git.mjs";
57
- import { planStop, applyStop, planRetire, descendantsOf, resolveInstance as resolveInstanceForCli, STOP_WARNINGS } from "../lib/instance-lifecycle.mjs";
58
- import { extraWorktreeLines, formatBytes, workRecoveryLines } from "../lib/retire-output.mjs";
60
+ import { planStop, applyStop, planRetire, retireDefaultsLine, stopClosingLine, descendantsOf, resolveInstance as resolveInstanceForCli, STOP_WARNINGS } from "../lib/instance-lifecycle.mjs";
61
+ import { extraWorktreeLines, formatBytes, warningLines, workRecoveryLines } from "../lib/retire-output.mjs";
59
62
  import { retainedRecoveryLines, retainedWorktreeLines, retainedWorktrees } from "../lib/retained-after-retire.mjs";
60
63
  const await_import_lifecycle = () => ({ resolveInstance: resolveInstanceForCli });
61
64
  import { homeTarget, soulTarget, isWorkspaceContext, inspectDocument, withComposedInstructions, readinessDocument, policyOf, policySoul, manifestMissingRequires, INSPECT_OPERATIONS_API } from "../lib/instance-inspect.mjs";
@@ -99,7 +102,7 @@ const OWN_ARGV_COMMANDS = new Set(["capture", "recall", "setup", "experimental",
99
102
  * probe) and in `status --json`, which a remote roster relays as the host's (feature
100
103
  * server-probe-features, lib/servers.mjs hostFeatures). ONE list for both, emitted at output
101
104
  * time, never stored. A name must pass hostFeatures's check (test/cli-json-contract.test.mjs). */
102
- const KERNEL_FEATURES = ["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources", "session-attach-detach-key", "lifecycle-kernel-codes", "schedule-run-warnings", "lifecycle-claim-stop", "launch-prompt-dev-channel"];
105
+ const KERNEL_FEATURES = ["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources", "session-attach-detach-key", "lifecycle-kernel-codes", "schedule-run-warnings", "lifecycle-claim-stop", "launch-prompt-dev-channel", "soul-launch", "retire-plan-own-worktree"];
103
106
  /** Commands `--server <id>` runs on a registered server. */
104
107
  const ROUTED_COMMANDS = new Set(["spawn", "retire", "status", "session", "okf", "schedule", "inspect", "operation", "launch-config", "readiness", "instance"]);
105
108
  const flag = (name) => {
@@ -298,6 +301,38 @@ async function doctorOperator(ws) {
298
301
  return { problems: found.map(({ code, label, message, remedy }) => ({ code, ...(label ? { label } : {}), message, remedy })), information: [] };
299
302
  }
300
303
 
304
+ /** The keys of oats-local.yaml souls.launch that name no soul (awebai/oats#989), in doctor, OFFLINE like
305
+ * doctorOperator: the souls are discovered from this machine's cache only, and the one function
306
+ * (launchKeysUnmatched) decides. A problem per unmatched key, which speaks about this machine's last
307
+ * read of the souls: a spawn reads the workspace itself and is the authority. A key that could not be
308
+ * checked, or a cache that cannot answer, is an information line (`launch-preference-unchecked`),
309
+ * never silence and never a failure of doctor. "*" is never reported.
310
+ * → { problems: [{ code, key, at, value, suggestions, message, remedy }], information: [string] } */
311
+ async function doctorLaunchPreferences(ws) {
312
+ const local = ws.local.value;
313
+ const entries = local?.souls?.launch && typeof local.souls.launch === "object" && !Array.isArray(local.souls.launch) ? local.souls.launch : {};
314
+ const keys = Object.keys(entries).filter((k) => k !== "*").sort();
315
+ if (!keys.length) return { problems: [], information: [] };
316
+ const shown = (list) => (list.length > 3 ? `${list.slice(0, 3).map(launchKeyQuoted).join(", ")} and ${list.length - 3} more` : list.map(launchKeyQuoted).join(", "));
317
+ let found;
318
+ try {
319
+ const { cacheOnlyRemote } = await import("../lib/operator-coverage.mjs");
320
+ const { discoverOrStandalone } = await import("../lib/instance-resolution.mjs");
321
+ const deployment = dirname(ws.local.path);
322
+ const discovery = await discoverOrStandalone(local, { lock: readLockIfPresent(deployment), deployment, remoteOptions: remoteOptionsFromEnv(), remote: cacheOnlyRemote() });
323
+ found = launchKeysUnmatched({ local, offered: soulsOffered(discovery) });
324
+ } catch (e) {
325
+ const why = e?.code === "E_REMOTE_UNREADABLE" ? `this machine's cache cannot answer (${e.message})` : `${e?.code ? `${e.code}: ` : ""}${e?.message ?? e}`;
326
+ return { problems: [], information: [`launch-preference-unchecked: the keys of oats-local.yaml souls.launch (${shown(keys)}) were not checked against the souls this workspace offers: ${why}; oats sync, then oats souls, then run doctor again (a spawn reads the workspace itself and refuses a key that names no soul)`] };
327
+ }
328
+ return {
329
+ problems: found.unmatched.map((row) => ({ code: LAUNCH_PREFERENCE_UNMATCHED, key: row.key, at: row.at, value: row.value, suggestions: row.suggestions,
330
+ message: unmatchedKeyMessage(row, { lastRead: true }),
331
+ remedy: `pin the soul it was meant for (${soulLaunchCommand("set")}), then: ${soulLaunchCommand("remove", { key: row.key })}` })),
332
+ information: found.unchecked.map((row) => `launch-preference-unchecked: oats-local.yaml souls.launch ${launchKeyQuoted(row.key)} was not checked against the souls this workspace offers: ${LAUNCH_KEY_UNCHECKED[row.reason] ?? row.reason}; this is this machine's last read, and a spawn reads the workspace itself`),
333
+ };
334
+ }
335
+
301
336
  /** What the deployment's capabilities declare and this kernel ignores (an unknown hook event), for
302
337
  * doctor without --soul, OFFLINE like doctorOperator, from this machine's parsed cache: each member's
303
338
  * capabilities as `oats sync` enumerated them (the workspace's members confirmed by the cached
@@ -594,6 +629,19 @@ async function homeLiveTeams(home) {
594
629
  return Array.isArray(teams) ? { teams, defaultTeam, teamsSource: source } : {};
595
630
  }
596
631
 
632
+ /** For `--reselect-launch`: what the home's launch layers need of the workspace to say which keys of
633
+ * souls.launch name no soul (lib/core.mjs homeLaunchLayers), read only when they need it and the layers
634
+ * decide (`named`: --harness names the launch, so no key is consulted). A home the start will refuse
635
+ * anyway (no record, no deployment) asks for nothing here: the start says why. A read that fails is
636
+ * this command's answer, before anything is stopped or started. */
637
+ async function homeLaunchOffered(home, { named = false } = {}) {
638
+ if (named) return null;
639
+ let needed = false;
640
+ try { needed = homeLaunchLayers(realpathSync(home), JSON.parse(readFileSync(join(home, "instance.json"), "utf8"))).needsOffered; } catch { return null; }
641
+ const { homeSoulsOffered } = await import("../lib/instance-resolution.mjs");
642
+ return homeSoulsOffered(realpathSync(home), { needed, remoteOptions: remoteOptionsFromEnv() });
643
+ }
644
+
597
645
  // ---------- operation run: generic invoke through the capability engine ----------
598
646
  /** `oats operation run <layer>:<name>`: resolve the provider that fills
599
647
  * <layer> for a running home (its snapshot) or for a soul in a scope (the
@@ -759,25 +807,29 @@ async function doctorWorkspaceJson(ctx, soulName, ws) {
759
807
  const localTeams = doctorLocalTeams(ws.local.value);
760
808
  const schedules = unresolvedScheduleAttempts(dirname(ws.local.path));
761
809
  const operator = await doctorOperator(ws);
810
+ const launchPreferences = await doctorLaunchPreferences(ws);
762
811
  // With --soul, the soul's composition; without, the deployment's capabilities (doctorHookWarnings).
763
812
  const hookEvents = composition ? { warnings: composition.warnings, information: [] } : await doctorHookWarnings(ws);
764
- const problems = [...legacyLayoutProblems(agentsRoot), readableInstanceHomes(agentsRoot), ...localTeams.problems, ...schedules.problems, ...operator.problems].filter(Boolean);
813
+ const problems = [...legacyLayoutProblems(agentsRoot), readableInstanceHomes(agentsRoot), ...localTeams.problems, ...schedules.problems, ...operator.problems, ...launchPreferences.problems].filter(Boolean);
765
814
  return {
766
815
  schemaVersion: 1, workspaceApi: 2, context: ctx,
767
816
  workspace: { file: ws.local.path, ref: ws.local.workspace },
768
817
  workspaceError: ws.localError, lockFile: ws.lockFile, packages: ws.packages, lockError: ws.lockError,
769
- information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information, ...processScanInformation(), ...doctorRetained(ws).flat()],
818
+ information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information, ...launchPreferences.information, ...hookEvents.information, ...processScanInformation(), ...doctorRetained(ws).flat()],
770
819
  composedInstructions: composition?.text, instructionBlocks: composition?.blocks,
771
820
  ...(problems.length ? { problems } : {}),
772
821
  warnings: hookEvents.warnings,
773
822
  };
774
823
  }
775
- /** Kernel/bridge version skew (published in lockstep from one tag). */
776
- function doctorVersionSkew() {
777
- const piPkgFile = join(homedir(), ".pi", "agent", "npm", "node_modules", "@awebai", "oats-pi", "package.json");
778
- if (!existsSync(piPkgFile)) return;
779
- const bridge = JSON.parse(readFileSync(piPkgFile, "utf8")).version;
780
- if (bridge !== OATS_VERSION) console.log(`WARNING: version skew — kernel ${OATS_VERSION}, pi bridge ${bridge}; run \`oats update\` (they publish in lockstep)\n`);
824
+ /** Kernel/bridge version skew (published in lockstep from one tag), in every pi folder a launch
825
+ * of the deployment uses (lib/pi-bridge.mjs): one warning per folder. Text output only. */
826
+ function doctorVersionSkew(deployment) {
827
+ let launchConfigs = {}, unread = null;
828
+ try { launchConfigs = launchConfigsAt(deployment); } catch (e) { unread = e.message; }
829
+ const warnings = piBridgeSkewWarnings(piBridgeFolders({ launchConfigs }), OATS_VERSION);
830
+ if (unread) warnings.push(`pi bridge — the launch configurations could not be read, so only the default pi folder and this shell's were looked at: ${unread}`);
831
+ for (const warning of warnings) console.log(`WARNING: ${warning}`);
832
+ if (warnings.length) console.log("");
781
833
  }
782
834
  /** The "Workspace (v2, offline view)" + "Locked packages" sections, shared by both doctor shapes. */
783
835
  function printDoctorWorkspace(ws) {
@@ -798,7 +850,7 @@ async function doctor(dir) {
798
850
  const { ctx, ws } = doctorDeployment(dir);
799
851
  const soulName = flag("soul");
800
852
  console.log(`oats doctor — resolved from ${shortPath(ctx)}\n`);
801
- doctorVersionSkew();
853
+ doctorVersionSkew(dirname(ws.local.path));
802
854
  const composition = await doctorComposition(ctx, soulName, ws, (code, msg) => die(`${msg} [${code}]`));
803
855
  printDoctorWorkspace(ws);
804
856
  const agentsRoot = join(dirname(ws.local.path), "agents");
@@ -809,9 +861,11 @@ async function doctor(dir) {
809
861
  for (const p of schedules.problems) console.log(`\n! ${p.code}: ${p.message}`);
810
862
  const operator = await doctorOperator(ws);
811
863
  for (const p of operator.problems) console.log(`\n! ${p.code}: ${p.message}\n ${p.remedy}`);
864
+ const launchPreferences = await doctorLaunchPreferences(ws);
865
+ for (const p of launchPreferences.problems) console.log(`\n! ${p.code}: ${p.message}\n ${p.remedy}`);
812
866
  const hookEvents = composition ? { warnings: composition.warnings, information: [] } : await doctorHookWarnings(ws);
813
867
  for (const w of hookEvents.warnings) console.log(`\nwarning ${w.code} ${w.message}`);
814
- for (const line of [...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information, ...processScanInformation()]) console.log(`\nINFO: ${line}`);
868
+ for (const line of [...localTeams.information, ...schedules.information, ...operator.information, ...launchPreferences.information, ...hookEvents.information, ...processScanInformation()]) console.log(`\nINFO: ${line}`);
815
869
  for (const block of doctorRetained(ws)) console.log(`\n${block.map((line) => `INFO: ${line}`).join("\n")}`);
816
870
  if (soulName) {
817
871
  const information = operationalKnowledgeNote(composition, soulName);
@@ -1022,18 +1076,13 @@ async function launchConfigCmd() {
1022
1076
  if (!file) bail("E_LOCAL_MISSING", `launch-config ${sub} writes the deployment's oats-local.yaml, and none is in reach of ${dir} — run it from the deployment (\`oats onboard\` creates one)`);
1023
1077
  const name = args[2];
1024
1078
  if (!name || name.startsWith("--")) bail("E_BAD_ARGS", `launch-config ${sub} needs a configuration name`);
1025
- const text = readFileSync(file, "utf8");
1026
- let model;
1027
- try { model = readLaunchConfigsModel(found.local); } catch (e) { bail(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1028
- const declaredHere = Object.hasOwn(model, name);
1029
- const before = declaredHere ? publicLaunchConfig(model[name]) : null;
1030
- if (sub === "remove") {
1031
- if (!declaredHere) bail("E_LAUNCH_CONFIG_UNKNOWN", `${name} is not declared in ${shortPath(file)}`);
1032
- delete model[name];
1033
- } else {
1034
- const f = flag("file");
1079
+ // What needs only the arguments is read and refused here, before the lock is taken: the definition
1080
+ // (stdin is read asynchronously, and the edit below is synchronous) and its own validity.
1081
+ let entry, f;
1082
+ const keepEnv = sub === "set" && args.includes("--keep-env");
1083
+ if (sub === "set") {
1084
+ f = flag("file");
1035
1085
  if (!f || f === true) bail("E_BAD_ARGS", "launch-config set needs --file <json> (an object with harness and optional executable, args, env, model, yolo)");
1036
- let entry;
1037
1086
  // A parse error is reported without the parser's text: its message can
1038
1087
  // quote the document, and a definition may carry environment literals.
1039
1088
  let raw;
@@ -1046,34 +1095,59 @@ async function launchConfigCmd() {
1046
1095
  try { raw = readFileSync(f, "utf8"); } catch (e) { bail("E_BAD_ARGS", `--file ${f}: ${e.code === "ENOENT" ? "no such file" : e.code || "cannot read"}`); }
1047
1096
  }
1048
1097
  try { entry = JSON.parse(raw); } catch { bail("E_BAD_ARGS", `--file ${f} is not valid JSON (one object with harness and optional executable, args, env, model, yolo)`); }
1049
- if (args.includes("--keep-env")) {
1050
- // An editor that saw only redacted values keeps the environment of the
1051
- // declared definition of that name: a one-time copy into the complete
1052
- // replacement entry.
1053
- if (entry && typeof entry === "object" && entry.env !== undefined) bail("E_BAD_ARGS", "--keep-env keeps the environment of the declared definition; omit env from --file");
1054
- const current = declaredHere ? model[name] : undefined;
1055
- if (!current) bail("E_LAUNCH_CONFIG_UNKNOWN", `--keep-env: no launch configuration ${name} is declared in ${shortPath(file)}, so there is no environment to keep; declare it with env`);
1056
- if (entry && typeof entry === "object" && Object.keys(current.env || {}).length) entry.env = { ...current.env };
1057
- }
1098
+ if (keepEnv && entry && typeof entry === "object" && entry.env !== undefined) bail("E_BAD_ARGS", "--keep-env keeps the environment of the declared definition; omit env from --file");
1099
+ // As given. With --keep-env it is judged again under the lock, with the environment it keeps.
1058
1100
  try { validateLaunchConfig(name, entry, `--file ${f}`); } catch (e) { bail(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1059
1101
  if (!Object.hasOwn(entry, "harness")) noteRuntimeName(`runtime in the --file definition (written as harness)`);
1060
- model[name] = normalizeLaunchConfig(entry);
1061
- // One default per harness, over the file as it would be written (no automatic move).
1062
- try { validateLaunchConfigDefaults(model, shortPath(file)); } catch (e) { bail(e.code || "E_LAUNCH_CONFIG_INVALID", e.message, e.details); }
1063
1102
  }
1064
- let next;
1065
- try { next = replaceLaunchConfigsBlock(text, serializeLaunchConfigs(model)); } catch (e) { bail(e.code || "E_CONFIG_BROKEN", `${e.message}; nothing was written`); }
1066
- // What is written must read back as exactly what was asked, by the kernel's
1067
- // own reader, before a byte of the file changes.
1068
- let readBack;
1069
- let nextLocal;
1070
- try { nextLocal = parseConfigData(next, { origin: { kind: "local", path: file } }).value; readBack = nextLocal["launch-configs"] || {}; } catch (e) { bail("E_LAUNCH_CONFIG_INVALID", `the rewritten block does not parse: ${e.message}; nothing was written`); }
1071
- const schemaProblems = validateLocal(nextLocal);
1072
- if (schemaProblems.length) bail("E_LAUNCH_CONFIG_INVALID", `the rewritten oats-local.yaml would be invalid (${schemaProblems.map((p) => `${p.path || "/"}: ${p.message}`).join("; ")}); nothing was written`);
1073
- const canonical = (m) => JSON.stringify(Object.keys(m).sort().map((n) => [n, normalizeLaunchConfig(m[n])]));
1074
- const same = canonical(readBack) === canonical(model);
1075
- if (!same) bail("E_LAUNCH_CONFIG_INVALID", `${name} would not read back as written; nothing was written`);
1076
- writeFileAtomic(file, next);
1103
+ // The write goes through the one path that rewrites oats-local.yaml (lib/local-edit.mjs editLocal): the
1104
+ // deployment's local lock, and the file as it is under it. Everything this command derives from the
1105
+ // file, it derives there: whether the name is declared, `before`, the environment --keep-env keeps and
1106
+ // the one default per harness. The edit runs with the lock held, so it never ends the process: a
1107
+ // refusal is thrown with the code, the text and the details it is answered with, and answered below,
1108
+ // once the lock is released.
1109
+ const refusal = (code, message, details) => Object.assign(new Error(message), { code, details });
1110
+ let model, before;
1111
+ const { editLocal } = await import("../lib/local-edit.mjs");
1112
+ try {
1113
+ editLocal({ deployment: level, localPath: file }, { verb: `oats launch-config ${sub}` }, ({ text, local }) => {
1114
+ try { model = readLaunchConfigsModel(local); } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1115
+ const declaredHere = Object.hasOwn(model, name);
1116
+ before = declaredHere ? publicLaunchConfig(model[name]) : null;
1117
+ if (sub === "remove") {
1118
+ if (!declaredHere) throw refusal("E_LAUNCH_CONFIG_UNKNOWN", `${name} is not declared in ${shortPath(file)}`);
1119
+ delete model[name];
1120
+ } else {
1121
+ let written = entry;
1122
+ if (keepEnv) {
1123
+ // An editor that saw only redacted values keeps the environment of the
1124
+ // declared definition of that name: a one-time copy into the complete
1125
+ // replacement entry.
1126
+ const current = declaredHere ? model[name] : undefined;
1127
+ if (!current) throw refusal("E_LAUNCH_CONFIG_UNKNOWN", `--keep-env: no launch configuration ${name} is declared in ${shortPath(file)}, so there is no environment to keep; declare it with env`);
1128
+ if (Object.keys(current.env || {}).length) written = { ...entry, env: { ...current.env } };
1129
+ try { validateLaunchConfig(name, written, `--file ${f}`); } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1130
+ }
1131
+ model[name] = normalizeLaunchConfig(written);
1132
+ // One default per harness, over the file as it would be written (no automatic move).
1133
+ try { validateLaunchConfigDefaults(model, shortPath(file)); } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message, e.details); }
1134
+ }
1135
+ let next;
1136
+ try { next = replaceLaunchConfigsBlock(text, serializeLaunchConfigs(model)); } catch (e) { throw refusal(e.code || "E_CONFIG_BROKEN", `${e.message}; nothing was written`); }
1137
+ // What is written must read back as exactly what was asked, by the kernel's
1138
+ // own reader, before a byte of the file changes. These refusals are this command's, with its
1139
+ // code: editLocal's own look at the text (E_WORKSPACE_SCHEMA) then finds nothing to refuse.
1140
+ let readBack;
1141
+ let nextLocal;
1142
+ try { nextLocal = parseConfigData(next, { origin: { kind: "local", path: file } }).value; readBack = nextLocal["launch-configs"] || {}; } catch (e) { throw refusal("E_LAUNCH_CONFIG_INVALID", `the rewritten block does not parse: ${e.message}; nothing was written`); }
1143
+ const schemaProblems = validateLocal(nextLocal);
1144
+ if (schemaProblems.length) throw refusal("E_LAUNCH_CONFIG_INVALID", `the rewritten oats-local.yaml would be invalid (${schemaProblems.map((p) => `${p.path || "/"}: ${p.message}`).join("; ")}); nothing was written`);
1145
+ const canonical = (m) => JSON.stringify(Object.keys(m).sort().map((n) => [n, normalizeLaunchConfig(m[n])]));
1146
+ const same = canonical(readBack) === canonical(model);
1147
+ if (!same) throw refusal("E_LAUNCH_CONFIG_INVALID", `${name} would not read back as written; nothing was written`);
1148
+ return { text: next };
1149
+ });
1150
+ } catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details); throw e; }
1077
1151
  let eff = null;
1078
1152
  try { eff = effective().find((c) => c.name === name) || null; } catch (e) { eff = { error: e.message }; }
1079
1153
  const receipt = { name, action: sub, level, file, before, after: Object.hasOwn(model, name) ? publicLaunchConfig(model[name]) : null, effective: eff };
@@ -1283,7 +1357,7 @@ function instanceCmd() {
1283
1357
  for (const w of receipt[STOP_WARNINGS] || []) console.error(`oats: warning: ${w}`);
1284
1358
  if (JSON_MODE) { jsonOk(receipt); return; }
1285
1359
  for (const r of receipt.results) console.log(` ${r.instance}: ${r.ok ? (r.stopped ? "stopped" : `already ${r.state}`) : `${r.code} — ${r.message}`}`);
1286
- console.log(receipt.ok ? `stopped${receipt.replayed ? " (replayed receipt)" : ""}; home, work, transcript and launch configuration retained — restart with \`oats session restart\`` : "some targets are still running; nothing was escalated");
1360
+ console.log(stopClosingLine(receipt));
1287
1361
  if (!receipt.ok) process.exit(1);
1288
1362
  return;
1289
1363
  } catch (e) {
@@ -1410,7 +1484,8 @@ function maxAgeRefusal(command, head) {
1410
1484
  case "workspace": return word(1) === "status" ? null : refuse(["workspace", word(1)].filter(Boolean).join(" "));
1411
1485
  case "teams": return word(1) === undefined ? null : refuse(`teams ${word(1)}`);
1412
1486
  // `soul teams` only reads (its edit flags were removed in 0.38.0, and refuse as such).
1413
- case "soul": return word(1) === "teams" ? null : refuse(["soul", word(1)].filter(Boolean).join(" "));
1487
+ // `soul launch set|remove` writes, and names its soul from what the workspace offers now: it reads live.
1488
+ case "soul": return word(1) === "teams" ? null : refuse(["soul", word(1), word(1) === "launch" ? word(2) : undefined].filter(Boolean).join(" "));
1414
1489
  // A capability source's poll resolves its soul as a read (the tick's child passes --max-age 600).
1415
1490
  case "trigger": return word(1) === "poll" ? null : refuse(["trigger", word(1)].filter(Boolean).join(" "));
1416
1491
  default: {
@@ -1530,8 +1605,8 @@ const originOf = (item) => (item.package ? `package ${item.package} v${item.vers
1530
1605
  /** A soul's launch here (feature launch-preference): the `Launch` report a spawn with no flags would decide
1531
1606
  * (souls.launch, the soul's own launch, the host default), and the desktop-facts `harness`, `model`,
1532
1607
  * `harnessFrom` equal to its effective launch (`harnessFrom` "kernel-default" for the host default). */
1533
- function soulLaunchFacts(entry, local, { launchConfigs, contextDir }) {
1534
- const launch = launchReportFor({ layers: launchLayers({ definition: entry.definition, entry, key: soulKeyOf(entry), local }), launchConfigs, contextDir });
1608
+ function soulLaunchFacts(entry, local, { launchConfigs, contextDir, offered }) {
1609
+ const launch = launchReportFor({ layers: launchLayers({ definition: entry.definition, entry, key: soulKeyOf(entry), local, offered }), launchConfigs, contextDir });
1535
1610
  return { harness: launch.effective.harness, model: launch.effective.model, harnessFrom: launch.from === "host" ? "kernel-default" : launch.from, launch };
1536
1611
  }
1537
1612
 
@@ -1544,7 +1619,9 @@ function workspaceItems(discovery, lock, local, deploymentDir) {
1544
1619
  const souls = [];
1545
1620
  let launchConfigs = {};
1546
1621
  try { launchConfigs = deploymentDir ? launchConfigsAt(deploymentDir) : {}; } catch { launchConfigs = {}; }
1547
- const soulDefaults = (entry) => soulLaunchFacts(entry, local, { launchConfigs, contextDir: deploymentDir });
1622
+ // One description of this read for every soul's launch: which keys of souls.launch name no soul.
1623
+ const offered = soulsOffered(discovery);
1624
+ const soulDefaults = (entry) => soulLaunchFacts(entry, local, { launchConfigs, contextDir: deploymentDir, offered });
1548
1625
  const capabilities = [];
1549
1626
  const model = teamModel(discovery.standalone === true ? null : discovery.workspace, local, { workspaceKey: discovery.key ?? null });
1550
1627
  const teamsHere = (entry) => {
@@ -1633,6 +1710,7 @@ async function performSync(ctx, bail, { onDiscovered, plan = false } = {}) {
1633
1710
  catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details ?? e.provenance); throw e; }
1634
1711
  const kept = (list) => list.filter((p) => typeof p.package !== "string");
1635
1712
  discovery.packageSouls = pkg.souls;
1713
+ discovery.soulsUnread = { ...discovery.soulsUnread, packages: pkg.skipped, unlocked: unlockedPackages(discovery.workspace, lock) };
1636
1714
  discovery.problems = [...kept(discovery.problems), ...pkg.problems];
1637
1715
  discovery.warnings = workspaceWarnings(discovery.workspace, discovery.members, discovery.external || [], pkg.souls);
1638
1716
  problems.splice(0, problems.length, ...kept(problems), ...pkg.problems);
@@ -1779,7 +1857,7 @@ const printWorkspaceAdd = (r) => r.written
1779
1857
  * `triggers.disabled` / `schedules.disabled`. */
1780
1858
  function setDisabledHereCli(ws, kind, qid, enabled) {
1781
1859
  const { path } = loadLocal(ws);
1782
- return A.setDisabledHere(path, kind, qid, !enabled, { validate: validateLocal });
1860
+ return A.setDisabledHere({ deployment: dirname(path), localPath: path }, kind, qid, !enabled);
1783
1861
  }
1784
1862
 
1785
1863
  const SYNC_USAGE = "usage: oats sync [--dir <deployment>] [--plan] [--json]";
@@ -2068,7 +2146,8 @@ const SOUL_TEAMS_REPLACEMENT = "souls: in oats-workspace.yaml (a PR to the works
2068
2146
  * model 3: the workspace's `souls:`, and the local teams it allows). Config only, read only. */
2069
2147
  async function soulCmd() {
2070
2148
  const bail = (code, msg, details) => (JSON_MODE ? jsonFail(code, msg, details) : die(msg));
2071
- const usage = "usage: oats soul teams <soul>|'*' [--dir <deployment>] [--max-age <s>] [--json]";
2149
+ const usage = `usage: oats soul teams <soul>|'*' [--dir <deployment>] [--max-age <s>] [--json] | ${SOUL_LAUNCH_USAGE}`;
2150
+ if (positional(1) === "launch") return soulLaunchCmd(bail, usage);
2072
2151
  const removed = SOUL_TEAMS_REMOVED_FLAGS.find((f) => args.some((a) => a === f || a.startsWith(`${f}=`)));
2073
2152
  if (removed) bail("E_BAD_ARGS", `oats soul teams ${removed} was removed in 0.38.0 (team model 3): which teams a soul may join, and its default, are ${SOUL_TEAMS_REPLACEMENT}`, { flag: removed, replacement: SOUL_TEAMS_REPLACEMENT });
2074
2153
  if (positional(1) !== "teams") bail("E_USAGE", usage);
@@ -2100,6 +2179,70 @@ async function soulCmd() {
2100
2179
  if (doc.teams.length) printTable(["team", "id", "from", "why"], doc.teams.map((t) => [t.default ? `${t.label} (default)` : t.label, t.team ?? "(no id yet)", t.from, t.via.join(",")]));
2101
2180
  }
2102
2181
 
2182
+ const SOUL_LAUNCH_USAGE = "oats soul launch set <soul>|'*' (--launch-config <name>|none | --harness pi|claude|codex [--model <id>]) [--plan] [--dir <deployment>] [--json] | oats soul launch remove <soul>|'*'|<exact key> [--plan] [--dir <deployment>] [--json]";
2183
+ /** The flags each `oats soul launch` form takes (value flags → true). Anything else is refused, never
2184
+ * ignored: `--home` and `--soul` among them, since the soul is the argument and the file the deployment's. */
2185
+ const SOUL_LAUNCH_FLAGS = {
2186
+ set: { "--launch-config": true, "--harness": true, "--model": true },
2187
+ remove: {},
2188
+ };
2189
+ /** A souls.launch entry in words: a launch configuration's name, or the inline harness and model. */
2190
+ const launchEntryText = (v) => (v === null ? "no entry" : typeof v === "string" ? (v === "none" ? "none (the bare harness)" : `launch configuration ${v}`) : `${v.harness}${v.model ? ` with model ${v.model}` : ""}`);
2191
+
2192
+ /** `oats soul launch set <soul>|'*' (--launch-config <name>|none | --harness <h> [--model <id>]) |
2193
+ * remove <soul>|'*'|<exact key> [--plan] [--dir <deployment>] [--json]` (feature soul-launch): the
2194
+ * writer of oats-local.yaml souls.launch (lib/soul-launch-verbs.mjs). It reads the workspace live. */
2195
+ async function soulLaunchCmd(bail, usage) {
2196
+ const sub = positional(2);
2197
+ if (!["set", "remove"].includes(sub)) bail("E_USAGE", usage);
2198
+ // Every argument is accounted for before anything is read or written: a flag the form does not take, a
2199
+ // value flag with no value at ANY of its occurrences (`--harness codex --harness`), a value flag given
2200
+ // twice (flag() would read the first and drop the second) and a second name are refused, never ignored.
2201
+ const takes = { "--dir": true, "--json": false, "--plan": false, ...SOUL_LAUNCH_FLAGS[sub] };
2202
+ const names = [], given = new Set();
2203
+ for (let i = 3; i < args.length; i++) {
2204
+ const a = args[i];
2205
+ if (!a.startsWith("-")) { names.push(a); continue; }
2206
+ if (!Object.hasOwn(takes, a)) bail("E_USAGE", `oats soul launch ${sub} does not take ${a} (nothing was changed) — usage: ${SOUL_LAUNCH_USAGE}`, { flag: a });
2207
+ if (!takes[a]) continue;
2208
+ if (args[i + 1] === undefined || args[i + 1].startsWith("--")) bail("E_BAD_ARGS", `${a} needs a value`);
2209
+ if (given.has(a)) bail("E_BAD_ARGS", `oats soul launch ${sub} takes ${a} once (nothing was changed)`);
2210
+ given.add(a);
2211
+ i++;
2212
+ }
2213
+ if (names.length === 0) bail("E_BAD_ARGS", `oats soul launch ${sub} needs ${sub === "set" ? "a soul (or '*')" : "a soul, '*' or the exact text of a key in souls.launch"} — usage: ${SOUL_LAUNCH_USAGE}`);
2214
+ if (names.length > 1) bail("E_BAD_ARGS", `oats soul launch ${sub} takes one ${sub === "set" ? "soul" : "soul or key"}, and got ${names.length}: ${names.map((n) => JSON.stringify(n)).join(", ")} (nothing was changed) — usage: ${SOUL_LAUNCH_USAGE}`);
2215
+ const name = names[0];
2216
+ const V = await import("../lib/soul-launch-verbs.mjs");
2217
+ let value = null;
2218
+ if (sub === "set") {
2219
+ try { value = V.soulLaunchValue({ launchConfig: valueFlag("launch-config"), harness: valueFlag("harness"), model: valueFlag("model") }); }
2220
+ catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details); throw e; }
2221
+ }
2222
+ const ctx = workspaceContext(bail);
2223
+ const readSouls = async () => {
2224
+ const { discoverOrStandalone } = await import("../lib/instance-resolution.mjs");
2225
+ return discoverOrStandalone(ctx.local, { lock: readLockIfPresent(ctx.deploymentDir), deployment: ctx.deploymentDir, remoteOptions: ctx.remoteOptions });
2226
+ };
2227
+ let r;
2228
+ try { r = await V.soulLaunch({ deployment: ctx.deploymentDir, localPath: ctx.localPath }, { action: sub, name, value, plan: args.includes("--plan") }, { readSouls }); }
2229
+ catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details ?? e.provenance); throw e; }
2230
+ if (JSON_MODE) { jsonOk(r); return; }
2231
+ const key = JSON.stringify(r.key), file = shortPath(r.file);
2232
+ if (!r.changed) console.log(`souls.launch ${key} is already ${launchEntryText(r.after)} in ${file}: nothing to change`);
2233
+ else if (r.action === "set") console.log(`${r.plan ? "Would set" : "Set"} souls.launch ${key} to ${launchEntryText(r.after)} in ${file}${r.before === null ? "" : ` (it was ${launchEntryText(r.before)})`}${r.plan ? "; nothing was written" : ""}`);
2234
+ else console.log(`${r.plan ? "Would remove" : "Removed"} souls.launch ${key} (${launchEntryText(r.before)}) from ${file}${r.plan ? "; nothing was written" : ""}`);
2235
+ if (r.unread) { console.log(`The workspace's souls could not be read (${r.unread.code}: ${r.unread.message}), so this says nothing about which soul the key applied to or which keys still match none`); return; }
2236
+ if (r.souls && r.souls.length > 1) console.log(`This entry applies to ${r.souls.length} souls: ${r.souls.join(", ")} (a member's soul is keyed by its bare name)`);
2237
+ if (r.key === "*") console.log(`"*" is the launch of every soul without an entry of its own`);
2238
+ else if (r.launch === null) console.log(`${key} is the key of no soul this workspace offers`);
2239
+ else {
2240
+ const e = r.launch.effective;
2241
+ console.log(`The next spawn of ${r.souls.length > 1 && name !== r.key ? name : r.souls[0]} selects ${e.harness}${e.model ? ` with model ${e.model}` : ""}${e.launchConfig ? ` (launch configuration ${e.launchConfig})` : ""}, from ${r.launch.at ?? "the host default"}${r.launch.problem ? `, and would be refused: ${r.launch.problem.code}: ${r.launch.problem.message}` : ""}`);
2242
+ }
2243
+ for (const u of r.unmatched) console.log(`souls.launch ${launchKeyQuoted(u.key)} is the key of no soul this workspace offers${u.suggestions.length ? ` (nearest: ${u.suggestions.join(", ")})` : ""}: ${soulLaunchCommand("remove", { key: u.key })}`);
2244
+ }
2245
+
2103
2246
  /** The catalog's rows of `kind` ("capabilities" | "souls") as `oats capabilities` / `oats souls` list them:
2104
2247
  * one discovery (honouring --max-age), the lock, workspaceItems. → { ctx, discovery, lock, items }. */
2105
2248
  async function catalogRows(kind, bail) {
@@ -2124,13 +2267,23 @@ async function itemsCmd(kind) {
2124
2267
  if (kind === "capabilities") await capabilityFacts(items, discovery, lock, ctx, remote);
2125
2268
  if (kind === "souls") await soulFacts(items, discovery, lock, ctx, remote);
2126
2269
  const standalone = discovery.standalone === true;
2127
- if (JSON_MODE) { jsonOk(withObservation({ [`${kind}Api`]: 1, standalone: standalone || undefined, workspace: { name: workspaceName(discovery), key: discovery.key, commit: discovery.commit }, [kind]: items, problems: discovery.problems })); return; }
2270
+ // `oats souls` reads souls.launch for every soul it lists: a key that names none of them is a problem
2271
+ // of this read, one row per key (the souls a spawn would refuse carry it as launch.problem).
2272
+ const unmatched = kind === "souls" ? launchKeysUnmatched({ local: ctx.local, offered: soulsOffered(discovery) }).unmatched.map(unmatchedProblemRow) : [];
2273
+ if (JSON_MODE) { jsonOk(withObservation({ [`${kind}Api`]: 1, standalone: standalone || undefined, workspace: { name: workspaceName(discovery), key: discovery.key, commit: discovery.commit }, [kind]: items, problems: [...discovery.problems, ...unmatched] })); return; }
2128
2274
  console.log(`${kind} of workspace ${workspaceName(discovery)} (${discovery.key} @ ${short(discovery.commit)})${standalone ? ` — ${standaloneNote(discovery)}` : ""}\n`);
2129
2275
  if (!items.length) console.log(" (none)");
2130
2276
  else if (kind === "souls") printTable(["name", "origin", "teams here", "work"], items.map((s) => [s.name, s.origin, s.teams === null ? "(invalid: oats teams)" : s.teams.map((t) => (t.default ? `${t.label}*` : t.label)).join(",") || "—", s.work ?? "—"]));
2131
2277
  else printTable(["name", "origin", "layer"], items.map((c) => [c.private ? `${c.name} (repo-owned)` : c.name, c.origin, c.layer ?? "—"]));
2132
2278
  const unsynced = Object.keys(discovery.workspace?.packages || {}).filter((id) => !lock.packages[id]);
2133
2279
  if (kind === "capabilities" && unsynced.length) console.log(`\n package capabilities of ${unsynced.join(", ")} appear after \`oats sync\``);
2280
+ for (const p of unmatched) console.log(`\n! ${p.code}: ${p.message}`);
2281
+ }
2282
+
2283
+ /** A key of souls.launch that names no soul (lib/launch-preference.mjs launchKeysUnmatched's row) as a
2284
+ * row of `oats souls --json` `problems`: `path` is where the key is. */
2285
+ function unmatchedProblemRow(row) {
2286
+ return { code: LAUNCH_PREFERENCE_UNMATCHED, path: row.at, message: unmatchedKeyMessage(row), key: row.key, value: row.value, suggestions: row.suggestions };
2134
2287
  }
2135
2288
 
2136
2289
  /** `oats capabilities` argv after the command: its words (the subcommand first) with every flag and a value
@@ -2884,7 +3037,7 @@ function retireCmd() {
2884
3037
  if (args.includes("--json")) { jsonOk(plan); return; }
2885
3038
  console.log(`retire ${name} — plan ${plan.planRevision}`);
2886
3039
  console.log(` session ${plan.facts.session.state}; work ${plan.facts.work.observed ? `${plan.facts.work.changed} changed / ${plan.facts.work.untracked} untracked on ${plan.facts.work.branch ?? (plan.facts.work.detached ? "detached" : "a ref OATS carries no branch name for")}` : `not observed (${plan.facts.work.reason})`}; children ${plan.facts.children.length}; pull request ${plan.facts.pullRequest}`);
2887
- console.log(` defaults: retain worktree ${plan.defaults.retainWorktree}, delete branch ${plan.defaults.deleteBranch}, stop children ${plan.defaults.stopChildren}`);
3040
+ console.log(` ${retireDefaultsLine(plan)}`);
2888
3041
  for (const n of plan.notes) console.log(` note: ${n}`);
2889
3042
  return;
2890
3043
  } catch (e) { return lifecycleFail(e, "E_LIFECYCLE_FAILED", e.candidates ? { ...e.details, candidates: e.candidates } : e.details); }
@@ -3002,7 +3155,7 @@ function retireCmd() {
3002
3155
  // which is most of the harm of deleting it. Name the classes and the path.
3003
3156
  for (const line of workRecoveryLines(r)) console.log(line);
3004
3157
  for (const line of extraWorktreeLines(r)) console.log(line);
3005
- for (const w of r.warnings || []) console.log(` WARNING: ${w}`);
3158
+ for (const line of warningLines(r)) console.log(line);
3006
3159
  if (isSelf) console.log("This window dies in ~8s — say any goodbyes now.");
3007
3160
  }
3008
3161
 
@@ -3308,7 +3461,7 @@ async function sessionCmd() {
3308
3461
  // recorded launch stays frozen (a changed preference never reaches an existing home on its own).
3309
3462
  const reselectLaunch = args.includes("--reselect-launch");
3310
3463
  if (reselectLaunch && launchConfig !== undefined) bad("--reselect-launch applies the launch preferences; --launch-config names one explicitly — choose one");
3311
- const opts = { model: model || undefined, launchConfig, harness, yolo: yoloFlag(), ...(reselectLaunch ? { reselectLaunch: true } : {}), env: process.env, ...(await homeLiveTeams(home)) };
3464
+ const opts = { model: model || undefined, launchConfig, harness, yolo: yoloFlag(), ...(reselectLaunch ? { reselectLaunch: true, launchOffered: await homeLaunchOffered(home, { named: harness !== undefined }) } : {}), env: process.env, ...(await homeLiveTeams(home)) };
3312
3465
  if (args[1] === "restart") {
3313
3466
  const grace = flag("stop-grace");
3314
3467
  if (grace !== undefined) { if (grace === true || !/^\d+$/.test(String(grace)) || Number(grace) < 1 || Number(grace) > 300) bad("--stop-grace needs a number of seconds (1..300) to wait for the harness after SIGTERM"); opts.stopGraceMs = Number(grace) * 1000; }
@@ -3742,6 +3895,8 @@ async function capabilityCommand() {
3742
3895
  // canonical absolute executable of THIS CLI; official consumers execFile
3743
3896
  // it directly and never resolve `oats` from PATH or a shell.
3744
3897
  OATS_CLI_BIN: CLI_BIN,
3898
+ // The node a command writes into anything that outlives it (lib/stable-node.mjs).
3899
+ OATS_NODE_BIN: kernelNode().node,
3745
3900
  ...teamEnv(null), ...(teamCtx || {}),
3746
3901
  // The soul the command acts for (an instance home's recorded soul directory):
3747
3902
  // homes carry no soul link, so providers read it here.
@@ -3763,40 +3918,70 @@ async function capabilityCommand() {
3763
3918
  // ---------- update ----------
3764
3919
  function updateCmd() {
3765
3920
  const checkOnly = args.includes("--check");
3766
- let latest;
3767
- try { latest = execFileSync("npm", ["view", "@awebai/oats", "version"], { encoding: "utf8", timeout: 30000 }).trim(); }
3768
- catch (e) { die(`cannot check npm for the latest version: ${e.message}`); }
3921
+ // The deployment whose launch configurations name pi folders: at or above the working
3922
+ // directory, or --dir. Without one, or with one that does not load, the update still runs on
3923
+ // the default folder and this shell's, and says so first and last: an operator reads the end.
3924
+ let deployment = null, launchConfigs = {}, notLookedAt = null;
3925
+ try { deployment = dirname(loadLocal(dirFlag()).path); launchConfigs = launchConfigsAt(deployment); }
3926
+ catch (e) {
3927
+ // An explicit --dir with no deployment at or above it is refused, a 0.25 configuration there included.
3928
+ if (e?.code === "E_LOCAL_MISSING" && flag("dir") !== undefined) die(e.message);
3929
+ if (e?.code !== "E_LOCAL_MISSING" || e.details?.legacy) notLookedAt = `No launch configuration was looked at: ${deployment ? `the launch configurations of ${deployment} do` : "the deployment does"} not load (${e.message}). Run \`oats doctor\` there, then \`oats update\` again.`;
3930
+ else notLookedAt = `No launch configuration was looked at: no deployment at or above ${process.cwd()}. Run \`oats update\` in each deployment, or with --dir <deployment>.`;
3931
+ launchConfigs = {};
3932
+ }
3933
+ const end = (text) => { console.log(text); if (notLookedAt) console.log(`\n${notLookedAt}`); };
3934
+ const fail = (text) => die(notLookedAt ? `${text}\n${notLookedAt}` : text);
3935
+ // What npm printed is checked to be one version before it reaches a step, an argument or the
3936
+ // screen (awebai/oats#1011). Both streams are captured: spawnSync forwards neither.
3937
+ const asked = kernelLookup();
3938
+ const { version: latest, problem: notChecked } = kernelLookupResult(spawnSync(asked[0], asked.slice(1), { encoding: "utf8", timeout: 30000 }));
3939
+ if (notChecked) fail(notChecked);
3769
3940
  console.log(`@awebai/oats installed: ${OATS_VERSION} latest: ${latest}`);
3770
- // pi bridge, if a pi installation carries it.
3771
- let piBridge;
3772
- const piPkg = join(homedir(), ".pi", "agent", "npm", "node_modules", "@awebai", "oats-pi", "package.json");
3773
- if (existsSync(piPkg)) piBridge = JSON.parse(readFileSync(piPkg, "utf8")).version;
3774
- if (piBridge) console.log(`@awebai/oats-pi installed: ${piBridge} latest: ${latest} (published in lockstep)`);
3775
- if (latest === OATS_VERSION && (!piBridge || piBridge === latest)) { console.log("Up to date."); return; }
3776
- const steps = [];
3777
- if (latest !== OATS_VERSION) steps.push(`npm install -g @awebai/oats@${latest}`);
3778
- if (piBridge && piBridge !== latest) steps.push(`pi uninstall npm:@awebai/oats-pi@${piBridge}`, `pi install npm:@awebai/oats-pi@${latest}`);
3941
+ // Forward only: the CLI moves to a newer version of the registry, never back to an older one.
3942
+ // `target` is the version the kernel has after the run, which the bridges are brought to.
3943
+ const cli = planCliUpdate(OATS_VERSION, latest), { target } = cli;
3944
+ if (cli.note) console.log(cli.note);
3945
+ // The pi bridge, in every pi folder a launch of the deployment uses (lib/pi-bridge.mjs).
3946
+ const plan = planPiBridges(piBridgeFolders({ launchConfigs }), target);
3947
+ console.log(`\n${PI_BRIDGE} ${target} (published in lockstep), by pi folder${deployment && !notLookedAt ? ` of ${deployment}` : ""}:`);
3948
+ for (const line of piBridgePlanLines(plan, cli)) console.log(line);
3949
+ if (notLookedAt) console.log(` ${notLookedAt}`);
3950
+ const moves = plan.filter((entry) => entry.step);
3951
+ const untouched = plan.filter((entry) => entry.action === "skip").length;
3952
+ const untouchedNote = untouched ? ` ${untouched} pi folder${untouched > 1 ? "s were" : " was"} not touched: see above for what to run there.` : "";
3953
+ const steps = [...(cli.step ? [cli.step] : []), ...moves.map((entry) => ({ ...entry.step, entry }))];
3954
+ // "Up to date" is not said over a folder it does not touch, nor over a CLI or a bridge ahead.
3955
+ const ahead = cli.ahead || plan.some((entry) => entry.ahead);
3956
+ if (!steps.length) return end(untouched || ahead ? `\nNothing for \`oats update\` to run.${untouchedNote}` : "\nUp to date.");
3779
3957
  console.log("\nUpdate steps:");
3780
- for (const s of steps) console.log(` ${s}`);
3781
- if (checkOnly) { console.log("\n(--check: not executing)"); return; }
3958
+ for (const s of steps) console.log(` ${s.display}`);
3959
+ if (checkOnly) return end("\n(--check: not executing)");
3782
3960
  const interactive = process.stdin.isTTY && process.stdout.isTTY;
3783
3961
  if (interactive) {
3784
3962
  process.stdout.write("\nRun these now? [y/N] ");
3785
3963
  const buf = Buffer.alloc(16);
3786
3964
  let answer = "";
3787
3965
  try { answer = buf.toString("utf8", 0, readSync(0, buf, 0, 16)).trim().toLowerCase(); } catch { /* no input */ }
3788
- if (answer !== "y" && answer !== "yes") { console.log("Not updating."); return; }
3789
- } else if (!args.includes("--yes")) {
3790
- console.log("\nNon-interactive: pass --yes to execute, or run the steps yourself.");
3791
- return;
3966
+ if (answer !== "y" && answer !== "yes") return end("Not updating.");
3967
+ } else if (!args.includes("--yes")) return end("\nNon-interactive: pass --yes to execute, or run the steps yourself.");
3968
+ // Before any step, the CLI's included: the bridge's exact version is seen on the registry by a
3969
+ // lookup that revalidates npm's cache (awebai/oats#852). A version is listed a while after it
3970
+ // is published, and the kernel's "latest" says nothing about the bridge's.
3971
+ if (moves.length) {
3972
+ const lookup = bridgeLookup(target);
3973
+ console.log(`\n$ ${lookup.join(" ")}`);
3974
+ const notSeen = bridgeLookupProblem(spawnSync(lookup[0], lookup.slice(1), { encoding: "utf8", timeout: 30000 }), cli);
3975
+ if (notSeen) fail(notSeen);
3792
3976
  }
3793
- for (const s of steps) {
3794
- console.log(`\n$ ${s}`);
3795
- const [bin, ...rest] = s.split(/\s+/);
3796
- const r = spawnSync(bin, rest, { stdio: "inherit" });
3797
- if (r.status !== 0) die(`step failed: ${s}`);
3977
+ for (const [i, s] of steps.entries()) {
3978
+ console.log(`\n$ ${s.display}`);
3979
+ const r = spawnSync(s.argv[0], s.argv.slice(1), { stdio: "inherit", env: { ...process.env, ...s.env } });
3980
+ const ran = r.error ? `${s.argv[0]}: ${r.error.message}` : r.status !== 0 ? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`) : null;
3981
+ const problem = s.entry ? piBridgeStepProblem(s.entry, target, ran) : ran;
3982
+ if (problem) fail(piBridgeFailure({ entry: s.entry, display: s.display, problem, notReached: steps.slice(i + 1).filter((next) => next.entry).map((next) => next.entry) }));
3798
3983
  }
3799
- console.log(`\nUpdated to ${latest}. Now verify each deployment: run \`oats doctor\` at your workspace/repo scopes — it reports config spellings this version rejects, version skew, and missing requirements. Restart running pi sessions to pick up the new bridge.`);
3984
+ end(`\nUpdated to ${target}.${untouchedNote} Now verify each deployment: run \`oats doctor\` at your workspace/repo scopes — it reports config spellings this version rejects, version skew, and missing requirements. Restart running pi sessions to pick up the new bridge.`);
3800
3985
  }
3801
3986
 
3802
3987
  // ---------- version (Desktop CLI API v1 probe) ----------
@@ -3831,6 +4016,16 @@ function versionCmd() {
3831
4016
  const EXPERIMENTAL_CMDS = new Set(["dress", "spawn", "segments", "mind"]);
3832
4017
  async function recordCmd(sub) {
3833
4018
  process.argv.splice(2, 1);
4019
+ if (sub === "setup") {
4020
+ // setup writes a node into the user's Claude settings and into the capture watcher's unit,
4021
+ // and nothing rewrites them but setup run again: it is handed the rule's answer for the node
4022
+ // running this kernel (docs/capabilities.md, "The node a hook writes down"). The script is
4023
+ // imported into this process, so the variable is set here, over whatever the caller's
4024
+ // environment held; packages/record imports nothing of the kernel.
4025
+ const { node, warning } = stableNode({ consequence: "the capture hooks and the capture watcher stop when it goes away", remedy: "run `oats setup` again" });
4026
+ if (warning) console.error(`oats: warning: ${warning}`);
4027
+ process.env.OATS_NODE_BIN = node;
4028
+ }
3834
4029
  await import(new URL(`../packages/record/bin/${sub}.mjs`, import.meta.url));
3835
4030
  }
3836
4031
  async function experimentalCmd() {
@@ -4446,9 +4641,12 @@ Usage:
4446
4641
  Desktop CLI API v1 probe payload
4447
4642
  oats status [--json] agents, souls, running instances
4448
4643
  [--max-age <s>] reuse head observations up to <s> s old (below)
4449
- oats tui [--ascii] PREVIEW: the full-screen terminal client (docs/tui.md);
4450
- ? help, q quit. Needs a terminal on stdin and stdout
4451
- and has no --json form; --ascii = ASCII rules and marks
4644
+ oats tui [--dir <path>] [--ascii] PREVIEW: the full-screen terminal client (docs/tui.md):
4645
+ the instances of the workspace of the deployment at or
4646
+ above <path> (default: where you are), on this machine
4647
+ and on the machines registered here; it changes nothing.
4648
+ ? help, w workspaces, q quit. Needs a terminal on stdin and
4649
+ stdout and has no --json form; --ascii = ASCII rules and marks
4452
4650
  oats server add <id> --ssh <alias> register another machine's OATS (OpenSSH alias,
4453
4651
  --workspace </abs/path> [--oats <p>] remote workspace, remote oats path; no keys stored;
4454
4652
  [--path <dir:dir>] --path = dirs prepended to the remote PATH, e.g. ~/.local/bin)
@@ -4616,8 +4814,9 @@ Usage:
4616
4814
  [--yolo | --no-yolo] --json a disagreeing --harness is refused
4617
4815
  oats doctor [dir] [--soul <name>] [--json] resolved targets, trust, requirements;
4618
4816
  --soul shows final composed AGENTS.md
4619
- oats update [--check] [--yes] check npm for a newer kernel+pi bridge and
4620
- optionally run the update; then run oats doctor
4817
+ oats update [--check] [--yes] check npm for a newer kernel and move the pi bridge
4818
+ [--dir <deployment>] in every pi folder the deployment's launches use
4819
+ (docs/upgrading.md); then run oats doctor
4621
4820
  oats sync [--dir <d>] [--plan] [--json] workspace model v2: observe the workspace named by
4622
4821
  oats-local.yaml over its Git remote, confirm every
4623
4822
  member (reciprocal oats-membership.yaml), resolve
@@ -4653,6 +4852,19 @@ Usage:
4653
4852
  where there is none / it is <label>
4654
4853
  oats soul teams <soul>|'*' [--dir <d>] which teams a soul may join here, its default, and
4655
4854
  [--max-age <s>] [--json] why (the workspace's souls: and local teams)
4855
+ oats soul launch set <soul>|'*' (--launch-config <name>|none | --harness pi|claude|codex [--model <id>])
4856
+ [--plan] [--dir <d>] [--json] pin a soul's launch on this machine: writes its key
4857
+ (its bare name, or <package>/<soul>; '*' = every soul
4858
+ without an entry) in oats-local.yaml souls.launch.
4859
+ The file is rewritten; every other entry keeps its
4860
+ value and its comments. --plan: every check, nothing
4861
+ written. It reads the workspace live (no --max-age)
4862
+ oats soul launch remove <soul>|'*'|<exact key> [--plan] [--dir <d>] [--json]
4863
+ remove one entry of souls.launch: a soul's, '*', or
4864
+ the exact text of a key in the file (that form works
4865
+ when the workspace's souls cannot be read, and is how
4866
+ a key that names no soul is removed); no such entry is
4867
+ E_LAUNCH_PREFERENCE_UNKNOWN
4656
4868
  oats instance git <instance> [--home <abs>] [--dir <d>] [--json]
4657
4869
  read-only Git observation of the instance's work
4658
4870
  tree: branch, status (renames kept), ahead/behind