@awebai/oats 0.52.0 → 0.54.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 (100) hide show
  1. package/README.md +2 -1
  2. package/bin/oats.mjs +314 -92
  3. package/docs/capabilities.md +66 -4
  4. package/docs/configuration.md +66 -3
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +3 -0
  6. package/docs/desktop-cli-api.md +696 -60
  7. package/docs/desktop-instance-start.md +25 -12
  8. package/docs/execution-targets.md +1 -0
  9. package/docs/implementation.md +184 -12
  10. package/docs/integrations.md +6 -3
  11. package/docs/knowledge.md +2 -2
  12. package/docs/macos-test-runs.md +246 -0
  13. package/docs/official-catalog.md +5 -5
  14. package/docs/packages.md +14 -14
  15. package/docs/release-lane.md +210 -6
  16. package/docs/release-notes/v0.53.0.md +1288 -0
  17. package/docs/release-notes/v0.54.0.md +142 -0
  18. package/docs/schedules.md +7 -1
  19. package/docs/souls-and-instances.md +239 -16
  20. package/docs/tui.md +453 -21
  21. package/docs/upgrading.md +310 -0
  22. package/docs/workspaces.md +123 -3
  23. package/lib/automations.mjs +22 -22
  24. package/lib/claim.mjs +93 -4
  25. package/lib/config-data.mjs +4 -1
  26. package/lib/core.mjs +569 -121
  27. package/lib/instance-events.mjs +19 -1
  28. package/lib/instance-git.mjs +39 -3
  29. package/lib/instance-inspect.mjs +5 -6
  30. package/lib/instance-lifecycle.mjs +145 -18
  31. package/lib/instance-resolution.mjs +59 -6
  32. package/lib/launch-preference.mjs +226 -15
  33. package/lib/local-edit.mjs +118 -0
  34. package/lib/packages.mjs +18 -5
  35. package/lib/pi-bridge.mjs +308 -0
  36. package/lib/refused-text.mjs +11 -0
  37. package/lib/remote.mjs +404 -60
  38. package/lib/resolve.mjs +2 -1
  39. package/lib/retained-after-retire.mjs +2 -2
  40. package/lib/retire-output.mjs +12 -1
  41. package/lib/schedule-host.mjs +6 -35
  42. package/lib/shell-word.mjs +13 -0
  43. package/lib/soul-launch-verbs.mjs +153 -0
  44. package/lib/stable-node.mjs +62 -0
  45. package/lib/teams-verbs.mjs +18 -46
  46. package/lib/workspace.mjs +75 -27
  47. package/package-catalog.json +4 -4
  48. package/package.json +2 -1
  49. package/packages/client/attach-exit.mjs +25 -0
  50. package/packages/client/cli-adapter.mjs +16 -3
  51. package/packages/client/cli-locator.mjs +2 -2
  52. package/packages/client/deployment-contract.mjs +4 -0
  53. package/packages/client/deployment-facts.mjs +71 -10
  54. package/packages/client/deployment-panel.mjs +49 -11
  55. package/packages/client/deployment-read-cli.mjs +7 -3
  56. package/packages/client/display-text.mjs +8 -2
  57. package/packages/client/instance-acts.mjs +46 -10
  58. package/packages/client/instance-events-contract.mjs +4 -2
  59. package/packages/client/instance-presentation.mjs +66 -2
  60. package/packages/client/instance-tree.mjs +23 -14
  61. package/packages/client/kernel-lines.mjs +31 -0
  62. package/packages/client/kernel-made.mjs +23 -0
  63. package/packages/client/launch-prompt-outcome.mjs +51 -16
  64. package/packages/client/lifecycle-contract.mjs +45 -4
  65. package/packages/client/liveness.mjs +14 -1
  66. package/packages/client/own-codes.mjs +31 -0
  67. package/packages/client/panel-views.mjs +18 -11
  68. package/packages/client/readiness-contract.mjs +3 -1
  69. package/packages/client/remote-address.mjs +34 -9
  70. package/packages/client/remote-identity-memory.mjs +94 -0
  71. package/packages/client/remote-roster.mjs +92 -6
  72. package/packages/client/session-attach.mjs +175 -0
  73. package/packages/client/spawn-apply-contract.mjs +16 -4
  74. package/packages/client/spawn-messages.mjs +26 -3
  75. package/packages/client/spawn-preview-cli.mjs +8 -2
  76. package/packages/client/spawn-preview-contract.mjs +5 -1
  77. package/packages/client/terminal-exec.mjs +21 -0
  78. package/packages/client/workspace-choices.mjs +95 -0
  79. package/packages/client/workspace-views.mjs +39 -3
  80. package/packages/record/README.md +21 -0
  81. package/packages/record/bin/setup.mjs +108 -15
  82. package/packages/tui/README.md +30 -12
  83. package/packages/tui/lib/actions.mjs +16 -1
  84. package/packages/tui/lib/client.mjs +32 -1
  85. package/packages/tui/lib/config.mjs +151 -0
  86. package/packages/tui/lib/main.mjs +117 -46
  87. package/packages/tui/lib/model.mjs +392 -0
  88. package/packages/tui/lib/read.mjs +473 -0
  89. package/packages/tui/lib/store.mjs +364 -0
  90. package/packages/tui/lib/term/keys.mjs +44 -0
  91. package/packages/tui/lib/term/screen.mjs +16 -4
  92. package/packages/tui/lib/term/text.mjs +60 -0
  93. package/packages/tui/lib/term/tty.mjs +13 -3
  94. package/packages/tui/lib/views/detail.mjs +46 -0
  95. package/packages/tui/lib/views/frame.mjs +230 -36
  96. package/packages/tui/lib/views/help.mjs +125 -13
  97. package/packages/tui/lib/views/instances.mjs +137 -0
  98. package/packages/tui/lib/views/scroll.mjs +19 -0
  99. package/packages/tui/lib/views/switcher.mjs +97 -0
  100. package/skills/oats-getting-started/SKILL.md +8 -2
