@awebai/oats 0.48.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 (41) hide show
  1. package/bin/oats.mjs +226 -14
  2. package/docs/capabilities.md +256 -8
  3. package/docs/capability-manifest.schema.json +18 -5
  4. package/docs/configuration.md +6 -0
  5. package/docs/desktop-cli-api.md +368 -31
  6. package/docs/desktop.md +72 -5
  7. package/docs/execution-targets.md +17 -2
  8. package/docs/implementation.md +62 -1
  9. package/docs/integrations.md +7 -5
  10. package/docs/knowledge.md +167 -197
  11. package/docs/official-catalog.md +2 -2
  12. package/docs/packages.md +8 -8
  13. package/docs/release-notes/v0.49.0.md +770 -0
  14. package/docs/schedules.md +62 -39
  15. package/docs/servers.md +7 -0
  16. package/docs/souls-and-instances.md +381 -53
  17. package/docs/workspaces.md +2 -2
  18. package/injects/work-checkout.md +17 -11
  19. package/injects/work-worktree.md +19 -13
  20. package/lib/capability-contract.mjs +100 -11
  21. package/lib/capability-show.mjs +5 -2
  22. package/lib/core.mjs +1109 -321
  23. package/lib/instance-events.mjs +6 -3
  24. package/lib/instance-git.mjs +11 -5
  25. package/lib/instance-inspect.mjs +14 -3
  26. package/lib/instance-lifecycle.mjs +106 -16
  27. package/lib/instance-resolution.mjs +15 -3
  28. package/lib/launch-prompt-policy.mjs +17 -3
  29. package/lib/packages.mjs +1 -0
  30. package/lib/real-path.mjs +27 -0
  31. package/lib/resolve.mjs +4 -4
  32. package/lib/retire-output.mjs +6 -1
  33. package/lib/schedule.mjs +1 -0
  34. package/lib/servers.mjs +32 -6
  35. package/lib/tree-copy.mjs +18 -7
  36. package/lib/triggers.mjs +201 -65
  37. package/lib/workspace.mjs +20 -5
  38. package/lib/worktree-hooks.mjs +392 -0
  39. package/lib/worktree.mjs +655 -0
  40. package/package-catalog.json +1 -1
  41. package/package.json +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, 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 {
@@ -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
  }
@@ -1954,6 +2137,8 @@ async function capabilityShowCmd(bail) {
1954
2137
  process.stdout.write(f.text.endsWith("\n") || f.text === "" ? f.text : `${f.text}\n`);
1955
2138
  if (f.truncated) console.log(`(${f.path}: truncated — ${formatBytes(f.bytes)}, the first ${formatBytes(S.TEXT_LIMIT)} shown)`);
1956
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}`);
1957
2142
  return;
1958
2143
  }
1959
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`);
@@ -1971,6 +2156,7 @@ async function capabilityShowCmd(bail) {
1971
2156
  }
1972
2157
  }
1973
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}`);
1974
2160
  console.log(`\n a file's text: oats capabilities show ${doc.name}${doc.kind === "package" ? ` --package ${doc.package}` : ""} --file <path>`);
1975
2161
  }
1976
2162
 
@@ -2230,7 +2416,9 @@ async function status() {
2230
2416
  }
2231
2417
  }
2232
2418
  const observation = maxAgeGiven === null ? {} : { observation: observationBlock() };
2233
- 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;
2234
2422
  }
2235
2423
  console.log(`oats status — agents root ${shortPath(root)}\n`);
2236
2424
  if (ws?.unreachable) console.log(` workspace: unreachable (${ws.unreachable.reason}) — drift unknown\n`);
@@ -2296,7 +2484,7 @@ function herdrSpawnFlag() {
2296
2484
  }
2297
2485
  async function spawnCmd() {
2298
2486
  // JSON mode: contract envelope, stable error codes, stderr-only progress.
2299
- 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));
2300
2488
  const note = (msg) => (JSON_MODE ? console.error(msg) : console.log(msg));
2301
2489
  const yolo = yoloFlag();
2302
2490
  { const herdr = herdrSpawnFlag(); if (herdr) { const e = herdrSettingRemoved(`${herdr} was given`); bail(e.code, e.message); } }
