@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
@@ -37,7 +37,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync
37
37
  import { join, resolve } from "node:path";
38
38
  import { oatsError } from "./errors.mjs";
39
39
  import { deploymentState, readDeploymentsDocument } from "./deployments.mjs";
40
- import { acquireDirLock, dirLockHeld } from "./dir-lock.mjs";
40
+ import { acquireDirLock, dirLockHeld, stuckLockRemedy } from "./dir-lock.mjs";
41
41
  import { homeClaimHolder, listInstances, launchEnvRefs, missingLaunchEnvRefs, owedRetireSaid, resumeConversation } from "./core.mjs";
42
42
  import { checkStartEnv, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning } from "./start-env.mjs";
43
43
  import { FRESH_REASON, NOT_SWEPT, OUTCOME, RESUME_WAITING, ROW_REASON, SESSION_END } from "./session-resume-contract.mjs";
@@ -56,26 +56,13 @@ const notePath = () => join(resumeStateDir(), "note.json");
56
56
 
57
57
  const readJson = (path) => { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return undefined; } };
58
58
 
59
- /** What to do about a sweep's lock `path` that needs a person, by what was found (lib/dir-lock.mjs
60
- * `found`). A directory is the lock of a kernel that locked with one: nothing here tells whether
61
- * that kernel's sweep runs, so it is the operator who removes it. A record that cannot be read,
62
- * or whose holder cannot be told to run, is removed once a person has seen that no sweep runs. A
63
- * gone holder's record is removed without that. Where nothing is in the way (the lock was taken
64
- * again each time, or this process cannot read its own start) there is nothing to remove. */
65
- const STUCK_REMEDY = {
66
- directory: (path) => `once no earlier oats is running on this machine, remove the directory ${path} and run it again`,
67
- "cannot-take-over": (path) => `remove ${path} and run it again`,
68
- "held-again": () => "run it again",
69
- "own-start-unreadable": (path) => `run it again; nothing at ${path} is to be removed`,
70
- };
71
- const removeOnceNoSweepRuns = (path) => `if no oats session resume is running on this machine, remove ${path} and run it again`;
72
59
  /** A sweep's lock `path` that needs a person, found as lib/dir-lock.mjs says it (`why`, `found`) →
73
60
  * what is said of it and what to do. Exported for its test. */
74
61
  export function resumeLockStuck(path, why, found) {
75
62
  return {
76
63
  lock: path, found,
77
64
  said: `the session resume lock ${path} cannot be taken (${why})`,
78
- remedy: (STUCK_REMEDY[found] ?? removeOnceNoSweepRuns)(path),
65
+ remedy: stuckLockRemedy(path, found, "oats session resume"),
79
66
  };
80
67
  }
81
68
 