package/bin/oats.mjs CHANGED
@@ -31,16 +31,19 @@ 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 { terminalText } from "../lib/refused-text.mjs";
46
+ import { soulsOffered } from "../lib/instance-resolution.mjs";
44
47
  import { parseConfigData } from "../lib/config-data.mjs";
45
48
  import * as remoteModule from "../lib/remote.mjs";
46
49
  import { activateLocalInputs, localRevision } from "../lib/local-inputs.mjs";
@@ -51,11 +54,12 @@ import { tickTriggers } from "../lib/triggers.mjs";
51
54
  import * as A from "../lib/automations.mjs";
52
55
  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
56
  import { hostUnitFiles, hostUnitStatus, installHostUnit, uninstallHostUnit } from "../lib/schedule-host.mjs";
57
+ import { kernelNode, stableNode } from "../lib/stable-node.mjs";
54
58
  import { receiveAttachment, uploadAttachment, readStreamBounded, MAX_ATTACHMENT_BYTES } from "../lib/attachments.mjs";
55
59
 
56
60
  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";
61
+ import { planStop, applyStop, planRetire, retireDefaultsLine, stopClosingLine, descendantsOf, resolveInstance as resolveInstanceForCli, STOP_WARNINGS } from "../lib/instance-lifecycle.mjs";
62
+ import { extraWorktreeLines, formatBytes, warningLines, workRecoveryLines } from "../lib/retire-output.mjs";
59
63
  import { retainedRecoveryLines, retainedWorktreeLines, retainedWorktrees } from "../lib/retained-after-retire.mjs";
60
64
  const await_import_lifecycle = () => ({ resolveInstance: resolveInstanceForCli });
61
65
  import { homeTarget, soulTarget, isWorkspaceContext, inspectDocument, withComposedInstructions, readinessDocument, policyOf, policySoul, manifestMissingRequires, INSPECT_OPERATIONS_API } from "../lib/instance-inspect.mjs";
@@ -99,7 +103,7 @@ const OWN_ARGV_COMMANDS = new Set(["capture", "recall", "setup", "experimental",
99
103
  * probe) and in `status --json`, which a remote roster relays as the host's (feature
100
104
  * server-probe-features, lib/servers.mjs hostFeatures). ONE list for both, emitted at output
101
105
  * 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"];
106
+ 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
107
  /** Commands `--server <id>` runs on a registered server. */
104
108
  const ROUTED_COMMANDS = new Set(["spawn", "retire", "status", "session", "okf", "schedule", "inspect", "operation", "launch-config", "readiness", "instance"]);
105
109
  const flag = (name) => {
@@ -298,6 +302,38 @@ async function doctorOperator(ws) {
298
302
  return { problems: found.map(({ code, label, message, remedy }) => ({ code, ...(label ? { label } : {}), message, remedy })), information: [] };
299
303
  }
300
304
 
305
+ /** The keys of oats-local.yaml souls.launch that name no soul (awebai/oats#989), in doctor, OFFLINE like
306
+ * doctorOperator: the souls are discovered from this machine's cache only, and the one function
307
+ * (launchKeysUnmatched) decides. A problem per unmatched key, which speaks about this machine's last
308
+ * read of the souls: a spawn reads the workspace itself and is the authority. A key that could not be
309
+ * checked, or a cache that cannot answer, is an information line (`launch-preference-unchecked`),
310
+ * never silence and never a failure of doctor. "*" is never reported.
311
+ * → { problems: [{ code, key, at, value, suggestions, message, remedy }], information: [string] } */
312
+ async function doctorLaunchPreferences(ws) {
313
+ const local = ws.local.value;
314
+ const entries = local?.souls?.launch && typeof local.souls.launch === "object" && !Array.isArray(local.souls.launch) ? local.souls.launch : {};
315
+ const keys = Object.keys(entries).filter((k) => k !== "*").sort();
316
+ if (!keys.length) return { problems: [], information: [] };
317
+ const shown = (list) => (list.length > 3 ? `${list.slice(0, 3).map(launchKeyQuoted).join(", ")} and ${list.length - 3} more` : list.map(launchKeyQuoted).join(", "));
318
+ let found;
319
+ try {
320
+ const { cacheOnlyRemote } = await import("../lib/operator-coverage.mjs");
321
+ const { discoverOrStandalone } = await import("../lib/instance-resolution.mjs");
322
+ const deployment = dirname(ws.local.path);
323
+ const discovery = await discoverOrStandalone(local, { lock: readLockIfPresent(deployment), deployment, remoteOptions: remoteOptionsFromEnv(), remote: cacheOnlyRemote() });
324
+ found = launchKeysUnmatched({ local, offered: soulsOffered(discovery) });
325
+ } catch (e) {
326
+ const why = e?.code === "E_REMOTE_UNREADABLE" ? `this machine's cache cannot answer (${e.message})` : `${e?.code ? `${e.code}: ` : ""}${e?.message ?? e}`;
327
+ 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)`] };
328
+ }
329
+ return {
330
+ problems: found.unmatched.map((row) => ({ code: LAUNCH_PREFERENCE_UNMATCHED, key: row.key, at: row.at, value: row.value, suggestions: row.suggestions,
331
+ message: unmatchedKeyMessage(row, { lastRead: true }),
332
+ remedy: `pin the soul it was meant for (${soulLaunchCommand("set")}), then: ${soulLaunchCommand("remove", { key: row.key })}` })),
333
+ 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`),
334
+ };
335
+ }
336
+
301
337
  /** What the deployment's capabilities declare and this kernel ignores (an unknown hook event), for
302
338
  * doctor without --soul, OFFLINE like doctorOperator, from this machine's parsed cache: each member's
303
339
  * capabilities as `oats sync` enumerated them (the workspace's members confirmed by the cached
@@ -594,6 +630,19 @@ async function homeLiveTeams(home) {
594
630
  return Array.isArray(teams) ? { teams, defaultTeam, teamsSource: source } : {};
595
631
  }
596
632
 
633
+ /** For `--reselect-launch`: what the home's launch layers need of the workspace to say which keys of
634
+ * souls.launch name no soul (lib/core.mjs homeLaunchLayers), read only when they need it and the layers
635
+ * decide (`named`: --harness names the launch, so no key is consulted). A home the start will refuse
636
+ * anyway (no record, no deployment) asks for nothing here: the start says why. A read that fails is
637
+ * this command's answer, before anything is stopped or started. */
638
+ async function homeLaunchOffered(home, { named = false } = {}) {
639
+ if (named) return null;
640
+ let needed = false;
641
+ try { needed = homeLaunchLayers(realpathSync(home), JSON.parse(readFileSync(join(home, "instance.json"), "utf8"))).needsOffered; } catch { return null; }
642
+ const { homeSoulsOffered } = await import("../lib/instance-resolution.mjs");
643
+ return homeSoulsOffered(realpathSync(home), { needed, remoteOptions: remoteOptionsFromEnv() });
644
+ }
645
+
597
646
  // ---------- operation run: generic invoke through the capability engine ----------
