@awebai/oats 0.69.14 → 0.69.15

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 (49) hide show
  1. package/bin/oats.mjs +79 -18
  2. package/docs/capabilities.md +54 -12
  3. package/docs/container.md +57 -12
  4. package/docs/desktop-cli-api.md +215 -19
  5. package/docs/execution-targets.md +15 -3
  6. package/docs/first-team.md +4 -3
  7. package/docs/implementation.md +18 -8
  8. package/docs/release-notes/v0.69.15.md +444 -0
  9. package/docs/schedules.md +133 -2
  10. package/docs/servers.md +60 -2
  11. package/docs/souls-and-instances.md +87 -7
  12. package/docs/upgrading.md +17 -5
  13. package/lib/claim.mjs +2 -3
  14. package/lib/command-flags.mjs +4 -2
  15. package/lib/core.mjs +215 -72
  16. package/lib/dir-lock.mjs +17 -0
  17. package/lib/errors.mjs +2 -1
  18. package/lib/host-run.mjs +218 -0
  19. package/lib/host-stop-child.mjs +21 -0
  20. package/lib/instance-git.mjs +32 -6
  21. package/lib/instance-lifecycle.mjs +4 -3
  22. package/lib/instance-listing.mjs +35 -6
  23. package/lib/kernel-features.mjs +4 -1
  24. package/lib/read-call.mjs +1 -1
  25. package/lib/remote.mjs +17 -14
  26. package/lib/schedule.mjs +237 -20
  27. package/lib/servers.mjs +83 -5
  28. package/lib/session-end.mjs +28 -8
  29. package/lib/session-resume.mjs +10 -18
  30. package/lib/session-seen.mjs +4 -64
  31. package/lib/status-words.mjs +11 -4
  32. package/lib/system-tools.mjs +1 -36
  33. package/lib/worktree-hooks.mjs +6 -175
  34. package/lib/worktree.mjs +19 -10
  35. package/package.json +4 -1
  36. package/packages/record/README.md +56 -21
  37. package/packages/record/docs/capture-service.md +8 -5
  38. package/packages/record/docs/turn-record-sot.md +9 -0
  39. package/packages/record/lib/capture-health.mjs +6 -4
  40. package/packages/record/lib/capture-lock.mjs +31 -27
  41. package/packages/record/lib/capture-retained-scratch.mjs +4 -3
  42. package/packages/record/lib/capture-scratch.mjs +2 -1
  43. package/packages/record/lib/derived-state.mjs +4 -2
  44. package/packages/record/lib/index-db.mjs +4 -2
  45. package/packages/record/lib/lock-holder.mjs +21 -0
  46. package/packages/record/lib/private-files.mjs +18 -0
  47. package/packages/record/lib/process-identity.mjs +310 -0
  48. package/packages/record/lib/store.mjs +31 -25
  49. package/skills/oats-getting-started/SKILL.md +1 -1
