@awebai/oats 0.69.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 (67) hide show
  1. package/bin/oats.mjs +79 -15
  2. package/docs/capabilities.md +24 -5
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  5. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  6. package/docs/desktop-cli-api.md +260 -28
  7. package/docs/desktop-instance-start.md +8 -37
  8. package/docs/desktop.md +76 -9
  9. package/docs/execution-targets.md +27 -5
  10. package/docs/implementation.md +6 -5
  11. package/docs/integrations.md +1 -1
  12. package/docs/knowledge.md +25 -16
  13. package/docs/official-catalog.md +3 -3
  14. package/docs/packages.md +12 -12
  15. package/docs/release-notes/v0.69.2.md +259 -0
  16. package/docs/servers.md +7 -2
  17. package/docs/soul.schema.json +1 -0
  18. package/docs/souls-and-instances.md +35 -2
  19. package/docs/tui.md +100 -9
  20. package/docs/upgrading.md +9 -5
  21. package/docs/workspaces.md +2 -2
  22. package/injects/instance-boundary.md +19 -33
  23. package/injects/work-attached.md +8 -13
  24. package/injects/work-checkout.md +16 -30
  25. package/injects/work-directory.md +9 -15
  26. package/injects/work-workspace.md +8 -19
  27. package/injects/work-worktree.md +18 -33
  28. package/lib/capability-contract.mjs +2 -2
  29. package/lib/core.mjs +162 -49
  30. package/lib/instance-background.mjs +54 -0
  31. package/lib/instance-inspect.mjs +3 -0
  32. package/lib/instance-lifecycle.mjs +35 -0
  33. package/lib/instance-resolution.mjs +3 -2
  34. package/lib/instance-same-work.mjs +67 -0
  35. package/lib/instance-upgrade.mjs +18 -0
  36. package/lib/materialize.mjs +23 -2
  37. package/lib/resolve.mjs +32 -5
  38. package/lib/servers.mjs +19 -4
  39. package/lib/session-resume-contract.mjs +1 -0
  40. package/lib/session-resume.mjs +36 -9
  41. package/lib/soul-composition.mjs +13 -10
  42. package/lib/workspace.mjs +3 -2
  43. package/package-catalog.json +2 -2
  44. package/package.json +1 -1
  45. package/packages/client/cli-adapter.mjs +30 -8
  46. package/packages/client/deployment-data.mjs +9 -0
  47. package/packages/client/deployment-panel.mjs +4 -0
  48. package/packages/client/instance-tree.mjs +64 -14
  49. package/packages/client/panel-views.mjs +11 -3
  50. package/packages/client/remote-roster.mjs +5 -1
  51. package/packages/client/roster-sections.mjs +50 -6
  52. package/packages/client/same-work.mjs +49 -0
  53. package/packages/client/session-resume.mjs +1 -1
  54. package/packages/client/soul-rows.mjs +2 -0
  55. package/packages/client/spawn-apply-contract.mjs +2 -1
  56. package/packages/client/spawn-decision.mjs +4 -1
  57. package/packages/client/spawn-preview-contract.mjs +12 -1
  58. package/packages/client/spawn-preview.mjs +2 -0
  59. package/packages/tui/README.md +2 -2
  60. package/packages/tui/lib/client.mjs +6 -2
  61. package/packages/tui/lib/main.mjs +44 -11
  62. package/packages/tui/lib/model.mjs +101 -43
  63. package/packages/tui/lib/store.mjs +76 -20
  64. package/packages/tui/lib/views/frame.mjs +2 -0
  65. package/packages/tui/lib/views/help.mjs +2 -0
  66. package/packages/tui/lib/views/instances.mjs +38 -1
  67. package/skills/oats-getting-started/SKILL.md +2 -2
package/lib/core.mjs CHANGED
@@ -95,7 +95,9 @@ import { systemTool } from "./system-tools.mjs";
95
95
  import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
96
96
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
97
97
  import { readInstanceColor } from "./instance-color.mjs";