598
647
  /** `oats operation run <layer>:<name>`: resolve the provider that fills
599
648
  * <layer> for a running home (its snapshot) or for a soul in a scope (the
@@ -759,25 +808,29 @@ async function doctorWorkspaceJson(ctx, soulName, ws) {
759
808
  const localTeams = doctorLocalTeams(ws.local.value);
760
809
  const schedules = unresolvedScheduleAttempts(dirname(ws.local.path));
761
810
  const operator = await doctorOperator(ws);
811
+ const launchPreferences = await doctorLaunchPreferences(ws);
762
812
  // With --soul, the soul's composition; without, the deployment's capabilities (doctorHookWarnings).
763
813
  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);
814
+ const problems = [...legacyLayoutProblems(agentsRoot), readableInstanceHomes(agentsRoot), ...localTeams.problems, ...schedules.problems, ...operator.problems, ...launchPreferences.problems].filter(Boolean);
765
815
  return {
766
816
  schemaVersion: 1, workspaceApi: 2, context: ctx,
767
817
  workspace: { file: ws.local.path, ref: ws.local.workspace },
768
818
  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()],
819
+ information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information, ...launchPreferences.information, ...hookEvents.information, ...processScanInformation(), ...doctorRetained(ws).flat()],
770
820
  composedInstructions: composition?.text, instructionBlocks: composition?.blocks,
771
821
  ...(problems.length ? { problems } : {}),
772
822
  warnings: hookEvents.warnings,
773
823
  };
774
824
  }
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`);
825
+ /** Kernel/bridge version skew (published in lockstep from one tag), in every pi folder a launch
826
+ * of the deployment uses (lib/pi-bridge.mjs): one warning per folder. Text output only. */
827
+ function doctorVersionSkew(deployment) {
828
+ let launchConfigs = {}, unread = null;
829
+ try { launchConfigs = launchConfigsAt(deployment); } catch (e) { unread = e.message; }
830
+ const warnings = piBridgeSkewWarnings(piBridgeFolders({ launchConfigs }), OATS_VERSION);
831
+ 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}`);
832
+ for (const warning of warnings) console.log(`WARNING: ${warning}`);
833
+ if (warnings.length) console.log("");
781
834
  }
782
835
  /** The "Workspace (v2, offline view)" + "Locked packages" sections, shared by both doctor shapes. */
783
836
  function printDoctorWorkspace(ws) {
@@ -798,7 +851,7 @@ async function doctor(dir) {
798
851
  const { ctx, ws } = doctorDeployment(dir);
799
852
  const soulName = flag("soul");
800
853
  console.log(`oats doctor — resolved from ${shortPath(ctx)}\n`);
801
- doctorVersionSkew();
854
+ doctorVersionSkew(dirname(ws.local.path));
802
855
  const composition = await doctorComposition(ctx, soulName, ws, (code, msg) => die(`${msg} [${code}]`));
803
856
  printDoctorWorkspace(ws);
804
857
  const agentsRoot = join(dirname(ws.local.path), "agents");
@@ -809,9 +862,11 @@ async function doctor(dir) {
809
862
  for (const p of schedules.problems) console.log(`\n! ${p.code}: ${p.message}`);
810
863
  const operator = await doctorOperator(ws);
811
864
  for (const p of operator.problems) console.log(`\n! ${p.code}: ${p.message}\n ${p.remedy}`);
865
+ const launchPreferences = await doctorLaunchPreferences(ws);
866
+ for (const p of launchPreferences.problems) console.log(`\n! ${p.code}: ${p.message}\n ${p.remedy}`);
812
867
  const hookEvents = composition ? { warnings: composition.warnings, information: [] } : await doctorHookWarnings(ws);
813
868
  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}`);
869
+ for (const line of [...localTeams.information, ...schedules.information, ...operator.information, ...launchPreferences.information, ...hookEvents.information, ...processScanInformation()]) console.log(`\nINFO: ${line}`);
815
870
  for (const block of doctorRetained(ws)) console.log(`\n${block.map((line) => `INFO: ${line}`).join("\n")}`);
