@awebai/oats 0.68.1 → 0.69.2

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 (99) hide show
  1. package/bin/oats.mjs +180 -36
  2. package/docs/capabilities.md +73 -10
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/configuration.md +68 -2
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  6. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  7. package/docs/desktop-cli-api.md +600 -25
  8. package/docs/desktop-instance-start.md +59 -3
  9. package/docs/desktop.md +175 -10
  10. package/docs/execution-targets.md +536 -62
  11. package/docs/harness-trust.md +3 -1
  12. package/docs/implementation.md +33 -15
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge.md +25 -16
  15. package/docs/oats-local.schema.json +2 -2
  16. package/docs/official-catalog.md +6 -5
  17. package/docs/packages.md +14 -14
  18. package/docs/release-notes/v0.69.0.md +658 -0
  19. package/docs/release-notes/v0.69.1.md +25 -0
  20. package/docs/release-notes/v0.69.2.md +259 -0
  21. package/docs/servers.md +51 -7
  22. package/docs/soul.schema.json +1 -0
  23. package/docs/souls-and-instances.md +46 -9
  24. package/docs/tui.md +177 -21
  25. package/docs/upgrading.md +16 -7
  26. package/docs/workspaces.md +2 -2
  27. package/injects/instance-boundary.md +19 -33
  28. package/injects/work-attached.md +8 -13
  29. package/injects/work-checkout.md +16 -30
  30. package/injects/work-directory.md +9 -15
  31. package/injects/work-workspace.md +8 -19
  32. package/injects/work-worktree.md +18 -33
  33. package/lib/capability-contract.mjs +2 -2
  34. package/lib/core.mjs +496 -127
  35. package/lib/file-pieces.mjs +49 -0
  36. package/lib/instance-background.mjs +54 -0
  37. package/lib/instance-events.mjs +25 -4
  38. package/lib/instance-inspect.mjs +3 -0
  39. package/lib/instance-lifecycle.mjs +35 -0
  40. package/lib/instance-resolution.mjs +3 -2
  41. package/lib/instance-same-work.mjs +67 -0
  42. package/lib/instance-upgrade.mjs +18 -0
  43. package/lib/launch-prompt-fixtures/README.md +62 -0
  44. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  45. package/lib/launch-prompt-fixtures.mjs +49 -0
  46. package/lib/launch-prompt-resume.mjs +55 -0
  47. package/lib/login-environment.mjs +27 -9
  48. package/lib/materialize.mjs +23 -2
  49. package/lib/resolve.mjs +32 -5
  50. package/lib/schedule.mjs +3 -3
  51. package/lib/servers.mjs +136 -27
  52. package/lib/session-end.mjs +82 -0
  53. package/lib/session-input.mjs +43 -9
  54. package/lib/session-resume-contract.mjs +33 -0
  55. package/lib/session-resume.mjs +337 -0
  56. package/lib/session-seen.mjs +163 -0
  57. package/lib/session-viewer.mjs +147 -44
  58. package/lib/soul-composition.mjs +15 -11
  59. package/lib/start-env.mjs +110 -0
  60. package/lib/tmux-server-scope.mjs +139 -14
  61. package/lib/workspace.mjs +41 -6
  62. package/package-catalog.json +11 -5
  63. package/package.json +1 -1
  64. package/packages/client/cli-adapter.mjs +39 -8
  65. package/packages/client/cli-locator.mjs +3 -2
  66. package/packages/client/deployment-data.mjs +16 -0
  67. package/packages/client/deployment-panel.mjs +7 -0
  68. package/packages/client/file-output-exec.mjs +98 -0
  69. package/packages/client/instance-tree.mjs +64 -14
  70. package/packages/client/launch-prompt-outcome.mjs +25 -13
  71. package/packages/client/own-codes.mjs +2 -0
  72. package/packages/client/panel-views.mjs +11 -3
  73. package/packages/client/remote-roster.mjs +5 -1
  74. package/packages/client/roster-sections.mjs +50 -6
  75. package/packages/client/same-work.mjs +49 -0
  76. package/packages/client/session-attach.mjs +35 -5
  77. package/packages/client/session-resume-cli.mjs +64 -0
  78. package/packages/client/session-resume-trigger.mjs +167 -0
  79. package/packages/client/session-resume.mjs +332 -0
  80. package/packages/client/soul-rows.mjs +2 -0
  81. package/packages/client/spawn-apply-contract.mjs +2 -1
  82. package/packages/client/spawn-decision.mjs +4 -1
  83. package/packages/client/spawn-preview-contract.mjs +12 -1
  84. package/packages/client/spawn-preview.mjs +2 -0
  85. package/packages/client/tmux-status.mjs +30 -7
  86. package/packages/client/waiting-on-you.mjs +11 -4
  87. package/packages/client/workspace-step.mjs +17 -5
  88. package/packages/record/lib/last-conversation.mjs +123 -0
  89. package/packages/record/lib/session-roots.mjs +10 -1
  90. package/packages/tui/README.md +2 -2
  91. package/packages/tui/lib/client.mjs +7 -3
  92. package/packages/tui/lib/main.mjs +49 -14
  93. package/packages/tui/lib/model.mjs +146 -55
  94. package/packages/tui/lib/store.mjs +84 -27
  95. package/packages/tui/lib/term/text.mjs +12 -9
  96. package/packages/tui/lib/views/frame.mjs +74 -7
  97. package/packages/tui/lib/views/help.mjs +10 -3
  98. package/packages/tui/lib/views/instances.mjs +41 -3
  99. package/skills/oats-getting-started/SKILL.md +117 -4
package/bin/oats.mjs CHANGED
@@ -33,7 +33,7 @@ import {
33
33
  LAYERS, OATS_VERSION, manifestOperations, upgradeHomeMeta,
34
34
  capabilityManifests, capabilityTrust, capabilityExecutablePath,
35
35
  officialPackageCatalog, officialCatalogFile, officialCapabilityAliases, resolvedFromHome, resolvedFromPrepared, teamEnv, isWorkspaceHome, preWorkspaceHome, isCapturedHome, capturedHomeRefusal, composeInstanceAgentsMd, parseYamlNested, withConfigFile,
36
- findInstanceHome, findInstanceHomes, homeLaunchLayers, processScanInformation, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, suggestSpawnName, 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,
36
+ findInstanceHome, findInstanceHomes, homeLaunchLayers, processScanInformation, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, suggestSpawnName, instanceSoulDir, stableSoulId, preparedSoulIdOf, recordedKernelBin, launchConfigsAt, machineLaunchConfigs, machineLaunchConfigsFile, 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,
37
37
  FAILED_SPAWN_BRANCH_LEFT, RETIRE_DELETE_BRANCH_REFUSED,
38
38
  } from "../lib/core.mjs";