@@ -222,16 +209,21 @@ function startEnvironment(env) {
222
209
  for (const k of ["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "PI_AGENT_INSTANCE", "PI_AGENT_HOME"]) delete out[k];
223
210
  return out;
224
211
  }
225
- function runStart({ execPath, bin, env }, row) {
212
+ /** Run this kernel (`execPath` `bin`) with `argv` as a child process → its JSON answer: the last
213
+ * line of its stdout. A child that printed none is answered as a failure envelope, `code`, that
214
+ * says how `what` exited. The child gets `env` without an instance identity (startEnvironment).
215
+ * Never rejects. */
216
+ export function kernelAnswer({ execPath, bin, env }, argv, { cwd, code, what }) {
226
217
  return new Promise((done) => {
227
- execFile(execPath, [bin, "session", "start", "--resume", "--home", row.home, "--json"], { cwd: row.deployment, env: startEnvironment(env), encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => {
218
+ execFile(execPath, [bin, ...argv], { cwd, env: startEnvironment(env), encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => {
228
219
  let answer;
229
220
  try { answer = JSON.parse(String(stdout).trim().split("\n").pop()); } catch { answer = undefined; }
230
- if (!answer || typeof answer !== "object") answer = { ok: false, error: { code: "E_SESSION_START_FAILED", message: `the start exited${error?.code !== undefined ? ` with status ${error.code}` : ""}${error?.signal ? ` on ${error.signal}` : ""} without an answer` } };
221
+ if (!answer || typeof answer !== "object") answer = { ok: false, error: { code, message: `${what} exited${error?.code !== undefined ? ` with status ${error.code}` : ""}${error?.signal ? ` on ${error.signal}` : ""} without an answer` } };
231
222
  done(answer);
232
223
  });
233
224
  });
234
225
  }
226
+ const runStart = (kernel, row) => kernelAnswer(kernel, ["session", "start", "--resume", "--home", row.home, "--json"], { cwd: row.deployment, code: "E_SESSION_START_FAILED", what: "the start" });
235
227
  /** `fn` over `items`, at most `limit` at once; once `stop()` holds no item is taken any more, and the
236
228
  * answer waits for every one already taken. */
237
229
  async function inBatches(items, limit, fn, stop = () => false) {
@@ -17,12 +17,13 @@
17
17
  * rename wins whole).
18
18
  * - Whether a loss is resumed is one pure function, resumeEligible.
19
19
  * Dependency-free. */
20
- import { execFileSync } from "node:child_process";
21
20
  import { createHash, randomBytes } from "node:crypto";
22
- import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
21
+ import { mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
23
22
  import { homedir } from "node:os";
24
23
  import { dirname, join, resolve } from "node:path";
25
- import { systemTool } from "./system-tools.mjs";
24
+ import { thisBoot } from "../packages/record/lib/process-identity.mjs";
25
+
26
+ export { bootId, identityHolderState, namesIdentity, takenInAnotherBoot, thisBoot, validPid } from "../packages/record/lib/process-identity.mjs";
26
27
 
27
28
  /** A loss first seen this long ago or more is not resumed. */
28
29
  export const FIRST_SEEN_MAX_MS = 24 * 60 * 60_000;
@@ -35,67 +36,6 @@ const oatsHomeDir = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
35
36
  /** The kernel-private directory of the sweep's lock, its per-boot note and this record. */
36
37
  export const resumeStateDir = () => join(oatsHomeDir(), "session-resume");
37
38
 
38
- /** What says this process runs in a container: a file each runtime puts in its containers, or the
39
- * variable Kubernetes sets in every pod. Docker writes `/.dockerenv`, Podman `/run/.containerenv`. */
40
- const CONTAINER_FILES = ["/.dockerenv", "/run/.containerenv"];
41
- const inContainer = (exists, env) => CONTAINER_FILES.some((file) => exists(file)) || Boolean(env.KUBERNETES_SERVICE_HOST);
42
-
43
- /** When PID 1 started, as this process sees PID 1: field 22 of `/proc/1/stat`, in clock ticks after
44
- * the kernel's boot, as the digits the kernel printed; null when the file cannot be read or does
45
- * not hold it. The fields are counted after the last ")": the name (field 2) may hold spaces and
46
- * parentheses. */
47
- function initStart(read) {
48
- try {
49
- const stat = read("/proc/1/stat"), named = stat.lastIndexOf(")");
50
- const start = named < 0 ? undefined : stat.slice(named + 1).trim().split(/\s+/)[19];
51
- return typeof start === "string" && /^\d+$/.test(start) ? start : null;
52
- } catch { return null; }
53
- }
54
-
55
- /** macOS's boot time, from the system's sysctl (systemTool), never one the caller's PATH names: a
56
- * PATH without /usr/sbin, or with another sysctl first, must not change or lose the boot id. */
57
- function systemSysctl() {
58
- const tool = systemTool("sysctl");
59
- if (!tool.file) throw new Error(tool.reason);
60
- return execFileSync(tool.file, ["-n", "kern.boottime"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] });
61
- }
62
- /** This boot's identity, or null where the kernel cannot read one. A boot is what ends every
63
- * process the kernel may have recorded: the sessions, their terminal server, a sweep.
64
- * - macOS: the boot time (`sysctl -n kern.boottime`, its `sec`/`usec`).
65
- * - Linux: the kernel's boot id (`/proc/sys/kernel/random/boot_id`).
66
- * - Linux in a container (inContainer): `<boot id>:<PID 1's start>`. A container shares its
67
- * host's kernel and so its boot id, which outlives a stop and start of the container; its PID 1
68
- * does not. PID 1 starts once per run of the container and ends every process of the run when
69
- * it ends, so its start is the same for every process of one run and another in the next; the
70
- * boot id keeps a start apart from the same number of ticks after another kernel boot. When
71
- * PID 1's start cannot be read there, the boot id alone: the sweep then counts a home's starts
72
- * across the runs and applies the in-boot clause across them, so it starts less, never more.
73
- * PID 1's start is read only in a container. A process in a PID namespace of its own on a host (a
74
- * command a harness runs in a sandbox) reads that namespace's PID 1, which is not the machine's,
75
- * and it is on the host's boot all the same.
76
- * Each is read from the kernel without privileges and written nowhere. */
77
- export function bootId({ platform = process.platform, read = (p) => readFileSync(p, "utf8"), exists = existsSync, env = process.env, sysctl = systemSysctl } = {}) {
78
- try {
79
- if (platform === "linux") {
80
- const id = read("/proc/sys/kernel/random/boot_id").trim();
81
- if (!id) return null;
82
- const start = inContainer(exists, env) ? initStart(read) : null;
83
- return start === null ? id : `${id}:${start}`;
84
- }
85
- if (platform === "darwin") { const m = /sec = (\d+), usec = (\d+)/.exec(sysctl()); return m ? `${m[1]}.${m[2]}` : null; }
86
- } catch { /* unknown */ }
87
- return null;
88
- }
89
- let processBoot;
90
- /** bootId, read once per process: a process never outlives its boot. */
91
- export const thisBoot = () => (processBoot === undefined ? (processBoot = bootId()) : processBoot);
92
- /** Whether the lock record `holder` (the sweep's lock, a cache write lock: lib/remote.mjs) was taken
93
- * in another boot than `boot`: its holder is gone then, whatever its pid reads as. A boot ends
94
- * every process, and a pid and a start counted from the boot can both come again in the next (in a
95
- * container, a boot is one run: bootId). Without a boot id on either side the process alone is
96
- * judged. */
97
- export const takenInAnotherBoot = (boot) => (holder) => Boolean(boot) && typeof holder.bootId === "string" && holder.bootId !== "" && holder.bootId !== boot;
98
-
99
39
  const realOrResolved = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
100
40
  /** The key of `home` in a record: its real path, so a deployment reached through a symlink (an
101
41
  * explicit `--deployment` spelled so, a cwd under one) reads and writes the same entry. */
@@ -3,9 +3,10 @@
3
3
  * in, strings out: the row is a `status --json` instance row, this kernel's or a host's (the roster
4
4
  * relays its `sessionEnd`), read as it is. A host on a kernel before `sessionEnd` (feature
5
5
  * session-resume) sends none, and its rows read `idle` as before. The JSON is never changed here.
6
- * Dependency-free. */
6
+ * Rows in, strings out, but for one read: a local lost row's reason (lostLine). Dependency-free. */
7
7
  import { terminalText } from "./refused-text.mjs";
8
8
  import { shellWord } from "./shell-word.mjs";
9
+ import { HOST_STOP_REASON, lostReasonOf } from "./session-end.mjs";
9
10
  import { SESSION_END } from "./session-resume-contract.mjs";
10
11
 
11
12
  const isLost = (i) => i.running === false && i.sessionEnd === SESSION_END.LOST;
@@ -50,13 +51,19 @@ export function waitingLine(i, { now = Date.now(), timeZone } = {}) {
50
51
  return `! needs input (${claim.reason ?? "unknown"})${timing}${claim.message ? `: ${claim.message}` : ""}`;
51
52
  }
52
53
 
54
+ /** What a lost row says of why it was lost, by the reason its home records (lib/session-end.mjs). */
55
+ const LOST_REASON_SAID = Object.freeze({ [HOST_STOP_REASON]: "stopped with the host" });
56
+
53
57
  /** The one line under a LOST row that says how to bring it back, or null for any other row. Local:
54
- * the resume by hand, or the next sweep. `host` (a `--server` or roster row): both refuse `--server`
55
- * (E_BAD_ARGS), so the line says to run them on that host. */
58
+ * the resume by hand, or the next sweep, after why it was lost when its home records that (read
59
+ * here from the home: the row carries no reason). `host` (a `--server` or roster row): both refuse
60
+ * `--server` (E_BAD_ARGS), so the line says to run them on that host; its home is not read. */
56
61
  export function lostLine(i, { host } = {}) {
57
62
  if (i.retirePending || !isLost(i)) return null;
58
63
  const start = typeof i.home === "string" && i.home ? `oats session start --resume --home ${shellWord(i.home)}` : null;
59
64
  if (host !== undefined) return terminalText(`lost: on ${host}, run ${start ? `${start} there, or its next oats session resume` : "oats session resume there"}`);
65
+ const why = start ? LOST_REASON_SAID[lostReasonOf(i.home, i)] : undefined;
66
+ const lost = why ? `lost (${why})` : "lost";
60
67
  const sweep = "the next oats session resume (run when OATS Desktop or oats tui opens)";
61
- return terminalText(start ? `lost: ${start} brings it back; so does ${sweep} if it can vouch for the loss` : `lost: ${sweep} brings it back if it can vouch for the loss`);
68
+ return terminalText(start ? `${lost}: ${start} brings it back; so does ${sweep} if it can vouch for the loss` : `${lost}: ${sweep} brings it back if it can vouch for the loss`);
62
69
  }
@@ -1,39 +1,4 @@
1
1
  /** System tools: programs the kernel runs from the system's own directories, never from the
2
2
  * caller's PATH. A job, a shell or an instance may have changed PATH; what a system tool does
3
3
  * (read a process's start, start the OATS tmux server in its own scope) must not depend on it. */
4
- import { accessSync, constants, statSync } from "node:fs";
5
- import { isAbsolute, join } from "node:path";
6
-
7
- /** Where a system tool is looked for, in order. */
8
- export const SYSTEM_TOOL_DIRS = Object.freeze(["/usr/bin", "/bin", "/usr/sbin", "/sbin"]);
9
-
10
- /** The directories a system tool is looked for in → { dirs } | { reason }. SYSTEM_TOOL_DIRS, or for a
11
- * test only, OATS_TEST_SYSTEM_TOOL_DIRS: absolute directories separated by `:`. A seam with any other
12
- * value names no tool at all, never a PATH-like lookup. */
13
- export function systemToolDirs() {
14
- const seam = process.env.OATS_TEST_SYSTEM_TOOL_DIRS;
15
- if (seam === undefined) return { dirs: SYSTEM_TOOL_DIRS };
16
- const dirs = seam.split(":");
17
- if (dirs.some((dir) => !isAbsolute(dir))) return { reason: `OATS_TEST_SYSTEM_TOOL_DIRS is ${JSON.stringify(seam)}, not absolute directories` };
18
- return { dirs };
19
- }
20
-
21
- /** `name` in the system directories (`dirs`, else systemToolDirs) → { file } (the first regular
22
- * executable file, an absolute path) or { reason } (none, and where it looked). Nothing is run. */
23
- export function systemTool(name, { dirs } = {}) {
24
- if (typeof name !== "string" || !/^[A-Za-z0-9._+-]+$/.test(name) || name === "." || name === "..") return { reason: `${JSON.stringify(name)} is not a tool name` };
25
- if (dirs === undefined) {
26
- const where = systemToolDirs();
27
- if (where.reason) return { reason: where.reason };
28
- dirs = where.dirs;
29
- }
30
- for (const dir of dirs) {
31
- const file = join(dir, name);
32
- try {
33
- if (!statSync(file).isFile()) continue;
34
- accessSync(file, constants.X_OK);
35
- return { file };
36
- } catch { /* not here */ }
37
- }
38
- return { reason: `no executable ${name} in ${dirs.join(", ")}` };
39
- }
4
+ export { SYSTEM_TOOL_DIRS, systemTool, systemToolDirs } from "../packages/record/lib/process-identity.mjs";
@@ -15,11 +15,13 @@
15
15
  * `warning` is read, and `env` is a contract error (as at retire).
16
16
  * The timeout is fixed (WORKTREE_HOOK_TIMEOUT_MS). OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS
17
17
  * is a test seam, not a setting. */
18
- import { spawn as spawnProcess, execFileSync, spawnSync } from "node:child_process";
19
- import { closeSync, existsSync, fchmodSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync } from "node:fs";
20
- import { dirname, isAbsolute, join } from "node:path";
18
+ import { spawn as spawnProcess, execFileSync } from "node:child_process";
19
+ import { closeSync, fchmodSync, mkdirSync, openSync, realpathSync, writeSync } from "node:fs";
20
+ import { dirname, join } from "node:path";
21
21
  import { terminateGroup, watchGroup, TERM_GRACE_MS } from "./process-group.mjs";
22
- import { SYSTEM_TOOL_DIRS } from "./system-tools.mjs";
22
+ import { isStartToken, processLiveness, processStart, processStartToken } from "../packages/record/lib/process-identity.mjs";
23
+
24
+ export { PS_ENV, isStartToken, processLiveness, processStart, processStartToken, runPs } from "../packages/record/lib/process-identity.mjs";
23
25
 
24
26
  export const WORKTREE_HOOK_TIMEOUT_MS = 30 * 60 * 1000;
25
27
  /** The fixed timeout, or the test seam's value (a positive integer of milliseconds). */
@@ -34,183 +36,12 @@ const SIGNAL_NUMBERS = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 };
34
36
  /** The exit status of a process ended by `signal`: 128 + its number. */
35
37
  export const interruptExitStatus = (signal) => 128 + (SIGNAL_NUMBERS[signal] ?? 15);
36
38
 
37
- // ---------- process identity: a pid is verified by its start time ----------
38
-
39
- /** Where a start time is read: /proc when this host has procfs, else `ps`. The test seam
40
- * OATS_TEST_PROCESS_START_PS (not a setting; a launch configuration cannot set it) takes the `ps`
41
- * path on any host: `1` runs the system `ps`, an absolute path runs that file as `ps`, and any
42
- * other value reads no start at all (psProgram). */
43
- const readsProc = () => process.env.OATS_TEST_PROCESS_START_PS === undefined && existsSync("/proc/self/stat");
44
- /** `ps` runs with a fixed environment, nothing inherited (runPs). Its PATH is the system directories only (SYSTEM_TOOL_DIRS),
45
- * never the caller's: what `ps` reports is the identity a claim is held or taken over on, so the
46
- * caller's PATH must not choose the program, and a caller whose PATH holds no `ps` reads the same
47
- * start as any other. `lstart` is local time in the locale's format, and two readers with another
48
- * TZ or LANG would otherwise read one live process's start differently, and take it for another. */
49
- export const PS_ENV = Object.freeze({ PATH: SYSTEM_TOOL_DIRS.join(":"), LC_ALL: "C", TZ: "UTC" });
50
- /** The `ps` a start is read with → { file, name } | { reason }: the system one, or the file the
51
- * test seam names by absolute path, run directly (no shell). A seam that names neither is never a
52
- * fallback to /proc or to a `ps` found on PATH; nor is a named file that cannot be run (readStart). */
53
- function psProgram() {
54
- const seam = process.env.OATS_TEST_PROCESS_START_PS;
55
- if (seam === undefined || seam === "1") return { file: "ps", name: "ps" };
56
- if (isAbsolute(seam)) return { file: seam, name: `the ps OATS_TEST_PROCESS_START_PS names (${seam})` };
57
- return { reason: `OATS_TEST_PROCESS_START_PS is ${JSON.stringify(seam)}, neither 1 nor an absolute path` };
58
- }
59
-
60
- /** Whether `pid` exists, from the kernel itself: kill(pid, 0). ESRCH is gone; EPERM (another user's
61
- * process) and success are "exists"; anything else is unknown. Never from how procfs or `ps`
62
- * word an absence: macOS's `ps` answers a pid that does not exist with an error and exit 1, which
63
- * says nothing a failing `ps` does not also say. */
64
- function existence(pid) {
65
- try { process.kill(pid, 0); return { state: "exists" }; }
66
- catch (e) {
67
- if (e.code === "ESRCH") return { state: "gone" };
68
- if (e.code === "EPERM") return { state: "exists" };
69
- return { state: "unknown", reason: `kill(${pid}, 0) failed (${e.code || e.message})` };
70
- }
71
- }
72
-
73
- /** Run the system `ps` once: `ps -o <column>= … <selection>`, each column without its header.
74
- * → { out } — its stdout as it was written, when it exited 0 and answered something;
75
- * → { reason } — it could not be run, was ended, failed or answered nothing: one line saying which.
76
- * The one way the kernel calls `ps` (awebai/oats#870, #882): the program (psProgram), the fixed
77
- * environment (PS_ENV), the time it is given and how its answer is classified are decided here.
78
- * `selection` is the rest of its arguments (`["-p", "<pid>"]`, `["-ax"]`). The environment is
79
- * PS_ENV whoever calls: what `ps` answers under it is the same for every reader. `path`, when
80
- * given, is the PATH the program is found on, in place of PS_ENV's and of nothing else in it: an
81
- * explicit argument, never read from the caller's environment here. The start reader passes
82
- * none, so the caller's PATH never chooses the program an identity is read with (#878). */
83
- export function runPs(columns, selection, { path } = {}) {
84
- const ps = psProgram();
85
- if (ps.reason) return { reason: ps.reason };
86
- const argv = [...columns.flatMap((column) => ["-o", `${column}=`]), ...selection];
87
- const r = spawnSync(ps.file, argv, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: path === undefined ? PS_ENV : { ...PS_ENV, PATH: path }, timeout: 10_000, maxBuffer: 4 * 1024 * 1024 });
88
- if (r.error) return { reason: `${ps.name} could not be run (${r.error.code || r.error.message})` };
89
- const out = String(r.stdout ?? ""), err = String(r.stderr ?? "").trim();
90
- if (r.status === 0 && out.trim()) return { out };
91
- return { reason: `ps ${argv.join(" ")} answered ${r.status === null ? `signal ${r.signal}` : `exit ${r.status}`}${err ? `: ${err.split("\n")[0]}` : out.trim() ? " with output" : " with no output"}` };
92
- }
93
-
94
- /** The start of a pid that exists, and whether it is a zombie (it exited, or was killed, and its
95
- * parent has not reaped it): one read gives both.
96
- * Linux: /proc/<pid>/stat, field 22 (clock ticks since boot) and field 3 (its state: `Z`, or `X`,
97
- * a process being removed). Elsewhere `ps -o lstart= -o stat=` (runPs): the start, then a state
98
- * that begins with `Z` (procps `Z`, macOS `Z` and `Z+`).
99
- * → { state: "alive", token, zombie? } | { state: "unknown", reason }. `zombie` is set only when
100
- * it is true. A state that cannot be read makes no zombie, and the start is what it was before
101
- * there was a second column: whatever `ps` prints as a state (`?` included) is only ever cut off
102
- * the start, and a `ps` that answers the start alone gives the start.
103
- * The token is what released kernels recorded, byte for byte (`proc:<ticks>`, `ps:<lstart>`): a
104
- * claim, a tree record or a marker written by an older kernel names its live holder by it, and a
105
- * reader that gave that holder another token would take it for a reused pid, which is gone. */
106
- function readStart(pid) {
107
- if (readsProc()) {
108
- let stat;
109
- try { stat = readFileSync(`/proc/${pid}/stat`, "utf8"); }
110
- catch (e) { return { state: "unknown", reason: `/proc/${pid}/stat could not be read (${e.code || e.message})` }; }
111
- // comm (field 2) is in parentheses and may hold spaces or parentheses itself.
112
- const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
113
- const start = fields[19]; // field 22 overall: after pid, comm and the 19 before it
114
- if (!/^[0-9]+$/.test(start ?? "")) return { state: "unknown", reason: `/proc/${pid}/stat has no start time` };
115
- return { state: "alive", token: `proc:${start}`, ...(fields[0] === "Z" || fields[0] === "X" ? { zombie: true } : {}) };
116
- }
117
- const r = runPs(["lstart", "stat"], ["-p", String(pid)]);
118
- if (r.reason) return { state: "unknown", reason: r.reason };
119
- // `Thu Jan 1 00:00:00 2026 Ss`: the state is the last field, one word whatever it says, and the
120
- // start before it is taken whole, as `ps -o lstart=` alone prints it. A start ends with its year,
121
- // so a last field of digits only is the start's own: that `ps` answered no state.
122
- const out = r.out.trim();
123
- const column = /^(.*\S)\s+(\S+)$/s.exec(out);
124
- if (!column || /^[0-9]+$/.test(column[2])) return { state: "alive", token: `ps:${out}` };
125
- return { state: "alive", token: `ps:${column[1]}`, ...(column[2].startsWith("Z") ? { zombie: true } : {}) };
126
- }
127
-
128
- /** Whether `token` has a shape readStart writes: `proc:` and a count of clock ticks (64 bits: at
129
- * most 20 digits), or `ps:` and a start as `ps -o lstart=` prints it under PS_ENV
130
- * (`Thu Jan 1 00:00:00 2026`). The shape is said here, beside its writer, and nowhere else.
131
- * It decides only what of a record may be SHOWN: a record is a file that others than its writer
132
- * can write, and text that is not the kernel's enters an answer only as an id or a code. It is
133
- * never a liveness decision: processLiveness compares the recorded string as it is, and a real
134
- * token this does not know (a `ps` that prints a start otherwise) is shown as none, never read
135
- * as gone. */
136
- const START_TOKEN = /^(?:proc:[0-9]{1,20}|ps:[A-Z][a-z]{2} [A-Z][a-z]{2} [ 0-9][0-9] [0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{4})$/;
137
- export const isStartToken = (token) => typeof token === "string" && START_TOKEN.test(token);
138
-
139
- /** When `pid` started, read three ways apart (lessons/observation-must-not-harm-the-observer.md:
140
- * "absent" never collapses with "unreadable"). One rule on every host: whether the pid exists is
141
- * the kernel's answer (existence), and only a pid that exists has its start read.
142
- * → { state: "alive", token, zombie? } — an opaque token for its start; two processes that held
143
- * one pid at different times never share it, so a pid is only ever compared WITH its token;
144
- * → { state: "gone" } — kill(pid, 0) answers ESRCH, before the read or (it exited in between)
145
- * after a read that failed;
146
- * → { state: "unknown", reason } — anything else: the pid exists and its start could not be read,
147
- * or kill(pid, 0) failed otherwise. Every caller fails safe on it.
148
- *
149
- * This answers WHOSE the pid is, and a zombie still holds its pid and its start: it is "alive"
150
- * here, with `zombie: true` as a fact beside it. That is what a recorded process group needs
151
- * (terminateRecordedGroup): while its leader is a zombie the group's id cannot be reused, so a
152
- * zombie leader with the recorded start is the best proof there is that the group is still that
153
- * run's, and its members are ended. Whether a process can still ACT is another question, and
154
- * processLiveness answers it (awebai/oats#870). */
155
- export function processStart(pid) {
156
- if (!Number.isSafeInteger(pid) || pid <= 0) return { state: "gone" };
157
- const before = existence(pid);
158
- if (before.state !== "exists") return before;
159
- const read = readStart(pid);
160
- if (read.state === "alive") return read;
161
- return existence(pid).state === "gone" ? { state: "gone" } : read;
162
- }
163
-
164
- /** The token of `processStart(pid)` when it is running, else null: for recording a process. A
165
- * liveness decision never uses this, since null merges "gone" with "unknown" (processLiveness). */
166
- export function processStartToken(pid) {
167
- const s = processStart(pid);
168
- return s.state === "alive" ? s.token : null;
169
- }
170
-
171
39
  /** This process, as a record names it: { pid, processStart } (null when its start cannot be read;
172
40
  * the callers that need it refuse then). */
173
41
  export function selfIdentity() {
174
42
  return { pid: process.pid, processStart: processStartToken(process.pid) };
175
43
  }
176
44
 
177
- /** Whether the COMMAND a record names (`{ pid, processStart }`) can still act:
178
- * → { state: "alive" } — its pid runs with the recorded start;
179
- * → { state: "gone", zombie? } — its pid does not run, or runs with another start (a reused pid),
180
- * or is a zombie (`zombie: true`): it exited or was killed and its parent has not reaped it;
181
- * → { state: "unknown", reason } — the start could not be read, or the record has none to
182
- * compare while its pid runs. Every caller fails safe on it: nothing is taken over, rolled back,
183
- * retired or signalled, and the refusal names the way out.
184
- *
185
- * A zombie is gone here (awebai/oats#870), though processStart still reads its pid and start. It
186
- * will never run again, and a parent that never waits for it would otherwise keep its claim or
187
- * marker refused for ever, with the advice to wait for it. Taking over from it is as safe as from
188
- * a holder that was killed and reaped: a process's children are re-parented when it exits, not
189
- * when it is reaped, so what a zombie leaves behind is exactly what that holder leaves: the steps
190
- * it recorded, which each takeover ends (lib/claim.mjs `endHolderStep`; the hook group of a tree
191
- * record or a spawn's marker), and for a retire its hook children (awebai/oats#865). The zombie
192
- * adds nothing to that; it only delays the takeover until a reap that may never come.
193
- * It is decided before the start is compared: a pid that is a zombie now is not a running
194
- * holder whichever start the record names (it is that holder, or the pid was reused), and so
195
- * neither when the record names none.
196
- *
197
- * WHOM THIS MAY BE ASKED ABOUT: the process of an `oats` command itself, which is what every
198
- * record read with it names (a claim's holder, the adder of a tree record, a spawn's `inProgress`,
199
- * a self-retire's completion). That is what makes "a zombie cannot act" true. On Linux a process
200
- * whose main thread has exited while other threads run also reads `Z` in /proc/<pid>/stat, and
201
- * it still acts; Node exits as a whole, so it does not arise for those records. Never ask this
202
- * about a hook's or a harness's pid: for a process that is not the kernel's own, a `Z` does not
203
- * say it is finished. (A recorded group's leader is asked through processStart, not through this.) */
204
- export function processLiveness(record) {
205
- const pid = record?.pid;
206
- if (!Number.isSafeInteger(pid) || pid <= 0) return { state: "gone" };
207
- const s = processStart(pid);
208
- if (s.state !== "alive") return s;
209
- if (s.zombie) return { state: "gone", zombie: true };
210
- if (typeof record.processStart !== "string" || !record.processStart) return { state: "unknown", reason: `pid ${pid} runs, and the record names no start time to compare it with` };
211
- return s.token === record.processStart ? { state: "alive" } : { state: "gone" };
212
- }
213
-
214
45
  /** Whether a record's process is verifiably the one still running (processLiveness "alive"). */
215
46
  export const verifiedAlive = (record) => processLiveness(record).state === "alive";
216
47
 
package/lib/worktree.mjs CHANGED
@@ -33,7 +33,7 @@ import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
33
33
  import { terminateGroup, watchGroup } from "./process-group.mjs";
34
34
  import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, recordInClaim, releaseClaim, shownHolder } from "./claim.mjs";
35
35
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
36
- import { filterOverrides } from "./instance-git.mjs";
36
+ import { NO_FILE_MONITOR, workTreeOverrides } from "./instance-git.mjs";
37
37
  import {
38
38
  cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
39
39
  refuseBesideRetire, retirePendingMarkerPath, stableSoulId, workspaceOf,
@@ -572,17 +572,25 @@ export async function worktreeAdd(homeArg, o = {}) {
572
572
  return Object.assign(oatsError(code, `${message}${note}`), { details: { purpose, path: tree, rolledBack: rb.owed.length === 0, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(rb.owed.length ? { owed: rb.owed } : {}), ...(warned.length ? { warnings: warned } : {}), ...details } });
573
573
  };
574
574
 
575
- const add = await trackedGit(["-C", clone, "worktree", "add", "--detach", "--end-of-options", tree], { track });
575
+ // The checkouts below (worktree add, switch) write the tree's files: no filter driver the
576
+ // repository's configuration defines runs in either, nor the file monitor it names
577
+ // (lib/instance-git.mjs workTreeOverrides, read before each).
578
+ const addFilters = workTreeOverrides(["-C", clone], gitEnv());
579
+ if (!addFilters.ok) throw await fail("E_GIT_FAILED", `git worktree add failed in ${clone}: ${addFilters.err}`);
580
+ const add = await trackedGit([...addFilters.args, "-C", clone, "worktree", "add", "--detach", "--end-of-options", tree], { track });
576
581
  if (!add.ok) throw await fail("E_GIT_FAILED", `git worktree add failed in ${clone}: ${firstLine(add.err) || "unknown error"}`);
577
582
  const treeReal = realpathOr(tree);
578
- const fetch = await trackedGit(["-C", tree, "fetch", "--refmap=", "--end-of-options", "origin", base], { track, timeout: worktreeFetchTimeoutMs() });
583
+ // The fetch writes no file of the tree, and reads its index (for submodules): no file monitor.
584
+ const fetch = await trackedGit([...NO_FILE_MONITOR, "-C", tree, "fetch", "--refmap=", "--end-of-options", "origin", base], { track, timeout: worktreeFetchTimeoutMs() });
579
585
  if (!fetch.ok) throw await fail("E_REMOTE_UNREADABLE", `cannot fetch ${base} from origin (${remote}): ${firstLine(fetch.err) || "timeout"}`, { base, remote });
580
586
  const fetched = git(["-C", tree, "rev-parse", "--verify", "--quiet", "FETCH_HEAD^{commit}"]);
581
587
  const oid = fetched.out.trim();
582
588
  if (!fetched.ok || !/^[0-9a-f]{40,64}$/.test(oid)) throw await fail("E_BASE_UNKNOWN", `the fetch of ${base} from origin left no commit in FETCH_HEAD`, { base });
583
589
  rec = { ...rec, baseOid: oid };
584
590
  writeRecord(recPath, rec); // before the branch exists: a rollback deletes it only at this oid, and only if this add made it
585
- const sw = await trackedGit(["-C", tree, "switch", "--no-guess", "-c", branch, "--end-of-options", oid], { track });
591
+ const switchFilters = workTreeOverrides(["-C", tree], gitEnv());
592
+ if (!switchFilters.ok) throw await fail("E_GIT_FAILED", `git switch failed in ${tree}: ${switchFilters.err}`, { branch });
593
+ const sw = await trackedGit([...switchFilters.args, "-C", tree, "switch", "--no-guess", "-c", branch, "--end-of-options", oid], { track });
586
594
  if (!sw.ok) {
587
595
  // Another add created the branch first (the precheck passed for both): that is E_BRANCH_EXISTS; any other failure is git's.
588
596
  const taken = git(["-C", clone, "rev-parse", "--verify", "--quiet", "--end-of-options", `refs/heads/${branch}`]).ok;
@@ -644,10 +652,11 @@ const manualResidueRemedy = (tree, purpose) => `save any work and remove ${tree}
644
652
  * configuration whoever works in a tree can write: Git runs one when it compares a tree's file
645
653
  * that carries the `filter` attribute, and the removal reads the tree's files as their bytes are
646
654
  * (lib/instance-git.mjs filterOverrides, which says what its read covers and what it does not).
655
+ * They keep it from running the file monitor that configuration names too (workTreeOverrides).
647
656
  * Throws `refused(why)` when the drivers cannot be read or one cannot be overridden: the caller
648
657
  * then runs no Git on the tree, and never takes it for a clean one. */
649
- function removalFilterOverrides(where, refused) {
650
- const filters = filterOverrides(where, { operatorEnv: gitEnv() });
658
+ function removalOverrides(where, refused) {
659
+ const filters = workTreeOverrides(where, gitEnv());
651
660
  if (!filters.ok) throw refused(filters.err);
652
661
  return filters.args;
653
662
  }
@@ -670,8 +679,8 @@ function checkRemovalResidue(clone, tree, rec, refuse) {
670
679
  if (!missingGitdir) throw refuse(`the unregistered tree has no .git file pointing at a missing gitdir; ${manualResidueRemedy(tree, rec.purpose)}`);
671
680
 
672
681
  // The refresh and diff-files below read the surviving files: no filter driver the clone's
673
- // configuration defines runs in them (removalFilterOverrides).
674
- const filters = removalFilterOverrides(["-C", clone], (err) => refuse(`the surviving files could not be checked (${err})`));
682
+ // configuration defines runs in them (removalOverrides).
683
+ const filters = removalOverrides(["-C", clone], (err) => refuse(`the surviving files could not be checked (${err})`));
675
684
  const scratch = mkdtempSync(join(tmpdir(), "oats-worktree-remove-"));
676
685
  try {
677
686
  const env = { GIT_INDEX_FILE: join(scratch, "index") };
@@ -778,8 +787,8 @@ export async function worktreeRemove(homeArg, o = {}) {
778
787
  } else {
779
788
  // The status, and the clean check inside `git worktree remove` (a `git status` Git starts
780
789
  // in the tree, which the `-c` settings reach), compare the tree's files: no filter driver
781
- // the tree's configuration defines runs in either (removalFilterOverrides).
782
- const filters = removalFilterOverrides(["-C", tree], (err) => refuse(`whether the tree is clean could not be read (${err})`));
790
+ // the tree's configuration defines runs in either (removalOverrides).
791
+ const filters = removalOverrides(["-C", tree], (err) => refuse(`whether the tree is clean could not be read (${err})`));
783
792
  const status = git([...filters, "-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
784
793
  started = true;
785
794
  const r = await trackedGit([...filters, "-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.69.14",
3
+ "version": "0.69.15",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",
@@ -13,6 +13,9 @@
13
13
  },
14
14
  "license": "MIT",
15
15
  "type": "module",
16
+ "engines": {
17
+ "node": ">=22.5.0"
18
+ },
16
19
  "scripts": {
17
20
  "test": "node scripts/run-tests.mjs",
18
21
  "test:session": "node scripts/test-session-inheritance.mjs",