@awebai/oats 0.50.0 → 0.51.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.
package/lib/servers.mjs CHANGED
@@ -26,6 +26,7 @@ import { noteRuntimeName } from "./deprecation.mjs";
26
26
  import { readWaitingClaim } from "./instance-events.mjs";
27
27
  import { withDirLock } from "./dir-lock.mjs";
28
28
  import { shellWord } from "./core.mjs";
29
+ import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
29
30
 
30
31
  const OATS_HOME_DIR = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
31
32
  export const SERVERS_FILE = () => join(OATS_HOME_DIR(), "servers.json");
@@ -921,8 +922,10 @@ export function resolveRoute(serverId, { instance, home } = {}, what = "session"
921
922
  if (home && !snap) snap = listSnapshots(serverId).find((s) => s.home && resolve(s.home) === resolve(home));
922
923
  if (instance && snap && snap.instance !== instance) throw serverError("E_HOME_MISMATCH", `--home ${home} is the saved route of ${snap.instance} on ${serverId}, not of ${instance}`);
923
924
  if (instance && !snap && home && basename(home) !== instance) throw serverError("E_HOME_MISMATCH", `--home ${home} is not the home of instance ${instance}`);
924
- const remoteHome = home || snap?.home || (instance ? instanceOnHost(serverId, instance, io).home : undefined);
925
925
  const target = snap?.target || targetOf(io.server || getServer(serverId));
926
+ // `io.beforeRoster(target)`: what a caller must establish about the host before this route asks
927
+ // it anything (a keyed attach's feature gate). It runs only when the roster is about to be read.
928
+ const remoteHome = home || snap?.home || (instance ? (io.beforeRoster?.(target), instanceOnHost(serverId, instance, io).home) : undefined);
926
929
  if (!remoteHome || !String(remoteHome).startsWith("/")) throw serverError("E_BAD_ARGS", `${what} --server needs --instance <name> or --home </absolute/remote/home>`);
927
930
  return { target, home: remoteHome, snapshot: snap };
928
931
  }
@@ -1162,11 +1165,24 @@ export function scheduleRemote(serverId, oatsArgs, io = {}) {
1162
1165
  return { envelope: envelope.ok ? { ...envelope, result: { ...envelope.result, server: serverId } } : envelope, stderr, target };
1163
1166
  }
1164
1167
 