39
39
  import {
@@ -52,6 +52,7 @@ import * as remoteModule from "../lib/remote.mjs";
52
52
  import { activateLocalInputs, localRevision } from "../lib/local-inputs.mjs";
53
53
  import YAML from "yaml";
54
54
  import { attachArgv, checkRemote, connectServer, forgetSnapshot, getServer, inspectRemote, startRemote, restartRemote, launchConfigRemote, scheduleRemote, listSnapshots, learnWorkspaceKey, readServers, redactArgv, reportedWorkspaceKey, rosterGroups, routeCapability, routeCommand, runRemote, serverFlagOf, targetOf, updateServers, validateServer, workspaceKeyOfStatus, workspaceMismatch, SERVERS_FILE } from "../lib/servers.mjs";
55
+ import { readSessionViewer } from "../lib/session-viewer.mjs";
55
56
  import { spawnSync as spawnSyncProc } from "node:child_process";
56
57
  import { tickTriggers } from "../lib/triggers.mjs";
57
58
  import * as A from "../lib/automations.mjs";
@@ -61,7 +62,7 @@ import { kernelNode, stableNode } from "../lib/stable-node.mjs";
61
62
  import { receiveAttachment, uploadAttachment, readStreamBounded, MAX_ATTACHMENT_BYTES } from "../lib/attachments.mjs";
62
63
 
63
64
  import { observeInstanceGit, diffInstanceFile } from "../lib/instance-git.mjs";
64
- import { planStop, applyStop, planRetire, retireDefaultsLine, stopClosingLine, descendantsOf, resolveInstance as resolveInstanceForCli, setInstanceColor, STOP_WARNINGS } from "../lib/instance-lifecycle.mjs";
65
+ import { planStop, applyStop, planRetire, retireDefaultsLine, stopClosingLine, descendantsOf, resolveInstance as resolveInstanceForCli, setInstanceColor, setInstanceBackground, setInstanceSameWork, STOP_WARNINGS } from "../lib/instance-lifecycle.mjs";
65
66
  import { extraWorktreeLines, formatBytes, warningLines, workRecoveryLines } from "../lib/retire-output.mjs";
66
67
  import { retainedRecoveryLines, retainedWorktreeLines, retainedWorktrees } from "../lib/retained-after-retire.mjs";
67
68
  const await_import_lifecycle = () => ({ resolveInstance: resolveInstanceForCli });
@@ -69,10 +70,11 @@ import { homeTarget, soulTarget, isWorkspaceContext, inspectDocument, withCompos
69
70
  import { readEvents, setWaiting, incarnationOf } from "../lib/instance-events.mjs";
70
71
  import { CLIENT_VIA, addDeployment, deploymentAtOrAbove, importDesktopDeployments, listDeployments, listResolved, removeDeployment } from "../lib/deployments.mjs";
71
72
  import { observeResolvedDeployment } from "../lib/resolved-deployment.mjs";
73
+ import { SESSION_RESUME_FEATURE } from "../lib/session-resume-contract.mjs";
72
74
 
73
75
  const rawArgs = process.argv.slice(2);
74
76
  /** The kernel's switches: a value never rides one (`--yolo=false` must not turn yolo on). */
75
- const KERNEL_SWITCHES = new Set(["allow-child-spawns", "apply", "check", "clear", "composed-skills", "delete-branch", "discard-worktree", "dry-run", "ephemeral", "force", "help", "host", "if-absent", "install-oats", "instructions", "json", "keep-dir", "keep-env", "no-child-spawns", "no-default", "no-launch", "no-recursive", "no-yolo", "plan", "policy", "preview", "print", "replace", "run-source", "self", "skills", "suggest-name", "verbose", "yes", "yolo"]);
77
+ const KERNEL_SWITCHES = new Set(["allow-child-spawns", "apply", "background", "check", "clear", "composed-skills", "delete-branch", "discard-worktree", "dry-run", "ephemeral", "force", "help", "host", "if-absent", "install-oats", "instructions", "json", "keep-dir", "keep-env", "no-background", "no-child-spawns", "no-default", "no-launch", "no-recursive", "no-yolo", "plan", "policy", "preview", "print", "replace", "run-source", "same-work", "self", "skills", "suggest-name", "verbose", "yes", "yolo"]);
76
78
  /** `--flag=value` is `--flag value`: every kernel reader (flag(), valueFlag(), the onboard and
77
79
  * routed-command loops) then applies the spaced form's validation to it. `problem` is an empty
78
80
  * `--flag=`, a switch given a value, or a value that is itself an option (`--model=--yolo`):
@@ -108,7 +110,7 @@ const OWN_ARGV_COMMANDS = new Set(["capture", "recall", "setup", "experimental",
108
110
  * probe) and in `status --json`, which a remote roster relays as the host's (feature
109
111
  * server-probe-features, lib/servers.mjs hostFeatures). ONE list for both, emitted at output
110
112
  * time, never stored. A name must pass hostFeatures's check (test/cli-json-contract.test.mjs). */
111
- 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", "spawn-kernel-codes", "soul-skills", "roster-workspace-key", "spawn-apply-max-age", "status-retire-state", "session-inspect-size", "session-inspect-running", "deployments-list", "soul-composed-skills", "instance-color", "spawn-suggest-name", "instance-upgrade", "instance-suggest-name", "spawn-apply-suggest-name"];
113
+ 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", "spawn-kernel-codes", "soul-skills", "roster-workspace-key", "spawn-apply-max-age", "status-retire-state", "session-inspect-size", "session-inspect-running", "deployments-list", "soul-composed-skills", "instance-color", "spawn-suggest-name", "instance-upgrade", "session-attach-no-status-line", "session-attach-prefix-scroll", "instance-suggest-name", "spawn-apply-suggest-name", SESSION_RESUME_FEATURE, "instance-background", "instance-same-work"];
112
114
  /** Commands `--server <id>` runs on a registered server. */
113
115
  const ROUTED_COMMANDS = new Set(["spawn", "retire", "status", "session", "okf", "schedule", "inspect", "operation", "launch-config", "readiness", "instance"]);
114
116
  const flag = (name) => {
@@ -824,6 +826,19 @@ function doctorRetained(ws) {
824
826
  const kept = retainedWorktrees(deployment);
825
827
  return [retainedRecoveryLines(join(deployment, "agents"), kept), retainedWorktreeLines(kept)].filter((block) => block.length);
826
828
  }
829
+ /** The machine's launch configurations file (awebai/oats#1506) as doctor reports it: its path, whether
830
+ * it is there, its entries' names and whether it is valid. A broken file is reported, never a failure
831
+ * of doctor; the launches it would affect refuse it. */
832
+ function doctorMachineLaunchConfigs() {
833
+ const file = machineLaunchConfigsFile();
834
+ try {
835
+ const machine = machineLaunchConfigs();
836
+ return { file, present: machine !== null, ok: true, configurations: Object.keys(machine?.configs ?? {}).sort() };
837
+ } catch (e) {
838
+ if (e?.code !== "E_LAUNCH_CONFIG_INVALID") throw e;
839
+ return { file, present: true, ok: false, configurations: [], error: e.message };
840
+ }
841
+ }
827
842
  async function doctorWorkspaceJson(ctx, soulName, ws) {
828
843
  const composition = await doctorComposition(ctx, soulName, ws, (code, msg, details) => jsonFail(code, msg, details));
829
844
  const agentsRoot = join(dirname(ws.local.path), "agents");
@@ -839,6 +854,7 @@ async function doctorWorkspaceJson(ctx, soulName, ws) {
839
854
  workspace: { file: ws.local.path, ref: ws.local.workspace },
840
855
  workspaceError: ws.localError, lockFile: ws.lockFile, packages: ws.packages, lockError: ws.lockError,
841
856
  information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information, ...launchPreferences.information, ...hookEvents.information, ...processScanInformation(), ...doctorRetained(ws).flat()],
857
+ machineLaunchConfigs: doctorMachineLaunchConfigs(),
842
858
  composedInstructions: composition?.text, instructionBlocks: composition?.blocks,
843
859
  ...(problems.length ? { problems } : {}),
844
860
  warnings: [...hookEvents.warnings, ...(soulName ? [] : doctorCaptureWarnings())],
@@ -876,6 +892,9 @@ async function doctor(dir) {
876
892
  doctorVersionSkew(dirname(ws.local.path));
877
893
  const composition = await doctorComposition(ctx, soulName, ws, (code, msg) => die(`${msg} [${code}]`));
878
894
  printDoctorWorkspace(ws);
895
+ const machine = doctorMachineLaunchConfigs();
896
+ console.log("\nThis machine's launch configurations:");
897
+ console.log(` ${shortPath(machine.file)} ${!machine.present ? "(none: no file)" : machine.ok ? (machine.configurations.join(", ") || "(none declared)") : `ERROR: ${terminalText(machine.error)}`}`);
879
898
  const agentsRoot = join(dirname(ws.local.path), "agents");
880
899
  const localTeams = doctorLocalTeams(ws.local.value);
881
900
  for (const p of [...legacyLayoutProblems(agentsRoot), readableInstanceHomes(agentsRoot)].filter(Boolean)) console.log(`\n! ${p.code}: ${p.message}`);
@@ -984,6 +1003,15 @@ function readLaunchConfigsModel(local) {
984
1003
  for (const [n, e] of Object.entries(map)) out[n] = normalizeLaunchConfig(e);
985
1004
  return out;
986
1005
  }
1006
+ /** Whether the machine's launch configurations file declares `name`; a broken file declares nothing here
1007
+ * (the launches it affects refuse it). */
1008
+ /** The file a launch configuration of this machine was declared in, from its `source` directory. */
1009
+ function launchConfigFile(source) {
1010
+ return source === dirname(machineLaunchConfigsFile()) ? machineLaunchConfigsFile() : join(source, "oats-local.yaml");
1011
+ }
1012
+ function machineDeclares(name) {
1013
+ try { return Object.hasOwn(machineLaunchConfigs()?.configs ?? {}, name); } catch (e) { if (e?.code === "E_LAUNCH_CONFIG_INVALID") return false; throw e; }
1014
+ }
987
1015
  /** What a GUI or an operator sees of one configuration. Environment values
988
1016
  * never leave the file: a literal is answered as {redacted: true} (literals
989
1017
  * are non-secret by contract, but no value is shown anywhere) and a
@@ -1092,10 +1120,10 @@ async function launchConfigCmd() {
1092
1120
  let configurations;
1093
1121
  try { configurations = effective(); } catch (e) { bail(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1094
1122
  if (JSON_MODE) { jsonOk({ context: dir, level, file, selected, configurations }); return; }
1095
- if (!configurations.length) { console.log(`No launch configurations are declared${file ? ` in ${shortPath(file)}` : ` (no oats-local.yaml in reach of ${dir})`}`); return; }
1123
+ if (!configurations.length) { console.log(`No launch configurations are declared${file ? ` in ${shortPath(file)}` : ` (no oats-local.yaml in reach of ${dir})`} or in ${shortPath(machineLaunchConfigsFile())}`); return; }
1096
1124
  for (const c of configurations) {
1097
1125
  const env = Object.entries(c.env).map(([n, v]) => v.fromEnv ? `${n}=$${v.fromEnv}` : `${n}=<redacted>`).join(" ");
1098
- console.log(`${c.name}: ${c.harness}${c.default ? ` (this machine's ${c.harness} default)` : ""}${c.executable ? ` ${c.executable}` : ""}${c.args.length ? ` ${c.args.map((a) => JSON.stringify(a)).join(" ")}` : ""}${env ? ` [${env}]` : ""}${c.model ? ` model ${c.model}` : ""}${c.yolo !== null ? ` yolo ${c.yolo}` : ""}`);
1126
+ console.log(`${c.name}: ${c.harness}${c.default ? ` (this machine's ${c.harness} default)` : ""}${c.executable ? ` ${c.executable}` : ""}${c.args.length ? ` ${c.args.map((a) => JSON.stringify(a)).join(" ")}` : ""}${env ? ` [${env}]` : ""}${c.model ? ` model ${c.model}` : ""}${c.yolo !== null ? ` yolo ${c.yolo}` : ""} (from ${shortPath(launchConfigFile(c.source))})${c.shadows.length ? ` (replaces ${c.shadows.map(shortPath).join(", ")}'s)` : ""}`);
1099
1127
  }
1100
1128
  return;
1101
1129
  }
@@ -1141,16 +1169,18 @@ async function launchConfigCmd() {
1141
1169
  const declaredHere = Object.hasOwn(model, name);
1142
1170
  before = declaredHere ? publicLaunchConfig(model[name]) : null;
1143
1171
  if (sub === "remove") {
1144
- if (!declaredHere) throw refusal("E_LAUNCH_CONFIG_UNKNOWN", `${name} is not declared in ${shortPath(file)}`);
1172
+ if (!declaredHere) throw refusal("E_LAUNCH_CONFIG_UNKNOWN", `${name} is not declared in ${shortPath(file)}${machineDeclares(name) ? `; it is this machine's, in ${shortPath(machineLaunchConfigsFile())}, which OATS never writes` : ""}`);
1145
1173
  delete model[name];
1146
1174
  } else {
1147
1175
  let written = entry;
1148
1176
  if (keepEnv) {
1149
1177
  // An editor that saw only redacted values keeps the environment of the
1150
1178
  // declared definition of that name: a one-time copy into the complete
1151
- // replacement entry.
1152
- const current = declaredHere ? model[name] : undefined;
1153
- 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`);
1179
+ // replacement entry. A name only this machine declares keeps the machine
1180
+ // entry's, so the first save of a machine row writes the entry that shadows it.
1181
+ let current = declaredHere ? model[name] : undefined;
1182
+ if (!current) { try { const machine = machineLaunchConfigs()?.configs ?? {}; if (Object.hasOwn(machine, name)) current = machine[name]; } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message, e.details); } }
1183
+ if (!current) throw refusal("E_LAUNCH_CONFIG_UNKNOWN", `--keep-env: no launch configuration ${name} is declared in ${shortPath(file)} or in ${shortPath(machineLaunchConfigsFile())}, so there is no environment to keep; declare it with env`);
1154
1184
  if (Object.keys(current.env || {}).length) written = { ...entry, env: { ...current.env } };
1155
1185
  try { validateLaunchConfig(name, written, `--file ${f}`); } catch (e) { throw refusal(e.code || "E_LAUNCH_CONFIG_INVALID", e.message); }
1156
1186
  }
@@ -1381,8 +1411,8 @@ async function instanceCmd() {
1381
1411
  if (sub === "upgrade") return instanceUpgradeCmd(name, bail);
1382
1412
  if (sub === "waiting" || sub === "attention") return instanceWaitingCmd(sub, bail);
1383
1413
  if (sub === "suggest-name") return instanceSuggestNameCmd(bail);
1384
- const usage = "usage: oats instance waiting <set|clear> --producer <id> [--reason permission|question|attention] [--message <text>] [--home <abs>] [--dir <d>] [--json] | oats instance attention [--message <text>] [--clear] [--json] | oats instance events <instance> [--limit <n>] [--since <iso>] [--home <abs>] [--dir <d>] [--json] | oats instance git <instance> [--home <abs>] [--dir <d>] [--json] | oats instance diff <instance> --file <id> --revision <rev> [--index-revision <rev>] [--home <abs>] [--dir <d>] [--json] | oats instance stop <instance> (--plan | --apply --plan-revision <rev> --idempotency-key <key>) [--no-recursive] [--grace-ms <n>] [--home <abs>] [--dir <d>] [--json] | oats instance color <instance> (<color> | --clear) [--home <abs>] [--dir <d>] [--json]";
1385
- if (!["git", "diff", "stop", "events", "color"].includes(sub) || !name || name.startsWith("--")) return bail("E_BAD_ARGS", usage);
1414
+ const usage = "usage: oats instance waiting <set|clear> --producer <id> [--reason permission|question|attention] [--message <text>] [--home <abs>] [--dir <d>] [--json] | oats instance attention [--message <text>] [--clear] [--json] | oats instance events <instance> [--limit <n>] [--since <iso>] [--home <abs>] [--dir <d>] [--json] | oats instance git <instance> [--home <abs>] [--dir <d>] [--json] | oats instance diff <instance> --file <id> --revision <rev> [--index-revision <rev>] [--home <abs>] [--dir <d>] [--json] | oats instance stop <instance> (--plan | --apply --plan-revision <rev> --idempotency-key <key>) [--no-recursive] [--grace-ms <n>] [--home <abs>] [--dir <d>] [--json] | oats instance color <instance> (<color> | --clear) [--home <abs>] [--dir <d>] [--json] | oats instance background <instance> on|off [--home <abs>] [--dir <d>] [--json] | oats instance same-work <instance> on|off [--home <abs>] [--dir <d>] [--json]";
1415
+ if (!["git", "diff", "stop", "events", "color", "background", "same-work"].includes(sub) || !name || name.startsWith("--")) return bail("E_BAD_ARGS", usage);
1386
1416
  dropAmbientRoot();
1387
1417
  if (sub === "events") {
1388
1418
  // K7: typed producer events, bounded window; nothing inferred.
@@ -1438,6 +1468,44 @@ async function instanceCmd() {
1438
1468
  return lifecycleFail(e, "E_LIFECYCLE_FAILED", e.candidates ? { candidates: e.candidates } : e.details);
1439
1469
  }
1440
1470
  }
1471
+ if (sub === "background") {
1472
+ // Feature instance-background: presentation only, so no plan; addressed as `instance color` addresses an instance.
1473
+ const homeOpt = flag("home");
1474
+ if (homeOpt === true || (homeOpt !== undefined && !isAbsolute(homeOpt))) return bail("E_BAD_ARGS", "--home needs an absolute instance home");
1475
+ const backgroundUsage = "usage: oats instance background <instance> on|off [--home <abs>] [--dir <d>] [--json]";
1476
+ // The words after the instance that are not a flag or the value of --home or --dir: exactly one, on or off.
1477
+ const words = [];
1478
+ for (let i = 3; i < args.length; i++) { if (args[i] === "--home" || args[i] === "--dir") i++; else if (!args[i].startsWith("--")) words.push(args[i]); }
1479
+ if (words.length !== 1 || !["on", "off"].includes(words[0])) return bail("E_BAD_ARGS", `give on or off; ${backgroundUsage}`);
1480
+ let root; try { root = ensureRoot(dirFlag()); } catch (e) { return lifecycleFail(e, "E_NO_ROOT"); }
1481
+ try {
1482
+ const r = setInstanceBackground(dirFlag(), root, name, { home: homeOpt, background: words[0] === "on" });
1483
+ if (JSON_MODE) { jsonOk(r); return; }
1484
+ console.log(`${r.instance}: ${r.background ? "background" : "not background"}${r.changed ? "" : " (unchanged)"}`);
1485
+ return;
1486
+ } catch (e) {
1487
+ return lifecycleFail(e, "E_LIFECYCLE_FAILED", e.candidates ? { candidates: e.candidates } : e.details);
1488
+ }
1489
+ }
1490
+ if (sub === "same-work") {
1491
+ // Feature instance-same-work: presentation only, so no plan; addressed as color addresses an instance.
1492
+ const homeOpt = flag("home");
1493
+ if (homeOpt === true || (homeOpt !== undefined && !isAbsolute(homeOpt))) return bail("E_BAD_ARGS", "--home needs an absolute instance home");
1494
+ const sameWorkUsage = "usage: oats instance same-work <instance> on|off [--home <abs>] [--dir <d>] [--json]";
1495
+ // The words after the instance that are not a flag or the value of --home or --dir: exactly one, on or off.
1496
+ const words = [];
1497
+ for (let i = 3; i < args.length; i++) { if (args[i] === "--home" || args[i] === "--dir") i++; else if (!args[i].startsWith("--")) words.push(args[i]); }
1498
+ if (words.length !== 1 || !["on", "off"].includes(words[0])) return bail("E_BAD_ARGS", `give on or off; ${sameWorkUsage}`);
1499
+ let root; try { root = ensureRoot(dirFlag()); } catch (e) { return lifecycleFail(e, "E_NO_ROOT"); }
1500
+ try {
1501
+ const r = setInstanceSameWork(dirFlag(), root, name, { home: homeOpt, on: words[0] === "on" });
1502
+ if (JSON_MODE) { jsonOk(r); return; }
1503
+ console.log(`${r.instance}: same work ${r.sameWork ? "on" : "off"}`);
1504
+ return;
1505
+ } catch (e) {
1506
+ return lifecycleFail(e, "E_LIFECYCLE_FAILED", e.candidates ? { candidates: e.candidates } : e.details);
1507
+ }
1508
+ }
1441
1509
  if (sub === "stop") {
1442
1510
  // K3: plan → apply. The plan is what a confirmation shows; apply carries
1443
1511
  // its revision back and refuses if reality moved.
@@ -1740,7 +1808,8 @@ function workspaceItems(discovery, lock, local, deploymentDir) {
1740
1808
  try { launchConfigs = deploymentDir ? launchConfigsAt(deploymentDir) : {}; } catch { launchConfigs = {}; }
1741
1809
  // One description of this read for every soul's launch: which keys of souls.launch name no soul.
1742
1810
  const offered = soulsOffered(discovery);
1743
- const soulDefaults = (entry) => soulLaunchFacts(entry, local, { launchConfigs, contextDir: deploymentDir, offered });
1811
+ // Feature instance-background: `background: true` on a soul that declares it, absent otherwise.
1812
+ const soulDefaults = (entry) => ({ ...soulLaunchFacts(entry, local, { launchConfigs, contextDir: deploymentDir, offered }), ...(entry.definition?.background === true ? { background: true } : {}) });
1744
1813
  const capabilities = [];
1745
1814
  const model = teamModel(discovery.standalone === true ? null : discovery.workspace, local, { workspaceKey: discovery.key ?? null });
1746
1815
  const teamsHere = (entry) => {
@@ -2754,7 +2823,7 @@ async function status() {
2754
2823
  const observation = maxAgeGiven === null ? {} : { observation: observationBlock() };
2755
2824
  // `features` (feature server-probe-features): this kernel's own list, as `version --json` answers
2756
2825
  // it, so a remote roster relays the host's without probing it. Never part of a reused observation.
2757
- console.log(JSON.stringify({ root, agents: data, ...observation, features: KERNEL_FEATURES, ...(ws ? { workspace: { ...(ws.unreachable ? { reachable: false, ...ws.unreachable } : { reachable: true }), ...workspaceIdentity(ws.local, ws.discovery) } } : {}), ...(problems.length ? { problems } : {}), ...envelopeWarnings() }, null, 2)); return;
2826
+ console.log(JSON.stringify({ root, agents: data, ...observation, features: KERNEL_FEATURES, sessionViewer: readSessionViewer(), ...(ws ? { workspace: { ...(ws.unreachable ? { reachable: false, ...ws.unreachable } : { reachable: true }), ...workspaceIdentity(ws.local, ws.discovery) } } : {}), ...(problems.length ? { problems } : {}), ...envelopeWarnings() }, null, 2)); return;
2758
2827
  }
2759
2828
  console.log(`oats status — agents root ${shortPath(root)}\n`);
2760
2829
  if (ws?.unreachable) console.log(` workspace: unreachable (${ws.unreachable.reason}) — drift unknown\n`);
@@ -2764,7 +2833,8 @@ async function status() {
2764
2833
  console.log(` ${a.name} [work: ${a.work || "checkout"}, repo: ${soulRepoLabel(a, ws)}]`);
2765
2834
  if (a.description) console.log(` ${a.description}`);
2766
2835
  for (const i of a.instances) {
2767
- console.log(` • ${i.instance} ${i.retirePending ? "RETIRING" : livenessWord(i)} (branch ${i.branch || "?"}, ${i.work || "?"})${i.runtimeError ? ` ${i.runtimeError}` : ""}`);
2836
+ // Feature instance-background: the row is marked; it is listed like any other.
2837
+ console.log(` • ${i.instance}${i.background === true ? " [background]" : ""} ${i.retirePending ? "RETIRING" : livenessWord(i)} (branch ${i.branch || "?"}, ${i.work || "?"})${i.runtimeError ? ` ${i.runtimeError}` : ""}`);
2768
2838
  // Feature waiting-on-you: non-null only on a running row; the reader has
2769
2839
  // already validated the message (one line, no control characters).
2770
2840
  if (i.running === true && i.waitingOnYou) console.log(` ! needs input (${i.waitingOnYou.reason ?? "unknown"})${i.waitingOnYou.message ? `: ${i.waitingOnYou.message}` : ""}`);
@@ -2791,7 +2861,7 @@ const livenessWord = (i) => i.running === true ? "RUNNING" : i.running === false
2791
2861
  * host through `--server`, whose route reads it. `--max-age` reaches here only on a preview or an
2792
2862
  * apply bound by --expect-decision: the dispatch allow-list (maxAgeRefusal) refuses it otherwise. */
2793
2863
  const SPAWN_VALUE_FLAGS = new Set(["agents-root", "backend", "base", "branch", "dir", "expect-decision", "harness", "idempotency-key", "instance", "launch-config", "max-age", "model", "name", "parent", "purpose", "relation", "relative-root", "relative-to", "repo", "runtime", "task", "task-file", "trigger-event", "wake-cron", "wake-every", "wake-file", "wake-json", "wake-message", "wake-message-file", "wake-tz", "work", "work-dir"]);
2794
- const SPAWN_SWITCHES = new Set(["allow-child-spawns", "json", "no-child-spawns", "no-launch", "no-yolo", "preview", "suggest-name", "yolo"]);
2864
+ const SPAWN_SWITCHES = new Set(["allow-child-spawns", "background", "json", "no-background", "no-child-spawns", "no-launch", "no-yolo", "preview", "same-work", "suggest-name", "yolo"]);
2795
2865
  /** `--suggest-name` (features spawn-suggest-name, spawn-apply-suggest-name): a preview's or an apply's,
2796
2866
  * with no --name, --purpose or --expect-decision. The kernel refuses the same (core.mjs spawnBody); the
2797
2867
  * CLI says it before anything is read or sent. */
@@ -2802,6 +2872,8 @@ function suggestNameProblem(argv) {
2802
2872
  if (given("--name") || given("--purpose")) return "--suggest-name chooses the name: it takes no --name or --purpose";
2803
2873
  return undefined;
2804
2874
  }
2875
+ /** `--background` / `--no-background` (feature instance-background): one of them, or neither. */
2876
+ const backgroundProblem = (argv) => (argv.includes("--background") && argv.includes("--no-background") ? "choose --background or --no-background, not both" : undefined);
2805
2877
  /** Why `argv` (after `spawn`, the soul first) is not a spawn, or undefined: a positional after the
2806
2878
  * soul or a flag spawn does not read is never ignored. A value flag consumes its value exactly as
2807
2879
  * flag() reads it; a missing value is the flag's own check. */
@@ -2840,9 +2912,10 @@ function namingLine(naming) {
2840
2912
  function printSpawnPreview(r, { server, soulFetched = false } = {}) {
2841
2913
  // A host before 0.27 names the harness `runtime` (it still answers spawn-preview-2).
2842
2914
  const harness = r.harness ?? r.runtime;
2843
- console.log(`preview ${r.agent} → ${r.instance}${server ? ` on ${server}` : ""} (${r.work}${r.branch ? `, branch ${r.branch}${r.base ? ` from ${r.base.ref}@${r.base.oid.slice(0, 12)}` : ""}` : ""}) harness ${harness}${r.model ? ` model ${r.model}` : ` (${r.modelSource})`}${r.launchConfig ? ` via launch configuration ${r.launchConfig}${r.launchConfigDefault ? ` (${server ? "the server's" : "this machine's"} ${harness} default)` : ""}` : ""}${r.yolo ? " YOLO" : ""}; nothing was created${soulFetched ? " (the soul source was fetched to a temporary copy, not kept)" : ""}`);
2915
+ console.log(`preview ${r.agent} → ${r.instance}${server ? ` on ${server}` : ""} (${r.work}${r.branch ? `, branch ${r.branch}${r.base ? ` from ${r.base.ref}@${r.base.oid.slice(0, 12)}` : ""}` : ""}) harness ${harness}${r.model ? ` model ${r.model}` : ` (${r.modelSource})`}${r.launchConfig ? ` via launch configuration ${r.launchConfig}${r.launchConfigDefault ? ` (${server ? "the server's" : "this machine's"} ${harness} default)` : ""}${r.launchConfigSource ? ` from ${server ? terminalText(r.launchConfigSource) : shortPath(launchConfigFile(r.launchConfigSource))}` : ""}` : ""}${r.yolo ? " YOLO" : ""}; nothing was created${soulFetched ? " (the soul source was fetched to a temporary copy, not kept)" : ""}`);
2844
2916
  // Feature spawn-suggest-name: how the name was chosen.
2845
2917
  { const line = namingLine(r.naming); if (line) console.log(`name: ${line}`); }
2918
+ if (r.background === true) console.log(`list: background (from the ${r.backgroundFrom === "flag" ? "--background flag" : "soul"})`);
2846
2919
  if (Array.isArray(r.worktreeHooks)) console.log(r.worktreeHooks.length ? `worktree hooks: ${r.worktreeHooks.map((h) => `${h.capability}${h.required ? " (required)" : ""}`).join(", ")}` : "worktree hooks: none");
2847
2920
  for (const w of r.warnings || []) console.log(` WARNING: ${terminalText(w)}`);
2848
2921
  }
@@ -2861,7 +2934,7 @@ async function spawnCmd() {
2861
2934
  };
2862
2935
  checkDirectoryOptions(requestedWork); // before anything is resolved or written
2863
2936
  const name = args[1];
2864
- if (!name || name.startsWith("--")) bail("E_USAGE", "usage: oats spawn <agent> [--task <text>|--task-file <f>] [--purpose <slug>|--name <slug>|--suggest-name] [--preview] [--base <ref>] [--model <id>|@native-default] [--allow-child-spawns|--no-child-spawns] [--relation child|sibling|parent|unrelated --relative-to <instance> [--relative-root <agents-root>]] [--parent <instance>] [--repo <r>] [--work worktree|checkout|attached|workspace|directory] [--work-dir <owner-work>] [--harness pi|claude|codex] [--backend tmux] [--yolo|--no-yolo] [--model <m>] [--branch <b>] [--no-launch] [--json]");
2937
+ if (!name || name.startsWith("--")) bail("E_USAGE", "usage: oats spawn <agent> [--task <text>|--task-file <f>] [--purpose <slug>|--name <slug>|--suggest-name] [--preview] [--base <ref>] [--model <id>|@native-default] [--allow-child-spawns|--no-child-spawns] [--relation child|sibling|parent|unrelated --relative-to <instance> [--relative-root <agents-root>]] [--parent <instance>] [--same-work] [--repo <r>] [--work worktree|checkout|attached|workspace|directory] [--work-dir <owner-work>] [--harness pi|claude|codex] [--backend tmux] [--yolo|--no-yolo] [--background|--no-background] [--model <m>] [--branch <b>] [--no-launch] [--json]");
2865
2938
  // Retired boundary flags (maintainer transport ruling): fail LOUDLY before
2866
2939
  // ANY side effect, including root discovery.
2867
2940
  // Local souls (local-agents/) are gone with the workspace model: a soul is a member
@@ -2872,7 +2945,7 @@ async function spawnCmd() {
2872
2945
  const nameFlag = flag("name");
2873
2946
  if (nameFlag === true) bail("E_BAD_ARGS", "--name needs an instance name (a slug: lowercase letters and digits, single dashes between them)");
2874
2947
  if (nameFlag !== undefined && flag("purpose") !== undefined) bail("E_BAD_ARGS", "--name and --purpose are mutually exclusive: --name is the exact instance name, --purpose derives <agent>-<purpose>");
2875
- { const problem = suggestNameProblem(args); if (problem) bail("E_BAD_ARGS", problem); }
2948
+ { const problem = suggestNameProblem(args) ?? backgroundProblem(args); if (problem) bail("E_BAD_ARGS", problem); }
2876
2949
  // The slug rule is checked here too, before any side effect (soul fetch).
2877
2950
  if (nameFlag !== undefined) { try { explicitInstanceName(String(nameFlag)); } catch (e) { bail(e.code, e.message); throw e; } }
2878
2951
  if (args.includes("--ephemeral")) bail("E_BAD_ARGS", "--ephemeral was removed by the runtime-boundary ruling — declare the agent in a capability manifest (agents:) for automatic ephemeral semantics");
@@ -3055,6 +3128,8 @@ async function spawnCmd() {
3055
3128
  prepared,
3056
3129
  purpose: flag("purpose"), ...(nameFlag !== undefined ? { name: String(nameFlag) } : {}), task: taskText, taskFile: taskFileFlag, relation, relativeTo, relativeRoot,
3057
3130
  ...(args.includes("--allow-child-spawns") ? { allowChildSpawns: true } : args.includes("--no-child-spawns") ? { allowChildSpawns: false } : {}),
3131
+ // Feature instance-same-work: the kernel binds it to the parent the new home records, or refuses.
3132
+ ...(args.includes("--same-work") ? { sameWork: true } : {}),
3058
3133
  // Directory execution uses deployment configuration, not an ambient Git
3059
3134
  // checkout (especially when invoked via --dir from a source instance).
3060
3135
  // An attached instance's repository is the repository of the tree it is attached to (derived by the kernel).
@@ -3062,6 +3137,8 @@ async function spawnCmd() {
3062
3137
  ? repo : repo || defaultRepo(workspaceOf(root)) || defaultRepo(process.cwd()),
3063
3138
  work: requestedWork, workDir, harness: harnessFlag(), backend, yolo, model: flag("model"), branch,
3064
3139
  launchConfig: valueFlag("launch-config"),
3140
+ // Feature instance-background: the flag wins over the soul's `background:`.
3141
+ ...(args.includes("--background") ? { background: true } : args.includes("--no-background") ? { background: false } : {}),
3065
3142
  launch: !args.includes("--no-launch"),
3066
3143
  ...(triggerEvent ? { triggerEvent } : {}),
3067
3144
  // K6: --preview decides everything and touches nothing; --base <ref>
@@ -3117,6 +3194,8 @@ async function spawnCmd() {
3117
3194
  sibling: r.siblingInstance || null, relation: r.relation || null,
3118
3195
  spawnOrigin: r.spawnOrigin, attach: r.attach,
3119
3196
  ...(r.yolo !== undefined ? { yolo: r.yolo } : {}),
3197
+ // Feature instance-background: whether the home is background, and which layer declared it.
3198
+ background: r.background === true, ...(r.backgroundFrom ? { backgroundFrom: r.backgroundFrom } : {}),
3120
3199
  // K6b/K6c: what bound this spawn, and whether this receipt is a replay of an earlier one.
3121
3200
  ...(r.decision ? { decision: r.decision } : {}), ...(r.replayed !== undefined ? { replayed: r.replayed } : {}),
3122
3201
  ...(r.wake !== undefined ? { wake: r.wake } : {}), // {requested, saved|null, error}: saved:null = outcome not recorded
@@ -3130,6 +3209,7 @@ async function spawnCmd() {
3130
3209
  }
3131
3210
  console.log(`Spawned ${r.instance} (${r.work}${r.branch ? `, branch ${r.branch}` : ""})${r.launched ? ` — tmux window "${r.tmux.window}"` : " — not launched"}`);
3132
3211
  console.log(` home: ${shortPath(r.home)}`);
3212
+ if (r.background === true) console.log(` list: background (from the ${r.backgroundFrom === "flag" ? "--background flag" : "soul"})`);
3133
3213
  { const line = namingLine(r.naming); if (line) console.log(` name: ${line}`); }
3134
3214
  if (r.base) console.log(` base: ${r.base.oid.slice(0, 12)} (${r.base.ref === r.workspace?.soul?.repoKey ? `observed head of ${r.base.ref}` : r.base.ref})`);
3135
3215
  for (const h of r.worktreeHooks || []) console.log(` setup: ${h.capability} worktree hook ${h.ok ? "ok" : "FAILED"} (log: ${shortPath(h.log)})`);
@@ -3579,14 +3659,37 @@ async function sessionCmd() {
3579
3659
  if (args[1] === "attach") {
3580
3660
  if (JSON_MODE) throw Object.assign(new Error("session attach is interactive; omit --json"), { code: "E_BAD_ARGS" });
3581
3661
  // --detach-key (feature session-attach-detach-key): the one key that leaves this viewer, with
3582
- // status 20. Without it every key reaches the agent and there is no keyboard exit.
3662
+ // status 20. Without it every key but the viewer's scrollback key reaches the agent and there is
3663
+ // no keyboard exit.
3583
3664
  // What earlier attaches left (a viewer whose attach died without detaching): one line, on
3584
3665
  // stderr, before the client takes the terminal, and only when something was removed.
3585
3666
  const onSwept = ({ sessions, tables }) => {
3586
3667
  const n = (count, what) => `${count} ${what}${count === 1 ? "" : "s"}`;
3587
3668
  if (sessions + tables > 0) console.error(`oats: removed ${n(sessions, "leftover viewer session")} and ${n(tables, "key table")} of earlier attaches`);
3588
3669
  };
3589
- process.exitCode = await attachInstanceSession(home, { detachKey: valueFlag("detach-key"), onSwept });
3670
+ // --no-status-line (feature session-attach-no-status-line): a viewer without its status line,
3671
+ // the scroll keys, for a caller that shows them itself.
3672
+ process.exitCode = await attachInstanceSession(home, { detachKey: valueFlag("detach-key"), statusLine: !args.includes("--no-status-line"), onSwept });
3673
+ return;
3674
+ }
3675
+ if (args[1] === "resume") {
3676
+ // The machine sweep (feature session-resume, #1559): lib/session-resume.mjs. No --home: one home
3677
+ // is `session start --resume`.
3678
+ const usage = "usage: oats session resume [--deployment <dir>] [--plan] [--json]";
3679
+ for (let i = 2; i < args.length; i++) {
3680
+ const a = args[i];
3681
+ if (a === "--deployment") { i++; continue; }
3682
+ if (a.startsWith("--deployment=") || a === "--plan" || a === "--json") continue;
3683
+ throw Object.assign(new Error(a.startsWith("-") ? `oats session resume: unknown flag ${a}\n${usage}` : `oats session resume takes no argument ${JSON.stringify(a)}\n${usage}`), { code: "E_BAD_ARGS" });
3684
+ }
3685
+ const deployment = flag("deployment");
3686
+ if (deployment === true || (typeof deployment === "string" && !deployment.trim())) throw Object.assign(new Error(`--deployment needs a deployment directory\n${usage}`), { code: "E_BAD_ARGS" });
3687
+ const { resumeSessions } = await import("../lib/session-resume.mjs");
3688
+ const answer = await resumeSessions({ deployment, plan: args.includes("--plan"), kernel: { execPath: process.execPath, bin: CLI_BIN } });
3689
+ if (JSON_MODE) { jsonOk(answer); return; }
3690
+ for (const d of answer.deployments) console.log(`${d.deployment}: ${d.swept ? "swept" : `not swept (${d.reason}${d.code ? `, ${d.code}` : ""})`}`);
3691
+ for (const r of answer.rows) console.log(` ${r.instance} ${answer.plan ? "would be " : ""}${r.outcome}${r.reason ? ` (${r.reason}${r.code ? `, ${r.code}` : ""})` : ""}${r.message ? `: ${terminalText(r.message)}` : ""}`);
3692
+ if (!answer.rows.length) console.log("nothing to resume");
3590
3693
  return;
3591
3694
  }
3592
3695
  if (args[1] === "inspect") result = inspectInstanceSession(home);
@@ -3603,9 +3706,19 @@ async function sessionCmd() {
3603
3706
  // recorded launch stays frozen (a changed preference never reaches an existing home on its own).
3604
3707
  const reselectLaunch = args.includes("--reselect-launch");
3605
3708
  if (reselectLaunch && launchConfig !== undefined) bad("--reselect-launch applies the launch preferences; --launch-config names one explicitly — choose one");
3606
- // Refuse before launch selection or live-team discovery can prepare this home.
3607
- assertNoPartialUpgrade(home);
3608
- 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)) };
3709
+ // --resume (feature session-resume): the recorded launch as it is, in the home's last conversation;
3710
+ // refused with a launch choice before anything of the home is read.
3711
+ const resume = args.includes("--resume");
3712
+ if (resume) {
3713
+ if (args[1] === "restart") bad("--resume exists on session start only: it brings back a session that was lost");
3714
+ const chosen = ["--launch-config", "--harness", "--model", "--yolo", "--no-yolo", "--reselect-launch"].filter((f) => args.some((a) => a === f || a.startsWith(`${f}=`)));
3715
+ if (chosen.length) bad(`--resume runs the launch this home recorded; it cannot be combined with ${chosen.join(", ")}; nothing was read or started`);
3716
+ }
3717
+ // Refuse before launch selection or live-team discovery can prepare this home. A resume is
3718
+ // refused under the home's lifecycle claim instead (lib/core.mjs startInstanceSession): beside
3719
+ // an upgrade that runs, it is busy, not a partial upgrade.
3720
+ if (!resume) assertNoPartialUpgrade(home);
3721
+ const opts = { model: model || undefined, launchConfig, harness, yolo: yoloFlag(), ...(reselectLaunch ? { reselectLaunch: true, launchOffered: await homeLaunchOffered(home, { named: harness !== undefined }) } : {}), ...(resume ? { resume: true } : {}), env: process.env, ...(await homeLiveTeams(home)) };
3609
3722
  if (args[1] === "restart") {
3610
3723
  const grace = flag("stop-grace");
3611
3724
  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; }
@@ -3628,7 +3741,7 @@ async function sessionCmd() {
3628
3741
  const file = flag("file");
3629
3742
  if (!file || file === true) throw Object.assign(new Error("session upload needs --file <local path>"), { code: "E_BAD_ARGS" });
3630
3743
  result = uploadAttachment({ file, home: home === true ? undefined : home });
3631
- } else throw Object.assign(new Error("usage: oats session inspect|input|attach|start|restart|receive|upload --home /absolute/home [--text-file path] [--detach-key key] [--model id] [--launch-config name|none | --reselect-launch] [--harness pi|claude|codex] [--yolo|--no-yolo] [--stop-grace seconds] [--name file] [--file path] [--json]"), { code: "E_BAD_ARGS" });
3744
+ } else throw Object.assign(new Error("usage: oats session inspect|input|attach|start|restart|receive|upload --home /absolute/home [--text-file path] [--detach-key key] [--no-status-line] [--model id] [--launch-config name|none | --reselect-launch] [--harness pi|claude|codex] [--yolo|--no-yolo] [--stop-grace seconds] [--name file] [--file path] [--json]"), { code: "E_BAD_ARGS" });
3632
3745
  if (JSON_MODE) jsonOk(result);
3633
3746
  else {
3634
3747
  console.log(JSON.stringify(result, null, 2));
@@ -4255,7 +4368,7 @@ function versionCmd() {
4255
4368
  // Phase B: `instance-modules` and `spawn-provider-payload` are advertised only once spawn
4256
4369
  // runs on resolve/materialize (contract §6); a feature the binary does not implement is
4257
4370
  // never listed.
4258
- console.log(JSON.stringify({ schemaVersion: 1, name: "@awebai/oats", version: OATS_VERSION, desktopApi: 1, harnesses: ["pi", "claude", "codex"], sessionBackends: ["tmux"], launchOptions: ["yolo"], remote: ["spawn", "retire", "status", "session", "session-start", "session-restart", "launch-config", "roster", "harvest", "schedule", "session-upload", "operations", "readiness", "instance-events", "instance-git", "lifecycle-plans"], features: KERNEL_FEATURES, automationsApi: A.AUTOMATIONS_API, workspaceApi: 2, instanceGitApi: 1, spawnApplyApi: 1, soulsApi: 2, lifecycleApi: 1, readinessApi: 2, spawnPreviewApi: 2, eventsApi: 2, scheduleHistoryApi: 3, scheduleApi: SCHEDULE_API, operationsApi: 2, capabilityShowApi: 1 }));
4371
+ console.log(JSON.stringify({ schemaVersion: 1, name: "@awebai/oats", version: OATS_VERSION, desktopApi: 1, harnesses: ["pi", "claude", "codex"], sessionBackends: ["tmux"], launchOptions: ["yolo"], remote: ["spawn", "retire", "status", "session", "session-start", "session-restart", "launch-config", "roster", "harvest", "schedule", "session-upload", "operations", "readiness", "instance-events", "instance-git", "lifecycle-plans"], features: KERNEL_FEATURES, automationsApi: A.AUTOMATIONS_API, workspaceApi: 2, instanceGitApi: 1, spawnApplyApi: 1, soulsApi: 2, lifecycleApi: 1, readinessApi: 2, spawnPreviewApi: 2, eventsApi: 2, scheduleHistoryApi: 3, scheduleApi: SCHEDULE_API, operationsApi: 2, capabilityShowApi: 1, sessionViewer: readSessionViewer() }));
4259
4372
  return;
4260
4373
  }
4261
4374
  console.log(`@awebai/oats ${OATS_VERSION} (desktop API v1)`);
@@ -4349,7 +4462,7 @@ async function serverCmd() {
4349
4462
  for (const g of out.groups) {
4350
4463
  console.log(` ${g.server}${g.label && g.label !== g.server ? ` ${g.label}` : ""} [${g.id}] ssh ${g.target.sshHost} workspace ${g.target.workspace}${g.registrationPresent ? "" : " (registration removed or changed; saved routes only)"}`);
4351
4464
  console.log(g.probe?.ok ? ` reachable, ${g.souls.length} soul(s)` : ` UNREACHABLE: ${g.probe?.error?.message || "?"}`);
4352
- for (const i of g.instances) console.log(` • ${i.instance} ${i.missingRemotely ? "GONE on the host (saved route is stale: oats server forget)" : i.running === true ? "RUNNING" : i.running === false ? "idle" : "unknown"}${i.retirePending ? " RETIRING" : ""}${i.rollbackIncomplete ? " QUARANTINED" : ""}${i.savedRoute ? "" : " (observed only, no saved route)"}${i.runtimeError ? ` ${i.runtimeError}` : ""}`);
4465
+ for (const i of g.instances) console.log(` • ${i.instance}${i.background === true ? " [background]" : ""} ${i.missingRemotely ? "GONE on the host (saved route is stale: oats server forget)" : i.running === true ? "RUNNING" : i.running === false ? "idle" : "unknown"}${i.retirePending ? " RETIRING" : ""}${i.rollbackIncomplete ? " QUARANTINED" : ""}${i.savedRoute ? "" : " (observed only, no saved route)"}${i.runtimeError ? ` ${i.runtimeError}` : ""}`);
4353
4466
  for (const f of g.retireFailures || []) console.log(` ! deferred retirement of ${f.instance} (${f.agent}) FAILED there${f.error?.message ? `: ${f.error.message}` : ""}${f.retry ? ` — retry on the host: ${f.retry}` : ""}`);
4354
4467
  }
4355
4468
  console.log(` bounds: ${out.bounds.perTargetTimeoutMs} ms per target within ${out.bounds.budgetMs} ms, ${out.bounds.elapsedMs} ms used`);
@@ -4637,7 +4750,7 @@ async function serverRouteCmd() {
4637
4750
  const detachKey = valueFlag("detach-key");
4638
4751
  if (detachKey !== undefined) process.on("SIGQUIT", () => {});
4639
4752
  let route;
4640
- try { route = attachArgv(id, { ...addr, detachKey }, { skipVersionCheck: args.includes("--print") }); }
4753
+ try { route = attachArgv(id, { ...addr, detachKey, statusLine: !args.includes("--no-status-line") }, { skipVersionCheck: args.includes("--print") }); }
4641
4754
  // ssh failing before the viewer (the version probe, a name resolved through the host's roster)
4642
4755
  // is the failure ssh has under it: exit 255, on which a caller reconnects. Every other refusal,
4643
4756
  // and an ssh that never started (no link can come back), exits 1.
@@ -4655,7 +4768,7 @@ async function serverRouteCmd() {
4655
4768
  const herdr = herdrSpawnFlag();
4656
4769
  if (herdr) { const e = herdrSettingRemoved(`${herdr} was given`); bail(e.code, e.message); }
4657
4770
  const local = args.slice(1).filter((a, i, all) => a !== "--server" && all[i - 1] !== "--server");
4658
- const problem = spawnArgvProblem(local) ?? suggestNameProblem(local);
4771
+ const problem = spawnArgvProblem(local) ?? suggestNameProblem(local) ?? backgroundProblem(local);
4659
4772
  if (problem) bail("E_BAD_ARGS", problem);
4660
4773
  }
4661
4774
  // Everything after the command word travels, minus the routing flags; a
@@ -4746,7 +4859,7 @@ async function serverRouteCmd() {
4746
4859
  console.log(`oats status — server ${id} (ssh ${r.target.sshHost}, workspace ${r.target.workspace})\n`);
4747
4860
  for (const a of r.agents || []) {
4748
4861
  console.log(` ${a.name} [work: ${a.work || "checkout"}, repo: ${a.repo || "?"}]`);
4749
- for (const i of a.instances || []) console.log(` • ${i.instance} ${i.retirePending ? "RETIRING" : livenessWord(i)}${i.runtimeError ? ` ${i.runtimeError}` : ""}`);
4862
+ for (const i of a.instances || []) console.log(` • ${i.instance}${i.background === true ? " [background]" : ""} ${i.retirePending ? "RETIRING" : livenessWord(i)}${i.runtimeError ? ` ${i.runtimeError}` : ""}`);
4750
4863
  }
4751
4864
  const snaps = r.snapshots || [];
4752
4865
  if (snaps.length) console.log(`\n spawned from this machine: ${snaps.map((s) => s.instance).join(", ")}`);
@@ -4779,7 +4892,10 @@ try {
4779
4892
  const kernelArgv = (KERNEL_COMMANDS.has(cmd) && !OWN_ARGV_COMMANDS.has(cmd)) || (ROUTED_COMMANDS.has(cmd) && flag("server") !== undefined);
4780
4893
  if (argvProblem && kernelArgv) cmdFail("E_BAD_ARGS", argvProblem);
4781
4894
  const end = args.indexOf("--"), head = end < 0 ? args : args.slice(0, end);
4782
- const selector = head.find((a) => /^--(deployment|resolution|artifact-set)$/.test(a));
4895
+ // `session resume --deployment <dir>` (feature session-resume) reuses the name for a deployment
4896
+ // the sweep is limited to, not a captured selector.
4897
+ const resumeSweep = cmd === "session" && args[1] === "resume";
4898
+ const selector = head.find((a) => /^--(deployment|resolution|artifact-set)$/.test(a) && !(resumeSweep && a === "--deployment"));
4783
4899
  const refuse = (message, details) => { if (JSON_MODE) jsonFail("E_UNSUPPORTED_MODE", message, details); die(message); };
4784
4900
  if (selector) refuse(`${selector}: a captured selector is refused (the captured/portable path was removed in 0.26); run the command in its workspace deployment or instance home instead`, { selector });
4785
4901
  // --max-age (feature observe-max-age): ONE allow-list for every kernel command, here — never a
@@ -4813,7 +4929,8 @@ try {
4813
4929
  // help, and silent: no output, no change to the command's answer or exit status.
4814
4930
  const LISTS_ITS_DEPLOYMENT = new Set(["automations", "capabilities", "doctor", "harness", "inspect", "instance", "launch-config", "operation", "package", "pane", "readiness", "retire", "schedule", "session", "soul", "souls", "spawn", "status", "sync", "teams", "trigger", "update", "workspace", "worktree"]);
4815
4931
  // `instance suggest-name` records nothing (#1490 §2): the oats-local.yaml it reads is not listed.
4816
- if (LISTS_ITS_DEPLOYMENT.has(cmd) && flag("server") === undefined && !(cmd === "instance" && args[1] === "suggest-name") && !args.slice(1).some((a) => a === "--help" || a === "-h")) observeResolvedDeployment(listResolved);
4932
+ // `session resume` reads the list and never writes it (#1559).
4933
+ if (LISTS_ITS_DEPLOYMENT.has(cmd) && flag("server") === undefined && !(cmd === "instance" && args[1] === "suggest-name") && !(cmd === "session" && args[1] === "resume") && !args.slice(1).some((a) => a === "--help" || a === "-h")) observeResolvedDeployment(listResolved);
4817
4934
  if (cmd === "onboard") {
4818
4935
  if (args.includes("--help") || args.includes("-h")) { if (JSON_MODE) jsonOk({ command: cmd, usage: usageLinesFor(cmd) }); else usageFor(cmd); process.exit(0); }
4819
4936
  await onboardCmd();
@@ -4828,6 +4945,8 @@ if (cmd && KERNEL_COMMANDS.has(cmd) && wantsHelp) { if (JSON_MODE) { jsonOk({ co
4828
4945
  if (cmd === "instance" && args[1] === "upgrade" && flag("server") !== undefined) cmdFail("E_BAD_ARGS", "instance upgrade supports local homes only; run it on the deployment host");
4829
4946
  // #1490 §2: the name is decided on the machine that asks, for a spawn that lands elsewhere.
4830
4947
  if (cmd === "instance" && args[1] === "suggest-name" && flag("server") !== undefined) cmdFail("E_BAD_ARGS", "instance suggest-name takes no --server: it runs this machine's harness, for a spawn that may land on another; the host it lands on makes the name unique (or names an unnamed --suggest-name spawn itself)");
4948
+ // Session resume is local only (#1559, D1): a server resumes its own instances.
4949
+ if (cmd === "session" && flag("server") !== undefined && (args[1] === "resume" || args.includes("--resume"))) cmdFail("E_BAD_ARGS", "session resume and session start --resume act on this machine's instances only; a server runs oats session resume itself");
4831
4950
  if (flag("server") !== undefined && ROUTED_COMMANDS.has(cmd)) await serverRouteCmd();
4832
4951
  else if (cmd === "server") await serverCmd();
4833
4952
  else if (cmd === "deployments") deploymentsCmd();
@@ -4965,8 +5084,10 @@ Usage:
4965
5084
  oats session inspect|attach --server <id> inspect (envelope) or attach a viewer (ssh PTY) for a
4966
5085
  --instance <name> | --home <abs> remote instance, by its saved route or the server's
4967
5086
  [--detach-key <key>] roster (--print shows attach); oats 0.22.2 or later.
4968
- attach --detach-key: as below; the server must
4969
- advertise session-attach-detach-key
5087
+ [--no-status-line] attach --detach-key: as below; the server must
5088
+ advertise session-attach-detach-key.
5089
+ --no-status-line: as below; a server without
5090
+ session-attach-no-status-line shows the line
4970
5091
  oats session start --server <id> start a stopped remote instance in its existing home
4971
5092
  --instance <name> | --home <abs> by its saved route or the server's roster; it must advertise
4972
5093
  [--model <m>] [--json] session-start (oats 0.22.9 or later)
@@ -5002,11 +5123,15 @@ Usage:
5002
5123
  oats deployments import --from desktop <path>... [--json]
5003
5124
  the Desktop's one-time import of its own lists
5004
5125
  oats session inspect|input|attach --home <absolute-home> [--text-file <path>] [--json]
5005
- oats session attach --home <absolute-home> [--detach-key <key>]
5126
+ oats session attach --home <absolute-home> [--detach-key <key>] [--no-status-line]
5006
5127
  a viewer of one instance. <key> (C-<letter>, M-<letter
5007
5128
  or digit>, F1 to F12; 'C-\\' is the suggested one)
5008
5129
  leaves it with exit status 20; without one no key
5009
- leaves it: every key goes to the agent
5130
+ leaves it. Shift+PageUp scrolls back (tmux copy mode:
5131
+ PageUp, PageDown, q leaves), and so does C-b [ in a
5132
+ viewer without a key, whose status line says so
5133
+ (--no-status-line: none); every other key goes to
5134
+ the agent, C-b and the key after it included
5010
5135
  oats schedule list|show <id>|test <id>|add <id> --file <spec.json>|update <id> --file <spec.json>
5011
5136
  enable|disable|run|remove|reconcile <id> workspace-scoped, host-owned schedules (spawn,
5012
5137
  tick [--dry-run] [--host] command or wake jobs on a five-field cron with an
@@ -5044,6 +5169,13 @@ Usage:
5044
5169
  [--reselect-launch] applies the launch preferences now (oats-local.yaml
5045
5170
  souls.launch, the soul's launch); a changed preference
5046
5171
  never reaches an existing home without it or a respawn
5172
+ oats session start --resume --home <abs> start a home whose session was LOST (a reboot, a dead
5173
+ tmux server) in its own last conversation, the
5174
+ recorded launch as is; fresh on TASK.md when none is
5175
+ found (docs/execution-targets.md#resume-after-a-shutdown)
5176
+ oats session resume [--deployment <dir>] resume every lost session of this computer's
5177
+ [--plan] [--json] deployments (one sweep per machine; at most 3 resumes
5178
+ of a home per boot); --plan starts nothing
5047
5179
  oats session restart --home <abs-home> stop the running harness (SIGTERM, bounded wait,
5048
5180
  [same flags] [--stop-grace <s>] never escalated) and start it again in place under
5049
5181
  the same lock; a stop that is not observed is
@@ -5063,6 +5195,9 @@ Usage:
5063
5195
  [--relation child|sibling|parent|unrelated] anchor with --relative-to (except unrelated);
5064
5196
  [--relative-to <instance>] default: unrelated, top-level
5065
5197
  [--relative-root <agents-root>] disambiguates same-named anchors
5198
+ [--same-work] record that the new instance does the same work as
5199
+ its parent; clients draw the parent line for it
5200
+ (needs a relation that records a parent)
5066
5201
  [--work worktree|checkout|attached|workspace|directory] override the soul's work mode
5067
5202
  [--work-dir <owner-work>] attached: the owner's work tree (always a child)
5068
5203
  [--branch <b>] [--base <ref>] worktree branch and starting ref;
@@ -5079,6 +5214,8 @@ Usage:
5079
5214
  [--model <id>|@native-default] override the selected model; @native-default
5080
5215
  selects the harness's own model default
5081
5216
  [--backend tmux] [--yolo|--no-yolo] session backend and launch permission option
5217
+ [--background|--no-background] list the instance under Background (presentation
5218
+ only); default: the soul's background:, else no
5082
5219
  [--no-launch] [--json] scaffold without launching; JSON result envelope
5083
5220
  [--allow-child-spawns|--no-child-spawns] this instance's child-spawn policy (default:
5084
5221
  allowed); enforced by OATS, not an OS sandbox
@@ -5243,6 +5380,13 @@ Usage:
5243
5380
  oats instance color <instance> (<color> | --clear) [--home <abs>] [--json]
5244
5381
  the instance's colour, presentation only: sand,
5245
5382
  sage, slate, mauve, clay or olive; --clear removes it
5383
+ oats instance background <instance> on|off [--home <abs>] [--json]
5384
+ whether clients list the instance under
5385
+ Background, presentation only
5386
+ oats instance same-work <instance> on|off [--home <abs>] [--json]
5387
+ record that this instance does the same work as
5388
+ its parent (on needs a recorded parent); clients
5389
+ draw the parent line for it; off removes it
5246
5390
  oats instance suggest-name --soul <soul> (--task <t> | --task-file <f>) [--harness claude|pi]
5247
5391
  [--model <m>] [--launch-config <n>] [--dir <d>] [--json]
5248
5392
  a name for a spawn of <soul> (only a name: it gives