@@ -2524,6 +2712,8 @@ async function spawnCmd() {
2524
2712
  if (prepared) r.soulFetched = soulFetched;
2525
2713
  if (JSON_MODE) { jsonOk(withObservation(r)); return; }
2526
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}`);
2527
2717
  return;
2528
2718
  }
2529
2719
  } catch (e) {
@@ -2541,6 +2731,12 @@ async function spawnCmd() {
2541
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; }
2542
2732
  if (e?.code === "E_CHILD_SPAWNS_DISABLED") { bail(e.code, e.message, { parent: e.parent, policy: e.policy }); throw e; }
2543
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; }
2544
2740
  // The observed base could not be fetched into the clone: the clone, the repository and the commit travel along.
2545
2741
  if (e?.code === "E_REMOTE_UNREADABLE" && e.details?.commit) { bail(e.code, e.message, e.details); throw e; }
2546
2742
  // K6b: the confirmed decision drifted — the fresh decision travels with the refusal so a GUI re-previews.
@@ -2581,12 +2777,15 @@ async function spawnCmd() {
2581
2777
  ...(r.decision ? { decision: r.decision } : {}), ...(r.replayed !== undefined ? { replayed: r.replayed } : {}),
2582
2778
  ...(r.wake !== undefined ? { wake: r.wake } : {}), // {requested, saved|null, error}: saved:null = outcome not recorded
2583
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 } : {}),
2584
2782
  });
2585
2783
  return;
2586
2784
  }
2587
2785
  console.log(`Spawned ${r.instance} (${r.work}${r.branch ? `, branch ${r.branch}` : ""})${r.launched ? ` — tmux window "${r.tmux.window}"` : " — not launched"}`);
2588
2786
  console.log(` home: ${shortPath(r.home)}`);
2589
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)})`);
2590
2789
  if (wakeSchedule) console.log(` wake: schedule ${wakeSchedule.id} (${wakeSchedule.cron} ${wakeSchedule.tz}), next ${wakeSchedule.nextRun || "disabled"}`);
2591
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)`);
2592
2791
  if (!r.launched) console.log(` launch: oats session start --home ${shellQuote(r.home)}`);
@@ -2633,7 +2832,6 @@ function retireCmd() {
2633
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)`);
2634
2833
  if (!isSelf && args.includes("--self")) die(`--self given but "${name}" is not the calling instance`);
2635
2834
  const root = ensureRoot(dirFlag());
2636
- const retiringHome = homeFlag || findInstanceHome(root, name);
2637
2835
  // K3: a GUI-driven Remove carries the plan revision it showed and an
2638
2836
  // idempotency key. The revision is revalidated against a fresh plan
2639
2837
  // (E_PLAN_STALE with that plan attached — re-confirm, never act on the old
@@ -2679,7 +2877,9 @@ function retireCmd() {
2679
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 */ } }
2680
2878
  // A retired home's wake jobs are forgotten (definitions only; nothing is
2681
2879
  // stopped by this); a deferred self-retire keeps them until the home is gone.
2682
- 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}`]; } }
2683
2883
  // Deferred self-retire: nothing has been inspected, run, or removed yet. The
2684
2884
  // caller's window dies first; a detached process then retires the instance
2685
2885
  // as an external operator and writes its outcome beside the home.
@@ -2712,7 +2912,9 @@ function retireCmd() {
2712
2912
  process.exit(1);
2713
2913
  }
2714
2914
  console.log(`Retired ${r.retired} (agent ${r.agent})${r.worktreeRemoved ? ", worktree removed" : ""}`);
2715
- for (const k of r.childrenStopped || []) console.log(` child ${k.instance}: ${k.alreadyIdle ? "already idle" : "stopped"}`);
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}` : ""}`);
2716
2918
  // Preserving work and not saying so leaves the operator believing it is gone,
2717
2919
  // which is most of the harm of deleting it. Name the classes and the path.
2718
2920
  for (const line of workRecoveryLines(r)) console.log(line);
@@ -3450,7 +3652,7 @@ function versionCmd() {
3450
3652
  // Phase B: `instance-modules` and `spawn-provider-payload` are advertised only once spawn
3451
3653
  // runs on resolve/materialize (contract §6); a feature the binary does not implement is
3452
3654
  // never listed.
3453
- 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", "teams-conditional-default"], 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 }));
3454
3656
  return;
3455
3657
  }
3456
3658
  console.log(`@awebai/oats ${OATS_VERSION} (desktop API v1)`);
@@ -4000,6 +4202,7 @@ else if (cmd === "update") {
4000
4202
  else if (cmd === "harness") harnessTrustCmd();
4001
4203
  else if (cmd === "readiness") await readinessCmd();
4002
4204
  else if (cmd === "instance") instanceCmd();
4205
+ else if (cmd === "worktree") await worktreeCmd();
4003
4206
  else if (cmd === "root") console.log(resolve(new URL("..", import.meta.url).pathname));
4004
4207
  else if (cmd === "sync") await syncCmd();
4005
4208
  else if (cmd === "package") await packageCmd();
@@ -4286,6 +4489,15 @@ Usage:
4286
4489
  oats instance stop <instance> --apply --plan-revision <rev> --idempotency-key <key>
4287
4490
  quiesce (SIGTERM, bounded, never escalated),
4288
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
4289
4501
  oats readiness (--soul <n> | --home <abs>) [--policy] [--json]
4290
4502
  readinessApi 2 for a soul or an instance home:
4291
4503
  installed | configured | member | providers, each