1165
- export function attachArgv(serverId, { instance, home } = {}, io = {}) {
1168
+ export function attachArgv(serverId, { instance, home, detachKey } = {}, io = {}) {
1166
1169
  io = { ...io, serverId };
1167
- const { target, home: remoteHome } = resolveRoute(serverId, { instance, home }, "session attach", io);
1170
+ const keyed = detachKey !== undefined;
1171
+ // A detach key is checked before anything is asked of the host.
1172
+ if (keyed) requireDetachKey(detachKey);
1173
+ // A kernel without the feature ignores the flag and opens a viewer no key leaves. So with a key
1174
+ // the probe always runs, under `skipVersionCheck` (--print) too: a printed argv is run as it is.
1175
+ // A host without the feature is sent the probe and nothing else: the gate comes before a name
1176
+ // is resolved through the host's roster, and before the `session` check, whose hint reads the
1177
+ // roster too. The probe is asked once (checkRemote keeps it).
1178
+ const requireDetachKeyRemote = (target) => {
1179
+ const remote = checkRemote(target, io);
1180
+ if (!remote.features.includes(DETACH_KEY_FEATURE)) throw Object.assign(serverError("E_REMOTE_INCOMPATIBLE", `remote oats ${remote.version} at ${target.sshHost} does not advertise ${DETACH_KEY_FEATURE}; upgrade it there, or attach without --detach-key; nothing was sent`), { details: { feature: DETACH_KEY_FEATURE } });
1181
+ };
1182
+ const { target, home: remoteHome } = resolveRoute(serverId, { instance, home }, "session attach", keyed ? { ...io, beforeRoster: requireDetachKeyRemote } : io);
1183
+ if (keyed) requireDetachKeyRemote(target);
1168
1184
  if (!io.skipVersionCheck) requireSessionRemote(target, io, remoteHome);
1169
- const [bin, ...rest] = sshArgv(target, ["session", "attach", "--home", remoteHome], { control: controlUsable(target, io) });
1185
+ const [bin, ...rest] = sshArgv(target, ["session", "attach", "--home", remoteHome, ...(detachKey !== undefined ? ["--detach-key", detachKey] : [])], { control: controlUsable(target, io) });
1170
1186
  // -t: allocate a PTY; placed before `--` with the other ssh options.
1171
1187
  return { argv: [bin, "-t", ...rest], target, home: remoteHome };
1172
1188
  }
@@ -3,7 +3,41 @@ import { execFileSync, spawn } from "node:child_process";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { inspectSessionTarget } from "./session-input.mjs";
5
5
 
6
- export function prepareSessionViewer(target, { exec = execFileSync } = {}) {
6
+ /** The kernel feature of `session attach --detach-key` (docs/execution-targets.md, "Inspect,
7
+ * input and attach"): a routed attach sends the flag only to a host that advertises it. */
8
+ export const DETACH_KEY_FEATURE = "session-attach-detach-key";
9
+ /** The status of an attach its detach key ended. Answered only when the key's own binding ran. */
10
+ export const SESSION_DETACHED_EXIT = 20;
11
+ /** The closed grammar of a detach key: Control with a letter other than h, i and m, or one of
12
+ * \ ] ^ _, Meta with a lowercase letter or a digit, or F1 to F12 with at most one modifier.
13
+ * Outside it: C-i and C-m (Tab and Enter), C-h (the byte many terminals send for
14
+ * Ctrl+Backspace, and some for Backspace: not one key everywhere), Escape (C-[), the ESC + C1
15
+ * introducers (M-[, M-], M-\, M-O: a terminal's reply can arrive as one), `Any` and the mouse
16
+ * key names. A closed grammar can be widened later and never narrowed. */
17
+ const DETACH_KEY = /^(?:C-[a-gj-ln-z\\\]^_]|M-[a-z0-9]|(?:[CMS]-)?F(?:[1-9]|1[0-2]))$/;
18
+ /** Whether a value is one detach key: the local and the routed attach both ask here. */
19
+ export function isDetachKey(value) { return typeof value === "string" && DETACH_KEY.test(value); }
20
+ /** The key, or E_BAD_ARGS: called before any tmux or ssh call. */
21
+ export function requireDetachKey(value) {
22
+ if (isDetachKey(value)) return value;
23
+ throw Object.assign(new Error(`--detach-key must be one key: C-<a letter except h, i and m, or one of \\ ] ^ _>, M-<a lowercase letter or digit>, or F1 to F12 with at most one of C-, M-, S- (got ${JSON.stringify(value)})`), { code: "E_BAD_ARGS" });
24
+ }
25
+
26
+ /** The table of a viewer without a detach key: one for the whole tmux server, emptied and bound
27
+ * again by each such viewer. */
28
+ const LOCKED_TABLE = "oatsview-locked";
29
+ /** The mouse bindings of a viewer's key table, the locked one or a keyed viewer's own. */
30
+ const MOUSE_BINDINGS = [
31
+ ["WheelUpPane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -e; send-keys -M"],
32
+ ["MouseDrag1Pane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -M"],
33
+ ];
34
+ /** What a detach key runs, as ONE bind-key argument (a bare `;` argument would end bind-key and
35
+ * run the rest at once): mark the viewer session, then detach the client that pressed the key.
36
+ * A constant: no caller text is ever part of a tmux command string. */
37
+ const DETACH_BINDING = "set-option @oats-detached 1 ; detach-client";
38
+
39
+ export function prepareSessionViewer(target, { exec = execFileSync, detachKey } = {}) {
40
+ if (detachKey !== undefined) requireDetachKey(detachKey);
7
41
  if (!inspectSessionTarget(target, { exec }).present) throw new Error("session no longer exists");
8
42
  // UTF-8 mode (-u) like the shared session helper: a service without a
9
43
  // UTF-8 locale (launchd) otherwise mangles tmux output.
@@ -11,7 +45,15 @@ export function prepareSessionViewer(target, { exec = execFileSync } = {}) {
11
45
  encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "pipe"],
12
46
  }).trim();