package/bin/oats.mjs CHANGED
@@ -78,11 +78,11 @@ const { attachArgv, checkRemote, connectServer, forgetSnapshot, getServer, inspe
78
78
  const { readSessionViewer } = await kernelImport("session-viewer", () => import("../lib/session-viewer.mjs"));
79
79
  const { tickTriggers } = await kernelImport("triggers", () => import("../lib/triggers.mjs"));
80
80
  const A = await kernelImport("automations", () => import("../lib/automations.mjs"));
81
- const { parseEnvelopeText, unresolvedScheduleAttempts, scheduleScopeOf, listSchedules, describe: describeSchedule, testSchedule, addSchedule, updateSchedule, updateScheduleDescription, setEnabled: setScheduleEnabled, removeSchedule, runNow: runScheduleNow, reconcile: reconcileSchedule, tickHost, tickWorkspace, scopeAutomations, scheduleKind, registerWorkspace, unregisterWorkspace, readRegistry, schedulerStatus, saveWakeForHome, removeWakeForHome, wakeFromFlags, withHostLock, scheduleError, SCHEDULE_API } = await kernelImport("schedule", () => import("../lib/schedule.mjs"));
81
+ const { parseEnvelopeText, SCHEDULE_SLOT_UNREADABLE, SCHEDULE_SLOT_ORPHANED, unresolvedScheduleAttempts, scheduleScopeOf, listSchedules, describe: describeSchedule, testSchedule, addSchedule, updateSchedule, updateScheduleDescription, setEnabled: setScheduleEnabled, removeSchedule, runNow: runScheduleNow, reconcile: reconcileSchedule, tickHost, tickWorkspace, scopeAutomations, scheduleKind, registerWorkspace, unregisterWorkspace, readRegistry, schedulerStatus, saveWakeForHome, removeWakeForHome, wakeFromFlags, withHostLock, scheduleError, SCHEDULE_API } = await kernelImport("schedule", () => import("../lib/schedule.mjs"));
82
82
  const { hostUnitFiles, hostUnitStatus, installHostUnit, uninstallHostUnit } = await kernelImport("schedule-host", () => import("../lib/schedule-host.mjs"));
83
83
  const { kernelNode, stableNode } = await kernelImport("stable-node", () => import("../lib/stable-node.mjs"));
84
84
  const { receiveAttachment, uploadAttachment, readStreamBounded, MAX_ATTACHMENT_BYTES } = await kernelImport("attachments", () => import("../lib/attachments.mjs"));
85
- const { observeInstanceGit, diffInstanceFile } = await kernelImport("instance-git", () => import("../lib/instance-git.mjs"));
85
+ const { observeInstanceGit, diffInstanceFile, NO_FILE_MONITOR } = await kernelImport("instance-git", () => import("../lib/instance-git.mjs"));
86
86
  const { planStop, applyStop, planRetire, retireDefaultsLine, stopClosingLine, descendantsOf, resolveInstance: resolveInstanceForCli, setInstanceColor, setInstanceBackground, setInstanceSameWork, STOP_WARNINGS } = await kernelImport("instance-lifecycle", () => import("../lib/instance-lifecycle.mjs"));
87
87
  const { extraWorktreeLines, formatBytes, warningLines, workRecoveryLines } = await kernelImport("retire-output", () => import("../lib/retire-output.mjs"));
88
88
  const { livenessWord, lostLine, statusWord, waitingLine } = await kernelImport("status-words", () => import("../lib/status-words.mjs"));
@@ -100,13 +100,13 @@ const { callSession, parseMaxAge, readBudget } = await kernelImport("read-call",
100
100
  const { cachedWorkspace, legacyLayoutProblems, statusAnswer, statusView } = await kernelImport("roster-read", () => import("../lib/roster-read.mjs"));
101
101
  const { memberLabel, memberRows, packageRows, standaloneCatalogVersion, standalonePackages, workspaceName, workspaceStatusAnswer, workspaceStatusView } = await kernelImport("workspace-read", () => import("../lib/workspace-read.mjs"));
102
102
  const { expandInlineValues, flagValue } = await kernelImport("argv", () => import("../lib/argv.mjs"));
103
- const { APPROVAL_REMOVED, NATIVE_RECORD_REFUSED, RESUME_LOCAL_ONLY, RETIRE_USAGE, SOUL_LAUNCH_USAGE, SPAWN_USAGE, SYNC_USAGE, TEAMS_USAGE, WORKTREE_USAGE, commandArgvProblem, commandFlags } = await kernelImport("command-flags", () => import("../lib/command-flags.mjs"));
103
+ const { APPROVAL_REMOVED, NATIVE_RECORD_REFUSED, HOST_RUN_USAGE, RESUME_LOCAL_ONLY, RETIRE_USAGE, SOUL_LAUNCH_USAGE, SPAWN_USAGE, SYNC_USAGE, TEAMS_USAGE, WORKTREE_USAGE, commandArgvProblem, commandFlags } = await kernelImport("command-flags", () => import("../lib/command-flags.mjs"));
104
104
 
105
105
  const rawArgs = process.argv.slice(2);
106
106
  const { argv: args, problem: argvProblem, inline: inlineValues } = expandInlineValues(rawArgs);
107
107
  let cmd = args[0];
108
108
  const HELP_WORDS = new Set(["help", "--help", "-h"]);
109
- const KERNEL_COMMANDS = new Set(["harness", "automations", "trigger", "capture", "capabilities", "deployments", "doctor", "inspect", "instance", "operation", "package", "readiness", "souls", "soul", "teams", "launch-config", "experimental", "onboard", "pane", "reader", "recall", "retire", "root", "schedule", "server", "session", "setup", "spawn", "status", "sync", "tui", "update", "version", "workspace", "worktree"]);
109
+ const KERNEL_COMMANDS = new Set(["harness", "automations", "trigger", "capture", "capabilities", "deployments", "doctor", "inspect", "instance", "operation", "package", "readiness", "souls", "soul", "teams", "launch-config", "experimental", "host", "onboard", "pane", "reader", "recall", "retire", "root", "schedule", "server", "session", "setup", "spawn", "status", "sync", "tui", "update", "version", "workspace", "worktree"]);
110
110
  /** Commands whose argv another parser reads (packages/record, packages/experimental and packages/tui parse process.argv). */
111
111
  const OWN_ARGV_COMMANDS = new Set(["capture", "recall", "setup", "experimental", "tui"]);
112
112
  /** Commands `--server <id>` runs on a registered server. */
@@ -944,7 +944,7 @@ async function doctor(dir) {
944
944
  for (const p of [...legacyLayoutProblems(agentsRoot), readableInstanceHomes(agentsRoot)].filter(Boolean)) console.log(`\n! ${p.code}: ${p.message}`);
945
945
  for (const p of localTeams.problems) console.log(`\n! ${p.code} (${p.condition}): ${p.message}`);
946
946
  const schedules = unresolvedScheduleAttempts(dirname(ws.local.path));
947
- for (const p of schedules.problems) console.log(`\n! ${p.code}: ${p.message}`);
947
+ for (const p of schedules.problems) console.log(`\n! ${p.code}: ${p.message}${[SCHEDULE_SLOT_UNREADABLE, SCHEDULE_SLOT_ORPHANED].includes(p.code) ? `\n ${p.remedy}` : ""}`);
948
948
  const operator = await doctorOperator(ws);
949
949
  for (const p of operator.problems) console.log(`\n! ${p.code}: ${p.message}\n ${p.remedy}`);
950
950
  const launchPreferences = await doctorLaunchPreferences(ws);
@@ -1312,6 +1312,19 @@ function instanceWaitingCmd(sub, bail) {
1312
1312
  } catch (e) { return bail(e.code || "E_EVENTS_FAILED", e.message, e.candidates ? { candidates: e.candidates } : undefined); }
1313
1313
  }
1314
1314
 
1315
+ /** A caller that closes its end of stdout or stderr (a tool shell killed, Desktop gone, an ssh
1316
+ * session that ended) has only stopped reading: the command goes on to its consistent end, what it
1317
+ * can no longer print is dropped, and its exit status is the one it would have had. Unhandled,
1318
+ * that EPIPE would end this process where it stands: a `worktree add` mid-hook, with no rollback; a
1319
+ * spawn, a retire, a start or a stop that has completed, as if it had failed. For the verbs that
1320
+ * change state: `worktree`, `spawn`, `retire`, `session start`, `session restart` and
1321
+ * `instance stop --apply`. */
1322
+ function outliveReader() {
1323
+ const readerGone = (e) => { if (e?.code !== "EPIPE" && e?.code !== "ERR_STREAM_DESTROYED") throw e; };
1324
+ process.stdout.on("error", readerGone);
1325
+ process.stderr.on("error", readerGone);
1326
+ }
1327
+
1315
1328
  /** `oats worktree add|remove` (#796, feature worktree-event): an instance's extra trees,
1316
1329
  * `<home>/.work-<purpose>`, made from its home (lib/worktree.mjs). The home is
1317
1330
  * $OATS_INSTANCE_HOME (or $OATS_HOME), else the home enclosing the working directory.
@@ -1327,12 +1340,7 @@ async function worktreeCmd() {
1327
1340
  const home = homeVariable ? process.env[homeVariable] : enclosingInstanceHome(logicalCwd());
1328
1341
  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}`);
1329
1342
  const W = await import("../lib/worktree.mjs");
1330
- // A caller that closes its end of stdout or stderr (a tool shell killed, Desktop gone) has only
1331
- // stopped reading: the add or remove goes on to its consistent end, and what it can no longer
1332
- // print is dropped. Unhandled, that EPIPE would end this process mid-hook, with no rollback.
1333
- const readerGone = (e) => { if (e?.code !== "EPIPE" && e?.code !== "ERR_STREAM_DESTROYED") throw e; };
1334
- process.stdout.on("error", readerGone);
1335
- process.stderr.on("error", readerGone);
1343
+ outliveReader();
1336
1344
  try {
1337
1345
  if (sub === "remove") {
1338
1346
  const r = await W.worktreeRemove(resolve(home), { purpose: value("purpose") });
@@ -1560,6 +1568,7 @@ async function instanceCmd() {
1560
1568
  }
1561
1569
  const rev = flag("plan-revision"), key = flag("idempotency-key"), grace = flag("grace-ms");
1562
1570
  if (rev === true || key === true || grace === true) return bail("E_BAD_ARGS", usage);
1571
+ outliveReader();
1563
1572
  const receipt = applyStop(dirFlag(), root, name, { home: homeOpt, recursive, planRevision: rev, idempotencyKey: key, ...(grace !== undefined ? { graceMs: Number(grace) } : {}) });
1564
1573
  // Not part of the receipt, whose shape is contract: on stderr in both modes.
1565
1574
  for (const w of receipt[STOP_WARNINGS] || []) console.error(`oats: warning: ${w}`);
@@ -2108,7 +2117,8 @@ function workspaceCheckoutFrom(dir) {
2108
2117
  let inCheckout = false;
2109
2118
  for (let d = current; ; d = dirname(d)) { if (existsSync(join(d, ".git"))) { inCheckout = true; break; } if (dirname(d) === d) break; }
2110
2119
  if (!inCheckout) return null;
2111
- const tracked = spawnSync("git", ["-C", current, "ls-files", "--error-unmatch", "--", "oats-workspace.yaml"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
2120
+ // Git reads the checkout's index for this: it does not run the file monitor the checkout's configuration names.
2121
+ const tracked = spawnSync("git", [...NO_FILE_MONITOR, "-C", current, "ls-files", "--error-unmatch", "--", "oats-workspace.yaml"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
2112
2122
  return tracked.status === 0 ? { file: candidate, root: current } : null;
2113
2123
  }
2114
2124
  const parent = dirname(current);
@@ -2673,6 +2683,8 @@ function printSpawnPreview(r, { server, soulFetched = false } = {}) {
2673
2683
  for (const w of r.warnings || []) console.log(` WARNING: ${terminalText(w)}`);
2674
2684
  }
2675
2685
  async function spawnCmd() {
2686
+ // The spawn does not need its caller to finish: see outliveReader.
2687
+ outliveReader();
2676
2688
  // JSON mode: contract envelope, stable error codes, stderr-only progress.
2677
2689
  const bail = (code, msg, details, exit) => (JSON_MODE ? jsonFail(code, msg, details, exit) : die(msg, exit));
2678
2690
  const note = (msg) => (JSON_MODE ? console.error(msg) : console.log(msg));
@@ -2802,7 +2814,13 @@ async function spawnCmd() {
2802
2814
  if (taskText === true) bail("E_BAD_ARGS", "--task needs a value (use --task-file for long tasks)");
2803
2815
  const taskFileFlag = flag("task-file");
2804
2816
  if (taskFileFlag === true) bail("E_BAD_ARGS", "--task-file needs a path");
2805
- if (taskFileFlag && !existsSync(taskFileFlag)) bail("E_BAD_ARGS", `--task-file not found: ${taskFileFlag}`);
2817
+ // `--task-file -` (feature spawn-task-stdin): the task's bytes arrive on stdin, which is how a
2818
+ // routed spawn sends them (lib/servers.mjs routeCommand), so that they are on no command line.
2819
+ let stdinTask;
2820
+ if (taskFileFlag === "-") {
2821
+ if (process.stdin.isTTY) bail("E_BAD_ARGS", "--task-file - reads the task from stdin");
2822
+ try { stdinTask = (await readStreamBounded(process.stdin, MAX_ATTACHMENT_BYTES)).toString("utf8"); } catch (e) { bail("E_BAD_ARGS", `--task-file -: the task could not be read from stdin (${e.message})`); }
2823
+ } else if (taskFileFlag && !existsSync(taskFileFlag)) bail("E_BAD_ARGS", `--task-file not found: ${taskFileFlag}`);
2806
2824
  // --trigger-event <file>: the event a trigger spawns this instance for (lib/triggers.mjs). It is
2807
2825
  // copied to <home>/.oats/trigger-event.json (OATS_TRIGGER_EVENT_FILE) and recorded as instance.json.trigger.
2808
2826
  let triggerEvent;
@@ -2877,7 +2895,7 @@ async function spawnCmd() {
2877
2895
  if (flag("base") === true) bail("E_BAD_ARGS", "--base needs a ref");
2878
2896
  { const spawnOpts = {
2879
2897
  prepared,
2880
- purpose: flag("purpose"), ...(nameFlag !== undefined ? { name: String(nameFlag) } : {}), task: taskText, taskFile: taskFileFlag, relation, relativeTo, relativeRoot,
2898
+ purpose: flag("purpose"), ...(nameFlag !== undefined ? { name: String(nameFlag) } : {}), task: taskText ?? stdinTask, taskFile: stdinTask === undefined ? taskFileFlag : undefined, relation, relativeTo, relativeRoot,
2881
2899
  ...(args.includes("--allow-child-spawns") ? { allowChildSpawns: true } : args.includes("--no-child-spawns") ? { allowChildSpawns: false } : {}),
2882
2900
  // Feature instance-same-work: the kernel binds it to the parent the new home records, or refuses.
2883
2901
  ...(args.includes("--same-work") ? { sameWork: true } : {}),
@@ -3009,6 +3027,7 @@ function retireCmd() {
3009
3027
  const isSelf = process.env.OATS_INSTANCE === name;
3010
3028
  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)`);
3011
3029
  if (!isSelf && args.includes("--self")) die(`--self given but "${name}" is not the calling instance`);
3030
+ outliveReader();
3012
3031
  const root = ensureRoot(dirFlag());
3013
3032
  // K3: a GUI-driven Remove carries the plan revision it showed and an
3014
3033
  // idempotency key. The revision is revalidated against a fresh plan
@@ -3201,6 +3220,8 @@ async function scheduleCmd() {
3201
3220
  const op = args[2];
3202
3221
  const os = flag("os");
3203
3222
  if (os !== undefined && !(op === "install" && args.includes("--print"))) throw scheduleError("E_BAD_ARGS", "--os is for oats schedule host install --print");
3223
+ const registerOnly = op === "install" && args.includes("--register-only");
3224
+ if (registerOnly && args.includes("--print")) throw scheduleError("E_BAD_ARGS", "--register-only records the scope and --print writes nothing: give one");
3204
3225
  if (op === "install" && args.includes("--print")) {
3205
3226
  // What install would write, rendered from this environment; nothing is written or loaded.
3206
3227
  if (os !== undefined && os !== "darwin" && os !== "linux") throw scheduleError("E_BAD_ARGS", "--os darwin|linux");
@@ -3222,14 +3243,17 @@ async function scheduleCmd() {
3222
3243
  };
3223
3244
  const caps = { maxConcurrent: cap("max-concurrent", "default"), triggersMaxConcurrent: cap("triggers-max-concurrent", "none") };
3224
3245
  registerWorkspace(ws(), caps);
3246
+ // --register-only: the scope is in the host registry and no unit is installed, for a host
3247
+ // whose ticker is `oats host run` (a container has neither launchd nor a systemd user manager).
3248
+ if (registerOnly) return out({ scheduler: schedulerStatus(ws(), io), warnings: [] });
3225
3249
  const { warnings } = installHostUnit();
3226
3250
  return out({ scheduler: schedulerStatus(ws(), io), warnings });
3227
3251
  }
3228
3252
  if (op === "uninstall") { unregisterWorkspace(ws()); if (!readRegistry().workspaces.length) uninstallHostUnit(); return out({ scheduler: schedulerStatus(ws(), io) }); }
3229
3253
  if (op === "status") return out({ scheduler: schedulerStatus(ws(), io) });
3230
- throw scheduleError("E_BAD_ARGS", "oats schedule host install [--print [--os darwin|linux]]|uninstall|status");
3254
+ throw scheduleError("E_BAD_ARGS", "oats schedule host install [--register-only | --print [--os darwin|linux]]|uninstall|status");
3231
3255
  }
3232
- default: throw scheduleError("E_BAD_ARGS", "usage: oats schedule list|show <id>|test <id>|add <id> --file <spec.json> [--description=<text>] [--workspace <member> --runs-on <host> --owner <host>/<login>]|update <id> (--file <spec.json> [--description=<text>] | --description=<text>)|enable <id>|disable <id>|run <id> [--force]|remove <id> [--force]|reconcile <id> [--clear]|tick [--dry-run] [--host]|host install [--max-concurrent <N|default>] [--triggers-max-concurrent <N|none>] | host install --print [--os darwin|linux]|uninstall|status [--dir <workspace>|--server <id>] [--json]");
3256
+ default: throw scheduleError("E_BAD_ARGS", "usage: oats schedule list|show <id>|test <id>|add <id> --file <spec.json> [--description=<text>] [--workspace <member> --runs-on <host> --owner <host>/<login>]|update <id> (--file <spec.json> [--description=<text>] | --description=<text>)|enable <id>|disable <id>|run <id> [--force]|remove <id> [--force]|reconcile <id> [--clear]|tick [--dry-run] [--host]|host install [--register-only] [--max-concurrent <N|default>] [--triggers-max-concurrent <N|none>] | host install --print [--os darwin|linux]|uninstall|status [--dir <workspace>|--server <id>] [--json]");
3233
3257
  }
3234
3258
  } catch (e) {
3235
3259
  // K8b: typed refusal details travel (identity mismatch: key/declared; a refused file: its integrity source).
@@ -3238,6 +3262,31 @@ async function scheduleCmd() {
3238
3262
  }
3239
3263
  }
3240
3264
 
3265
+ /** `oats host run` (lib/host-run.mjs): the resume sweep once, the schedule tick each minute and an
3266
+ * ordered stop of the agents when the host stops, in the foreground. Progress goes to stderr; the
3267
+ * one answer is written when the run ends. */
3268
+ async function hostCmd() {
3269
+ try {
3270
+ const bad = (message) => Object.assign(new Error(message), { code: "E_BAD_ARGS" });
3271
+ if (args[1] !== "run") throw bad(HOST_RUN_USAGE);
3272
+ const grace = flag("stop-grace");
3273
+ if (grace !== undefined && (grace === true || !/^\d+$/.test(String(grace)) || Number(grace) < 1 || Number(grace) > 300)) throw bad("--stop-grace needs a number of seconds (1..300) to wait for each harness after SIGTERM");
3274
+ const { hostRun, hostRunPlan, NO_SCOPE_SAID } = await import("../lib/host-run.mjs");
3275
+ if (args.includes("--plan")) {
3276
+ const plan = await hostRunPlan();
3277
+ if (JSON_MODE) return jsonOk(plan);
3278
+ for (const r of plan.refusals) console.log(`would refuse (${r.code}): ${terminalText(r.message)}`);
3279
+ for (const w of plan.warnings) console.log(`warning: ${terminalText(w)}`);
3280
+ console.log(plan.scopes.length ? `would tick ${plan.scopes.length} scope${plan.scopes.length === 1 ? "" : "s"} each minute: ${plan.scopes.join(", ")}` : NO_SCOPE_SAID);
3281
+ for (const r of plan.sweep.rows) console.log(` ${r.instance} would be ${r.outcome}${r.reason ? ` (${r.reason}${r.code ? `, ${r.code}` : ""})` : ""}${r.message ? `: ${terminalText(r.message)}` : ""}`);
3282
+ if (!plan.sweep.rows.length) console.log("the sweep would find nothing to resume");
3283
+ return;
3284
+ }
3285
+ const answer = await hostRun({ kernel: { execPath: process.execPath, bin: CLI_BIN }, ...(grace !== undefined ? { stopGraceMs: Number(grace) * 1000 } : {}) });
3286
+ if (JSON_MODE) jsonOk(answer);
3287
+ } catch (e) { lifecycleFail(e, "E_HOST_RUN_FAILED", e?.details); }
3288
+ }
3289
+
3241
3290
  /** `oats trigger …` (lib/triggers.mjs): event-driven spawns stored beside the schedules of the
3242
3291
  * deployment scope and evaluated by the same host tick. Every subcommand answers the envelope. */
3243
3292
  async function triggerCmd() {
@@ -3438,6 +3487,7 @@ async function sessionCmd() {
3438
3487
  if (args[1] === "inspect") result = inspectInstanceSession(home);
3439
3488
  else if (args[1] === "recompose") throw Object.assign(new Error('unknown command "session recompose" — removed by the workspace model v2; use a re-spawn: an instance never changes under itself'), { code: "E_UNKNOWN_COMMAND" });
3440
3489
  else if (args[1] === "start" || args[1] === "restart") {
3490
+ outliveReader();
3441
3491
  const bad = (msg) => { throw Object.assign(new Error(msg), { code: "E_BAD_ARGS" }); };
3442
3492
  const model = flag("model");
3443
3493
  if (model === true) bad("--model needs a model id; omit it to keep the recorded model");
@@ -4570,10 +4620,12 @@ async function serverRouteCmd() {
4570
4620
  const local = args.slice(1).filter((a, i, all) => a !== "--server" && all[i - 1] !== "--server");
4571
4621
  const problem = suggestNameProblem(local) ?? backgroundProblem(local);
4572
4622
  if (problem) bail("E_BAD_ARGS", problem);
4623
+ if (flag("task") === true) bail("E_BAD_ARGS", "--task needs a value (use --task-file for long tasks)");
4573
4624
  }
4574
4625
  // Everything after the command word travels, minus the routing flags; a
4575
- // local --task-file is read here and travels as --task text, since the
4576
- // remote cannot read this machine's files.
4626
+ // local --task-file is read here and handed on as --task text, since the
4627
+ // remote cannot read this machine's files. A spawn's task is then sent on
4628
+ // the remote command's stdin to a host that reads it there (routeCommand).
4577
4629
  const rest = [];
4578
4630
  for (let i = 1; i < args.length; i++) {
4579
4631
  const a = args[i];
@@ -4777,6 +4829,7 @@ else if (cmd === "version" || cmd === "--version" || cmd === "-v") versionCmd();
4777
4829
  else if (cmd === "reader") await readerCmd();
4778
4830
  else if (cmd === "session") await sessionCmd();
4779
4831
  else if (cmd === "schedule") await scheduleCmd();
4832
+ else if (cmd === "host") await hostCmd();
4780
4833
  else if (cmd === "trigger") await triggerCmd();
4781
4834
  else if (cmd === "automations") await automationsCmd();
4782
4835
  // What a spawn throws outside its kernel stage goes through the same door as the inner catch.
@@ -4937,6 +4990,8 @@ Usage:
4937
4990
  host install|uninstall|status explicit IANA tz; see docs/schedules.md); --server
4938
4991
  routes to that host's workspace
4939
4992
  install [--max-concurrent N|default] [--triggers-max-concurrent N|none]
4993
+ install --register-only records the scope and installs no timer, for a
4994
+ host whose ticker is oats host run
4940
4995
  oats schedule add|update <id> … --description=<text> a one-line summary (1-200 characters)
4941
4996
  oats schedule update <id> --description=<text> change only it (--description= clears it)
4942
4997
  oats trigger add (--file <json> | --from <package>:<template> [--set k=v]) | list | show | enable
@@ -4975,6 +5030,12 @@ Usage:
4975
5030
  oats session resume [--deployment <dir>] resume every lost session of this computer's
4976
5031
  [--plan] [--json] deployments (one sweep per machine; at most 3 resumes
4977
5032
  of a home per boot); --plan starts nothing
5033
+ oats host run [--stop-grace <s>] run the kernel in the foreground where no host timer
5034
+ [--plan] [--json] can (a container): the resume sweep once, the schedule
5035
+ tick each minute; on SIGTERM it stops ticking, then
5036
+ stops every running instance (SIGTERM, bounded wait,
5037
+ never escalated) so that the next start resumes it
5038
+ (docs/container.md); --plan starts nothing
4978
5039
  oats session restart --home <abs-home> stop the running harness (SIGTERM, bounded wait,
4979
5040
  [same flags] [--stop-grace <s>] never escalated) and start it again in place under
4980
5041
  the same lock; a stop that is not observed is
@@ -142,6 +142,14 @@ A self-contained package has an `oats.json`:
142
142
  Doctor without `--soul` reads every member and locked package capability
143
143
  from this machine's cache only. What the cache cannot answer is reported as
144
144
  unchecked (`hook-events-unchecked` in its information), never as no warning.
145
+ - **A retire hook must be safe to run when its spawn hook did not finish, and
146
+ when it has run before.** It runs after a spawn that was killed while the
147
+ spawn hook ran (below), which may have registered everything, something or
148
+ nothing, and then gets an empty `OATS_META`: the spawn hook never answered
149
+ its receipt. It runs again on every retry of an incomplete cleanup. It
150
+ reads what there is to undo from the home and from the service it
151
+ registered with, and answers `meta: { retired: false, reason:
152
+ "nothing-to-delete" }` when there is nothing: that is a complete cleanup.
145
153
  - A capability declaring a **required** spawn hook should declare a `retire` hook
146
154
  too. Without one, OATS has no way to undo what the spawn hook did and no way to
147
155
  know whether it did anything, so a failure quarantines the home rather than
@@ -169,7 +177,17 @@ A self-contained package has an `oats.json`:
169
177
  with `git branch <b>: could not verify whether it still exists (…)`. A retry that still cannot
170
178
  finish keeps the home again, names what is outstanding, and exits nonzero.
171
179
  - The **escape hatch is `oats retire <instance> --force`**, for a home OATS cannot
172
- identify at all: no `instance.json` and no **usable** cleanup descriptor. Usable
180
+ identify at all: no `instance.json` and no **usable** cleanup descriptor, or an
181
+ `instance.json` that does not say which retire hooks to run and no usable
182
+ descriptor beside it. Such a record names no repository (`repo`), which the
183
+ retire hooks are run for, and does not show (`capabilityRuntime`) that no
184
+ capability has a retire hook: the stub a spawn leaves when it is killed
185
+ before its record, where no marker was written before its hooks (a spawn by
186
+ a kernel before this rule, or a marker since removed). Retire refuses it
187
+ with `E_UNIDENTIFIED_INSTANCE_HOME` before anything is stopped, run or
188
+ removed: the spawn hooks may have registered an identity that only the
189
+ retire hooks would release. Clean up by hand what the capabilities
190
+ registered, then `--force` removes the home, running no hook. Usable
173
191
  means it satisfies the versioned cleanup contract the rollback writes, checked
174
192
  to the depth the retry consumes it: `version`, a context `repo`, a recognised
175
193
  `work` mode (plus a `branch` for `worktree` — an unknown mode would skip the
@@ -187,17 +205,34 @@ A self-contained package has an `oats.json`:
187
205
  success, and every Git step it records must be re-run and verified. A retry that resolves no
188
206
  capabilities — a hand-edited descriptor, or config drift since the spawn — is an
189
207
  incomplete cleanup, not a clean one, and the home stays.
190
- - **A spawn in progress** (0.49.0). A `work: worktree` spawn that fires
191
- [`worktree` hooks](#the-worktree-event) writes the same marker just before
192
- the first of them, so a parent killed while they run (SIGKILL included)
193
- leaves a home `oats retire` can clean up. Its `outstanding` holds the retire
194
- hooks of the capabilities whose spawn hooks ran, plus the Git steps
195
- `worktree` and `branch`. It adds an optional top-level `inProgress: { pid,
196
- processStart, startedAt, branch, baseOid, hookPgid?, hookStart? }`: the
197
- spawning process, identified by its pid and start time, the branch the spawn
198
- created and the commit it created it at, and the process group of the hook
199
- running. The spawn removes the marker once its final `instance.json` and
200
- baseline are written; a failure's compensation replaces it in one rename.
208
+ - **A spawn in progress** (0.49.0). A spawn writes the same marker before
209
+ the first hook whose effects a retire would have to undo, so a parent
210
+ killed from there on (SIGKILL, a container stop, a dropped connection)
211
+ leaves a home `oats retire` can clean up:
212
+ - before its first **spawn hook**, in every work mode, when a capability
213
+ with a spawn hook also has a retire hook. Until the spawn writes its
214
+ final `instance.json`, the home's record is a stub that names neither the
215
+ repository nor the capabilities, and the marker is the only record of
216
+ which retire hooks to run. Its `outstanding.hooks` holds the retire hooks
217
+ of every capability with a spawn hook; once the spawn hooks have
218
+ answered, the marker is written again with their receipt
219
+ (`cleanup.capabilityMeta`, a retire hook's `OATS_META`). Its `cleanup`
220
+ also holds the record's `workspace`, `teams` and `defaultTeam`, so the
221
+ retire hooks get the team and workspace environment a retire of a whole
222
+ home gives them;
223
+ - before its first [`worktree` hook](#the-worktree-event), for a `work:
224
+ worktree` spawn that fires them. Its `outstanding` holds the retire
225
+ hooks of the capabilities whose spawn hooks ran, plus the Git steps
226
+ `worktree` and `branch` (a `work: worktree` marker written before the
227
+ spawn hooks holds those Git steps too).
228
+
229
+ It adds an optional top-level `inProgress: { pid,
230
+ processStart, startedAt, branch?, baseOid?, hookPgid?, hookStart? }`: the
231
+ spawning process, identified by its pid and start time, the branch of the
232
+ work and, for a `work: worktree` spawn, the commit the spawn created it at,
233
+ and the process group of the worktree hook running. The spawn removes the marker
234
+ once its final `instance.json` is written, before it takes the final
235
+ baseline; a failure's compensation replaces it in one rename.
201
236
  Such a marker satisfies every rule above, so a reader that does not know
202
237
  `inProgress` reads it as a quarantine. While the spawning process is
203
238
  verifiably alive (its pid runs with the recorded start time):
@@ -868,6 +903,13 @@ Spawn order is by capability name; retirement reverses successful
868
903
  spawn order. Hooks run from the instance's own copy
869
904
  (`<home>/.oats/modules/<cap>/`).
870
905
 
906
+ A retire hook must be safe to run again, and safe to run beside itself. A
907
+ retire whose process is killed while one of its retire hooks runs leaves that
908
+ hook running. A later retire takes the home's claim over, does not run again
909
+ the hooks the claim records as finished
910
+ ([one retire at a time](desktop-cli-api.md#retire-hooks-in-claim)), and runs
911
+ the unfinished one again, possibly while the first run of it is still going.
912
+
871
913
  ### A declared name is the provider's
872
914
 
873
915
  A variable a capability declares in `environment` is the capability's to
package/docs/container.md CHANGED
@@ -61,10 +61,10 @@ version and regenerate this directory's lock with
61
61
  `npm install --package-lock-only --ignore-scripts`; review both files. Do not
62
62
  use `--install-oats` or `--install-aw` against a running container.
63
63
 
64
- The committed OATS 0.69.12 pin supports container/SSH checks and spawn
65
- preview. Live token delivery requires a new pin to a release that includes
66
- `env: { fromFile: ... }` and the operator's `oats harness token set` route.
67
- Until that image is built, the two-seat inference milestone remains unproven.
64
+ The committed OATS 0.69.14 pin supports `env: { fromFile: ... }` and the
65
+ operator's `oats harness token set` route. Provision the token through the
66
+ [harness credential route](servers.md#harness-credentials) and collect live
67
+ acceptance evidence before claiming the two-seat inference milestone.
68
68
 
69
69
  ## Mounts and UID
70
70
 
@@ -169,8 +169,7 @@ Preview runs no provider hook and does not validate a missing seat. Apply
169
169
  only after reviewing it and provisioning its seat; use the same arguments
170
170
  without `--preview`. Keep the team and controller keys outside the container.
171
171
 
172
- On an OATS release supporting file-backed launch environment, the launch
173
- configuration uses:
172
+ The pinned OATS release supports this file-backed launch configuration:
174
173
 
175
174
  ```yaml
176
175
  launch-configs:
@@ -187,9 +186,52 @@ Select it with `--launch-config team-claude`. The operator provisions only a
187
186
  by every agent in the same trust group; read-only mounting does not hide it
188
187
  or narrow its authority. Never share the mount across trust groups.
189
188
 
189
+ ## The kernel's periodic work
190
+
191
+ The image's entrypoint starts sshd and nothing else. A container has no
192
+ launchd and no systemd user manager, so in it nothing resumes the sessions
193
+ that were lost when it last stopped, nothing runs the schedule tick, and
194
+ nothing stops the agents in order when the runtime stops it: they are killed
195
+ with the container and read `lost`.
196
+
197
+ `oats host run`
198
+ ([desktop-cli-api.md](desktop-cli-api.md#the-host-run-oats-host-run)) is the
199
+ kernel command that does those three things in one foreground process. The
200
+ image's pinned OATS does not have it, and the image does not run it. An operator can run it by hand in a
201
+ container whose OATS has it, and the entrypoint of a derived image can end
202
+ in it. What such an entrypoint has to respect:
203
+
204
+ - **`oats host run` is the process the runtime's signal must reach and
205
+ wait for.** Under `tini -g` that is tini's direct child: start sshd in the
206
+ background, then `exec oats host run`. `tini -g` signals its child's
207
+ process group; the OATS tmux server and the harnesses under it are in
208
+ sessions of their own, outside that group, so they run until `oats host
209
+ run` stops them. Measured with tini 0.19.0 and tmux 3.3a.
210
+ - **The runtime's stop timeout must be longer than the stop.** On SIGTERM
211
+ `oats host run` waits for a tick that is running, lists the instances and
212
+ gives each harness `--stop-grace` seconds (default 20). Docker's default
213
+ stop timeout is 10 seconds.
214
+ - **It does not supervise sshd.** If sshd ends while it runs, the agents and
215
+ the tick go on and the operator's route is gone.
216
+ - **The tmux server a resume starts gets its environment**, its `PATH`
217
+ included.
218
+
219
+ It ticks the deployments the container's host schedule registry lists. To
220
+ register one where no timer can be installed:
221
+
222
+ ```sh
223
+ oats schedule host install --register-only --dir /state/deploy
224
+ ```
225
+
226
+ ([schedules.md](schedules.md#without-a-host-timer)). Plain `host install`
227
+ fails in a container after registering, since there is no systemd user
228
+ manager. Over the route (`--server team-agent`) the option is refused
229
+ (`E_REMOTE_INCOMPATIBLE`, nothing sent) unless the container's OATS
230
+ advertises `schedule-host-register-only`; the image's pin does not.
231
+
190
232
  ## Acceptance and evidence
191
233
 
192
- The host needs Docker and Node 22+. Export the same plain variables used for
234
+ The host needs Docker and Node 22.5+. Export the same plain variables used for
193
235
  Compose, then run:
194
236
 
195
237
  ```sh
@@ -200,9 +242,12 @@ container/agent/accept.sh "oats-agent-${TEAM}" --evidence live-lab \
200
242
  ```
201
243
 
202
244
  Choose the label matching the actual run. `local` accepts the builder's
203
- architecture; the other labels require amd64 and root:GID 0440 token / 0750
204
- login-directory metadata. Local fixtures use a dummy file, never a real
205
- login. Run the live Claude mode separately for each admitted instance home;
245
+ architecture; the other labels require amd64 and root:GID 0750
246
+ login-directory metadata, plus root:GID 0440 when a token is present.
247
+ If the token file is absent, its check reports `NOT RUN` and acceptance
248
+ continues; `claude -p` is skipped until the token exists. Do not create a
249
+ placeholder token. Local fixtures never use a real login.
250
+ Run the live Claude mode separately for each admitted instance home;
206
251
  the home is an evidence label and an `instance.json` existence check. The
207
252
  probe runs from a private temporary directory under `/tmp`, removed on
208
253
  success or failure, with `--setting-sources user`. It uses the container's
@@ -225,8 +270,8 @@ It checks the process's UID/GID/supplementary groups/capabilities/no-new-privile
225
270
  and non-root sshd's banner, scans `/` as container root (pruning `/proc`,
226
271
  `/sys`, `/dev` and the agent-scanned `/state`, `/tmp`, `/run`, `/work`),
227
272
  and scans those trees plus writable `/dev/shm` and `/dev/mqueue` as the agent
228
- for `.credentials.json`. It checks
229
- the token is readable and not writable, and proves a global npm install fails using an
273
+ for `.credentials.json`. When a token is present, it checks
274
+ that the token is readable and not writable. It proves a global npm install fails using an
230
275
  offline local package. Scan errors fail acceptance. The root inspection
231
276
  process receives no added capabilities. Token provenance still needs the
232
277
  operator's receipt: permissions and successful inference cannot distinguish