@awebai/oats 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/bin/oats.mjs +293 -41
  2. package/docs/capabilities.md +264 -8
  3. package/docs/capability-manifest.schema.json +18 -5
  4. package/docs/configuration.md +7 -1
  5. package/docs/desktop-cli-api.md +439 -40
  6. package/docs/desktop.md +72 -5
  7. package/docs/execution-targets.md +19 -1
  8. package/docs/implementation.md +81 -1
  9. package/docs/integrations.md +7 -5
  10. package/docs/knowledge.md +167 -197
  11. package/docs/official-catalog.md +6 -5
  12. package/docs/packages.md +14 -14
  13. package/docs/release-notes/v0.48.0.md +106 -0
  14. package/docs/release-notes/v0.49.0.md +770 -0
  15. package/docs/schedules.md +62 -39
  16. package/docs/servers.md +7 -0
  17. package/docs/souls-and-instances.md +395 -52
  18. package/docs/workspaces.md +18 -3
  19. package/injects/work-checkout.md +17 -11
  20. package/injects/work-worktree.md +19 -13
  21. package/lib/capability-contract.mjs +100 -11
  22. package/lib/capability-show.mjs +5 -2
  23. package/lib/core.mjs +1147 -319
  24. package/lib/instance-events.mjs +6 -3
  25. package/lib/instance-git.mjs +11 -5
  26. package/lib/instance-inspect.mjs +14 -3
  27. package/lib/instance-lifecycle.mjs +106 -16
  28. package/lib/instance-resolution.mjs +15 -3
  29. package/lib/launch-prompt-policy.mjs +17 -3
  30. package/lib/packages.mjs +1 -0
  31. package/lib/real-path.mjs +27 -0
  32. package/lib/resolve.mjs +4 -4
  33. package/lib/retire-output.mjs +6 -1
  34. package/lib/schedule.mjs +1 -0
  35. package/lib/servers.mjs +32 -6
  36. package/lib/teams-verbs.mjs +40 -9
  37. package/lib/tree-copy.mjs +18 -7
  38. package/lib/triggers.mjs +201 -65
  39. package/lib/workspace.mjs +20 -5
  40. package/lib/worktree-hooks.mjs +392 -0
  41. package/lib/worktree.mjs +655 -0
  42. package/package-catalog.json +12 -5
  43. package/package.json +1 -1
  44. package/skills/oats-getting-started/SKILL.md +1 -1
package/bin/oats.mjs CHANGED
@@ -19,7 +19,7 @@
19
19
  * `init` / `use` / `install` / `restore` / `list` / `catalog` / `remove` /
20
20
  * `migrate` / `trust` / `inject` are gone with the installed-capability tier.
21
21
  */
22
- import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readSync, readdirSync, realpathSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
22
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
23
23
  import { execFileSync, spawnSync } from "node:child_process";
24
24
  import { constants as osConstants, homedir, tmpdir } from "node:os";
25
25
  import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
@@ -30,7 +30,7 @@ import {
30
30
  LAYERS, OATS_VERSION, manifestOperations, upgradeHomeMeta,
31
31
  capabilityManifests, capabilityTrust, capabilityExecutablePath,
32
32
  officialPackageCatalog, officialCatalogFile, officialCapabilityAliases, resolvedFromHome, resolvedFromPrepared, teamEnv, isWorkspaceHome, preWorkspaceHome, isCapturedHome, capturedHomeRefusal, composeInstanceAgentsMd, parseYamlNested, withConfigFile,
33
- findInstanceHome, findInstanceHomes, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, stopInstanceSession, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, instanceSoulDir, stableSoulId, preparedSoulIdOf, recordedKernelBin, launchConfigsAt, launchPromptPolicyAt, LAUNCH_PROMPT_UPDATE_WARNING, launchReportFor, explicitInstanceName, retireInstance, inspectInstanceSession, inputInstanceSession, attachInstanceSession, startInstanceSession, defaultRepo, RELATIONS, validateLaunchConfig, validateLaunchConfigDefaults, renderLaunchRecipe, describeLaunchCommand, redactLaunchRecipe, withSafeTaskPrompt, LAUNCH_HARNESSES, planLaunch, redactLaunchCommand, restartInstanceSession,
33
+ findInstanceHome, findInstanceHomes, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, instanceSoulDir, stableSoulId, preparedSoulIdOf, recordedKernelBin, launchConfigsAt, launchPromptPolicyAt, LAUNCH_PROMPT_UPDATE_WARNING, launchReportFor, explicitInstanceName, retireInstance, RETIRE_SELECTED_HOME, inspectInstanceSession, inputInstanceSession, attachInstanceSession, startInstanceSession, defaultRepo, RELATIONS, validateLaunchConfig, validateLaunchConfigDefaults, renderLaunchRecipe, describeLaunchCommand, redactLaunchRecipe, withSafeTaskPrompt, LAUNCH_HARNESSES, planLaunch, redactLaunchCommand, restartInstanceSession,
34
34
  FAILED_SPAWN_BRANCH_LEFT, RETIRE_DELETE_BRANCH_REFUSED,
35
35
  } from "../lib/core.mjs";