13
47
  const viewer = `oatsview-${process.pid}-${randomUUID().slice(0, 8)}`;
14
- const cleanup = () => { try { run(["kill-session", "-t", `=${viewer}`]); } catch { /* already detached/ended */ } };
48
+ // A keyed viewer reads a table of its own, named as its session: a binding in the locked table
49
+ // would be every viewer's, and the next viewer's unbind would remove it.
50
+ const table = detachKey === undefined ? LOCKED_TABLE : viewer;
51
+ const cleanup = () => {
52
+ try { run(["kill-session", "-t", `=${viewer}`]); } catch { /* already detached/ended */ }
53
+ // A key table belongs to the tmux server and outlives the session; tmux drops it with its
54
+ // last binding.
55
+ if (table !== LOCKED_TABLE) { try { run(["unbind-key", "-a", "-q", "-T", table]); } catch { /* the server is gone */ } }
56
+ };
15
57
  try {
16
58
  const placeholder = run(["new-session", "-d", "-s", viewer, "-P", "-F", "#{window_id}"]);
17
59
  if (!/^@\d+$/.test(placeholder)) throw new Error("tmux returned no viewer window id");
@@ -20,33 +62,68 @@ export function prepareSessionViewer(target, { exec = execFileSync } = {}) {
20
62
  // One linked window prevents a stale viewer from selecting a sibling agent
21
63
  // when this agent retires. Disable window navigation in the viewer only.
22
64
  for (const name of ["prefix", "prefix2"]) run(["set-option", "-t", viewer, name, "None"]);
23
- run(["set-option", "-t", viewer, "key-table", "oatsview-locked"]);
65
+ run(["set-option", "-t", viewer, "key-table", table]);
24
66
  // The viewer shows one agent; its status line only repeats that name.
25
67
  // Session-scoped on the temporary viewer: the agents' own session and
26
68
  // the operator's tmux settings are untouched.
27
69
  run(["set-option", "-t", viewer, "status", "off"]);
28
- run(["unbind-key", "-a", "-q", "-T", "oatsview-locked"]);
29
- run(["bind-key", "-T", "oatsview-locked", "WheelUpPane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -e; send-keys -M"]);
30
- run(["bind-key", "-T", "oatsview-locked", "MouseDrag1Pane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -M"]);
70
+ run(["unbind-key", "-a", "-q", "-T", table]);
71
+ for (const binding of MOUSE_BINDINGS) run(["bind-key", "-T", table, ...binding]);
72
+ // The key is its own argv element, after the grammar admitted it.
73
+ if (detachKey !== undefined) run(["bind-key", "-T", table, detachKey, DETACH_BINDING]);
31
74
  run(["set-option", "-t", viewer, "mouse", "on"]);
32
75
  const env = { ...process.env }; delete env.TMUX;
33
- return { binary: "tmux", args: ["-u", "-S", target.socket, "attach-session", "-t", `=${viewer}`], env, cleanup };
76
+ /** Whether the detach key's binding ran: it marks the viewer session before it detaches. A
77
+ * client that left any other way (its window ended, another client detached it) left no
78
+ * mark, and a session that is gone answers nothing. The target is `=<session>:`:
79
+ * show-options reads -t as a pane, and under -q answers nothing at all for `=<session>`. */
80
+ const detached = () => {
81
+ if (detachKey === undefined) return false;
82
+ try { return run(["show-options", "-t", `=${viewer}:`, "-qv", "@oats-detached"]) === "1"; } catch { return false; }
83
+ };
84
+ return { binary: "tmux", args: ["-u", "-S", target.socket, "attach-session", "-t", `=${viewer}`], env, cleanup, detached };
34
85
  } catch (e) { cleanup(); throw e; }
35
86
  }
36
87
 