816
871
  if (soulName) {
817
872
  const information = operationalKnowledgeNote(composition, soulName);
@@ -1022,18 +1077,13 @@ async function launchConfigCmd() {
1022
1077
  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
1078
  const name = args[2];
1024
1079
  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");
1080
+ // What needs only the arguments is read and refused here, before the lock is taken: the definition
1081
+ // (stdin is read asynchronously, and the edit below is synchronous) and its own validity.
1082
+ let entry, f;
1083
+ const keepEnv = sub === "set" && args.includes("--keep-env");
1084
+ if (sub === "set") {
1085
+ f = flag("file");
1035
1086
  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
1087
  // A parse error is reported without the parser's text: its message can
1038
1088
  // quote the document, and a definition may carry environment literals.
1039
1089
  let raw;
@@ -1046,34 +1096,59 @@ async function launchConfigCmd() {
1046
1096
  try { raw = readFileSync(f, "utf8"); } catch (e) { bail("E_BAD_ARGS", `--file ${f}: ${e.code === "ENOENT" ? "no such file" : e.code || "cannot read"}`); }
1047
1097
  }
1048
1098
  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
- }
1099
+ 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");
1100
+ // As given. With --keep-env it is judged again under the lock, with the environment it keeps.
1058
1101
  try { validateLaunchConfig(name, entry, `--file ${f}`); } catch (e) { bail(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1059
1102
  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
1103
  }
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);
1104
+ // The write goes through the one path that rewrites oats-local.yaml (lib/local-edit.mjs editLocal): the
1105
+ // deployment's local lock, and the file as it is under it. Everything this command derives from the
1106
+ // file, it derives there: whether the name is declared, `before`, the environment --keep-env keeps and
1107
+ // the one default per harness. The edit runs with the lock held, so it never ends the process: a
1108
+ // refusal is thrown with the code, the text and the details it is answered with, and answered below,
1109
+ // once the lock is released.
1110
+ const refusal = (code, message, details) => Object.assign(new Error(message), { code, details });
1111
+ let model, before;
1112
+ const { editLocal } = await import("../lib/local-edit.mjs");
1113
+ try {
1114
+ editLocal({ deployment: level, localPath: file }, { verb: `oats launch-config ${sub}` }, ({ text, local }) => {
1115
+ try { model = readLaunchConfigsModel(local); } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1116
+ const declaredHere = Object.hasOwn(model, name);
1117
+ before = declaredHere ? publicLaunchConfig(model[name]) : null;
1118
+ if (sub === "remove") {
1119
+ if (!declaredHere) throw refusal("E_LAUNCH_CONFIG_UNKNOWN", `${name} is not declared in ${shortPath(file)}`);
1120
+ delete model[name];
1121
+ } else {
1122
+ let written = entry;
1123
+ if (keepEnv) {
1124
+ // An editor that saw only redacted values keeps the environment of the
1125
+ // declared definition of that name: a one-time copy into the complete
1126
+ // replacement entry.
1127
+ const current = declaredHere ? model[name] : undefined;
1128
+ 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`);
1129
+ if (Object.keys(current.env || {}).length) written = { ...entry, env: { ...current.env } };
1130
+ try { validateLaunchConfig(name, written, `--file ${f}`); } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1131
+ }
1132
+ model[name] = normalizeLaunchConfig(written);
1133
+ // One default per harness, over the file as it would be written (no automatic move).
1134
+ try { validateLaunchConfigDefaults(model, shortPath(file)); } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message, e.details); }
1135
+ }
1136
+ let next;
1137
+ try { next = replaceLaunchConfigsBlock(text, serializeLaunchConfigs(model)); } catch (e) { throw refusal(e.code || "E_CONFIG_BROKEN", `${e.message}; nothing was written`); }
1138
+ // What is written must read back as exactly what was asked, by the kernel's
1139
+ // own reader, before a byte of the file changes. These refusals are this command's, with its
1140
+ // code: editLocal's own look at the text (E_WORKSPACE_SCHEMA) then finds nothing to refuse.
1141
+ let readBack;
1142
+ let nextLocal;
1143
+ 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`); }
1144
+ const schemaProblems = validateLocal(nextLocal);
1145
+ 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`);
1146
+ const canonical = (m) => JSON.stringify(Object.keys(m).sort().map((n) => [n, normalizeLaunchConfig(m[n])]));
1147
+ const same = canonical(readBack) === canonical(model);
1148
+ if (!same) throw refusal("E_LAUNCH_CONFIG_INVALID", `${name} would not read back as written; nothing was written`);
1149
+ return { text: next };
1150
+ });
1151
+ } catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details); throw e; }
1077
1152
  let eff = null;
1078
1153
  try { eff = effective().find((c) => c.name === name) || null; } catch (e) { eff = { error: e.message }; }
1079
1154
  const receipt = { name, action: sub, level, file, before, after: Object.hasOwn(model, name) ? publicLaunchConfig(model[name]) : null, effective: eff };
@@ -1283,7 +1358,7 @@ function instanceCmd() {
1283
1358
  for (const w of receipt[STOP_WARNINGS] || []) console.error(`oats: warning: ${w}`);
1284
1359
  if (JSON_MODE) { jsonOk(receipt); return; }
1285
1360
  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");
1361
+ console.log(stopClosingLine(receipt));
1287
1362
  if (!receipt.ok) process.exit(1);
1288
1363
  return;
1289
1364
  } catch (e) {
@@ -1410,7 +1485,8 @@ function maxAgeRefusal(command, head) {
1410
1485
  case "workspace": return word(1) === "status" ? null : refuse(["workspace", word(1)].filter(Boolean).join(" "));
1411
1486
  case "teams": return word(1) === undefined ? null : refuse(`teams ${word(1)}`);
1412
1487
  // `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(" "));
1488
+ // `soul launch set|remove` writes, and names its soul from what the workspace offers now: it reads live.
1489
+ case "soul": return word(1) === "teams" ? null : refuse(["soul", word(1), word(1) === "launch" ? word(2) : undefined].filter(Boolean).join(" "));
1414
1490
  // A capability source's poll resolves its soul as a read (the tick's child passes --max-age 600).
1415
1491
  case "trigger": return word(1) === "poll" ? null : refuse(["trigger", word(1)].filter(Boolean).join(" "));
1416
1492
  default: {
@@ -1530,8 +1606,8 @@ const originOf = (item) => (item.package ? `package ${item.package} v${item.vers
1530
1606
  /** A soul's launch here (feature launch-preference): the `Launch` report a spawn with no flags would decide
1531
1607
  * (souls.launch, the soul's own launch, the host default), and the desktop-facts `harness`, `model`,
1532
1608
  * `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 });
1609
+ function soulLaunchFacts(entry, local, { launchConfigs, contextDir, offered }) {
1610
+ const launch = launchReportFor({ layers: launchLayers({ definition: entry.definition, entry, key: soulKeyOf(entry), local, offered }), launchConfigs, contextDir });
1535
1611
  return { harness: launch.effective.harness, model: launch.effective.model, harnessFrom: launch.from === "host" ? "kernel-default" : launch.from, launch };
1536
1612
  }
1537
1613
 
@@ -1544,7 +1620,9 @@ function workspaceItems(discovery, lock, local, deploymentDir) {
1544
1620
  const souls = [];
1545
1621
  let launchConfigs = {};
1546
1622
  try { launchConfigs = deploymentDir ? launchConfigsAt(deploymentDir) : {}; } catch { launchConfigs = {}; }
1547
- const soulDefaults = (entry) => soulLaunchFacts(entry, local, { launchConfigs, contextDir: deploymentDir });
1623
+ // One description of this read for every soul's launch: which keys of souls.launch name no soul.
1624
+ const offered = soulsOffered(discovery);
1625
+ const soulDefaults = (entry) => soulLaunchFacts(entry, local, { launchConfigs, contextDir: deploymentDir, offered });
1548
1626
  const capabilities = [];
1549
1627
  const model = teamModel(discovery.standalone === true ? null : discovery.workspace, local, { workspaceKey: discovery.key ?? null });
1550
1628
  const teamsHere = (entry) => {
@@ -1633,6 +1711,7 @@ async function performSync(ctx, bail, { onDiscovered, plan = false } = {}) {
1633
1711
  catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details ?? e.provenance); throw e; }
1634
1712
  const kept = (list) => list.filter((p) => typeof p.package !== "string");
1635
1713
  discovery.packageSouls = pkg.souls;
1714
+ discovery.soulsUnread = { ...discovery.soulsUnread, packages: pkg.skipped, unlocked: unlockedPackages(discovery.workspace, lock) };
1636
1715
  discovery.problems = [...kept(discovery.problems), ...pkg.problems];
1637
1716
  discovery.warnings = workspaceWarnings(discovery.workspace, discovery.members, discovery.external || [], pkg.souls);
1638
1717
  problems.splice(0, problems.length, ...kept(problems), ...pkg.problems);
@@ -1779,7 +1858,7 @@ const printWorkspaceAdd = (r) => r.written
1779
1858
  * `triggers.disabled` / `schedules.disabled`. */
1780
1859
  function setDisabledHereCli(ws, kind, qid, enabled) {
1781
1860
  const { path } = loadLocal(ws);
1782
- return A.setDisabledHere(path, kind, qid, !enabled, { validate: validateLocal });
1861
+ return A.setDisabledHere({ deployment: dirname(path), localPath: path }, kind, qid, !enabled);
1783
1862
  }
1784
1863
 
1785
1864
  const SYNC_USAGE = "usage: oats sync [--dir <deployment>] [--plan] [--json]";
@@ -2068,7 +2147,8 @@ const SOUL_TEAMS_REPLACEMENT = "souls: in oats-workspace.yaml (a PR to the works
2068
2147
  * model 3: the workspace's `souls:`, and the local teams it allows). Config only, read only. */
2069
2148
  async function soulCmd() {
2070
2149
  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]";
2150
+ const usage = `usage: oats soul teams <soul>|'*' [--dir <deployment>] [--max-age <s>] [--json] | ${SOUL_LAUNCH_USAGE}`;
2151
+ if (positional(1) === "launch") return soulLaunchCmd(bail, usage);
2072
2152
  const removed = SOUL_TEAMS_REMOVED_FLAGS.find((f) => args.some((a) => a === f || a.startsWith(`${f}=`)));
2073
2153
  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
2154
  if (positional(1) !== "teams") bail("E_USAGE", usage);
@@ -2100,6 +2180,70 @@ async function soulCmd() {
2100
2180
  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
2181
  }
2102
2182
 
2183
+ 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]";
2184
+ /** The flags each `oats soul launch` form takes (value flags → true). Anything else is refused, never
2185
+ * ignored: `--home` and `--soul` among them, since the soul is the argument and the file the deployment's. */
2186
+ const SOUL_LAUNCH_FLAGS = {
2187
+ set: { "--launch-config": true, "--harness": true, "--model": true },
2188
+ remove: {},
2189
+ };
2190
+ /** A souls.launch entry in words: a launch configuration's name, or the inline harness and model. */
2191
+ 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}` : ""}`);
2192
+
2193
+ /** `oats soul launch set <soul>|'*' (--launch-config <name>|none | --harness <h> [--model <id>]) |
2194
+ * remove <soul>|'*'|<exact key> [--plan] [--dir <deployment>] [--json]` (feature soul-launch): the
2195
+ * writer of oats-local.yaml souls.launch (lib/soul-launch-verbs.mjs). It reads the workspace live. */
2196
+ async function soulLaunchCmd(bail, usage) {
2197
+ const sub = positional(2);
2198
+ if (!["set", "remove"].includes(sub)) bail("E_USAGE", usage);
2199
+ // Every argument is accounted for before anything is read or written: a flag the form does not take, a
2200
+ // value flag with no value at ANY of its occurrences (`--harness codex --harness`), a value flag given
2201
+ // twice (flag() would read the first and drop the second) and a second name are refused, never ignored.
2202
+ const takes = { "--dir": true, "--json": false, "--plan": false, ...SOUL_LAUNCH_FLAGS[sub] };
2203
+ const names = [], given = new Set();
2204
+ for (let i = 3; i < args.length; i++) {
2205
+ const a = args[i];
2206
+ if (!a.startsWith("-")) { names.push(a); continue; }
2207
+ 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 });
2208
+ if (!takes[a]) continue;
2209
+ if (args[i + 1] === undefined || args[i + 1].startsWith("--")) bail("E_BAD_ARGS", `${a} needs a value`);
2210
+ if (given.has(a)) bail("E_BAD_ARGS", `oats soul launch ${sub} takes ${a} once (nothing was changed)`);
2211
+ given.add(a);
2212
+ i++;
2213
+ }
2214
+ 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}`);
2215
+ 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}`);
2216
+ const name = names[0];
2217
+ const V = await import("../lib/soul-launch-verbs.mjs");
2218
+ let value = null;
2219
+ if (sub === "set") {
2220
+ try { value = V.soulLaunchValue({ launchConfig: valueFlag("launch-config"), harness: valueFlag("harness"), model: valueFlag("model") }); }
2221
+ catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details); throw e; }
2222
+ }
2223
+ const ctx = workspaceContext(bail);
2224
+ const readSouls = async () => {
2225
+ const { discoverOrStandalone } = await import("../lib/instance-resolution.mjs");
2226
+ return discoverOrStandalone(ctx.local, { lock: readLockIfPresent(ctx.deploymentDir), deployment: ctx.deploymentDir, remoteOptions: ctx.remoteOptions });
2227
+ };
2228
+ let r;
2229
+ try { r = await V.soulLaunch({ deployment: ctx.deploymentDir, localPath: ctx.localPath }, { action: sub, name, value, plan: args.includes("--plan") }, { readSouls }); }
2230
+ catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details ?? e.provenance); throw e; }
2231
+ if (JSON_MODE) { jsonOk(r); return; }
2232
+ const key = JSON.stringify(r.key), file = shortPath(r.file);
2233
+ if (!r.changed) console.log(`souls.launch ${key} is already ${launchEntryText(r.after)} in ${file}: nothing to change`);
2234
+ 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" : ""}`);
2235
+ else console.log(`${r.plan ? "Would remove" : "Removed"} souls.launch ${key} (${launchEntryText(r.before)}) from ${file}${r.plan ? "; nothing was written" : ""}`);
2236
+ 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; }
2237
+ 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)`);
2238
+ if (r.key === "*") console.log(`"*" is the launch of every soul without an entry of its own`);
2239
+ else if (r.launch === null) console.log(`${key} is the key of no soul this workspace offers`);
2240
+ else {
2241
+ const e = r.launch.effective;
2242
+ 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}` : ""}`);
2243
+ }
2244
+ 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 })}`);
2245
+ }
2246
+
2103
2247
  /** The catalog's rows of `kind` ("capabilities" | "souls") as `oats capabilities` / `oats souls` list them:
2104
2248
  * one discovery (honouring --max-age), the lock, workspaceItems. → { ctx, discovery, lock, items }. */