36
36
  import {
@@ -53,7 +53,7 @@ import { hostUnitStatus, installHostUnit, uninstallHostUnit } from "../lib/sched
53
53
  import { receiveAttachment, uploadAttachment, readStreamBounded, MAX_ATTACHMENT_BYTES } from "../lib/attachments.mjs";
54
54
 
55
55
  import { observeInstanceGit, diffInstanceFile } from "../lib/instance-git.mjs";
56
- import { planStop, applyStop, planRetire, resolveInstance as resolveInstanceForCli } from "../lib/instance-lifecycle.mjs";
56
+ import { planStop, applyStop, planRetire, descendantsOf, resolveInstance as resolveInstanceForCli } from "../lib/instance-lifecycle.mjs";
57
57
  import { extraWorktreeLines, formatBytes, workRecoveryLines } from "../lib/retire-output.mjs";
58
58
  const await_import_lifecycle = () => ({ resolveInstance: resolveInstanceForCli });
59
59
  import { homeTarget, soulTarget, isWorkspaceContext, inspectDocument, withComposedInstructions, readinessDocument, policyOf, policySoul, manifestMissingRequires, INSPECT_OPERATIONS_API } from "../lib/instance-inspect.mjs";
@@ -61,7 +61,7 @@ import { readEvents, setWaiting, incarnationOf } from "../lib/instance-events.mj
61
61
 
62
62
  const rawArgs = process.argv.slice(2);
63
63
  /** The kernel's switches: a value never rides one (`--yolo=false` must not turn yolo on). */
64
- const KERNEL_SWITCHES = new Set(["allow-child-spawns", "apply", "check", "clear", "delete-branch", "discard-worktree", "dry-run", "ephemeral", "force", "help", "host", "install-oats", "instructions", "json", "keep-dir", "keep-env", "no-child-spawns", "no-launch", "no-recursive", "no-yolo", "plan", "policy", "preview", "print", "replace", "self", "verbose", "yes", "yolo"]);
64
+ const KERNEL_SWITCHES = new Set(["allow-child-spawns", "apply", "check", "clear", "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", "self", "verbose", "yes", "yolo"]);
65
65
  /** `--flag=value` is `--flag value`: every kernel reader (flag(), valueFlag(), the onboard and
66
66
  * routed-command loops) then applies the spaced form's validation to it. `problem` is an empty
67
67
  * `--flag=`, a switch given a value, or a value that is itself an option (`--model=--yolo`):
@@ -90,9 +90,14 @@ function expandInlineValues(argv) {
90
90
  const { argv: args, problem: argvProblem, inline: inlineValues } = expandInlineValues(rawArgs);
91
91
  let cmd = args[0];
92
92
  const HELP_WORDS = new Set(["help", "--help", "-h"]);
93
- const KERNEL_COMMANDS = new Set(["harness", "automations", "trigger", "capture", "capabilities", "doctor", "inspect", "instance", "operation", "package", "readiness", "souls", "soul", "teams", "launch-config", "experimental", "onboard", "pane", "recall", "retire", "root", "schedule", "server", "session", "setup", "spawn", "status", "sync", "update", "version", "workspace"]);
93
+ const KERNEL_COMMANDS = new Set(["harness", "automations", "trigger", "capture", "capabilities", "doctor", "inspect", "instance", "operation", "package", "readiness", "souls", "soul", "teams", "launch-config", "experimental", "onboard", "pane", "recall", "retire", "root", "schedule", "server", "session", "setup", "spawn", "status", "sync", "update", "version", "workspace", "worktree"]);
94
94
  /** Commands whose argv another parser reads (packages/record and packages/experimental parse process.argv). */
95
95
  const OWN_ARGV_COMMANDS = new Set(["capture", "recall", "setup", "experimental"]);
96
+ /** The kernel features this binary implements: `features` in `version --json` (the Desktop API v1
97
+ * probe) and in `status --json`, which a remote roster relays as the host's (feature
98
+ * server-probe-features, lib/servers.mjs hostFeatures). ONE list for both, emitted at output
99
+ * time, never stored. A name must pass hostFeatures's check (test/cli-json-contract.test.mjs). */
100
+ 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"];
96
101
  /** Commands `--server <id>` runs on a registered server. */
97
102
  const ROUTED_COMMANDS = new Set(["spawn", "retire", "status", "session", "okf", "schedule", "inspect", "operation", "launch-config", "readiness", "instance"]);
98
103
  const flag = (name) => {
@@ -218,7 +223,8 @@ async function doctorComposition(ctx, soulName, ws, bail) {
218
223
  const pv = await previewWorkspaceSoul(prepared, root);
219
224
  cleanups.push(pv.cleanup);
220
225
  const { text, blocks, resolved, oatsCoreDeclared } = await composeSoulInstructions({ deployment, prepared, soulDir: pv.soulDir });
221
- return { text, blocks, resolved, oatsCoreDeclared };
226
+ const { resolutionContractWarnings } = await import("../lib/instance-resolution.mjs");
227
+ return { text, blocks, resolved, oatsCoreDeclared, warnings: resolutionContractWarnings(prepared.resolution) };
222
228
  } catch (e) {
223
229
  if (e?.code?.startsWith?.("E_")) bail(e.code, e.message, e.details);
224
230
  throw e;
@@ -273,6 +279,84 @@ async function doctorOperator(ws) {
273
279
  return { problems: found.map(({ code, label, message, remedy }) => ({ code, ...(label ? { label } : {}), message, remedy })), information: [] };
274
280
  }
275
281
 
282
+ /** What the deployment's capabilities declare and this kernel ignores (an unknown hook event), for
283
+ * doctor without --soul, OFFLINE like doctorOperator, from this machine's parsed cache: each member's
284
+ * capabilities as `oats sync` enumerated them (the workspace's members confirmed by the cached
285
+ * membership; a standalone deployment's own repository), and every capability of every locked package.
286
+ * Each source is read on its own, so one the cache cannot answer leaves the others' warnings, and is
287
+ * said to be unchecked (information, `hook-events-unchecked`), never read as "no warning".
288
+ * → { warnings: [{ code, capability, path, message }], information } */
289
+ async function doctorHookWarnings(ws) {
290
+ const { cacheOnlyRemote } = await import("../lib/operator-coverage.mjs");
291
+ const { lockedPackageCapabilities } = await import("../lib/resolve.mjs");
292
+ const { capabilityContractWarnings, confirmMembership, observeWorkspace } = await import("../lib/workspace.mjs");
293
+ const { locatedContractWarnings } = await import("../lib/capability-contract.mjs");
294
+ const deployment = dirname(ws.local.path);
295
+ const local = ws.local.value;
296
+ const { bindRemote } = await import("../lib/packages.mjs");
297
+ const remoteOptions = remoteOptionsFromEnv();
298
+ // This machine's cache directory travels with every read (discovery binds it the same way).
299
+ const remote = bindRemote(cacheOnlyRemote(), remoteOptions);
300
+ const warnings = [], information = [];
301
+ const unchecked = (what, e) => information.push(`hook-events-unchecked: ${what} not checked for hook events this kernel does not run: ${e?.code === "E_REMOTE_UNREADABLE" ? `this machine's cache cannot answer (${e.message})` : `${e?.code ? `${e.code}: ` : ""}${e?.message ?? e}`}; oats sync, then run doctor again`);
302
+ // A member's capabilities as its enumeration at the observed commit lists them (lib/workspace.mjs enumerateRepo).
303
+ const memberCapabilities = async (ref) => {
304
+ const { commit } = await remote.observeRemote(ref);
305
+ // The cache-only remote never computes; the compute argument keeps bindRemote's options in place.
306
+ return (await remote.memoAtCommit(ref, commit, "enumerate", () => undefined)).capabilities || [];
307
+ };
308
+ const standalone = typeof local.standalone === "string" && local.standalone !== "" ? local.standalone : null;
309
+ if (standalone) {
310
+ try { warnings.push(...capabilityContractWarnings(await memberCapabilities(standalone))); }
311
+ catch (e) { unchecked(`member ${standalone}'s capabilities were`, e); }
312
+ } else {
313
+ let observed = null;
314
+ try { observed = await observeWorkspace(local.workspace, { remote }); }
315
+ catch (e) {
316
+ if (e?.code !== "E_WORKSPACE_SCHEMA" || e?.details?.notAHost !== true) unchecked("member capabilities were", e);
317
+ else {
318
+ // `workspace:` names a member (docs/workspaces.md), as discovery follows it: its host, from the
319
+ // member's cached oats-membership.yaml. Without the host (unreadable, or never read here), the
320
+ // member's own capabilities (discovery's standalone view), and the other members unchecked.
321
+ const member = local.workspace;
322
+ let backlink;
323
+ try { const { commit } = await remote.observeRemote(member); backlink = await remote.memoAtCommit(member, commit, "membership", () => undefined); }
324
+ catch (miss) { backlink = { miss }; }
325
+ if (backlink && !backlink.miss && backlink.kind !== "ok") unchecked("member capabilities were", e);
326
+ else {
327
+ try { if (backlink.miss) throw backlink.miss; observed = await observeWorkspace(backlink.value.workspace, { remote }); }
328
+ catch (host) {
329
+ try { warnings.push(...capabilityContractWarnings(await memberCapabilities(member))); }
330
+ catch (own) { unchecked(`member ${member}'s capabilities were`, own); }
331
+ unchecked("the workspace's other members' capabilities were", host);
332
+ }
333
+ }
334
+ }
335
+ }
336
+ for (const ref of observed?.workspace?.members || []) {
337
+ try {
338
+ const membership = await confirmMembership(observed, ref, { remote });
339
+ if (!membership.confirmed) {
340
+ // Not a member: discovery lists none of its capabilities. Not read: unchecked.
341
+ if (membership.reason === "cannot-read") unchecked(`member ${membership.key}'s capabilities were`, { code: "E_REMOTE_UNREADABLE", message: membership.detail });
342
+ continue;
343
+ }
344
+ warnings.push(...capabilityContractWarnings(await memberCapabilities(ref)));
345
+ } catch (e) { unchecked(`member ${ref}'s capabilities were`, e); }
346
+ }
347
+ }
348
+ let lock = null;
349
+ try { lock = readLockIfPresent(deployment); } catch { lock = null; } // an invalid lock is doctor's own problem, reported above
350
+ let catalog = null; try { catalog = officialPackageCatalog(); } catch { catalog = null; }
351
+ for (const [id, entry] of Object.entries(lock?.packages || {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
352
+ try {
353
+ const { capabilities } = await lockedPackageCapabilities(id, entry, { catalog, remote, remoteOptions });
354
+ for (const c of capabilities) warnings.push(...locatedContractWarnings(c.manifest, `package:${id}:${c.dir}/oats.json`));
355
+ } catch (e) { unchecked(`package ${id}'s capabilities were`, e); }
356
+ }
357
+ return { warnings, information };
358
+ }
359
+
276
360
  /** Workspace-model v2 doctor data, OFFLINE: the deployment declaration found
277
361
  * walking up from ctx (oats-local.yaml) and the lock v3 beside it. Doctor never
278
362
  * goes to the network for this view (only `--soul`, which resolves the soul like a
@@ -473,6 +557,7 @@ function printWorkspaceInspect(doc) {
473
557
  for (const l of LAYERS) console.log(` ${l} capability: ${doc.layers[l].id || "none"}`);
474
558
  for (const c of doc.capabilities) console.log(` ${c.id}@${c.version || "?"} ${c.from?.kind === "package" ? `package ${c.from.package}` : c.from?.kind === "member" ? `member ${c.from.repoKey}` : ""}${c.operations.length ? ` ops: ${c.operations.map((o) => `${o.name}${o.available ? "" : "(unavailable)"}`).join(", ")}` : ""}`);
475
559
  for (const p of doc.problems) console.log(` ! ${p.code}: ${p.message}`);
560
+ for (const w of doc.warnings) console.log(` warning ${w.code} ${w.message}`);
476
561
  const composed = doc.souls[0].composedInstructions;
477
562
  if (composed !== undefined) console.log(composed ? `\nComposed AGENTS.md (a spawn here, resolution ${composed.resolution ?? "?"}${composed.truncated ? ", truncated" : ""}):\n\n${composed.text}` : "\nComposed AGENTS.md: unavailable (see the problems above)");
478
563
  }
@@ -647,14 +732,17 @@ async function doctorWorkspaceJson(ctx, soulName, ws) {
647
732
  const localTeams = doctorLocalTeams(ws.local.value);
648
733
  const schedules = unresolvedScheduleAttempts(dirname(ws.local.path));
649
734
  const operator = await doctorOperator(ws);
735
+ // With --soul, the soul's composition; without, the deployment's capabilities (doctorHookWarnings).
736
+ const hookEvents = composition ? { warnings: composition.warnings, information: [] } : await doctorHookWarnings(ws);
650
737
  const problems = [...legacyLayoutProblems(agentsRoot), readableInstanceHomes(agentsRoot), ...localTeams.problems, ...schedules.problems, ...operator.problems].filter(Boolean);
651
738
  return {
652
739
  schemaVersion: 1, workspaceApi: 2, context: ctx,
653
740
  workspace: { file: ws.local.path, ref: ws.local.workspace },
654
741
  workspaceError: ws.localError, lockFile: ws.lockFile, packages: ws.packages, lockError: ws.lockError,
655
- information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information],
742
+ information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information],
656
743
  composedInstructions: composition?.text, instructionBlocks: composition?.blocks,
657
744
  ...(problems.length ? { problems } : {}),
745
+ warnings: hookEvents.warnings,
658
746
  };
659
747
  }
660
748
  /** Kernel/bridge version skew (published in lockstep from one tag). */
@@ -694,7 +782,9 @@ async function doctor(dir) {
694
782
  for (const p of schedules.problems) console.log(`\n! ${p.code}: ${p.message}`);
695
783
  const operator = await doctorOperator(ws);
696
784
  for (const p of operator.problems) console.log(`\n! ${p.code}: ${p.message}\n ${p.remedy}`);
697
- for (const line of [...localTeams.information, ...schedules.information, ...operator.information]) console.log(`\nINFO: ${line}`);
785
+ const hookEvents = composition ? { warnings: composition.warnings, information: [] } : await doctorHookWarnings(ws);
786
+ for (const w of hookEvents.warnings) console.log(`\nwarning ${w.code} ${w.message}`);
787
+ for (const line of [...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information]) console.log(`\nINFO: ${line}`);
698
788
  if (soulName) {
699
789
  const information = operationalKnowledgeNote(composition, soulName);
700
790
  if (information) console.log(`\nINFO: ${information}`);
@@ -1018,6 +1108,85 @@ function instanceWaitingCmd(sub, bail) {
1018
1108
  } catch (e) { return bail(e.code || "E_EVENTS_FAILED", e.message, e.candidates ? { candidates: e.candidates } : undefined); }
1019
1109
  }
1020
1110
 
1111
+ /** `oats worktree add|remove` (#796, feature worktree-event): an instance's extra trees,
1112
+ * `<home>/.work-<purpose>`, made from its home (lib/worktree.mjs). The home is
1113
+ * $OATS_INSTANCE_HOME (or $OATS_HOME), else the home enclosing the working directory.
1114
+ * `add` streams the worktree hooks' output to stderr; stdout holds only the answer
1115
+ * (one envelope with --json). An interrupt exits 128+signal after the rollback. */
1116
+ async function worktreeCmd() {
1117
+ const bail = (code, msg, details, exit) => (JSON_MODE ? jsonFail(code, msg, details, exit) : die(msg, exit));
1118
+ const sub = args[1];
1119
+ const usage = "usage: oats worktree add --purpose <p> --branch <b> --base <remote-branch> [--repo <member key|clone path>] [--preview] [--json] | oats worktree remove --purpose <p> [--json]";
1120
+ if (!["add", "remove"].includes(sub)) return bail("E_BAD_ARGS", usage);
1121
+ if (flag("server") !== undefined) return bail("E_BAD_ARGS", "oats worktree runs in an instance home on this machine; --server is not accepted");
1122
+ for (const f of ["dir", "home"]) if (args.includes(`--${f}`)) return bail("E_BAD_ARGS", `oats worktree has no --${f}: it acts on the instance home it runs in; ${usage}`);
1123
+ const value = (name) => { const v = flag(name); if (v === true) throw Object.assign(new Error(`--${name} needs a value`), { code: "E_BAD_ARGS" }); return v === undefined ? undefined : String(v); };
1124
+ const homeVariable = ["OATS_INSTANCE_HOME", "OATS_HOME"].find((name) => process.env[name]);
1125
+ const home = homeVariable ? process.env[homeVariable] : enclosingInstanceHome(logicalCwd());
1126
+ if (!home) return bail("E_BAD_ARGS", `oats worktree runs from an instance home: run it in the home (or below it), or with $OATS_INSTANCE_HOME set; ${usage}`);
1127
+ const W = await import("../lib/worktree.mjs");
1128
+ // A caller that closes its end of stdout or stderr (a tool shell killed, Desktop gone) has only
1129
+ // stopped reading: the add or remove goes on to its consistent end, and what it can no longer
1130
+ // print is dropped. Unhandled, that EPIPE would end this process mid-hook, with no rollback.
1131
+ const readerGone = (e) => { if (e?.code !== "EPIPE" && e?.code !== "ERR_STREAM_DESTROYED") throw e; };
1132
+ process.stdout.on("error", readerGone);
1133
+ process.stderr.on("error", readerGone);
1134
+ try {
1135
+ if (sub === "remove") {
1136
+ for (const f of ["branch", "base", "repo", "preview"]) if (args.includes(`--${f}`)) return bail("E_BAD_ARGS", `oats worktree remove takes only --purpose; ${usage}`);
1137
+ const r = await W.worktreeRemove(resolve(home), { purpose: value("purpose") });
1138
+ if (JSON_MODE) { jsonOk(r); return; }
1139
+ console.log(r.rolledBack
1140
+ ? `rolled back the interrupted add of ${r.path}; branch ${r.branch} ${r.branchKept ? `kept${r.branchKeptReason ? ` (${r.branchKeptReason})` : ""}` : "not left behind"}`
1141
+ : `removed ${r.path}; branch ${r.branch} kept`);
1142
+ for (const w of r.warnings || []) console.error(`oats: warning: ${w}`);
1143
+ return;
1144
+ }
1145
+ const r = await W.worktreeAdd(resolve(home), { purpose: value("purpose"), branch: value("branch"), base: value("base"), repo: value("repo"), preview: args.includes("--preview") });
1146
+ if (JSON_MODE) { jsonOk(r); return; }
1147
+ if (r.preview) {
1148
+ console.log(`preview ${r.path} from ${r.clone} (origin ${r.remote || "?"}): branch ${r.branch} at origin's ${r.base}${r.resume === "noop" ? " — already made: add is a no-op" : r.resume === "recover" ? " — an interrupted add is rolled back first" : ""}; nothing was fetched or written`);
1149
+ const hooks = r.resume === "noop" ? [] : r.hooks;
1150
+ console.log(hooks.length ? `worktree hooks: ${hooks.map((h) => `${h.capability}${h.required ? " (required)" : ""}`).join(", ")}` : "worktree hooks: none");
1151
+ return;
1152
+ }
1153
+ console.log(r.resumed ? `${r.path} is already made (branch ${r.branch} from ${r.base} @ ${String(r.baseOid).slice(0, 12)}); nothing was run` : `made ${r.path}: branch ${r.branch} from origin's ${r.base} @ ${String(r.baseOid).slice(0, 12)}${r.hooks.length ? `; worktree hooks: ${r.hooks.map((h) => `${h.capability} ${h.ok ? "ok" : "FAILED"}`).join(", ")}` : ""}`);
1154
+ for (const w of r.warnings || []) console.error(`oats: warning: ${w}`);
1155
+ } catch (e) {
1156
+ if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details, e.exitStatus);
1157
+ throw e;
1158
+ }
1159
+ }
1160
+
1161
+ /** realpath of `p`, or of its nearest existing ancestor with the rest re-appended:
1162
+ * how lib/instance-events.mjs names a removed home (realOrNearest). */
1163
+ function realOrNearestPath(p) {
1164
+ let d = resolve(p); const tail = [];
1165
+ while (!existsSync(d) && dirname(d) !== d) { tail.unshift(basename(d)); d = dirname(d); }
1166
+ try { return join(realpathSync(d), ...tail); } catch { return resolve(p); }
1167
+ }
1168
+ /** #642: the addresses of a RETIRED instance `name` under `root`, from the
1169
+ * workspace logs that outlive its home (<deployment>/.agents/events/
1170
+ * <agent>--<name>.jsonl), as `{ root, agent, home }` like resolveInstance's
1171
+ * candidates. Asked only when no live home resolves. A `home` (the --home
1172
+ * claim) counts only when it is <root>/<agent>/instances/<name> by real path
1173
+ * and that agent's log exists; the agent is then read from the path, never
1174
+ * from the log's file name, and the row carries the claim as `asked` while
1175
+ * `home` is the scope's spelling, from which the logs are found (an alias of
1176
+ * the agents root elsewhere would lead readEvents to another deployment). */
1177
+ function retiredInstanceAddresses(root, name, home) {
1178
+ const events = join(workspaceOf(root), ".agents", "events"), suffix = `--${name}.jsonl`;
1179
+ const logged = (agent) => { try { return lstatSync(join(events, `${agent}${suffix}`)).isFile(); } catch { return false; } };
1180
+ if (home !== undefined) {
1181
+ const h = resolve(home), agent = basename(dirname(dirname(h)));
1182
+ const ok = basename(h) === name && basename(dirname(h)) === "instances" && agent && realOrNearestPath(h) === realOrNearestPath(join(root, agent, "instances", name)) && logged(agent);
1183
+ return ok ? [{ root, agent, home: join(root, agent, "instances", name), asked: home }] : [];
1184
+ }
1185
+ let entries; try { entries = readdirSync(events, { withFileTypes: true }); } catch { return []; }
1186
+ return entries.filter((e) => e.isFile() && e.name.endsWith(suffix) && e.name.length > suffix.length).map((e) => e.name.slice(0, -suffix.length)).sort()
1187
+ .map((agent) => ({ root, agent, home: join(root, agent, "instances", name) }));
1188
+ }
1189
+
1021
1190
  /** `oats instance <git|diff> <instance>` — K1: read-only Git observation of one
1022
1191
  * instance's work tree. The instance is addressed qualified: an explicit
1023
1192
  * --home, or a name under the --dir scope (team roots included) that resolves
@@ -1039,8 +1208,21 @@ function instanceCmd() {
1039
1208
  const { resolveInstance } = await_import_lifecycle();
1040
1209
  // K7b: --home is an ADDRESS claim, checked like K1 — it must be a home of
1041
1210
  // exactly this name under the scope (E_HOME_MISMATCH otherwise).
1042
- const home = resolveInstance(dirFlag(), root, name, homeOpt ? { home: homeOpt } : {}).home;
1043
- const ev = readEvents(home, { ...(limit !== undefined ? { limit: Math.max(1, Math.min(2000, Number(limit) || 200)) } : {}), ...(since ? { since } : {}) });
1211
+ let home, asked;
1212
+ try { home = resolveInstance(dirFlag(), root, name, homeOpt ? { home: homeOpt } : {}).home; }
1213
+ catch (e) {
1214
+ // #642: no live home — a retired instance still answers from the
1215
+ // workspace log, which outlives its home (home source absent,
1216
+ // incarnation null). A live home never reaches this.
1217
+ const gone = homeOpt ? e.code === "E_HOME_MISMATCH" && !existsSync(homeOpt) : e.code === "E_SESSION_UNKNOWN";
1218
+ const candidates = gone ? retiredInstanceAddresses(root, name, homeOpt) : [];
1219
+ if (candidates.length > 1) return bail("E_AMBIGUOUS_INSTANCE", `retired instance ${JSON.stringify(name)} has ${candidates.length} workspace logs (one per agent); pass --home <abs>`, { candidates });
1220
+ if (!candidates.length) throw e;
1221
+ home = candidates[0].home;
1222
+ // The logs are found from the scope's spelling; the answer names the home as --home spelled it.
1223
+ asked = candidates[0].asked;
1224
+ }
1225
+ const ev = readEvents(home, { ...(limit !== undefined ? { limit: Math.max(1, Math.min(2000, Number(limit) || 200)) } : {}), ...(since ? { since } : {}), ...(asked !== undefined ? { asked } : {}) });
1044
1226
  if (JSON_MODE) { jsonOk(ev); return; }
1045
1227
  console.log(`${ev.instance}: ${ev.returned} of ${ev.count} event(s)${ev.truncated ? " (window truncated)" : ""}${ev.waitingOnYou ? ` — waiting on you since ${ev.waitingOnYou.since} (${ev.waitingOnYou.producer})` : ""}`);
1046
1228
  for (const e of ev.events) console.log(` ${e.at ?? "?"} ${e.kind.padEnd(20)} ${e.producer}${e.data ? ` ${JSON.stringify(e.data).slice(0, 120)}` : ""}`);
@@ -1140,6 +1322,7 @@ async function readinessCmd() {
1140
1322
  for (const i of check.items) console.log(` ${i.status.padEnd(14)} ${i.subject}${i.required ? "" : " (optional)"}${i.reason ? ` — ${i.reason}` : ""}${i.remedy ? ` → ${i.remedy}` : ""}`);
1141
1323
  }
1142
1324
  if (doc.policy) console.log(` policy: child spawns ${doc.policy.childSpawns.allowed ? "allowed" : "disabled"} (${doc.policy.childSpawns.origin.kind}${doc.policy.childSpawns.enforced ? ", enforced" : ""}); worktrees ${doc.policy.worktrees.allowed === null ? "unknown" : doc.policy.worktrees.allowed ? "allowed" : "not in this work mode"}`);
1325
+ for (const w of doc.warnings) console.log(` warning ${w.code} ${w.message}`);
1143
1326
  for (const n of doc.notes) console.log(` note: ${n}`);
1144
1327
  return;
1145
1328
  }
@@ -1775,26 +1958,55 @@ async function teamsContext(bail) {
1775
1958
  }
1776
1959
  const positional = (i) => (args[i] !== undefined && !args[i].startsWith("--") ? args[i] : undefined);
1777
1960
 
1778
- /** `oats teams [--json] | add <label> --team <id> [--description <d>] | remove <label> | default <label>` —
1779
- * this deployment's teams (team model 3). Config only: never a provider call. */
1961
+ /** The flags each `oats teams` form takes (value flags → true), beyond the global `--dir` and `--json`.
1962
+ * Anything else is refused, never ignored: a kernel that ignored `--if-absent` would set unconditionally. */
1963
+ const TEAMS_FLAGS = {
1964
+ "": { "--max-age": true },
1965
+ add: { "--team": true, "--description": true, "--no-default": false },
1966
+ remove: {},
1967
+ default: { "--if-absent": false, "--expect": true },
1968
+ };
1969
+ /** The first flag `oats teams <sub>` does not take, or undefined. A value flag's value is skipped as flag()
1970
+ * reads it (the next word unless it starts with `--`). */
1971
+ function teamsUnknownFlag(sub) {
1972
+ const takes = { "--dir": true, "--json": false, ...TEAMS_FLAGS[sub ?? ""] };
1973
+ for (let i = 1; i < args.length; i++) {
1974
+ const a = args[i];
1975
+ if (!a.startsWith("-")) continue;
1976
+ if (!Object.hasOwn(takes, a)) return a;
1977
+ if (takes[a] && args[i + 1] !== undefined && !args[i + 1].startsWith("--")) i++;
1978
+ }
1979
+ return undefined;
1980
+ }
1981
+
1982
+ /** `oats teams [--json] | add <label> --team <id> [--description <d>] [--no-default] | remove <label> |
1983
+ * default <label> [--if-absent | --expect <label>]` — this deployment's teams (team model 3). Config only:
1984
+ * never a provider call. */
1780
1985
  async function teamsCmd() {
1781
1986
  const bail = (code, msg, details) => (JSON_MODE ? jsonFail(code, msg, details) : die(msg));
1782
- const usage = "usage: oats teams [--json] | oats teams add <label> --team <id> [--description <d>] | oats teams remove <label> | oats teams default <label> [--dir <deployment>] [--json]";
1783
- const sub = positional(1);
1987
+ const usage = "usage: oats teams [--json] | oats teams add <label> --team <id> [--description <d>] [--no-default] | oats teams remove <label> | oats teams default <label> [--if-absent | --expect <label>] [--dir <deployment>] [--json]";
1988
+ // A single-dash word (`-x`) is a flag, never the subcommand: teamsUnknownFlag names it.
1989
+ const sub = positional(1)?.startsWith("-") ? undefined : positional(1);
1784
1990
  if (sub !== undefined && !["add", "remove", "default"].includes(sub)) bail("E_USAGE", usage);
1991
+ const unknown = teamsUnknownFlag(sub);
1992
+ if (unknown !== undefined) {
1993
+ const form = sub ? `oats teams ${sub}` : "oats teams";
1994
+ bail("E_USAGE", `${form} does not take ${unknown} (an option this kernel does not know may need a newer kernel; nothing was changed) — ${usage}`, { flag: unknown });
1995
+ }
1785
1996
  const label = sub ? positional(2) : undefined;
1786
1997
  if (sub && label === undefined) bail("E_BAD_ARGS", `oats teams ${sub} needs a team label — ${usage}`);
1787
1998
  const ctx = await teamsContext(bail);
1788
1999
  const V = await import("../lib/teams-verbs.mjs");
1789
2000
  let result = null;
1790
2001
  try {
1791
- if (sub === "add") result = V.teamsAdd(ctx, label, { team: valueFlag("team"), description: valueFlag("description") });
2002
+ if (sub === "add") result = V.teamsAdd(ctx, label, { team: valueFlag("team"), description: valueFlag("description"), noDefault: args.includes("--no-default") });
1792
2003
  else if (sub === "remove") result = V.teamsRemove(ctx, label);
1793
- else if (sub === "default") result = V.teamsDefault(ctx, label);
2004
+ else if (sub === "default") result = V.teamsDefault(ctx, label, { ifAbsent: args.includes("--if-absent"), expect: valueFlag("expect") });
1794
2005
  } catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return bail(e.code, e.message, e.details); throw e; }
1795
2006
  const doc = V.teamsDocument(result ? { ...ctx, local: result.local } : ctx);
1796
- if (JSON_MODE) { jsonOk(result ? { ...doc, changed: result.changed } : withObservation(doc)); return; }
1797
- if (result) console.log(result.changed ? `${sub === "add" ? `Declared team ${label}` : sub === "remove" ? `Removed team ${label}` : `The default team is now ${label}`} in ${shortPath(ctx.localPath)}` : "Nothing to change");
2007
+ if (JSON_MODE) { jsonOk(result ? { ...doc, changed: result.changed, ...(result.reused ? { reused: true } : {}) } : withObservation(doc)); return; }
2008
+ if (result?.reused) console.log(`Team ${label} is already declared with that id: nothing to change`);
2009
+ else if (result) console.log(result.changed ? `${sub === "add" ? `Declared team ${label}` : sub === "remove" ? `Removed team ${label}` : `The default team is now ${label}`} in ${shortPath(ctx.localPath)}` : "Nothing to change");
1798
2010
  console.log(`default ${doc.defaultTeam ? `${doc.defaultTeam.label} (${doc.defaultTeam.from})` : "(none)"}`);
1799
2011
  console.log(`local ${doc.localTeams === null ? "allowed (standalone)" : doc.localTeams ? "allowed (localTeams: true)" : "not allowed"}`);
1800
2012
  if (!doc.teams.length) console.log("teams (none: `oats aweb setup` creates them, or `oats teams add <label> --team <id>`)");
@@ -1925,6 +2137,8 @@ async function capabilityShowCmd(bail) {
1925
2137
  process.stdout.write(f.text.endsWith("\n") || f.text === "" ? f.text : `${f.text}\n`);
1926
2138
  if (f.truncated) console.log(`(${f.path}: truncated — ${formatBytes(f.bytes)}, the first ${formatBytes(S.TEXT_LIMIT)} shown)`);
1927
2139
  }
2140
+ // The file's text is stdout's alone: a warning goes to stderr.
2141
+ for (const w of doc.warnings) console.error(`warning ${w.code} ${w.message}`);
1928
2142
  return;
1929
2143
  }
1930
2144
  console.log(`${doc.name} — ${doc.kind === "member" ? `member ${doc.repoKey}` : `package ${doc.package} v${doc.version} (${doc.repoKey})`} @ ${short(doc.commit)}, ${doc.path}\n`);
@@ -1942,6 +2156,7 @@ async function capabilityShowCmd(bail) {
1942
2156
  }
1943
2157
  }
1944
2158
  for (const p of doc.problems) console.log(` problem: ${p.code}${p.path ? ` ${p.path}` : ""} — ${p.message}`);
2159
+ for (const w of doc.warnings) console.log(` warning ${w.code} ${w.message}`);
1945
2160
  console.log(`\n a file's text: oats capabilities show ${doc.name}${doc.kind === "package" ? ` --package ${doc.package}` : ""} --file <path>`);
1946
2161
  }
1947
2162
 
@@ -2201,7 +2416,9 @@ async function status() {
2201
2416
  }
2202
2417
  }
2203
2418
  const observation = maxAgeGiven === null ? {} : { observation: observationBlock() };
2204
- console.log(JSON.stringify({ root, agents: data, ...observation, ...(ws ? { workspace: { ...(ws.unreachable ? { reachable: false, ...ws.unreachable } : { reachable: true }), ...workspaceIdentity(ws.local, ws.discovery) } } : {}), ...(problems.length ? { problems } : {}), ...envelopeWarnings() }, null, 2)); return;
2419
+ // `features` (feature server-probe-features): this kernel's own list, as `version --json` answers
2420
+ // it, so a remote roster relays the host's without probing it. Never part of a reused observation.
2421
+ 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;
2205
2422
  }
2206
2423
  console.log(`oats status — agents root ${shortPath(root)}\n`);
2207
2424
  if (ws?.unreachable) console.log(` workspace: unreachable (${ws.unreachable.reason}) — drift unknown\n`);
@@ -2267,7 +2484,7 @@ function herdrSpawnFlag() {
2267
2484
  }
2268
2485
  async function spawnCmd() {
2269
2486
  // JSON mode: contract envelope, stable error codes, stderr-only progress.
2270
- const bail = (code, msg, details) => (JSON_MODE ? jsonFail(code, msg, details) : die(msg));
2487
+ const bail = (code, msg, details, exit) => (JSON_MODE ? jsonFail(code, msg, details, exit) : die(msg, exit));
2271
2488
  const note = (msg) => (JSON_MODE ? console.error(msg) : console.log(msg));
2272
2489
  const yolo = yoloFlag();
2273
2490
  { const herdr = herdrSpawnFlag(); if (herdr) { const e = herdrSettingRemoved(`${herdr} was given`); bail(e.code, e.message); } }
@@ -2495,6 +2712,8 @@ async function spawnCmd() {
2495
2712
  if (prepared) r.soulFetched = soulFetched;
2496
2713
  if (JSON_MODE) { jsonOk(withObservation(r)); return; }
2497
2714
  console.log(`preview ${r.agent} → ${r.instance} (${r.work}${r.branch ? `, branch ${r.branch} from ${r.base.ref}@${r.base.oid.slice(0, 12)}` : ""}) harness ${r.harness}${r.model ? ` model ${r.model}` : ` (${r.modelSource})`}${r.launchConfig ? ` via launch configuration ${r.launchConfig}${r.launchConfigDefault ? ` (this machine's ${r.harness} default)` : ""}` : ""}${r.yolo ? " YOLO" : ""}; nothing was created${soulFetched ? " (the soul source was fetched to a temporary copy, not kept)" : ""}`);
2715
+ 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");
2716
+ for (const w of r.warnings || []) console.log(` WARNING: ${w}`);
2498
2717
  return;
2499
2718
  }
2500
2719
  } catch (e) {
@@ -2512,6 +2731,12 @@ async function spawnCmd() {
2512
2731
  if (e?.code === "E_REQUIREMENT_INACTIVE") { bail(e.code, e.message, { soul: e.soul, capabilities: e.capabilities, context: e.context, remedy: e.remedy }); throw e; }
2513
2732
  if (e?.code === "E_CHILD_SPAWNS_DISABLED") { bail(e.code, e.message, { parent: e.parent, policy: e.policy }); throw e; }
2514
2733
  if (["E_BRANCH_EXISTS", "E_BASE_UNKNOWN"].includes(e?.code)) { bail(e.code, e.message); throw e; }
2734
+ // #796: interrupted while its worktree hooks ran: rolled back (the message says how far), 128+signal.
2735
+ if (e?.code === "E_INTERRUPTED") { bail(e.code, e.message, e.details, e.exitStatus); throw e; }
2736
+ // A required spawn or worktree hook that failed, or answered outside its environment contract, keeps
2737
+ // its typed code: the hooks' receipt (`details.hooks`, paths only) and `unconfirmed` when the rollback
2738
+ // could not confirm its effects. Never `home`: a consumer reads that as retained effects.
2739
+ if (e?.code === "E_REQUIRED_HOOK_FAILED" || e?.code === "E_HOOK_ENVIRONMENT_CONTRACT") { bail(e.code, e.message, { hooks: e.details?.hooks ?? [], ...(e.details?.unconfirmed === true ? { unconfirmed: true } : {}) }); throw e; }
2515
2740
  // The observed base could not be fetched into the clone: the clone, the repository and the commit travel along.
2516
2741
  if (e?.code === "E_REMOTE_UNREADABLE" && e.details?.commit) { bail(e.code, e.message, e.details); throw e; }
2517
2742
  // K6b: the confirmed decision drifted — the fresh decision travels with the refusal so a GUI re-previews.
@@ -2552,12 +2777,15 @@ async function spawnCmd() {
2552
2777
  ...(r.decision ? { decision: r.decision } : {}), ...(r.replayed !== undefined ? { replayed: r.replayed } : {}),
2553
2778
  ...(r.wake !== undefined ? { wake: r.wake } : {}), // {requested, saved|null, error}: saved:null = outcome not recorded
2554
2779
  launchConfig: r.launch?.launchConfig ?? null, launch: r.launch || null, // already redacted by the kernel
2780
+ // #796: the worktree hooks this spawn ran, with their logs; only when it ran any.
2781
+ ...(r.worktreeHooks ? { worktreeHooks: r.worktreeHooks } : {}),
2555
2782
  });
2556
2783
  return;
2557
2784
  }
2558
2785
  console.log(`Spawned ${r.instance} (${r.work}${r.branch ? `, branch ${r.branch}` : ""})${r.launched ? ` — tmux window "${r.tmux.window}"` : " — not launched"}`);
2559
2786
  console.log(` home: ${shortPath(r.home)}`);
2560
2787
  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})`);
2788
+ for (const h of r.worktreeHooks || []) console.log(` setup: ${h.capability} worktree hook ${h.ok ? "ok" : "FAILED"} (log: ${shortPath(h.log)})`);
2561
2789
  if (wakeSchedule) console.log(` wake: schedule ${wakeSchedule.id} (${wakeSchedule.cron} ${wakeSchedule.tz}), next ${wakeSchedule.nextRun || "disabled"}`);
2562
2790
  if (wakeScheduleError) console.error(` wake: NOT saved — ${wakeScheduleError.message} (the instance is created and launched; add the wake by hand with oats schedule add)`);
2563
2791
  if (!r.launched) console.log(` launch: oats session start --home ${shellQuote(r.home)}`);
@@ -2604,7 +2832,6 @@ function retireCmd() {
2604
2832
  if (isSelf && !args.includes("--self")) die(`"${name}" is the calling instance — self-retire is irreversible; if your task is complete and you were told to retire, re-run with --self (finish your memory files FIRST; your session dies ~8s after)`);
2605
2833
  if (!isSelf && args.includes("--self")) die(`--self given but "${name}" is not the calling instance`);
2606
2834
  const root = ensureRoot(dirFlag());
2607
- const retiringHome = homeFlag || findInstanceHome(root, name);
2608
2835
  // K3: a GUI-driven Remove carries the plan revision it showed and an
2609
2836
  // idempotency key. The revision is revalidated against a fresh plan
2610
2837
  // (E_PLAN_STALE with that plan attached — re-confirm, never act on the old
@@ -2612,39 +2839,47 @@ function retireCmd() {
2612
2839
  const planRev = flag("plan-revision"), idemKey = flag("idempotency-key");
2613
2840
  if (planRev === true || idemKey === true) die("--plan-revision and --idempotency-key need values");
2614
2841
  if ((planRev !== undefined) !== (idemKey !== undefined)) die("--plan-revision and --idempotency-key go together");
2615
- let replayPath = null, childrenStopped = null, plannedExtraWorktrees;
2842
+ // What the plan says about recorded children holds on every apply path: the
2843
+ // retirement stops them first and keeps them (retireInstance, once it has
2844
+ // resolved the home). A guarded apply acts on the children of the plan it
2845
+ // revalidated; a plain or --self retire computes them as the plan does, and
2846
+ // passes none when there are none.
2847
+ let replayPath = null, plannedExtraWorktrees, fresh, children;
2616
2848
  if (planRev !== undefined) {
2617
2849
  if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(idemKey)) die("--idempotency-key: 1-128 chars of [A-Za-z0-9._:-]");
2618
2850
  // Replay first: after a successful retire the home is gone, so the receipt
2619
2851
  // (beside the instances dir, keyed by the idempotency key) is the answer.
2620
2852
  const replay = (dir) => { const p = join(dir, `.oats-retire-receipt.${idemKey}.json`); if (!existsSync(p)) return false; try { const prior = JSON.parse(readFileSync(p, "utf8")); if (prior.retired !== name) return false; if (args.includes("--json")) jsonOk({ ...prior, replayed: true }); else console.log(`retire ${name}: replayed receipt for key ${idemKey}`); return true; } catch { return false; } };
2621
2853
  for (const a of listAgents(root)) if (replay(join(a._dir, "instances"))) return;
2622
- let fresh;
2623
2854
  try { fresh = planRetire(dirFlag(), root, name, { home: homeFlag }); } catch (e) { return args.includes("--json") ? jsonFail(e.code || "E_LIFECYCLE_FAILED", e.message, e.details) : die(e.message); }
2624
2855
  replayPath = join(dirname(fresh.home), `.oats-retire-receipt.${idemKey}.json`);
2625
2856
  // The extra trees the confirmed plan names, as it names them: the retire refuses as stale rather than
2626
2857
  // move or remove one that no longer reads that way when it gets to them.
2627
2858
  plannedExtraWorktrees = fresh.facts.extraWorktrees;
2628
2859
  if (fresh.planRevision !== planRev) return args.includes("--json") ? jsonFail("E_PLAN_STALE", `the retire plan changed since it was shown (${planRev} → ${fresh.planRevision}); review the fresh plan`, { plan: fresh }) : die(`the retire plan changed since it was shown; re-run oats retire ${name} --plan`);
2629
- // The plan promised: recorded children are STOPPED first (bounded, never
2630
- // escalated) and retained. A child still running after the grace refuses
2631
- // the retirement — nothing is retired, the receipt names the pid.
2632
- childrenStopped = [];
2633
- for (const kid of fresh.facts.children) {
2634
- try { const s = stopInstanceSession(kid.home, {}); childrenStopped.push({ instance: kid.instance, home: kid.home, ok: true, stopped: s.stopped, alreadyIdle: s.alreadyIdle }); }
2635
- catch (e) { childrenStopped.push({ instance: kid.instance, home: kid.home, ok: false, code: e.code || "E_SESSION_STOP_FAILED", message: e.message, stillRunning: e.receipt?.stillRunning ?? null }); }
2636
- }
2637
- const running = childrenStopped.filter((k) => !k.ok);
2638
- if (running.length) return args.includes("--json") ? jsonFail("E_CHILDREN_RUNNING", `${running.map((k) => k.instance).join(", ")} ${running.length === 1 ? "is" : "are"} still running after a bounded stop; nothing was retired and nothing was escalated`, { childrenStopped, plan: fresh }) : die(`children still running: ${running.map((k) => k.instance).join(", ")}; nothing retired`);
2860
+ children = fresh.facts.children;
2861
+ } else {
2862
+ const recorded = descendantsOf(root, name);
2863
+ if (recorded.length) children = recorded;
2639
2864
  }
2640
2865
  let r;
2641
- try { r = retireInstance(root, name, { home: homeFlag, self: isSelf, discardWorktree: args.includes("--discard-worktree"), keepDir: args.includes("--keep-dir"), force: args.includes("--force"), ...(plannedExtraWorktrees ? { plannedExtraWorktrees } : {}) }); }
2642
- catch (e) { if (!e?.code) throw e; return args.includes("--json") ? jsonFail(e.code, e.message, e.candidates ? { ...e.details, candidates: e.candidates } : e.details) : die(e.message); }
2643
- if (childrenStopped) r.childrenStopped = childrenStopped;
2866
+ try { r = retireInstance(root, name, { home: homeFlag, self: isSelf, discardWorktree: args.includes("--discard-worktree"), keepDir: args.includes("--keep-dir"), force: args.includes("--force"), ...(plannedExtraWorktrees ? { plannedExtraWorktrees } : {}), ...(children ? { children } : {}) }); }
2867
+ catch (e) {
2868
+ if (!e?.code) throw e;
2869
+ // A child still running (or whose stop could not be established) refused the retirement: the
2870
+ // guarded apply returns the plan it acted on, and the text names each child's reason.
2871
+ if (e.code === "E_CHILDREN_RUNNING") {
2872
+ const running = e.details.childrenStopped.filter((k) => !k.ok);
2873
+ return args.includes("--json") ? jsonFail(e.code, e.message, { ...e.details, ...(planRev !== undefined ? { plan: fresh } : {}) }) : die(`children still running: ${running.map((k) => `${k.instance} (${k.code})`).join(", ")}; nothing retired`);
2874
+ }
2875
+ return args.includes("--json") ? jsonFail(e.code, e.message, e.candidates ? { ...e.details, candidates: e.candidates } : e.details) : die(e.message);
2876
+ }
2644
2877
  if (replayPath) { r.planRevision = planRev; r.idempotencyKey = idemKey; r.replayed = false; try { writeFileAtomic(replayPath, JSON.stringify(r, null, 2)); } catch { /* receipt is evidence, not authority */ } }
2645
2878
  // A retired home's wake jobs are forgotten (definitions only; nothing is
2646
2879
  // stopped by this); a deferred self-retire keeps them until the home is gone.
2647
- if (retiringHome && r.removedDir !== false && !r.deferred) { try { const gone = removeWakeForHome(scheduleScopeOf(workspaceOf(root)), retiringHome); if (gone.length) r.wakeSchedulesRemoved = gone; } catch (e) { r.warnings = [...(r.warnings || []), `wake schedules not cleaned: ${e.message}`]; } }
2880
+ // The home is the one the retire selected (awebai/oats#693), as a path.
2881
+ const retiringHome = r[RETIRE_SELECTED_HOME];
2882
+ if (typeof retiringHome === "string" && r.removedDir !== false && !r.deferred) { try { const gone = removeWakeForHome(scheduleScopeOf(workspaceOf(root)), retiringHome); if (gone.length) r.wakeSchedulesRemoved = gone; } catch (e) { r.warnings = [...(r.warnings || []), `wake schedules not cleaned: ${e.message}`]; } }
2648
2883
  // Deferred self-retire: nothing has been inspected, run, or removed yet. The
2649
2884
  // caller's window dies first; a detached process then retires the instance
2650
2885
  // as an external operator and writes its outcome beside the home.
@@ -2677,6 +2912,9 @@ function retireCmd() {
2677
2912
  process.exit(1);
2678
2913
  }
2679
2914
  console.log(`Retired ${r.retired} (agent ${r.agent})${r.worktreeRemoved ? ", worktree removed" : ""}`);
2915
+ // An attached child the retire repointed to the retained worktree (#718), as its link now reads.
2916
+ const followsWorktree = (k) => { if (r.retention?.worktree !== "retained") return false; try { return readlinkSync(join(k.home, "work")) === r.retention.movedTo; } catch { return false; } };
2917
+ for (const k of r.childrenStopped || []) console.log(` child ${k.instance}: ${k.alreadyIdle ? "already idle" : "stopped"}${followsWorktree(k) ? `; its work now links to the retained worktree ${r.retention.movedTo}` : ""}`);
2680
2918
  // Preserving work and not saying so leaves the operator believing it is gone,
2681
2919
  // which is most of the harm of deleting it. Name the classes and the path.
2682
2920
  for (const line of workRecoveryLines(r)) console.log(line);
@@ -3414,7 +3652,7 @@ function versionCmd() {
3414
3652
  // Phase B: `instance-modules` and `spawn-provider-payload` are advertised only once spawn
3415
3653
  // runs on resolve/materialize (contract §6); a feature the binary does not implement is
3416
3654
  // never listed.
3417
- 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: ["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"], 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 }));
3655
+ 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 }));
3418
3656
  return;
3419
3657
  }
3420
3658
  console.log(`@awebai/oats ${OATS_VERSION} (desktop API v1)`);
@@ -3964,6 +4202,7 @@ else if (cmd === "update") {
3964
4202
  else if (cmd === "harness") harnessTrustCmd();
3965
4203
  else if (cmd === "readiness") await readinessCmd();
3966
4204
  else if (cmd === "instance") instanceCmd();
4205
+ else if (cmd === "worktree") await worktreeCmd();
3967
4206
  else if (cmd === "root") console.log(resolve(new URL("..", import.meta.url).pathname));
3968
4207
  else if (cmd === "sync") await syncCmd();
3969
4208
  else if (cmd === "package") await packageCmd();
@@ -4217,10 +4456,14 @@ Usage:
4217
4456
  [--max-age <s>] (souls have no private mode), with origin
4218
4457
  (member <key> @ <commit> | package <id> v<ver>) and its
4219
4458
  teams on this deployment
4220
- oats teams [--json] | add <label> --team <id> [--description <d>] | remove <label>
4221
- | default <label> [--dir <d>] this deployment's teams (shared + local), the
4459
+ oats teams [--json] | add <label> --team <id> [--description <d>] [--no-default] | remove <label>
4460
+ | default <label> [--if-absent | --expect <label>]
4461
+ [--dir <d>] this deployment's teams (shared + local), the
4222
4462
  [--max-age <s>] (the read form only) default, the workspace's souls:; add/remove/default
4223
- edit oats-local.yaml (only with localTeams: true)
4463
+ edit oats-local.yaml (only with localTeams: true);
4464
+ --no-default: the mapping only (an exact repeat is
4465
+ reuse); --if-absent / --expect: set the default only
4466
+ where there is none / it is <label>
4224
4467
  oats soul teams <soul>|'*' [--dir <d>] which teams a soul may join here, its default, and
4225
4468
  [--max-age <s>] [--json] why (the workspace's souls: and local teams)
4226
4469
  oats instance git <instance> [--home <abs>] [--dir <d>] [--json]
@@ -4246,6 +4489,15 @@ Usage:
4246
4489
  oats instance stop <instance> --apply --plan-revision <rev> --idempotency-key <key>
4247
4490
  quiesce (SIGTERM, bounded, never escalated),
4248
4491
  children first; home/work/launch retained
4492
+ oats worktree add --purpose <p> --branch <b> --base <remote-branch> from an instance home: make the
4493
+ [--repo <member key|clone path>] extra tree <home>/.work-<p> on a new branch at origin's
4494
+ [--preview] [--json] <base> (the clone's refs are not moved), then run the
4495
+ worktree hooks of the home's capabilities (they may take
4496
+ minutes; their output goes to stderr and .oats/logs/);
4497
+ again with the same arguments: a no-op; --preview:
4498
+ the clone, path, branch, base and hooks, nothing done
4499
+ oats worktree remove --purpose <p> [--json] git worktree remove of a tree made by add (a dirty
4500
+ tree is refused: E_WORKTREE_DIRTY); the branch is kept
4249
4501
  oats readiness (--soul <n> | --home <abs>) [--policy] [--json]
4250
4502
  readinessApi 2 for a soul or an instance home:
4251
4503
  installed | configured | member | providers, each