98
- import { readStartExited, sessionEndOf, START_EXITED_FILE } from "./session-end.mjs";
98
+ import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
99
+ import { SAME_WORK_FILE, sameWorkOf, writeSameWork } from "./instance-same-work.mjs";
100
+ import { readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
99
101
  import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
100
102
  import { recordSeen } from "./session-seen.mjs";
101
103
  import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, fromEnvNames, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
@@ -1199,7 +1201,10 @@ export function materializedHookCommands(row, home) {
1199
1201
 
1200
1202
  /** Compose, but never mutate, an instance instruction view from canonical soul instructions.
1201
1203
  * `kind` tunes composition: "capability" suppresses the knowledge layer's injection (ephemeral service
1202
- * agents — reviewers, harvesters — carry no episodic memory by design). */
1204
+ * agents — reviewers, harvesters — carry no episodic memory by design).
1205
+ * → { text, body, blocks, resolved, oatsCoreDeclared }: `body` is the soul's AGENTS.md; `blocks` are the
1206
+ * capability blocks whose inject already exists (none before materialize), in the resolution's
1207
+ * instructionOrder, then the kernel's instance-boundary and work-mode blocks, last. */
1203
1208
  export function composeInstanceAgentsMd(soulDir, contextDir, soulName, workMode, kind, prepared = undefined, { launchConfigs = true } = {}) {
1204
1209
  const agentsMd = join(soulDir, "AGENTS.md");
1205
1210
  if (!existsSync(agentsMd)) throw new Error(`canonical soul instructions missing: ${agentsMd}`);
@@ -1212,20 +1217,27 @@ export function composeInstanceAgentsMd(soulDir, contextDir, soulName, workMode,
1212
1217
  // Operational knowledge is a capability (oats.core / oats.setup) the resolution
1213
1218
  // carries like any other; the kernel composes no operational block of its own.
1214
1219
  const oatsCoreDeclared = (prepared.resolution?.modules || []).some((m) => m.name === "oats.core" || m.name === "oats.setup");
1215
- // The home/work boundary is runtime-neutral and mode-independent: every
1216
- // instance — including capability service agents in attached mode — needs to
1217
- // know which directory is its brain and which is the repository, and where
1218
- // `aw`/`oats` resolve their scope from. It precedes the mode block, which then
1219
- // adds only that mode's ownership and branch rules.
1220
+ // Capability injects first, in the resolution's instruction order (the soul's
1221
+ // listing, then the workspace defaults'), as materialize writes them.
1222
+ const order = Array.isArray(prepared.resolution?.instructionOrder) ? prepared.resolution.instructionOrder : [];
1223
+ const rank = (cap) => { const i = order.indexOf(cap.id); return i < 0 ? order.length : i; };
1224
+ const capabilities = resolved.capabilities.map((cap, i) => ({ cap, i })).sort((a, b) => rank(a.cap) - rank(b.cap) || a.i - b.i).map(({ cap }) => cap);
1225
+ for (const cap of capabilities) {
1226
+ if (cap.inject && existsSync(cap.inject)) wanted.push([`capability:${cap.id}`, cap.inject]);
1227
+ }
1228
+ // The kernel's blocks close the document. The home/work boundary is
1229
+ // runtime-neutral and mode-independent: every instance — including capability
1230
+ // service agents in attached mode — needs to know which directory is its
1231
+ // brain and which is the repository, and where `aw`/`oats` resolve their
1232
+ // scope from. It precedes the mode block, which then adds only that mode's
1233
+ // ownership and branch rules.
1220
1234
  const boundaryInject = packagedInject("instance-boundary");
1221
1235
  if (boundaryInject && existsSync(boundaryInject)) wanted.push(["kernel:instance-boundary", boundaryInject]);
1222
1236
  const workModeInject = packagedInject(`work-${workMode || "checkout"}`);
1223
1237
  if (workModeInject && existsSync(workModeInject)) wanted.push([`work-mode:${workMode || "checkout"}`, workModeInject]);
1224
- for (const cap of resolved.capabilities) {
1225
- if (cap.inject && existsSync(cap.inject)) wanted.push([`capability:${cap.id}`, cap.inject]);
1226
- }
1227
1238
  const blocks = wanted.map(([source, file]) => ({ source, file, content: readFileSync(file, "utf8").trim() }));
1228
- return { text: renderInstructionText(readFileSync(agentsMd, "utf8"), blocks), blocks, resolved, oatsCoreDeclared };
1239
+ const body = readFileSync(agentsMd, "utf8");
1240
+ return { text: renderInstructionText(body, blocks), body, blocks, resolved, oatsCoreDeclared };
1229
1241
  }
1230
1242
 
1231
1243
  /** Per slot `{ capability, from }` (from: "soul" | "workspace" | "team:<label>", the Desktop's
@@ -1369,6 +1381,19 @@ export function planInstanceResources({ resolved, soulDir, agent, contextDir, co
1369
1381
  return expected;
1370
1382
  }
1371
1383
 
1384
+ /** Reorder `expected`'s instruction-block entries, in the slots they hold, to `blocks`' order
1385
+ * (the written AGENTS.md's), so the record lists them as the file has them; an entry `blocks`
1386
+ * does not name keeps its relative place after them. Mutates and returns `expected`. */
1387
+ export function orderInstructionBlocks(expected, blocks) {
1388
+ const key = (source, file) => `${source}\u0000${file}`;
1389
+ const rank = new Map(blocks.map((b, i) => [key(b.source, b.file), i]));
1390
+ const at = (r) => rank.get(key(r.source, r.declared)) ?? blocks.length;
1391
+ const slots = [], rows = [];
1392
+ expected.forEach((r, i) => { if (r.type === "instruction-block") { slots.push(i); rows.push({ r, i }); } });
1393
+ rows.sort((a, b) => at(a.r) - at(b.r) || a.i - b.i).forEach(({ r }, j) => { expected[slots[j]] = r; });
1394
+ return expected;
1395
+ }
1396
+
1372
1397
  // ---------- harness packages (satisfied by a harness's own package manager) ----------
1373
1398
 
1374
1399
  /** pi's config dir, officially relocatable via PI_CODING_AGENT_DIR (pi
@@ -4036,7 +4061,7 @@ function* spawnBody(root, agent, o = {}) {
4036
4061
  if (prior.spawnCompleted !== true) throw unconfirmedSpawn(Object.assign(oatsError("E_SPAWN_INCOMPLETE", `${prior.instance} was created for this key but its spawn did not complete (launch or lineage unfinished); inspect it with oats session inspect --home ${prior.home} — do not spawn again`), { instance: prior.instance, home: prior.home, launched: prior.launched === true ? "unknown" : false }));
4037
4062
  // The receipt's warnings that are facts of the composition (a hook event this kernel ignores),
4038
4063
  // from the home's module copies: nothing runs again, and the captured composition is unchanged.
4039
- return { ...prior, replayed: true, launch: undefined, command: undefined, wake: prior.wake ?? { requested: null, saved: null, error: null }, warnings: replayedContractWarnings(prior.home) };
4064
+ return { ...prior, background: readInstanceBackground(prior.home), replayed: true, launch: undefined, command: undefined, wake: prior.wake ?? { requested: null, saved: null, error: null }, warnings: replayedContractWarnings(prior.home) };
4040
4065
  }
4041
4066
  }
4042
4067
 
@@ -4082,6 +4107,7 @@ function* spawnBody(root, agent, o = {}) {
4082
4107
  if (relation === "unrelated" && relativeTo) throw new Error(`relation "unrelated" takes no relativeTo`);
4083
4108
  if (relation && relation !== "unrelated" && !relativeTo) throw new Error(`relation "${relation}" needs a relative-to instance`);
4084
4109
  if (typeof o.relativeRoot === "string" && o.relativeRoot.trim() && !relativeTo && !legacyParent) throw new Error(`relativeRoot only qualifies relativeTo/parent`);
4110
+ if (o.sameWork !== undefined && typeof o.sameWork !== "boolean") throw oatsError("E_BAD_ARGS", "sameWork must be true or false");
4085
4111
  if (!relation && legacyParent) { relation = "child"; relativeTo = legacyParent; }
4086
4112
  if (relation === "unrelated") { relation = undefined; relativeTo = undefined; }
4087
4113
 
@@ -4212,6 +4238,12 @@ function* spawnBody(root, agent, o = {}) {
4212
4238
  if (anchorMeta?.siblingInstance) siblingInstance = anchorMeta.siblingInstance;
4213
4239
  }
4214
4240
  if (!relation && attachedOwner && attachedOwner !== instance) parentInstance = attachedOwner;
4241
+ // Feature instance-same-work: the flag binds the parent the new home records, whichever relation gave
4242
+ // it (child, a sibling of a non-root, --relation parent under a parented anchor, attached). None: refused
4243
+ // here, before any home, worktree or hook, a preview's included.
4244
+ if (o.sameWork === true && !(parentInstance && parentInstance !== instance)) {
4245
+ throw oatsError("E_BAD_ARGS", `--same-work needs a parent: ${instance} would record no parent instance${relation ? ` (relation ${relation}${relativeTo ? ` to ${relativeTo}` : ""})` : ""}; spawn it with --parent <instance>, or without --same-work; nothing was spawned`);
4246
+ }
4215
4247
  // K5 §4 — child-spawn permission is ENFORCED here, by the spawn route. The
4216
4248
  // parent's recorded policy (instance.json policy.childSpawns) says whether
4217
4249
  // it may have children; off refuses, attributed to that policy and its
@@ -4319,6 +4351,12 @@ function* spawnBody(root, agent, o = {}) {
4319
4351
  const composition = composeInstanceAgentsMd(soulDir, repoAbs, agent.name, work, agent.kind, o.prepared);
4320
4352
  const resolvedCfg = composition.resolved;
4321
4353
  const yolo = resolveYolo(o.yolo ?? launchSelection.configuredYolo);
4354
+ // Feature instance-background (#1579): the flag, else the soul's `background:`, else not background.
4355
+ // `backgroundFrom` names the layer that declared it, and is absent when neither did.
4356
+ if (o.background !== undefined && typeof o.background !== "boolean") throw oatsError("E_BAD_ARGS", "background must be true or false");
4357
+ const soulBackground = o.prepared?.soulEntry?.definition?.background;
4358
+ const backgroundFrom = o.background !== undefined ? "flag" : typeof soulBackground === "boolean" ? "soul" : null;
4359
+ const background = o.background ?? soulBackground === true;
4322
4360
  const expectedResources = planInstanceResources({ resolved: resolvedCfg, soulDir, agent, contextDir: repoAbs, composition, prepared: o.prepared });
4323
4361
  // Harness extensions selected by ACTIVE capabilities for THIS instance's
4324
4362
  // harness. Strict launch disables ambient extension discovery, so each one has
@@ -4439,7 +4477,9 @@ function* spawnBody(root, agent, o = {}) {
4439
4477
  const buildDecision = () => {
4440
4478
  const d = { instance, home, branch: plannedBranch, base: plannedBase,
4441
4479
  effective: { repo: repoAbs, work, harness, model: model || null, launchConfig: launchConfig?.name ?? null, yolo: yolo ?? null, backend, // backend regardless of --no-launch: the decision is what WOULD launch
4442
- childSpawns: ownChildPolicy.allowed, relation: relation ? { kind: relation, anchor: { instance: relativeTo ?? null, agentsRoot: anchorHome ? dirname(dirname(dirname(anchorHome))) : null } } : null } };
4480
+ childSpawns: ownChildPolicy.allowed, relation: relation ? { kind: relation, anchor: { instance: relativeTo ?? null, agentsRoot: anchorHome ? dirname(dirname(dirname(anchorHome))) : null } } : null,
4481
+ // Feature instance-background: bound only when true, so a decision without it keeps its revision.
4482
+ ...(background ? { background: true } : {}) } };
4443
4483
  // Workspace model: the decision binds WHAT WILL BE MATERIALIZED — the
4444
4484
  // resolution revision (member commits, package commits, payloads). A member
4445
4485
  // that moved between preview and apply changes it → E_DECISION_STALE.
@@ -4490,6 +4530,7 @@ function* spawnBody(root, agent, o = {}) {
4490
4530
  decision, preflight,
4491
4531
  backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
4492
4532
  harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigSource: launchConfig?.source ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4533
+ background, ...(backgroundFrom ? { backgroundFrom } : {}),
4493
4534
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
4494
4535
  branch: plannedBranch, base: plannedBase, worktree: work === "worktree" ? join(home, "work") : null,
4495
4536
  // #796: the `worktree` hooks a worktree-mode spawn would fire, in the order they run; null in other modes.
@@ -4576,10 +4617,11 @@ function* spawnBody(root, agent, o = {}) {
4576
4617
  // and instance.json all read the rebuilt rows from here on.
4577
4618
  let materializeOutcome = null;
4578
4619
  if (o.prepared) {
4579
- // The kernel's composed text (soul AGENTS.md + kernel/work-mode injects) is
4580
- // the body materialize composes the capability injects onto.
4620
+ // The soul's AGENTS.md is the body materialize composes onto: the capability
4621
+ // injects in the resolution's instruction order, then the kernel's blocks.
4581
4622
  try {
4582
- materializeOutcome = yield () => (o.materialize ?? materializePreparedDefault)({ ...o.prepared, soulAgentsMd: composition.text, soulDir }, home);
4623
+ const kernelBlocks = composition.blocks.filter((b) => !b.source.startsWith("capability:"));
4624
+ materializeOutcome = yield () => (o.materialize ?? materializePreparedDefault)({ ...o.prepared, soulAgentsMd: composition.body, blocks: kernelBlocks, soulDir }, home);
4583
4625
  const rows = (typeof o.prepared.toCapabilityRows === "function" ? o.prepared.toCapabilityRows : toCapabilityRows)(o.prepared.resolution, home);
4584
4626
  if (!Array.isArray(rows)) throw new Error("toCapabilityRows returned no rows");
4585
4627
  for (const row of rows) row.hooks = materializedHookCommands(row, home);
@@ -4603,6 +4645,12 @@ function* spawnBody(root, agent, o = {}) {
4603
4645
  expectedResources.push({ type: "instruction-block", source, declared: file, path: file, materialized: true });
4604
4646
  known.add(`${source}\u0000${file}`);
4605
4647
  }
4648
+ // The record lists the blocks in the order the written file has them
4649
+ // (capability injects, then the kernel's); a block not found keeps its place after them.
4650
+ const bodyEnd = composition.body.replace(/\n*$/, "\n").length;
4651
+ const at = (b) => { const i = written.indexOf(`<!-- oats:${b.source} src=${b.file} -->\n`, bodyEnd); return i < 0 ? Infinity : i; };
4652
+ composition.blocks = composition.blocks.map((b, i) => ({ b, i, at: at(b) })).sort((x, y) => (x.at === y.at ? x.i - y.i : x.at < y.at ? -1 : 1)).map(({ b }) => b);
4653
+ orderInstructionBlocks(expectedResources, composition.blocks);
4606
4654
  // The expected resources deferred to materialize (module skills/injects)
4607
4655
  // are now resolvable: fill their paths so the record and the completeness
4608
4656
  // check compare promised against landed.
@@ -5128,6 +5176,9 @@ You are instance "${instance}" of agent "${agent.name}".
5128
5176
  - Work tree: ./work — ${workDesc}
5129
5177
  - Do all repository work inside ./work. Read ./work/AGENTS.md or ./work/CLAUDE.md first if present.${briefLines}${harness === "codex" ? "\n## Harness notification delivery\n\nNative Codex has no built-in messaging channel. Follow the explicit delivery briefing for this instance from your messaging capability, if present; it may arrange notification through this terminal. Shared channel instructions alone do not establish that delivery is configured. Without an instance delivery briefing, check your messaging capability's inbox and pending commands at task boundaries or when the operator asks; do not assume messages will wake this session.\n" : ""}
5130
5178
  ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spawn time — await instructions.\n"}`, { mode: 0o600 }); // human text: the owner's only
5179
+ // Feature instance-background: the home's record, beside its other files, so the spawn's rollback
5180
+ // (which removes the home) leaves nothing of it.
5181
+ if (background) writeInstanceBackground(home, true);
5131
5182
 
5132
5183
  // Launch command. Spawn IS session start: the recipe is persisted in
5133
5184
  // instance.json beside its rendering, which is executed in the instance's
@@ -5253,6 +5304,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5253
5304
  meta.defaultTeam = structuredClone(o.prepared.resolution.defaultTeam ?? null);
5254
5305
  }
5255
5306
  const spawnWarnings = warnings;
5307
+ // Feature instance-same-work: bound to the parent the home records, written before the launch so that
5308
+ // the instance's first status shows it; the home's removal on a rollback takes it with the rest.
5309
+ if (o.sameWork === true && meta.parentInstance) writeSameWork(home, meta.parentInstance);
5256
5310
 
5257
5311
  spawnTmux = meta.tmux;
5258
5312
  if (work === "directory") assertDirectoryRoots(home, homeReal);
@@ -5375,7 +5429,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5375
5429
  meta.spawnCompleted = true;
5376
5430
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n"); // a kernel-owned field: the baseline fingerprint ignores it
5377
5431
  }
5378
- return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined, ...(naming ? { naming } : {}) });
5432
+ return deliver({ ...meta, background, ...(backgroundFrom ? { backgroundFrom } : {}), ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined, ...(naming ? { naming } : {}) });
5379
5433
  } catch (error) {
5380
5434
  if (promptDispatched) {
5381
5435
  // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
@@ -5551,12 +5605,7 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5551
5605
  // A self-retire that has been requested but not completed: the home is
5552
5606
  // owed a retirement, not live work. Read-only here — completion is the
5553
5607
  // detached child's or an operator's `oats retire`, never status.
5554
- const pending = retirePendingMarkerPath(home);
5555
- let retirePending, marker;
5556
- if (existsSync(pending)) {
5557
- try { retirePending = JSON.parse(readFileSync(pending, "utf8")); marker = { read: retirePending }; }
5558
- catch { retirePending = { reason: "retire pending" }; marker = { read: undefined }; }
5559
- }
5608
+ const { retirePending, marker } = readRetirePending(home);
5560
5609
  const retire = retireStateOf(home, marker);
5561
5610
  // A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
5562
5611
  // A home whose record cannot be read is listed, never observed: where its session is, is in the record.
@@ -5593,16 +5642,19 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5593
5642
  try { const s = instanceSessionTarget(home); if (!s.target) waitingOnYou = null; }
5594
5643
  catch { waitingOnYou = null; }
5595
5644
  }
5596
- // `retire` is only ever the value read above: a record that carries one (hand-edited, or
5597
- // copied from a row) never stands in for it.
5598
- const { retire: _recordedRetire, ...recorded } = meta;
5645
+ // `retire` is only ever the value read above, and `background` and `sameWork` the home's own records
5646
+ // (below): a record that carries any of them (hand-edited, or copied from a row) never stands in for it.
5647
+ const { retire: _recordedRetire, background: _recordedBackground, sameWork: _recordedSameWork, ...recorded } = meta;
5599
5648
  // Feature session-resume: how the last session of a launched home that does not run ended
5600
5649
  // (lib/session-end.mjs): lost, stopped or exited. Absent while it runs or reads unknown, for a
5601
5650
  // home never launched, and for one being set up, retired or quarantined.
5602
5651
  const sessionEnd = record.state === "record" && liveness.running === false && meta.launched === true && !rollbackIncomplete && !spawnInProgress && !retirePending ? sessionEndOf(home, meta) : null;
5603
5652
  // Feature instance-color: the home's own colour record (lib/instance-color.mjs), a palette name or
5604
5653
  // null, after the record so that nothing in instance.json stands in for it.
5605
- return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, ...(sessionEnd ? { sessionEnd } : {}), waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
5654
+ // Feature instance-same-work: `sameWork: true` only while the home's flag is bound to the parent
5655
+ // its readable record names (lib/instance-same-work.mjs sameWorkOf); absent otherwise, never false.
5656
+ const sameWork = record.state === "record" && sameWorkOf(home, meta.parentInstance);
5657
+ return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(readInstanceBackground(home) ? { background: true } : {}), ...(sameWork ? { sameWork: true } : {}), ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, ...(sessionEnd ? { sessionEnd } : {}), waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
5606
5658
 
5607
5659
  });
5608
5660
  };
@@ -6154,12 +6206,14 @@ function retireGitProbe(repo, args, { encoding } = {}) {
6154
6206
  * MUST be added in the same change to the names a capability may not declare
6155
6207
  * as its own (`retirement.disposable.home`: KERNEL_HOME_NAMES and
6156
6208
  * KERNEL_HOME_NAME_PREFIXES in lib/capability-contract.mjs, and the schema). */
6157
- // `.oats-color.json` (feature instance-color) is presentation anyone may change at any time: never work.
6209
+ // `.oats-color.json` (feature instance-color) and `.oats-background.json` (feature instance-background) are
6210
+ // presentation anyone may change at any time: never work.
6211
+ // `.oats-same-work.json` (feature instance-same-work) is kernel presentation of the same kind.
6158
6212
  // `.oats-start-exited` (lib/session-end.mjs) is the window's record of how the harness ended: every
6159
6213
  // launched home whose harness ever ended holds it.
6160
6214
  // `.oats-start-env.json` and its key (lib/start-env.mjs) are written at every start that renders a
6161
6215
  // recipe, after the spawn's baseline: every launched home holds them.
6162
- const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
6216
+ const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", ".oats-background.json", SAME_WORK_FILE, START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
6163
6217
  const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, START_ENV_TMP];
6164
6218
  /** Harness project settings in the home are configuration, not work: the
6165
6219
  * home's `.claude/` is harness layout the kernel already shapes (the skills
@@ -7345,6 +7399,14 @@ function stopStartId(home) {
7345
7399
  const id = readJsonOrUndefined(join(home, "instance.json"))?.startId;
7346
7400
  return typeof id === "string" && id ? id : null;
7347
7401
  }
7402
+ /** Record that OATS stopped the session of `home`'s current start (lib/session-end.mjs): the stop
7403
+ * receipt `.oats-stop.json`, `stop` being what was done to the harness (stopHarness's receipt, or
7404
+ * null when nothing was signalled). Its `startId` names the start, so the home reads `stopped`
7405
+ * and no resume brings that start back. The one writer of the receipt: a stop, an idle stop, and
7406
+ * a retire before it ends the session. Throws what the write throws. */
7407
+ function recordStop(home, stop) {
7408
+ writeJsonAtomic(join(home, STOP_RECEIPT_FILE), { instance: basename(home), at: new Date().toISOString(), stop, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(home) });
7409
+ }
7348
7410
  /** An explicit stop of a launched home found idle whose session reads `lost` (the host went down or
7349
7411
  * its tmux server died; or a home from before 0.69 whose harness ended): nothing is signalled, but
7350
7412
  * the stop is recorded (`stop: null`), so a resume does not bring the home back. Best effort: a
@@ -7352,7 +7414,7 @@ function stopStartId(home) {
7352
7414
  function recordIdleStop(realHome) {
7353
7415
  const meta = readJsonOrUndefined(join(realHome, "instance.json"));
7354
7416
  if (meta?.launched !== true || sessionEndOf(realHome, meta) !== SESSION_END.LOST) return;
7355
- try { writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: null, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(realHome) }); }
7417
+ try { recordStop(realHome, null); }
7356
7418
  catch { /* the idle stop's answer is unchanged: see above */ }