2105
2249
  async function catalogRows(kind, bail) {
@@ -2124,13 +2268,32 @@ async function itemsCmd(kind) {
2124
2268
  if (kind === "capabilities") await capabilityFacts(items, discovery, lock, ctx, remote);
2125
2269
  if (kind === "souls") await soulFacts(items, discovery, lock, ctx, remote);
2126
2270
  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; }
2271
+ // `oats souls` reads souls.launch for every soul it lists: a key that names none of them is a problem
2272
+ // of this read, one row per key (the souls a spawn would refuse carry it as launch.problem).
2273
+ const unmatched = kind === "souls" ? launchKeysUnmatched({ local: ctx.local, offered: soulsOffered(discovery) }).unmatched.map(unmatchedProblemRow) : [];
2274
+ const problems = [...discovery.problems, ...unmatched];
2275
+ if (JSON_MODE) { jsonOk(withObservation({ [`${kind}Api`]: 1, standalone: standalone || undefined, workspace: { name: workspaceName(discovery), key: discovery.key, commit: discovery.commit }, [kind]: items, problems })); return; }
2128
2276
  console.log(`${kind} of workspace ${workspaceName(discovery)} (${discovery.key} @ ${short(discovery.commit)})${standalone ? ` — ${standaloneNote(discovery)}` : ""}\n`);
2129
2277
  if (!items.length) console.log(" (none)");
2130
2278
  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
2279
  else printTable(["name", "origin", "layer"], items.map((c) => [c.private ? `${c.name} (repo-owned)` : c.name, c.origin, c.layer ?? "—"]));
2132
2280
  const unsynced = Object.keys(discovery.workspace?.packages || {}).filter((id) => !lock.packages[id]);
2133
2281
  if (kind === "capabilities" && unsynced.length) console.log(`\n package capabilities of ${unsynced.join(", ")} appear after \`oats sync\``);
2282
+ for (const p of problems) console.log(`\n${catalogProblemLine(p)}`);
2283
+ }
2284
+
2285
+ /** Owner fields decide context, never message text. A problem source is display data;
2286
+ * render that projection without changing the operational external source. */
2287
+ function catalogProblemLine(p) {
2288
+ const owner = p.repoKey || p.package || (p.source ? remoteModule.redactUrl(p.source, null, { pinned: true }) : null);
2289
+ const where = owner ? ` [${terminalText(`${owner}: ${p.path}`)}]` : "";
2290
+ return `! ${p.code}: ${p.message}${where}`;
2291
+ }
2292
+
2293
+ /** A key of souls.launch that names no soul (lib/launch-preference.mjs launchKeysUnmatched's row) as a
2294
+ * row of `oats souls --json` `problems`: `path` is where the key is. */
2295
+ function unmatchedProblemRow(row) {
2296
+ return { code: LAUNCH_PREFERENCE_UNMATCHED, path: row.at, message: unmatchedKeyMessage(row), key: row.key, value: row.value, suggestions: row.suggestions };
2134
2297
  }