37
- export async function attachSessionTarget(target) {
38
- const viewer = prepareSessionViewer(target);
88
+ // SIGQUIT under a keyed attach. The key may be C-\, the tty's QUIT character: pressed before the
89
+ // tmux client has taken the tty, or again once the client has given it back, it reaches this
90
+ // process as SIGQUIT, whose default action ends Node before any `finally` (status 131, the viewer
91
+ // session and its table left on the server). One listener, added by the first keyed attach and
92
+ // never removed, calls whatever the attach in progress set.
93
+ let onQuit = null;
94
+ let quitHeld = false;
95
+ function holdQuit() {
96
+ if (quitHeld) return;
97
+ quitHeld = true;
98
+ process.on("SIGQUIT", () => onQuit?.());
99
+ }
100
+
101
+ /** Attach this terminal to a viewer of the target and answer the client's status, or
102
+ * SESSION_DETACHED_EXIT when `detachKey` was given and ended the attach. */
103
+ export async function attachSessionTarget(target, { detachKey } = {}) {
104
+ if (detachKey !== undefined) { requireDetachKey(detachKey); holdQuit(); }
105
+ const viewer = prepareSessionViewer(target, { detachKey });
39
106
  let child;
107
+ let quit = false;
40
108
  const stop = () => { viewer.cleanup(); child?.kill(); };
41
109
  const signals = ["SIGHUP", "SIGTERM", "SIGINT"];
42
110
  for (const sig of signals) process.on(sig, stop);
111
+ // Until the client has exited, a QUIT stops the attach as the other signals do, with status 1.
112
+ // Unless the key's binding has already run: then the client is on its way out, the QUIT is the
113
+ // key pressed again, and the attach ends as a detach.
114
+ if (detachKey !== undefined) onQuit = () => { if (viewer.detached()) return; quit = true; stop(); };
43
115
  try {
44
- return await new Promise((resolve, reject) => {
116
+ const code = await new Promise((resolve, reject) => {
45
117
  child = spawn(viewer.binary, viewer.args, { env: viewer.env, stdio: "inherit" });
46
118
  child.once("error", reject);
47
119
  child.once("exit", (code) => resolve(code ?? 1));
48
120
  });
121
+ if (quit) return 1;
122
+ return viewer.detached() ? SESSION_DETACHED_EXIT : code;
49
123
  } finally {
124
+ // The client has exited (or never started): a QUIT from here on changes nothing. One that
125
+ // arrives during the calls below waits for them, so cleanup completes and the status stands.
126
+ onQuit = null;
50
127
  for (const sig of signals) process.removeListener(sig, stop);
51
128
  viewer.cleanup();
52
129
  }
@@ -17,7 +17,7 @@
17
17
  * is a test seam, not a setting. */
18
18
  import { spawn as spawnProcess, execFileSync, spawnSync } from "node:child_process";
19
19
  import { closeSync, existsSync, fchmodSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync } from "node:fs";
20
- import { dirname, join } from "node:path";
20
+ import { dirname, isAbsolute, join } from "node:path";
21
21
  import { terminateGroup, watchGroup, TERM_GRACE_MS } from "./process-group.mjs";
22
22
 
23
23
  export const WORKTREE_HOOK_TIMEOUT_MS = 30 * 60 * 1000;
@@ -36,12 +36,25 @@ export const interruptExitStatus = (signal) => 128 + (SIGNAL_NUMBERS[signal] ??
36
36
  // ---------- process identity: a pid is verified by its start time ----------
37
37
 
38
38
  /** Where a start time is read: /proc when this host has procfs, else `ps`. The test seam
39
- * OATS_TEST_PROCESS_START_PS=1 (not a setting) takes the `ps` path on a host with procfs. */
40
- const readsProc = () => process.env.OATS_TEST_PROCESS_START_PS !== "1" && existsSync("/proc/self/stat");
41
- /** `ps` runs with a fixed environment, nothing inherited: `lstart` is local time in the locale's
42
- * format, and two readers with another TZ or LANG would otherwise read one live process's start
43
- * differently, and take it for another. */
44
- const psEnv = () => ({ PATH: process.env.PATH ?? "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" });
39
+ * OATS_TEST_PROCESS_START_PS (not a setting; a launch configuration cannot set it) takes the `ps`
40
+ * path on any host: `1` runs the system `ps`, an absolute path runs that file as `ps`, and any
41
+ * other value reads no start at all (psProgram). */
42
+ const readsProc = () => process.env.OATS_TEST_PROCESS_START_PS === undefined && existsSync("/proc/self/stat");
43
+ /** `ps` runs with a fixed environment, nothing inherited. Its PATH is the system directories only,
44
+ * never the caller's: what `ps` reports is the identity a claim is held or taken over on, so the
45
+ * caller's PATH must not choose the program, and a caller whose PATH holds no `ps` reads the same
46
+ * start as any other. `lstart` is local time in the locale's format, and two readers with another
47
+ * TZ or LANG would otherwise read one live process's start differently, and take it for another. */
48
+ const PS_ENV = Object.freeze({ PATH: "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" });
49
+ /** The `ps` a start is read with → { file, name } | { reason }: the system one, or the file the
50
+ * test seam names by absolute path, run directly (no shell). A seam that names neither is never a
51
+ * fallback to /proc or to a `ps` found on PATH; nor is a named file that cannot be run (readStart). */
52
+ function psProgram() {
53
+ const seam = process.env.OATS_TEST_PROCESS_START_PS;
54
+ if (seam === undefined || seam === "1") return { file: "ps", name: "ps" };
55
+ if (isAbsolute(seam)) return { file: seam, name: `the ps OATS_TEST_PROCESS_START_PS names (${seam})` };
56
+ return { reason: `OATS_TEST_PROCESS_START_PS is ${JSON.stringify(seam)}, neither 1 nor an absolute path` };
57
+ }
45
58
 
46
59
  /** Whether `pid` exists, from the kernel itself: kill(pid, 0). ESRCH is gone; EPERM (another user's
47
60
  * process) and success are "exists"; anything else is unknown. Never from how procfs or `ps`
@@ -68,9 +81,11 @@ function readStart(pid) {
68
81
  const start = fields[19]; // field 22 overall: after pid, comm and the 19 before it
69
82
  return /^[0-9]+$/.test(start ?? "") ? { state: "alive", token: `proc:${start}` } : { state: "unknown", reason: `/proc/${pid}/stat has no start time` };
70
83
  }
71
- const r = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: psEnv(), timeout: 10_000 });
84
+ const ps = psProgram();
85
+ if (ps.reason) return { state: "unknown", reason: ps.reason };
86
+ const r = spawnSync(ps.file, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: PS_ENV, timeout: 10_000 });
72
87
  const out = String(r.stdout ?? "").trim(), err = String(r.stderr ?? "").trim();
73
- if (r.error) return { state: "unknown", reason: `ps could not be run (${r.error.code || r.error.message})` };
88
+ if (r.error) return { state: "unknown", reason: `${ps.name} could not be run (${r.error.code || r.error.message})` };
74
89
  if (r.status === 0 && out) return { state: "alive", token: `ps:${out}` };
75
90
  return { state: "unknown", reason: `ps -o lstart= -p ${pid} answered ${r.status === null ? `signal ${r.signal}` : `exit ${r.status}`}${err ? `: ${err.split("\n")[0]}` : out ? " with output" : " with no output"}` };
76
91
  }
package/lib/worktree.mjs CHANGED
@@ -27,8 +27,8 @@ import { recordedTeams } from "./teams.mjs";
27
27
  import { canonicalCloneKey, memberCloneOf } from "./instance-resolution.mjs";
28
28
  import { loadLocal } from "./workspace.mjs";
29
29
  import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
30
- import { randomBytes } from "node:crypto";
31
30
  import { terminateGroup, watchGroup } from "./process-group.mjs";
31
+ import { CLAIM_WAIT_MS, acquireClaim, recordInClaim, releaseClaim } from "./claim.mjs";
32
32
  import {
33
33
  cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
34
34
  retirePendingMarkerPath, stableSoulId, workspaceOf,
@@ -348,101 +348,29 @@ function withPurposeClaim(home, purpose, fn) {
348
348
  return withClaim(lock, fn, { busy });
349
349
  }
350
350
 
351
- const CLAIM_WAIT_MS = 3000;
352
- const CLAIM_MAX_DEPTH = 8;
353
- const pauseSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
354
- function readClaim(path) {
355
- try { const o = JSON.parse(readFileSync(path, "utf8")); return o && typeof o === "object" ? o : { unreadable: true }; }
356
- catch (e) { return e.code === "ENOENT" ? null : { unreadable: true }; }
357
- }
358
-
359
- /** Run `fn` holding the claim file `path`. Exported for its tests.
351
+ /** Run `fn` holding the claim file `path` (lib/claim.mjs: how a claim is taken, taken over from a
352
+ * dead holder and released). Exported for its tests.
360
353
  *
361
- * - Taking it: the owner's facts `{ pid, processStart, nonce }` are written to a private file and
362
- * hard-linked to `path`, which fails if `path` exists. So a claim is never seen without its
363
- * owner, and the nonce makes each holding distinct, even for the same process.
364
- * - Its owner is gone (processLiveness "gone"; "unknown" is refused, never taken over): the claim
365
- * is removed under a second claim,
366
- * `<path>.reclaim-<owner nonce>`, taken by this same protocol. Its holder re-reads `path` and
367
- * removes it only if it still names that owner. Nothing else removes another's claim: its
368
- * owner never releases it, and a new acquirer cannot write over an existing file. Two takeovers
369
- * of one dead owner are therefore serialized, and neither removes a claim made after it read.
370
- * A takeover cut short leaves its own claim behind, which the next takeover takes over in
371
- * turn, up to CLAIM_MAX_DEPTH nested levels.
372
- * - The holder's running git step (`gitPid`, `gitStart`; trackedGit) is in the claim. A takeover
373
- * ends it first (endRecordedGit) and refuses, keeping the claim, if it cannot be ended.
374
- * - Released by unlinking `path`, only while it still names this holding.
375
- * - An unreadable claim file is never removed: the command is refused as busy, naming the file. */
354
+ * The holder's running git step (`gitPid`, `gitStart`; trackedGit) is in the claim. A takeover
355
+ * ends it first (endRecordedGit) and refuses, keeping the claim, if it cannot be ended.
356
+ * `fn({ track, warnings })`; → Promise of what `fn` returns. An error with `keepClaim` leaves the
357
+ * claim held, for the step it names. */
376
358
  export async function withClaim(path, fn, { busy, waitMs = CLAIM_WAIT_MS } = {}) {
377
359
  const warnings = [];
378
- const me = acquireClaim(path, { busy, waitMs, warnings }, 0);
360
+ const me = acquireClaim(path, {
361
+ busy, waitMs, warnings,
362
+ ownStartUnreadable: (_reason, at) => Object.assign(busy(null), { message: `this process's start time cannot be read, so it cannot hold ${at} verifiably; nothing was done` }),
363
+ unreadableClaim: (at) => Object.assign(busy(null), { message: `${at} is not a readable claim; inspect it and remove it if no oats worktree command holds it; nothing was done` }),
364
+ endHolderStep: (holder, at) => ({ ...endRecordedGit(holder, at), details: { gitPid: holder.gitPid, gitStart: holder.gitStart ?? null } }),
365
+ });
379
366
  // Record (or clear) the holder's running git step in the claim; only its live holder writes it.
380
- const track = (gitStep) => {
381
- const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
382
- writeFileSync(tmp, JSON.stringify({ ...me, ...(gitStep ?? {}) }) + "\n", { mode: 0o600 });
383
- renameSync(tmp, path);
384
- };
367
+ const track = (gitStep) => recordInClaim(path, me, gitStep);
385
368
  let keep = false;
386
369
  try { return await fn({ track, warnings }); }
387
370
  catch (e) { keep = e?.keepClaim === true; throw e; }
388
371
  finally { if (!keep) releaseClaim(path, me); }
389
372
  }
390
373
 
391
- function acquireClaim(path, opts, depth) {
392
- const { busy, waitMs } = opts;
393
- const self = selfIdentity();
394
- if (!self.processStart) throw Object.assign(busy(null), { message: `this process's start time cannot be read, so it cannot hold ${path} verifiably; nothing was done` });
395
- const me = { ...self, nonce: randomBytes(16).toString("hex"), at: new Date().toISOString() };
396
- const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
397
- writeFileSync(tmp, JSON.stringify(me) + "\n", { mode: 0o600 });
398
- try {
399
- const deadline = Date.now() + waitMs;
400
- for (;;) {
401
- try { linkSync(tmp, path); return me; }
402
- catch (e) { if (e.code !== "EEXIST") throw e; }
403
- const holder = readClaim(path);
404
- if (holder === null) continue; // released in between
405
- if (holder.unreadable) throw Object.assign(busy(null), { message: `${path} is not a readable claim; inspect it and remove it if no oats worktree command holds it; nothing was done` });
406
- const live = processLiveness(holder);
407
- // Unreadable is never taken for gone: the claim is kept, and the refusal names the way out.
408
- if (live.state === "unknown") throw busy(holder, live.reason, path);
409
- if (live.state === "gone") {
410
- if (depth >= CLAIM_MAX_DEPTH || typeof holder.nonce !== "string" || !/^[0-9a-f]{32}$/.test(holder.nonce)) throw busy(holder, null, path);
411
- takeOver(path, holder, opts, depth);
412
- continue;
413
- }
414
- if (Date.now() >= deadline) throw busy(holder, null, path);
415
- pauseSync(50);
416
- }
417
- } finally {
418
- try { unlinkSync(tmp); } catch { /* gone */ }
419
- }
420
- }
421
-
422
- /** Remove `path`, held by the dead `holder`, under the claim that serializes takeovers of it. */
423
- function takeOver(path, holder, opts, depth) {
424
- const reclaim = `${path}.reclaim-${holder.nonce}`;
425
- const me = acquireClaim(reclaim, opts, depth + 1);
426
- try {
427
- const now = readClaim(path);
428
- if (now?.nonce === holder.nonce) {
429
- const ended = endRecordedGit(now, path);
430
- if (ended.owed) {
431
- const e = opts.busy(now);
432
- throw Object.assign(e, { message: `${ended.owed}; ${path} is kept and nothing was done — ${ended.remedy}`, details: { ...e.details, gitPid: now.gitPid, gitStart: now.gitStart ?? null } });
433
- }
434
- if (ended.warning) opts.warnings?.push(ended.warning);
435
- unlinkSync(path);
436
- }
437
- } finally {
438
- releaseClaim(reclaim, me);
439
- }
440
- }
441
-
442
- function releaseClaim(path, me) {
443
- if (readClaim(path)?.nonce === me.nonce) { try { unlinkSync(path); } catch { /* gone */ } }
444
- }
445
-
446
374
  /** A `creating` record whose adder may still run: its start cannot be read. Never rolled back on
447
375
  * that; the refusal names the pid and the record's exact path, the way out once the pid is
448
376
  * checked by hand. */
@@ -3,12 +3,12 @@
3
3
  "packages": {
4
4
  "oats.okf": {
5
5
  "url": "https://github.com/awebai/oats-okf.git",
6
- "ref": "v5.0.0",
6
+ "ref": "v5.0.1",
7
7
  "path": "oats-package"
8
8
  },
9
9
  "oats.aweb": {
10
10
  "url": "https://github.com/awebai/oats-aweb.git",
11
- "ref": "v1.24.0",
11
+ "ref": "v1.24.1",
12
12
  "path": "oats-package"
13
13
  },
14
14
  "oats.jira": {
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "oats.framework": {
45
45
  "url": "https://github.com/awebai/oats.git",
46
- "ref": "oats-framework/v1.9.0",
46
+ "ref": "oats-framework/v1.9.1",
47
47
  "path": "oats-package"
48
48
  }
49
49
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.50.0",
3
+ "version": "0.51.0",
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",
@@ -60,7 +60,7 @@ members:
60
60
  - git:github.com/acme/agents # the host is a member too
61
61
  - git:github.com/acme/platform
62
62
  packages:
63
- oats.framework: v1.9.0 # bare versions resolve through the official catalog
63
+ oats.framework: v1.9.1 # bare versions resolve through the official catalog
64
64
  oats.okf: v4.1.1
65
65
  defaults:
66
66
  capabilities: { oats.core: { from: package } }