7357
7419
  }
7358
7420
  /** The stop of stopInstanceSession, under the home's claim. The pending self-retire marker is read
@@ -7378,8 +7440,7 @@ function stopSessionClaimed(home, o) {
7378
7440
  }
7379
7441
  signalling = true;
7380
7442
  receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
7381
- // `startId` names the start this stop ended, so a resume never brings it back (lib/session-end.mjs).
7382
- writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(realHome) });
7443
+ recordStop(realHome, receipt);
7383
7444
  appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
7384
7445
  if (!receipt.exited) throw Object.assign(oatsError("E_SESSION_STOP_FAILED", `${basename(realHome)} was asked to stop (${receipt.signal} to ${receipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")}) and is still running after ${receipt.waitedMs} ms; nothing was escalated`), { receipt });
7385
7446
  return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
@@ -7839,12 +7900,27 @@ function resumePaneTarget(target, socket, output) {
7839
7900
  }
7840
7901
  export function startInstanceSession(home, o = {}) {
7841
7902
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session start needs an absolute instance home");
7903
+ if (o.resume !== true) return startSession(home, o);
7842
7904
  // --resume (feature session-resume) runs the recorded launch as it is: a launch choice cannot go with it.
7843
- if (o.resume === true) {
7844
- if (o.restart) throw oatsError("E_BAD_ARGS", "--resume brings back a session that was lost; it is not a restart: use session start --resume");
7845
- const chosen = [[o.launchConfig !== undefined, "--launch-config"], [o.harness !== undefined, "--harness"], [o.model !== undefined && o.model !== null, "--model"], [o.yolo === true, "--yolo"], [o.yolo === false, "--no-yolo"], [o.reselectLaunch === true, "--reselect-launch"]].filter(([given]) => given).map(([, name]) => name);
7846
- if (chosen.length) throw oatsError("E_BAD_ARGS", `--resume runs the launch this home recorded; it cannot be combined with ${chosen.join(", ")}; nothing was read or started`);
7847
- }
7905
+ if (o.restart) throw oatsError("E_BAD_ARGS", "--resume brings back a session that was lost; it is not a restart: use session start --resume");
7906
+ const chosen = [[o.launchConfig !== undefined, "--launch-config"], [o.harness !== undefined, "--harness"], [o.model !== undefined && o.model !== null, "--model"], [o.yolo === true, "--yolo"], [o.yolo === false, "--no-yolo"], [o.reselectLaunch === true, "--reselect-launch"]].filter(([given]) => given).map(([, name]) => name);
7907
+ if (chosen.length) throw oatsError("E_BAD_ARGS", `--resume runs the launch this home recorded; it cannot be combined with ${chosen.join(", ")}; nothing was read or started`);
7908
+ // A resume holds the home's lifecycle claim for the whole start, as a retire, a stop and an
7909
+ // upgrade do (claimHomeFor): none of them runs while it starts, and it starts nothing beside one
7910
+ // of them (lifecycleClaimRefusals: E_INSTANCE_RETIRING beside a retire, E_LIFECYCLE_BUSY beside
7911
+ // the others). What it reads under the claim (the retire it owes, whether its session is still
7912
+ // lost) is what it starts from. A home that is not there has no claim to take: it answers as it
7913
+ // always did. An ordinary start or restart does not take the claim. The claim is the one of the
7914
+ // home as it is on disk, through any link to the home itself, and the start runs on that path,
7915
+ // never on the spelling it was given again: a link changed after the claim was taken does not
7916
+ // move the start to a home whose claim it does not hold.
7917
+ if (!existsSync(home)) return startSession(home, o);
7918
+ const real = canonicalHomePath(home);
7919
+ const held = claimHomeFor("resume", basename(real), real);
7920
+ try { return startSession(real, o); } finally { releaseHomeClaim(held); }
7921
+ }
7922
+ /** The start of startInstanceSession, its arguments checked; a resume's under the home's claim. */
7923
+ function startSession(home, o) {
7848
7924
  // A home whose record is there and cannot be read is refused before anything of it is read (#896).
7849
7925
  identifiedHomeRecord(home);
7850
7926
  // A home opened in Herdr, or an earlier start that allocated a Herdr pane, is refused before any
@@ -8098,6 +8174,10 @@ export function startInstanceSession(home, o = {}) {
8098
8174
  const observed = recordedState();
8099
8175
  if (observed.error) { const e = observed.error; throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${meta.instance} is running, so nothing was started: ${String(e.stderr ?? e.message ?? "").trim() || e.message}`); }
8100
8176
  if (observed.state.present && observed.state.state !== "shell") throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${observed.state.state}); nothing was started`);
8177
+ // A home whose retire runs, cannot be told, failed or was interrupted is owed it, never a
8178
+ // resume (read as its status row reads it, under the claim this resume holds).
8179
+ const owed = owedRetire(realHome);
8180
+ if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(meta.instance, owed.state)}; nothing was started`);
8101
8181
  const end = meta.launched === true ? sessionEndOf(realHome, meta) : "never-launched";
8102
8182
  if (end !== SESSION_END.LOST) throw oatsError("E_RESUME_NOT_LOST", `${meta.instance} did not lose its session (${end === "never-launched" ? "it was never launched" : `it ${end}`}); --resume brings back only a lost session; nothing was started (an ordinary session start opens a fresh conversation)`);
8103
8183
  resume = resumeConversation(realHome, meta);
@@ -9961,6 +10041,25 @@ export function retirePendingMarkerPath(home) {
9961
10041
  return join(dirname(home), `.oats-retire-pending-${basename(home)}.json`);
9962
10042
  }
9963
10043
 
10044
+ /** The retire-pending marker of `home` as a status row reads it → `{ retirePending, marker }`: both
10045
+ * undefined when there is none; `retirePending` what it parsed as (a placeholder when it did not
10046
+ * parse), `marker` what retireStateOf takes. */
10047
+ function readRetirePending(home) {
10048
+ const pending = retirePendingMarkerPath(home);
10049
+ if (!existsSync(pending)) return {};
10050
+ try { const read = JSON.parse(readFileSync(pending, "utf8")); return { retirePending: read, marker: { read } }; }
10051
+ catch { return { retirePending: { reason: "retire pending" }, marker: { read: undefined } }; }
10052
+ }
10053
+ /** The retire `home` owes, as a status row's `retire` reads it (retireStateOf), or undefined. */
10054
+ function owedRetire(home) {
10055
+ return retireStateOf(home, readRetirePending(home).marker);
10056
+ }
10057
+ /** Why `instance`, whose status row's `retire` has `state`, is not resumed: one clause. */
10058
+ export function owedRetireSaid(instance, state) {
10059
+ const said = { running: "is running", unknown: "cannot be told", failed: "failed", interrupted: "was interrupted" }[state] ?? "cannot be told";
10060
+ return `${instance} is owed a retire (its retire ${said}); a home OATS is retiring is never resumed`;
10061
+ }
10062
+
9964
10063
  /** A status row's `retire` (feature status-retire-state, lib/retire-state.mjs): whether a retire of
9965
10064
  * `home` runs, could not be told, failed or was interrupted, read from what is beside the home
9966
10065
  * (`marker`: `{ read }` when its retire marker is there, `read` what its file parsed as, undefined
@@ -10329,15 +10428,19 @@ const RETIRE_CLAIM_RESTARTS = 2;
10329
10428
 
10330
10429
  /** The lifecycle claim file of `home`: `<instances>/.oats-retirement/claims/<name>.lock`. Beside
10331
10430
  * the homes, never inside one: a home's bytes are what its retire observes, copies and removes.
10332
- * One file for every verb that holds a home (a retire, a stop): its record names the holder's
10333
- * verb (`action`) from the instant it exists (lib/claim.mjs `facts`). */
10431
+ * One file for every verb that holds a home (a retire, a stop, an upgrade, a resume): its record
10432
+ * names the holder's verb (`action`) from the instant it exists (lib/claim.mjs `facts`). One file
10433
+ * for every spelling of the home: `<instances>` is the instances directory's own spelling on disk
10434
+ * (canonicalHomePath), and `<name>` the home's name once `.` and `..` are resolved, so that
10435
+ * `H/.`, or `H` through a link to its deployment, names H's claim. */
10334
10436
  export function retireClaimPath(home) {
10335
- return join(instancesRetirementRoot(dirname(home)), "claims", `${basename(home)}.lock`);
10437
+ const at = resolve(home);
10438
+ return join(instancesRetirementRoot(canonicalHomePath(dirname(at))), "claims", `${basename(at)}.lock`);
10336
10439
  }
10337
10440
 
10338
10441
  /** The verbs that take a home's lifecycle claim: what claimHomeFor accepts, and so every `action`
10339
- * a claim of the kernel's names. */
10340
- const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade"]);
10442
+ * a claim of the kernel's names. `resume` is a `session start --resume`. */
10443
+ const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade", "resume"]);
10341
10444
  /** The verb the holder of a home's claim recorded (`action`): one of CLAIM_VERBS, never the
10342
10445
  * record's text. A claim is read back as whatever is in its file, which other instances of the
10343
10446
  * deployment can write, and this goes into messages, remedies and `details` (lib/claim.mjs
@@ -10346,14 +10449,14 @@ const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade"]);
10346
10449
  * retire took the claim. */
10347
10450
  const claimAction = (holder) => CLAIM_VERBS.includes(holder?.action) ? holder.action : "retire";
10348
10451
  /** The command that takes a home's claim for `action`, as a person types it. */
10349
- const claimCommand = (action) => ["stop", "upgrade"].includes(action) ? `oats instance ${action}` : `oats ${action}`;
10452
+ const claimCommand = (action) => action === "resume" ? "oats session start --resume" : ["stop", "upgrade"].includes(action) ? `oats instance ${action}` : `oats ${action}`;
10350
10453
  /** What each verb that meets a held claim says it did not do: the words its refusals end with,
10351
10454
  * before any effect. After a takeover ended a dead holder's step, every verb says the same
10352
10455
  * (lib/errors.mjs nothingAfter). */
10353
- const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", "worktree add": "no tree was made", "instance color": "the colour was not changed" };
10456
+ const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", resume: "nothing was started", "worktree add": "no tree was made", "instance color": "the colour was not changed", "instance same-work": "the flag was not changed", "instance background": "the background was not changed" };
10354
10457
 
10355
- /** The refusals of `arriving` ("retire", "stop", or "worktree add", which reads the claim and does
10356
- * not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
10458
+ /** The refusals of `arriving` ("retire", "stop", "upgrade", "resume", or "worktree add", which
10459
+ * reads the claim and does not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
10357
10460
  * for them: one builder for every pair (arriving verb, holder's verb), so that the pair table of
10358
10461
  * docs/desktop-cli-api.md has one source. One line each, saying what was not done, once.
10359
10462
  * - A live holder: E_INSTANCE_RETIRING when the holder is a retire and the arriving verb is not
@@ -10373,7 +10476,7 @@ const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing wa
10373
10476
  export function lifecycleClaimRefusals(arriving, name, home, lock) {
10374
10477
  const nothing = (ended) => nothingAfter(ended, CLAIM_NOTHING[arriving]);
10375
10478
  const own = { instance: name, home };
10376
- const holders = "oats retire, oats instance stop or oats instance upgrade";
10479
+ const holders = "oats retire, oats instance stop, oats instance upgrade or oats session start --resume";
10377
10480
  // The holder of `at`, as an answer names it: `shown` for the message, `details` beside it.
10378
10481
  const held = (holder, at) => {
10379
10482
  const shown = shownHolder(holder), action = claimAction(holder);
@@ -10420,7 +10523,7 @@ export function retireClaimRefusals(name, home, lock) {
10420
10523
  * parsed arguments or JSON. */
10421
10524
  export const READ_CLAIM_WHEN_UNWRITABLE = Symbol("oats.readClaimWhenUnwritable");
10422
10525
 
10423
- /** Take the lifecycle claim of `home` for `verb` ("retire", "stop") → the holding, for
10526
+ /** Take the lifecycle claim of `home` for `verb` (one of CLAIM_VERBS) → the holding, for
10424
10527
  * releaseHomeClaim. The one way a verb takes it: the record carries the verb from the instant the
10425
10528
  * file exists, and a holder of any verb is refused at once (`waitMs: 0`; only a deferred
10426
10529
  * self-retire's completion waits, for the retire that scheduled it). The claim's directory is
@@ -10443,7 +10546,7 @@ export function claimHomeFor(verb, name, home, { waitMs = 0, [READ_CLAIM_WHEN_UN
10443
10546
  const refusals = lifecycleClaimRefusals(verb, name, home, lock);
10444
10547
  try {
10445
10548
  try {
10446
- claimWrite(() => mkdirSync(instancesRetirementRoot(dirname(home)), { recursive: true }));
10549
+ claimWrite(() => mkdirSync(dirname(dirname(lock)), { recursive: true }));
10447
10550
  claimWrite(() => mkdirSync(dirname(lock), { recursive: true, mode: 0o700 }));
10448
10551
  } catch (e) { throw claimUnavailable(lock, e); }
10449
10552
  return { lock, me: acquireClaim(lock, { ...refusals, facts: { action: verb }, waitMs }) };
@@ -10963,6 +11066,13 @@ function retireSteps(root, name, o, found, at) {
10963
11066
  const tmux = ["-S", runtimeSocket];
10964
11067
  at.sessionTouched = true;
10965
11068
  ownSession = "unverified";
11069
+ // The stop is recorded before the window is ended, so that at no instant the window is gone
11070
+ // and the home reads `lost` (a resume would bring it back): a retire that fails after this
11071
+ // leaves a home that reads `stopped`. A record that cannot be written (a full disk) does not
11072
+ // fail the retire: the home reads lost, and this retire's claim keeps a resume off it while it
11073
+ // runs. Should the retire then fail too, nothing records that it was asked for, and the home
11074
+ // reads lost as it did before this record existed.
11075
+ try { recordStop(found.home, null); } catch { /* see above */ }
10966
11076
  try { execFileSync("tmux", [...tmux, "kill-window", "-t", `=${runtimeSession}:=${runtimeWindow}`], { stdio: ["ignore", "pipe", "pipe"] }); } catch { /* verify the effect below */ }
10967
11077
  try {
10968
11078
  const windows = execFileSync("tmux", [...tmux, "list-windows", "-t", runtimeSession, "-F", "#{window_name}"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).split("\n").filter(Boolean);
@@ -11567,6 +11677,9 @@ function retireSteps(root, name, o, found, at) {
11567
11677
  // literal # in the socket path is written ##.
11568
11678
  const killSocket = runtimeAuthority?.tmux?.socket || meta?.tmux?.socket;
11569
11679
  const killTarget = shq(`=${killSession}:=${killWindow}`);
11680
+ // The home `--keep-dir` keeps reads `stopped` once its window is gone, never `lost` (recordStop,
11681
+ // as above). A record that cannot be written stops nothing: the home then reads lost, as before.
11682
+ if (o.keepDir) { try { recordStop(found.home, null); } catch { /* see above */ } }
11570
11683
  if (typeof killSocket === "string" && killSocket) {
11571
11684
  const kill = `sleep ${o.selfKillDelaySec ?? 8}; tmux -u -S ${shq(killSocket)} kill-window -t ${killTarget} 2>/dev/null || true`;
11572
11685
  shTry(`tmux -u -S ${shq(killSocket)} run-shell -b ${shq(kill.replace(/#/g, "##"))}`);
@@ -0,0 +1,54 @@
1
+ /** Whether an instance is background (feature instance-background, awebai/oats#1579): presentation like
2
+ * the colour (lib/instance-color.mjs), never identity or policy. A client lists a background instance
3
+ * under its own section; nothing else about the instance changes. It is a home file of its own,
4
+ * `<home>/.oats-background.json`, so that a start or restart, which rewrites instance.json, can never
5
+ * lose it; a later edit of the soul does not move an existing home.
6
+ *
7
+ * The record is `{ backgroundApi: 1, at }` (#1579 item 3: present means background), written atomically
8
+ * (writeThroughPrivateFile) at mode 0600; absent means not background, and `off` removes the file. A
9
+ * reader takes a regular file only, without following a link, up to RECORD_MAX bytes: anything that is
10
+ * not a valid record reads as not background (false), never an error. Dependency-free: spawn, the status
11
+ * rows, inspect and the command all read and write it through here. */
12
+ import { lstatSync, rmSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { readFileHead } from "./bounded-read.mjs";
15
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
16
+
17
+ /** The record's own version, and the command answer's. */
18
+ export const BACKGROUND_API = 1;
19
+ export const INSTANCE_BACKGROUND_API = 1;
20
+ /** The home file, kernel-owned: in KERNEL_HOME_NAME_PREFIXES (lib/capability-contract.mjs), the retire
21
+ * fingerprint's receipts (lib/core.mjs KERNEL_HOME_RECEIPTS) and the manifest schema. */
22
+ export const BACKGROUND_FILE = ".oats-background.json";
23
+ /** A record larger than this is not one. */
24
+ export const RECORD_MAX = 4096;
25
+
26
+ /** Whether `home` records itself background: false for no file, not a regular file (a link is never
27
+ * followed), over RECORD_MAX bytes, unreadable, not a JSON object or another backgroundApi. Never throws. */
28
+ export function readInstanceBackground(home) {
29
+ try {
30
+ const { bytes, size } = readFileHead(join(home, BACKGROUND_FILE), RECORD_MAX + 1);
31
+ if (size > RECORD_MAX) return false;
32
+ const record = JSON.parse(bytes.toString("utf8"));
33
+ return !!record && typeof record === "object" && !Array.isArray(record) && record.backgroundApi === BACKGROUND_API;
34
+ } catch { return false; }
35
+ }
36
+
37
+ /** Record `home` as background (`on` true), or remove the record (`on` false). → `{ background, changed }`.
38
+ * A home already background is no change: nothing is written. `off` removes whatever file stands at the
39
+ * name (a link or an invalid record included) and is a change only when the home read as background.
40
+ * The caller holds the right to change the home. */
41
+ export function writeInstanceBackground(home, on, { now = () => new Date() } = {}) {
42
+ const path = join(home, BACKGROUND_FILE);
43
+ const before = readInstanceBackground(home);
44
+ if (!on) {
45
+ let present = false;
46
+ try { lstatSync(path); present = true; } catch (e) { if (e?.code !== "ENOENT") throw e; }
47
+ if (present) rmSync(path, { force: true });
48
+ return { background: false, changed: before };
49
+ }
50
+ if (before) return { background: true, changed: false };
51
+ const bytes = JSON.stringify({ backgroundApi: BACKGROUND_API, at: now().toISOString() }) + "\n";
52
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, bytes, 0o600);
53
+ return { background: true, changed: true };
54
+ }
@@ -29,6 +29,7 @@ import { operatorCoverage, operatorProblems } from "./operator-coverage.mjs";
29
29
  import { readLockIfPresent } from "./packages.mjs";
30
30
  import { composeSoulInstructions } from "./soul-composition.mjs";
31
31
  import { readInstanceColor } from "./instance-color.mjs";
32
+ import { readInstanceBackground } from "./instance-background.mjs";
32
33
  /** Bounds of a provider check's answer (bytes, nesting, entries), as the released binding wire set them. */
33
34
  const BINDING_LIMITS = Object.freeze({ maxBytes: 1024 * 1024, maxDepth: 32, maxEntries: 16384 });
34
35
  import { parseStrictJson } from "./canonical-json.mjs";
@@ -539,6 +540,8 @@ export function inspectDocument(t, { kernel }) {
539
540
  launchConfig: m.launch?.launchConfig ?? null, launchConfigDefault: m.launch?.launchConfigDefault === true, launched: !!m.launched, createdAt: m.createdAt || null,
540
541
  // Feature instance-color: the home's colour record (lib/instance-color.mjs), a palette name or null.
541
542
  color: readInstanceColor(t.home),
543
+ // Feature instance-background: `true` while the home holds a valid record, absent otherwise (as on a row).
544
+ ...(readInstanceBackground(t.home) ? { background: true } : {}),
542
545
  resolution: m.workspace?.resolution ?? null, soulDir: t.soul.soulDir, instructions: { ...readTextCapped(join(t.home, "AGENTS.md")), sources: m.instructions || [] } } : null,
543
546
  ...(m ? { identity: servedIdentityOf(m) } : {}),
544
547
  problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.composedInstructionsProblem ? [t.composedInstructionsProblem] : []), ...(t.skillsProblems || []), ...(t.composedSkillsProblems || []), ...(t.discoveryError ? [t.discoveryError] : []),
@@ -17,6 +17,8 @@ import { appendEvent } from "./instance-events.mjs";
17
17
  import { afterFirstEffect, isAnswerCode, kernelCode, lifecycleBusy, oatsError, reportDefect } from "./errors.mjs";
18
18
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
19
19
  import { INSTANCE_COLOR_API, INSTANCE_COLORS, writeInstanceColor } from "./instance-color.mjs";
20
+ import { INSTANCE_BACKGROUND_API, writeInstanceBackground } from "./instance-background.mjs";
21
+ import { sameWorkOf, writeSameWork } from "./instance-same-work.mjs";
20
22
 
21
23
  export const LIFECYCLE_API = 1;
22
24
  const KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -88,6 +90,39 @@ export function setInstanceColor(ctx, root, name, { home, color }) {
88
90
  return { instanceColorApi: INSTANCE_COLOR_API, instance: name, home: me.home, color, changed };
89
91
  }
90
92
 
93
+ /** `oats instance background <instance> on|off` (feature instance-background, awebai/oats#1579): record or
94
+ * remove the background record of the home `name` resolves to, with the authority and the refusals of
95
+ * `instance color` above (setInstanceColor), a stopped home included. `background` is a boolean; the caller
96
+ * refused anything else. → `{ instanceBackgroundApi, instance, home, background, changed }`. */
97
+ export function setInstanceBackground(ctx, root, name, { home, background }) {
98
+ if (typeof background !== "boolean") throw oatsError("E_BAD_ARGS", "background must be on or off");
99
+ const me = resolveTarget(ctx, root, name, { home });
100
+ if (existsSync(join(me.home, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${me.home} is a quarantined home (or a spawn still in progress); finish its retirement (oats retire); the background was not changed`);
101
+ if (existsSync(retirePendingMarkerPath(me.home))) throw oatsError("E_INSTANCE_RETIRING", `${name} is being retired; the background was not changed`);
102
+ refuseBesideRetire("instance background", me.home);
103
+ const { changed } = writeInstanceBackground(me.home, background);
104
+ return { instanceBackgroundApi: INSTANCE_BACKGROUND_API, instance: name, home: me.home, background, changed };
105
+ }
106
+
107
+ /** `oats instance same-work <instance> on|off` (feature instance-same-work, awebai/oats#1577): bind the flag
108
+ * of the home `name` resolves to to its recorded parent (`on`), or remove it (`off`). Addressed, and refused
109
+ * beside a retire or in a quarantined home, exactly as setInstanceColor is. `on` needs a recorded
110
+ * `parentInstance` (E_BAD_ARGS without one) and rebinds a record bound to an old parent; the same parent
111
+ * again writes nothing. `off` succeeds whatever stands there, parent or none. → `{ instance, sameWork }`,
112
+ * the rule (sameWorkOf) read after the write. */
113
+ export function setInstanceSameWork(ctx, root, name, { home, on }) {
114
+ if (typeof on !== "boolean") throw oatsError("E_BAD_ARGS", "instance same-work takes on or off");
115
+ const me = resolveTarget(ctx, root, name, { home });
116
+ if (existsSync(join(me.home, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${me.home} is a quarantined home (or a spawn still in progress); finish its retirement (oats retire); the flag was not changed`);
117
+ if (existsSync(retirePendingMarkerPath(me.home))) throw oatsError("E_INSTANCE_RETIRING", `${name} is being retired; the flag was not changed`);
118
+ refuseBesideRetire("instance same-work", me.home);
119
+ const recorded = targetRecord(me.home)?.parentInstance;
120
+ const parent = typeof recorded === "string" && recorded !== "" ? recorded : null;
121
+ if (on && parent === null) throw oatsError("E_BAD_ARGS", `${name} has no parent instance: same work is declared against a recorded parent; the flag was not changed`);
122
+ writeSameWork(me.home, on ? parent : null);
123
+ return { instance: name, sameWork: sameWorkOf(me.home, parent) };
124
+ }
125
+
91
126
  /** Every instance under the roots whose recorded parent chain reaches `name`,
92
127
  * deepest first (children are acted on before their parent). Recorded
93
128
  * parentage is the only relation the kernel knows; it is reported as such. */
@@ -654,9 +654,10 @@ export async function discoverOrStandalone(local, { lock, deployment, remoteOpti
654
654
  }
655
655
 
656
656
  /** Materialize a prepared resolution into `home`. Called by spawnInstance after
657
- * the home directory exists and before the harness is launched. */
657
+ * the home directory exists and before the harness is launched. `prepared.blocks`
658
+ * (the kernel's blocks) close the AGENTS.md, after the capability injects. */
658
659
  export async function materializePrepared(prepared, home) {
659
- return materialize(prepared.resolution, home, { lock: prepared.lock, remoteOptions: prepared.remoteOptions, soulAgentsMd: prepared.soulAgentsMd, soulDir: prepared.soulDir });
660
+ return materialize(prepared.resolution, home, { lock: prepared.lock, remoteOptions: prepared.remoteOptions, soulAgentsMd: prepared.soulAgentsMd, soulDir: prepared.soulDir, blocks: prepared.blocks });
660
661
  }
661
662
  /** The capability skills materializePrepared would copy, named before anything is fetched (the spawn preview). */
662
663
  export async function plannedPreparedSkills(prepared) {