2135
2298
 
2136
2299
  /** `oats capabilities` argv after the command: its words (the subcommand first) with every flag and a value
@@ -2884,7 +3047,7 @@ function retireCmd() {
2884
3047
  if (args.includes("--json")) { jsonOk(plan); return; }
2885
3048
  console.log(`retire ${name} — plan ${plan.planRevision}`);
2886
3049
  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}`);
3050
+ console.log(` ${retireDefaultsLine(plan)}`);
2888
3051
  for (const n of plan.notes) console.log(` note: ${n}`);
2889
3052
  return;
2890
3053
  } catch (e) { return lifecycleFail(e, "E_LIFECYCLE_FAILED", e.candidates ? { ...e.details, candidates: e.candidates } : e.details); }
@@ -3002,7 +3165,7 @@ function retireCmd() {
3002
3165
  // which is most of the harm of deleting it. Name the classes and the path.
3003
3166
  for (const line of workRecoveryLines(r)) console.log(line);
3004
3167
  for (const line of extraWorktreeLines(r)) console.log(line);
3005
- for (const w of r.warnings || []) console.log(` WARNING: ${w}`);
3168
+ for (const line of warningLines(r)) console.log(line);
3006
3169
  if (isSelf) console.log("This window dies in ~8s — say any goodbyes now.");
3007
3170
  }
3008
3171
 
@@ -3308,7 +3471,7 @@ async function sessionCmd() {
3308
3471
  // recorded launch stays frozen (a changed preference never reaches an existing home on its own).
3309
3472
  const reselectLaunch = args.includes("--reselect-launch");
3310
3473
  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)) };
3474
+ 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
3475
  if (args[1] === "restart") {
3313
3476
  const grace = flag("stop-grace");
3314
3477
  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 +3905,8 @@ async function capabilityCommand() {
3742
3905
  // canonical absolute executable of THIS CLI; official consumers execFile
3743
3906
  // it directly and never resolve `oats` from PATH or a shell.
3744
3907
  OATS_CLI_BIN: CLI_BIN,
3908
+ // The node a command writes into anything that outlives it (lib/stable-node.mjs).
3909
+ OATS_NODE_BIN: kernelNode().node,
3745
3910
  ...teamEnv(null), ...(teamCtx || {}),
3746
3911
  // The soul the command acts for (an instance home's recorded soul directory):
3747
3912
  // homes carry no soul link, so providers read it here.
@@ -3763,40 +3928,70 @@ async function capabilityCommand() {
3763
3928
  // ---------- update ----------
3764
3929
  function updateCmd() {
3765
3930
  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}`); }
3931
+ // The deployment whose launch configurations name pi folders: at or above the working
3932
+ // directory, or --dir. Without one, or with one that does not load, the update still runs on
3933
+ // the default folder and this shell's, and says so first and last: an operator reads the end.
3934
+ let deployment = null, launchConfigs = {}, notLookedAt = null;
3935
+ try { deployment = dirname(loadLocal(dirFlag()).path); launchConfigs = launchConfigsAt(deployment); }
3936
+ catch (e) {
3937
+ // An explicit --dir with no deployment at or above it is refused, a 0.25 configuration there included.
3938
+ if (e?.code === "E_LOCAL_MISSING" && flag("dir") !== undefined) die(e.message);
3939
+ 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.`;
3940
+ 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>.`;
3941
+ launchConfigs = {};
3942
+ }
3943
+ const end = (text) => { console.log(text); if (notLookedAt) console.log(`\n${notLookedAt}`); };
3944
+ const fail = (text) => die(notLookedAt ? `${text}\n${notLookedAt}` : text);
3945
+ // What npm printed is checked to be one version before it reaches a step, an argument or the
3946
+ // screen (awebai/oats#1011). Both streams are captured: spawnSync forwards neither.
3947
+ const asked = kernelLookup();
3948
+ const { version: latest, problem: notChecked } = kernelLookupResult(spawnSync(asked[0], asked.slice(1), { encoding: "utf8", timeout: 30000 }));
3949
+ if (notChecked) fail(notChecked);
3769
3950
  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}`);
3951
+ // Forward only: the CLI moves to a newer version of the registry, never back to an older one.
3952
+ // `target` is the version the kernel has after the run, which the bridges are brought to.
3953
+ const cli = planCliUpdate(OATS_VERSION, latest), { target } = cli;
3954
+ if (cli.note) console.log(cli.note);
3955
+ // The pi bridge, in every pi folder a launch of the deployment uses (lib/pi-bridge.mjs).
3956
+ const plan = planPiBridges(piBridgeFolders({ launchConfigs }), target);
3957
+ console.log(`\n${PI_BRIDGE} ${target} (published in lockstep), by pi folder${deployment && !notLookedAt ? ` of ${deployment}` : ""}:`);
3958
+ for (const line of piBridgePlanLines(plan, cli)) console.log(line);
3959
+ if (notLookedAt) console.log(` ${notLookedAt}`);
3960
+ const moves = plan.filter((entry) => entry.step);
3961
+ const untouched = plan.filter((entry) => entry.action === "skip").length;
3962
+ const untouchedNote = untouched ? ` ${untouched} pi folder${untouched > 1 ? "s were" : " was"} not touched: see above for what to run there.` : "";
3963
+ const steps = [...(cli.step ? [cli.step] : []), ...moves.map((entry) => ({ ...entry.step, entry }))];
3964
+ // "Up to date" is not said over a folder it does not touch, nor over a CLI or a bridge ahead.
3965
+ const ahead = cli.ahead || plan.some((entry) => entry.ahead);
3966
+ if (!steps.length) return end(untouched || ahead ? `\nNothing for \`oats update\` to run.${untouchedNote}` : "\nUp to date.");
3779
3967
  console.log("\nUpdate steps:");
3780
- for (const s of steps) console.log(` ${s}`);
3781
- if (checkOnly) { console.log("\n(--check: not executing)"); return; }
3968
+ for (const s of steps) console.log(` ${s.display}`);
3969
+ if (checkOnly) return end("\n(--check: not executing)");
3782
3970
  const interactive = process.stdin.isTTY && process.stdout.isTTY;
3783
3971
  if (interactive) {
3784
3972
  process.stdout.write("\nRun these now? [y/N] ");
3785
3973
  const buf = Buffer.alloc(16);
3786
3974
  let answer = "";
3787
3975
  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;
3976
+ if (answer !== "y" && answer !== "yes") return end("Not updating.");
3977
+ } else if (!args.includes("--yes")) return end("\nNon-interactive: pass --yes to execute, or run the steps yourself.");
3978
+ // Before any step, the CLI's included: the bridge's exact version is seen on the registry by a
3979
+ // lookup that revalidates npm's cache (awebai/oats#852). A version is listed a while after it
3980
+ // is published, and the kernel's "latest" says nothing about the bridge's.
3981
+ if (moves.length) {
3982
+ const lookup = bridgeLookup(target);
3983
+ console.log(`\n$ ${lookup.join(" ")}`);
3984
+ const notSeen = bridgeLookupProblem(spawnSync(lookup[0], lookup.slice(1), { encoding: "utf8", timeout: 30000 }), cli);
3985
+ if (notSeen) fail(notSeen);
3792
3986
  }
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}`);
3987
+ for (const [i, s] of steps.entries()) {
3988
+ console.log(`\n$ ${s.display}`);
3989
+ const r = spawnSync(s.argv[0], s.argv.slice(1), { stdio: "inherit", env: { ...process.env, ...s.env } });
3990
+ const ran = r.error ? `${s.argv[0]}: ${r.error.message}` : r.status !== 0 ? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`) : null;
3991
+ const problem = s.entry ? piBridgeStepProblem(s.entry, target, ran) : ran;
3992
+ 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
3993
  }
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.`);
3994
+ 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
3995
  }
3801
3996
 
3802
3997
  // ---------- version (Desktop CLI API v1 probe) ----------
@@ -3831,6 +4026,16 @@ function versionCmd() {
3831
4026
  const EXPERIMENTAL_CMDS = new Set(["dress", "spawn", "segments", "mind"]);
3832
4027
  async function recordCmd(sub) {
3833
4028
  process.argv.splice(2, 1);
4029
+ if (sub === "setup") {
4030
+ // setup writes a node into the user's Claude settings and into the capture watcher's unit,
4031
+ // and nothing rewrites them but setup run again: it is handed the rule's answer for the node
4032
+ // running this kernel (docs/capabilities.md, "The node a hook writes down"). The script is
4033
+ // imported into this process, so the variable is set here, over whatever the caller's
4034
+ // environment held; packages/record imports nothing of the kernel.
4035
+ const { node, warning } = stableNode({ consequence: "the capture hooks and the capture watcher stop when it goes away", remedy: "run `oats setup` again" });
4036
+ if (warning) console.error(`oats: warning: ${warning}`);
4037
+ process.env.OATS_NODE_BIN = node;
4038
+ }
3834
4039
  await import(new URL(`../packages/record/bin/${sub}.mjs`, import.meta.url));
3835
4040
  }
3836
4041
  async function experimentalCmd() {
@@ -4446,9 +4651,12 @@ Usage:
4446
4651
  Desktop CLI API v1 probe payload
4447
4652
  oats status [--json] agents, souls, running instances
4448
4653
  [--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
4654
+ oats tui [--dir <path>] [--ascii] PREVIEW: the full-screen terminal client (docs/tui.md):
4655
+ the instances of the workspace of the deployment at or
4656
+ above <path> (default: where you are), on this machine
4657
+ and on the machines registered here; it changes nothing.
4658
+ ? help, w workspaces, q quit. Needs a terminal on stdin and
4659
+ stdout and has no --json form; --ascii = ASCII rules and marks
4452
4660
  oats server add <id> --ssh <alias> register another machine's OATS (OpenSSH alias,
4453
4661
  --workspace </abs/path> [--oats <p>] remote workspace, remote oats path; no keys stored;
4454
4662
  [--path <dir:dir>] --path = dirs prepended to the remote PATH, e.g. ~/.local/bin)
@@ -4616,8 +4824,9 @@ Usage:
4616
4824
  [--yolo | --no-yolo] --json a disagreeing --harness is refused
4617
4825
  oats doctor [dir] [--soul <name>] [--json] resolved targets, trust, requirements;
4618
4826
  --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
4827
+ oats update [--check] [--yes] check npm for a newer kernel and move the pi bridge
4828
+ [--dir <deployment>] in every pi folder the deployment's launches use
4829
+ (docs/upgrading.md); then run oats doctor
4621
4830
  oats sync [--dir <d>] [--plan] [--json] workspace model v2: observe the workspace named by
4622
4831
  oats-local.yaml over its Git remote, confirm every
4623
4832
  member (reciprocal oats-membership.yaml), resolve
@@ -4653,6 +4862,19 @@ Usage:
4653
4862
  where there is none / it is <label>
4654
4863
  oats soul teams <soul>|'*' [--dir <d>] which teams a soul may join here, its default, and
4655
4864
  [--max-age <s>] [--json] why (the workspace's souls: and local teams)
4865
+ oats soul launch set <soul>|'*' (--launch-config <name>|none | --harness pi|claude|codex [--model <id>])
4866
+ [--plan] [--dir <d>] [--json] pin a soul's launch on this machine: writes its key
4867
+ (its bare name, or <package>/<soul>; '*' = every soul
4868
+ without an entry) in oats-local.yaml souls.launch.
4869
+ The file is rewritten; every other entry keeps its
4870
+ value and its comments. --plan: every check, nothing
4871
+ written. It reads the workspace live (no --max-age)
4872
+ oats soul launch remove <soul>|'*'|<exact key> [--plan] [--dir <d>] [--json]
4873
+ remove one entry of souls.launch: a soul's, '*', or
4874
+ the exact text of a key in the file (that form works
4875
+ when the workspace's souls cannot be read, and is how
4876
+ a key that names no soul is removed); no such entry is
4877
+ E_LAUNCH_PREFERENCE_UNKNOWN
4656
4878
  oats instance git <instance> [--home <abs>] [--dir <d>] [--json]
4657
4879
  read-only Git observation of the instance's work
4658
4880
  tree: branch, status (renames kept), ahead/behind