@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.
@@ -0,0 +1,156 @@
1
+ # OATS 0.51.0
2
+
3
+ 2026-10-11
4
+
5
+ ## Added
6
+
7
+ - **`oats session attach --detach-key <key>`: a key that leaves the viewer
8
+ (#856).** A viewer sets no tmux prefix and a locked key table, so every key
9
+ reaches the agent and nothing on the keyboard leaves it. A caller may now
10
+ name one key that detaches its own viewer, on the local form and with
11
+ `--server`. The agent's window and every other viewer are untouched, and
12
+ the agent never receives that key while this viewer is attached. Nothing
13
+ changes for a caller that names none: a plain attach still has no keyboard
14
+ exit, the tmux prefix included, and is left by closing the terminal.
15
+ - **The key** is `C-` with a letter other than `h`, `i` and `m` or one of
16
+ `\ ] ^ _`, `M-` with a lowercase letter or a digit, or `F1` to `F12` with
17
+ at most one of `C-`, `M-`, `S-`. Anything else is `E_BAD_ARGS` before any
18
+ tmux or ssh call. The suggested key is `C-\`, written `--detach-key
19
+ 'C-\'`; `F12` where `\` needs AltGr.
20
+ - **Exit status 20** when the viewer was left by the key. 0 (the viewer
21
+ ended without the key) and 1 (a refusal, or tmux failing under the
22
+ viewer) are unchanged, and so is ssh's own 255 on the routed form. 20 is
23
+ nonzero, so `set -e`, an `&&` chain and tmux's `remain-on-exit failed`
24
+ treat a leave by the key as a failure.
25
+ - **While the pane is scrolled back**, tmux's copy mode reads its own key
26
+ table first: a key copy mode binds (`C-e`, for example) detaches only
27
+ once the mode is left. `C-\` and `F12` are unbound in tmux's default
28
+ copy-mode tables (3.7c) and detach from there.
29
+ - **Feature `session-attach-detach-key`** in `oats version --json`, and so
30
+ in `oats status --json` and each `oats server roster --json` group's
31
+ `probe.features`. Gate on it and never try: a kernel without the feature
32
+ ignores the flag and opens a viewer with no exit. A routed attach sends
33
+ the flag only to a host that advertises the feature, and probes for it
34
+ under `--print` too. A host without it is refused here with
35
+ `E_REMOTE_INCOMPATIBLE`, exit 1, nothing else sent; its `details` are
36
+ `{"feature":"session-attach-detach-key"}`.
37
+
38
+ See [Inspect, input and
39
+ attach](../execution-targets.md#inspect-input-and-attach) and
40
+ [servers.md](../servers.md#run-there).
41
+
42
+ ## Changed
43
+
44
+ - **The Desktop accepts OATS CLIs `>=0.25.8 <0.52.0`.** The compatibility band
45
+ admits 0.51. Upgrade the CLI and the Desktop together: a 0.50.0 Desktop
46
+ refuses a 0.51.0 CLI. No feature gate changes: the Desktop does not use
47
+ `--detach-key`, and it already words `E_LIFECYCLE_BUSY`, the answer a second
48
+ retire of an instance now gets.
49
+
50
+ - **oats.okf 5.0.1: collision-safe harvest publication**
51
+ ([oats-okf#63](https://github.com/awebai/oats-okf/pull/63), fixes
52
+ [#62](https://github.com/awebai/oats-okf/issues/62) and
53
+ [#60](https://github.com/awebai/oats-okf/issues/60)). The official catalog,
54
+ reference workspace and generated mirrors take published `v5.0.1` at
55
+ `96b28d5cd4f01e48ed50d8e999e8715749a99e87`. Harvest refs use a fixed
56
+ prefix, UTC date and fresh UUID, not a source/harvester name. Git validates
57
+ the full ref; a create-only push plus new-ref confirmation refuses both
58
+ divergent and identical pre-existing targets without overwriting or retrying.
59
+ Source provenance remains in the commit and PR. A publication failure
60
+ **keeps the live harvester home**, with exact diagnostics and clone/commit/
61
+ PR-text locations, and notifies the reachable source through its existing
62
+ messaging. No standing-maintainer recipient or messaging preflight is
63
+ added; existing attention is used where supported. Missing/failed messaging
64
+ cannot turn failure into retirement. Partial or uncertain gh publication
65
+ stays live and does not authorize retries or remote cleanup.
66
+ The OATS floor remains `>=0.29.0`; old homes retain their copied modules
67
+ until respawn. No pre-5.0 source migration or new custody engine is included.
68
+ See [Knowledge](../knowledge.md#the-flow).
69
+
70
+ - **oats.framework 1.9.1: oats.core 2.5.1.** Instruction text only; no
71
+ kernel, schema or provider contract changes. `oats-operate` says that a
72
+ plain `oats session attach` has no keyboard exit, and that
73
+ `--detach-key <key>` leaves the viewer on a kernel whose
74
+ `oats version --json` lists `session-attach-detach-key` (#856). The
75
+ capability floors are unchanged. A deployment takes it at the tag
76
+ `oats-framework/v1.9.1`; a running instance keeps the text it was spawned
77
+ with until it is respawned.
78
+
79
+ - **oats.aweb 1.24.1: `setup --join` on a closed workspace**
80
+ ([oats-aweb#95](https://github.com/awebai/oats-aweb/pull/95)). The official
81
+ catalog, reference workspace and generated `mirrors/oats-aweb` take published
82
+ `v1.24.1` at `4212db16668c9bd837d7d99f287ed9e9ae303a0e`. On a workspace that
83
+ forbids local team writes, `oats aweb setup --join <label>` refuses only when
84
+ its plan would write a mapping or a default. A label the workspace already
85
+ commits to the joined team, and already its default, joins and records its
86
+ minting root without touching the team configuration. A conflicting mapping or
87
+ another configuration failure is reported as that (`E_SETUP_TEAM_CONFLICT`,
88
+ `E_SETUP_CONFIGURATION`) instead of `E_SETUP_POLICY`, and still refuses before
89
+ any write. Known limit: joining a second committed team on a closed workspace
90
+ whose default is another label still refuses
91
+ ([oats-aweb#96](https://github.com/awebai/oats-aweb/issues/96)). The OATS
92
+ floor stays `>=0.42.0`; old homes keep their copied modules until respawn.
93
+
94
+ ## Fixed
95
+
96
+ - **Retire: one retire of an instance at a time (#863).** Two `oats retire`
97
+ of the same instance, started moments apart from two sessions, both ran to
98
+ completion: two recovery copies, and every capability's retire hook ran
99
+ twice, at the same time. A retire hook releases things that exist once (a
100
+ messaging identity, a scheduled job). A retire now holds the instance's
101
+ claim from the moment it has resolved the home until it ends, and any other
102
+ retire of that instance is refused at once with `E_LIFECYCLE_BUSY` (exit 1),
103
+ before it stops a session or a child, writes a recovery, runs a hook or
104
+ changes a file of the home: `a retire of <name> is already running (pid
105
+ <pid>, since <at>); nothing was done — wait for it to finish`. This holds
106
+ for a plain retire, a guarded apply with any idempotency key, `--self` and
107
+ its detached completion, and `--server`; `--force` does not bypass it, and
108
+ `--plan` is unchanged. `details` is `{instance, home, lock, pid, since}`.
109
+ A guarded apply answers it whatever its plan would read by then: the plan
110
+ its revision is checked against is now read once the retire holds the
111
+ claim, so a retire in flight, which has usually changed the plan already,
112
+ is answered as busy and not as `E_PLAN_STALE`. A stale apply with nobody
113
+ else retiring answers `E_PLAN_STALE` as before.
114
+ - **A scheduled `--self` counts.** From the moment a self-retire is
115
+ scheduled until its completion has ended, every other retire of the
116
+ instance is refused the same way (`a retire of <name> is already
117
+ scheduled …`, `details.lock` the pending marker). The marker
118
+ `.oats-retire-pending-<instance>.json` now records the completion process
119
+ (`completionPid`, `completionStart`). A completion that failed or died
120
+ refuses nothing: `oats retire <instance>` retries it, as before. A second
121
+ `--self` answers `alreadyScheduled: true` while the completion has not
122
+ started (see the changed answers below).
123
+ - **The claim file** is
124
+ `<agents>/<agent>/instances/.oats-retirement/claims/<instance>.lock`,
125
+ beside the homes, and names its holder by pid and start time. A retire
126
+ that ends leaves none. A retire that was killed leaves its file until
127
+ that name is retired again: the next retire takes the claim over, because
128
+ its holder is verifiably gone. The file is safe to remove by hand once
129
+ its pid is gone. The claim does not end what a killed retire left
130
+ running: one of its retire hooks may still be running when the next
131
+ retire takes the claim over and runs the hooks again (#865).
132
+ - **A host that cannot read a process's start time** (no `/proc`, and `ps`
133
+ failing): a retire could not hold its claim verifiably there, so it is
134
+ now refused with `E_LIFECYCLE_BUSY`, and the message says what could not
135
+ be read. Likewise a claim or a pending marker whose holder's start cannot
136
+ be read is never taken for gone: the refusal names the pid, the file and
137
+ the way out (check that pid by hand; if it is not an `oats retire`,
138
+ remove the file, then retry).
139
+ - **Two changed answers**, both `E_LIFECYCLE_BUSY` where the answer was
140
+ `alreadyScheduled: true`. A second `--self` gets it while the first is
141
+ still scheduling, and once the completion has started and holds the
142
+ claim: it answers `alreadyScheduled: true` only between the two, while
143
+ the completion has not started. And `--self --keep-dir` runs the retire in
144
+ the calling process, so it is refused while a `--self` completion is
145
+ pending: on a home opened in Herdr (removed in 0.31.0), where `--self
146
+ --keep-dir` is deferred like a plain `--self`, a second one inside that
147
+ window gets it too.
148
+
149
+ The claim orders retires only: `oats instance stop`, `oats session start`
150
+ and `oats worktree add` against a retire in flight are unchanged (#866). See
151
+ [Retire](../desktop-cli-api.md#retire).
152
+
153
+ - **A retire, and anything else that reads a process's start, no longer
154
+ depends on the caller's `PATH` for `ps` (#878):** it runs the system `ps`
155
+ from `/usr/bin:/bin`, so a retire whose `PATH` holds no `ps` is no longer
156
+ refused with `E_LIFECYCLE_BUSY` (`ps could not be run (ENOENT)`).
package/docs/servers.md CHANGED
@@ -180,12 +180,16 @@ Every routed ssh call carries these options, before `--` and the host:
180
180
  - When ssh fails under an attached viewer (a lost link, or one never made),
181
181
  `session attach --server` exits 255 and says that, if the link was lost,
182
182
  the instance keeps running on the server, with the command to reattach.
183
+ When `--detach-key` was given, that command carries it (` --detach-key
184
+ <key>`, shell-quoted); without one the line is as before.
183
185
  When ssh fails before the viewer opens (the version probe, or a name
184
186
  resolved through the host's roster), it also exits 255, with `oats: ssh to
185
187
  <host> failed: …` (`--json`: the `E_SSH` envelope). Every other refusal
186
188
  (an incompatible host, an unknown or ambiguous name, bad arguments) exits 1,
187
189
  and so does an ssh that cannot be run on this machine at all: no link can
188
- come back.
190
+ come back. Otherwise the host's own status is relayed through ssh: 20 when
191
+ the viewer was left by its detach key (`--detach-key`, below), 0 when it
192
+ ended without the key, 1 for a refusal or a tmux failure there.
189
193
  - Every routed command reports ssh's own failure as `E_SSH` (`ssh to <host>
190
194
  failed: …`). When ssh never started on this machine, the `--json` envelope
191
195
  says so with `error.details: {"sshStarted": false}`; without details, ssh
@@ -210,7 +214,7 @@ sent as text or on stdin, never as paths.
210
214
  | `spawn` | registered workspace | the requested harness, backend and yolo option; `launch-config` for `--launch-config`; `schedule` for a wake schedule |
211
215
  | `status` | registered workspace | |
212
216
  | `retire` | the instance's home | `retire-home` to retire by exact home |
213
- | `session inspect`, `session attach` | the instance's home | `session` |
217
+ | `session inspect`, `session attach` | the instance's home | `session`; `session-attach-detach-key` for `attach --detach-key` |
214
218
  | `session start`, `session restart` | the instance's home | `session-start`; `session-restart`; `launch-config` when `--launch-config`, `--harness` or `--yolo` is given |
215
219
  | `session upload` | the instance's home | `session-upload` |
216
220
  | `okf harvest --instance <name>` | the saved home | `harvest` |
@@ -271,6 +275,21 @@ side answers one envelope (`E_SSH`, or `E_REMOTE_ENVELOPE`). Wherever this
271
275
  side prints the argv, `--invite` values are replaced by `<redacted>`.
272
276
  Kernel commands keep the table above.
273
277
 
278
+ **A detach key on a routed attach.** `session attach --server <id>
279
+ --detach-key <key>` names the key that leaves the viewer, as on the host
280
+ itself ([execution-targets.md](execution-targets.md#inspect-input-and-attach):
281
+ the grammar, the suggested `'C-\'`, exit status 20). The key is checked here
282
+ first, before any ssh call (`E_BAD_ARGS`). The flag travels only to a host
283
+ that advertises `session-attach-detach-key`: a kernel without the feature
284
+ would ignore it and open a viewer with no exit. Such a host is refused on
285
+ this machine after the version probe, with nothing else sent, exit 1:
286
+ `E_REMOTE_INCOMPATIBLE`, `remote oats <version> at <host> does not advertise
287
+ session-attach-detach-key; upgrade it there, or attach without --detach-key;
288
+ nothing was sent`. Under `--json` the envelope's `error.details` is
289
+ `{"feature":"session-attach-detach-key"}`. With a key the probe also runs
290
+ under `--print`, which otherwise skips it: a printed command must not carry
291
+ a flag its host would ignore.
292
+
274
293
  **Not routed.** `session input` runs on the execution host, where schedules
275
294
  and messaging capabilities call it. `session restart --stop-grace` is refused
276
295
  with `--server`; the remote default applies. `session attach --print` shows
@@ -434,6 +434,28 @@ takes a final capture of notes and the session record into durable custody; an
434
434
  incomplete capture keeps the home for a retry. Retirement never waits for a
435
435
  model or GitHub: processing continues after the home is gone.
436
436
 
437
+ One retire of an instance runs at a time. A retire holds the instance's claim
438
+ from the moment it has resolved the home until it ends: the file
439
+ `.oats-retirement/claims/<instance>.lock` in the agent's instances directory,
440
+ beside the homes, which names its holder by pid and start time. Any other
441
+ retire of that instance (plain, guarded or `--self`, `--force` included) is
442
+ refused at once with `E_LIFECYCLE_BUSY`, before it stops anything, copies
443
+ anything or runs a hook: a retire hook releases things that exist once, such
444
+ as a messaging identity or a scheduled job. A self-retire's completion is
445
+ refused the same way, after it has waited up to 3 s for the retire that
446
+ scheduled it to release the claim. A self-retire that is scheduled counts from the moment it is scheduled,
447
+ while its completion lives. A retire killed while it holds the claim leaves
448
+ the file behind until that name is retired again: the next retire takes the
449
+ claim over, because its holder is verifiably gone, and the file is safe to
450
+ remove by hand once its pid is gone. The claim does not end what the killed
451
+ retire left running: one of its retire hooks may still be running when the
452
+ next retire takes the claim over and runs the hooks again (#865). A holder whose start time cannot be
453
+ read is never taken for gone; the refusal names the pid, the file and the
454
+ way out. The claim orders retires only: `oats instance stop`, `oats session
455
+ start` and `oats worktree add` do not take it, and `oats status` does not
456
+ show it (#866). The refusals are in
457
+ [desktop-cli-api.md](desktop-cli-api.md#retire).
458
+
437
459
  Recorded children (the instances whose recorded parent chain reaches this
438
460
  one) are stopped first, never escalated, and kept: their homes stay. If one is
439
461
  still running after the grace, or its stop cannot be established, retire
@@ -939,7 +961,7 @@ can be inspected, and it is the process the scan exists to find.
939
961
  or briefing says it is done. A live harness cannot give a stable final
940
962
  inspection of its own work, so the calling process inspects, runs, and removes
941
963
  nothing: it records the intent beside its home as
942
- `.oats-retire-pending-<instance>.json` and starts a detached completion, then returns so the instance can report final
964
+ `.oats-retire-pending-<instance>.json`, which names the completion process, and starts a detached completion, then returns so the instance can report final
943
965
  status before its tmux window dies a few seconds later. The completion then
944
966
  retires the instance exactly as an external `oats retire` would: quiesce the
945
967
  harness, preserve uncommitted work, run retire hooks, repair lineage, remove
@@ -54,8 +54,8 @@ members: # repo refs, NO @revision (E_WORKSPAC
54
54
  - git:github.com/acme/tools # a member that ALSO publishes a package (see below)
55
55
 
56
56
  packages: # the ONLY versioned things
57
- oats.framework: v1.9.0 # bare version → resolves through the official catalog
58
- oats.okf: v5.0.0
57
+ oats.framework: v1.9.1 # bare version → resolves through the official catalog
58
+ oats.okf: v5.0.1
59
59
  acme.tools: git:github.com/acme/tools@v0.4.0 # outside the catalog → git:<repo>@<tag|OID>; still a package
60
60
 
61
61
  teams: # SHARED teams: the same provider team for everyone
package/lib/claim.mjs ADDED
@@ -0,0 +1,126 @@
1
+ /** The claim: one file that says which process is doing a thing that must happen once at a time.
2
+ * One protocol, used by `oats worktree add|remove` (the purpose's claim, lib/worktree.mjs
3
+ * `withClaim`) and by `oats retire` (the home's claim, lib/core.mjs `retireInstance`).
4
+ *
5
+ * Unlike lib/dir-lock.mjs, a claim left by a process that died is taken over, so a killed command
6
+ * can always be run again: the owner is named by pid AND start time (processLiveness), never by a
7
+ * pid alone, and a holder whose start cannot be read is never taken for gone.
8
+ *
9
+ * - Taking it: the owner's facts `{ pid, processStart, nonce, at }` are written to a private file
10
+ * and hard-linked to `path`, which fails if `path` exists. So a claim is never seen without its
11
+ * owner, and the nonce makes each holding distinct, even for the same process.
12
+ * - Its owner is alive: waited for up to `waitMs`, then refused (`busy`).
13
+ * - Its owner is gone (processLiveness "gone"; "unknown" is refused, never taken over): the claim
14
+ * is removed under a second claim, `<path>.reclaim-<owner nonce>`, taken by this same protocol.
15
+ * Its holder re-reads `path` and removes it only if it still names that owner. Nothing else
16
+ * removes another's claim: its owner never releases it, and a new acquirer cannot write over an
17
+ * existing file. Two takeovers of one dead owner are therefore serialized, and neither removes
18
+ * a claim made after it read. A takeover cut short leaves its own claim behind, which the next
19
+ * takeover takes over in turn, up to CLAIM_MAX_DEPTH nested levels.
20
+ * - A step the holder recorded in its claim (recordInClaim) is ended by a takeover first
21
+ * (`endHolderStep`), which refuses, keeping the claim, if the step cannot be ended.
22
+ * - Released by unlinking `path`, only while it still names this holding.
23
+ * - An unreadable claim file is never removed: the command is refused, naming the file.
24
+ *
25
+ * Everything is synchronous. What is the caller's own goes in `opts`:
26
+ * busy(holder, unknown, at) the refusal for a holder that lives (`unknown` unset) or whose
27
+ * liveness cannot be read (`unknown` is the reason); `at` is the
28
+ * claim file that names it
29
+ * ownStartUnreadable(reason, at) the refusal when this process's own start cannot be read, so
30
+ * it could not hold `at` verifiably
31
+ * unreadableClaim(at) the refusal for a claim file that does not parse
32
+ * endHolderStep(holder, at) optional: end the step a dead holder recorded
33
+ * → { owed?, remedy?, warning?, details? }
34
+ * waitMs how long a live holder is waited for (default CLAIM_WAIT_MS)
35
+ * warnings optional array a takeover's warnings are pushed to */
36
+ import { linkSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
37
+ import { randomBytes } from "node:crypto";
38
+ import { processLiveness, processStart } from "./worktree-hooks.mjs";
39
+
40
+ export const CLAIM_WAIT_MS = 3000;
41
+ const CLAIM_MAX_DEPTH = 8;
42
+ const NONCE_RE = /^[0-9a-f]{32}$/;
43
+ const pauseSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
44
+
45
+ /** The claim at `path` → its record, `{ unreadable: true }` when it does not parse, null when there is none. */
46
+ export function readClaim(path) {
47
+ try { const o = JSON.parse(readFileSync(path, "utf8")); return o && typeof o === "object" ? o : { unreadable: true }; }
48
+ catch (e) { return e.code === "ENOENT" ? null : { unreadable: true }; }
49
+ }
50
+
51
+ /** Take the claim `path` → this holding (`{ pid, processStart, nonce, at }`), to pass to
52
+ * releaseClaim. Throws the caller's refusal when it cannot be taken. The directory exists. */
53
+ export function acquireClaim(path, opts, depth = 0) {
54
+ const { busy, waitMs = CLAIM_WAIT_MS } = opts;
55
+ const own = processStart(process.pid);
56
+ if (own.state !== "alive") throw opts.ownStartUnreadable(own.reason ?? `pid ${process.pid} reads as ${own.state}`, path);
57
+ const me = { pid: process.pid, processStart: own.token, nonce: randomBytes(16).toString("hex"), at: new Date().toISOString() };
58
+ const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
59
+ writeFileSync(tmp, JSON.stringify(me) + "\n", { mode: 0o600 });
60
+ try {
61
+ const deadline = Date.now() + waitMs;
62
+ for (;;) {
63
+ try { linkSync(tmp, path); return me; }
64
+ catch (e) { if (e.code !== "EEXIST") throw e; }
65
+ const holder = readClaim(path);
66
+ if (holder === null) continue; // released in between
67
+ if (holder.unreadable) throw opts.unreadableClaim(path);
68
+ const live = processLiveness(holder);
69
+ // Unreadable is never taken for gone: the claim is kept, and the refusal names the way out.
70
+ if (live.state === "unknown") throw busy(holder, live.reason, path);
71
+ if (live.state === "gone") {
72
+ if (depth >= CLAIM_MAX_DEPTH || typeof holder.nonce !== "string" || !NONCE_RE.test(holder.nonce)) throw busy(holder, null, path);
73
+ takeOver(path, holder, opts, depth);
74
+ continue;
75
+ }
76
+ if (Date.now() >= deadline) throw busy(holder, null, path);
77
+ pauseSync(50);
78
+ }
79
+ } finally {
80
+ try { unlinkSync(tmp); } catch { /* gone */ }
81
+ }
82
+ }
83
+
84
+ /** Remove `path`, held by the dead `holder`, under the claim that serializes takeovers of it. */
85
+ function takeOver(path, holder, opts, depth) {
86
+ const reclaim = `${path}.reclaim-${holder.nonce}`;
87
+ const me = acquireClaim(reclaim, opts, depth + 1);
88
+ try {
89
+ const now = readClaim(path);
90
+ if (now?.nonce === holder.nonce) {
91
+ const ended = opts.endHolderStep?.(now, path) ?? {};
92
+ if (ended.owed) {
93
+ const e = opts.busy(now);
94
+ throw Object.assign(e, { message: `${ended.owed}; ${path} is kept and nothing was done — ${ended.remedy}`, details: { ...e.details, ...ended.details } });
95
+ }
96
+ if (ended.warning) opts.warnings?.push(ended.warning);
97
+ unlinkSync(path);
98
+ }
99
+ } finally {
100
+ releaseClaim(reclaim, me);
101
+ }
102
+ }
103
+
104
+ /** Release the claim `path`, only while it still names the holding `me`. */
105
+ export function releaseClaim(path, me) {
106
+ if (readClaim(path)?.nonce === me.nonce) { try { unlinkSync(path); } catch { /* gone */ } }
107
+ }
108
+
109
+ /** Record (or, with null, clear) a step of the holding `me` in its claim `path`, for a takeover to
110
+ * end (`endHolderStep`). Only the live holder writes its claim. */
111
+ export function recordInClaim(path, me, step) {
112
+ const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
113
+ writeFileSync(tmp, JSON.stringify({ ...me, ...(step ?? {}) }) + "\n", { mode: 0o600 });
114
+ renameSync(tmp, path);
115
+ }
116
+
117
+ /** Remove the claim `path` when its holder is verifiably gone, through the takeover above, and
118
+ * take nothing: for a claim nobody will come back for. → whether it was removed. A claim whose
119
+ * holder is alive, unknown or unreadable is left as it is. Throws what a takeover throws. */
120
+ export function removeGoneClaim(path, opts) {
121
+ const holder = readClaim(path);
122
+ if (!holder || holder.unreadable || typeof holder.nonce !== "string" || !NONCE_RE.test(holder.nonce)) return false;
123
+ if (processLiveness(holder).state !== "gone") return false;
124
+ takeOver(path, holder, opts, 0);
125
+ return readClaim(path)?.nonce !== holder.nonce;
126
+ }
package/lib/core.mjs CHANGED
@@ -45,11 +45,12 @@ import { createHash, randomUUID } from "node:crypto";
45
45
  import { fileURLToPath } from "node:url";
46
46
  import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
47
47
  import { noteRuntimeName } from "./deprecation.mjs";
48
- import { attachSessionTarget } from "./session-viewer.mjs";
48
+ import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
49
49
  import { inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
50
50
  import { appendEvent, liveWaiting, recordStartBoundary } from "./instance-events.mjs";
51
51
  import { killGroup } from "./process-group.mjs";
52
52
  import { interruptExitStatus, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
53
+ import { CLAIM_WAIT_MS, acquireClaim, releaseClaim, removeGoneClaim } from "./claim.mjs";
53
54
  import { captureLoginEnvironment } from "./login-environment.mjs";
54
55
 
55
56
  import { oatsError, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
@@ -588,7 +589,7 @@ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME
588
589
  "OATS_TEST_LOGIN_SHELL",
589
590
  // The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
590
591
  // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
591
- // process's start time on a host with procfs (lib/worktree-hooks.mjs processStart).
592
+ // process's start time on a host with procfs, and the `ps` it runs (lib/worktree-hooks.mjs processStart).
592
593
  "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS"]);
593
594
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
594
595
  const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
@@ -6147,10 +6148,11 @@ function stopRecordedChildren(children) {
6147
6148
  });
6148
6149
  }
6149
6150
 
6150
- export async function attachInstanceSession(home) {
6151
+ export async function attachInstanceSession(home, { detachKey } = {}) {
6152
+ if (detachKey !== undefined) requireDetachKey(detachKey);
6151
6153
  const s = instanceSessionTarget(home);
6152
6154
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
6153
- return attachSessionTarget(s.target);
6155
+ return attachSessionTarget(s.target, { detachKey });
6154
6156
  }
6155
6157
 
6156
6158
  export function inputInstanceSession(home, text) {
@@ -8177,7 +8179,9 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8177
8179
  } catch { /* the marker alone then shows RETIRING; status names its age */ }
8178
8180
  });
8179
8181
  child.unref();
8180
- writeFileSync(marker, JSON.stringify(intent, null, 2) + "\n");
8182
+ // The marker names its completion (pid and start time; the start is null when it cannot be read):
8183
+ // while that process lives, any other retire of this home is refused (refusePendingCompletion).
8184
+ writeFileSync(marker, JSON.stringify({ ...intent, completionPid: child.pid, completionStart: processStartToken(child.pid) }, null, 2) + "\n");
8181
8185
  return {
8182
8186
  retired: name, agent: found.agent.name, deferred: true, pendingMarker: marker,
8183
8187
  resultPath, logPath, completesInSec: delaySec, completionPid: child.pid,
@@ -8199,6 +8203,9 @@ const OBSOLETE_DELETE_BRANCH_SENTENCE = "this self-retire was requested with --d
8199
8203
  /** The one internal option that says the retirement completes such an intent.
8200
8204
  * A symbol, so no caller can set it from parsed arguments or JSON. */
8201
8205
  const OBSOLETE_DELETE_BRANCH = Symbol("an older self-retire intent with --delete-branch");
8206
+ /** The one internal option that says the retirement is a deferred self-retire's completion
8207
+ * (completeDeferredRetirement). A symbol, so no caller can set it from parsed arguments or JSON. */
8208
+ const COMPLETES_DEFERRED = Symbol("the completion of a deferred self-retire");
8202
8209
  export const RETIRE_DELETE_BRANCH_REFUSED = "oats retire no longer deletes branches: --delete-branch is not accepted. Retire without it; the branch is left in the repository. Inspect it there and delete it with Git if it is no longer wanted.";
8203
8210
 
8204
8211
  export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
@@ -8230,6 +8237,10 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8230
8237
  ...(Array.isArray(intent.options?.plannedExtraWorktrees) ? { plannedExtraWorktrees: intent.options.plannedExtraWorktrees } : {}),
8231
8238
  ...(Array.isArray(intent.options?.children) ? { children: intent.options.children } : {}),
8232
8239
  ...(obsoleteDeleteBranch ? { [OBSOLETE_DELETE_BRANCH]: true } : {}),
8240
+ // The retire that scheduled this completion may still hold the home's claim, about to write
8241
+ // the marker and return: it is waited for, so the two are ordered by the claim and never by
8242
+ // which process is faster.
8243
+ [COMPLETES_DEFERRED]: true,
8233
8244
  });
8234
8245
  } catch (e) {
8235
8246
  record({ ok: false, error: { code: e.code, message: e.message }, ...(e.details?.childrenStopped ? { childrenStopped: e.details.childrenStopped } : {}), ...(obsoleteDeleteBranch ? { warnings: [OBSOLETE_DELETE_BRANCH_SENTENCE] } : {}), retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` });
@@ -8259,30 +8270,153 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8259
8270
  * (awebai/oats#693): the CLI cleans that home's wake schedules. A symbol, so
8260
8271
  * the printed and JSON receipt, and a recorded one, do not carry it. */
8261
8272
  export const RETIRE_SELECTED_HOME = Symbol("oats.retireSelectedHome");
8262
- export function retireInstance(root, name, o = {}) {
8263
- if (o.deleteBranch) throw oatsError("E_BAD_ARGS", RETIRE_DELETE_BRANCH_REFUSED);
8264
- const session = o.tmuxSession || DEFAULT_TMUX_SESSION;
8265
- // self-retire: the caller IS the instance. Without --keep-dir the whole
8266
- // retirement is deferred to a detached external completion (below); with
8267
- // --keep-dir the old in-process path runs and kills the window LAST.
8268
- const self = o.self === true;
8269
- // Names are unique per agent dir only: two agents can own an instance of
8270
- // the same name (dev --purpose foo-1 and agent dev-foo). Retirement is
8271
- // destructive, so a name that resolves to several homes is refused unless
8272
- // the caller says which home (--home), and a home is accepted only when it
8273
- // is one of that name's homes under this root.
8273
+ /** An option of retireInstance: a function it calls once it holds the home's claim, has resolved
8274
+ * the home again and has found no pending self-retire, before it reads anything else. What the
8275
+ * function throws is the retire's answer, and nothing was done; what it returns, `{ children?,
8276
+ * plannedExtraWorktrees? }`, sets those two options. `oats retire` reads here what the retire
8277
+ * acts on, so that it is the state the retire starts from, never one another retire changed
8278
+ * afterwards: a guarded apply its plan, once, refusing a revision that is not the one shown
8279
+ * (E_PLAN_STALE); a plain or `--self` retire its recorded children. Against a retire in flight
8280
+ * the answer is that it is running, and neither is read. A symbol, so no caller can set it from
8281
+ * parsed arguments or JSON. */
8282
+ export const RETIRE_UNDER_CLAIM = Symbol("oats.retireUnderClaim");
8283
+ /** How many times a retire starts over because the name resolved to another home once it held the
8284
+ * claim of the first (that one removed, a same-named home of another agent made, in between). */
8285
+ const RETIRE_CLAIM_RESTARTS = 2;
8286
+
8287
+ /** The claim file of a retire of `home`: `<instances>/.oats-retirement/claims/<name>.lock`. Beside
8288
+ * the homes, never inside one: a home's bytes are what its retire observes, copies and removes. */
8289
+ function retireClaimPath(home) {
8290
+ return join(instancesRetirementRoot(dirname(home)), "claims", `${basename(home)}.lock`);
8291
+ }
8292
+
8293
+ /** The refusals of a retire of `name` (home `home`) that cannot take its claim `lock`, as
8294
+ * lib/claim.mjs asks for them. All E_LIFECYCLE_BUSY, one line, saying that nothing was done;
8295
+ * `details.lock` is the file that names the holder. */
8296
+ function retireClaimRefusals(name, home, lock) {
8297
+ const refuse = (message, details) => Object.assign(oatsError("E_LIFECYCLE_BUSY", message), { details: { instance: name, home, ...details } });
8298
+ return {
8299
+ busy: (holder, unknown, at = lock) => {
8300
+ const details = { lock: at, pid: holder?.pid ?? null, since: holder?.at ?? null };
8301
+ return unknown
8302
+ ? refuse(`whether the retire of ${name} that holds ${at} (pid ${holder?.pid ?? "?"}, recorded start ${holder?.processStart ?? "none"}) still runs cannot be read (${unknown}); nothing was done — check that pid by hand, and if it is not an oats retire, remove ${at}, then retry`, { ...details, unknown })
8303
+ : refuse(`a retire of ${name} is already running (pid ${holder?.pid ?? "?"}, since ${holder?.at ?? "?"}); nothing was done — wait for it to finish`, details);
8304
+ },
8305
+ ownStartUnreadable: (reason, at) => refuse(`this process's start time cannot be read (${reason}), so oats retire cannot hold ${at} verifiably; nothing was done`, { lock: at }),
8306
+ unreadableClaim: (at) => refuse(`${at} is not a readable claim; inspect it and remove it if no oats retire holds it; nothing was done`, { lock: at }),
8307
+ };
8308
+ }
8309
+
8310
+ /** The homes `name` resolves to under `root`, and the one a retire acts on. Names are unique per
8311
+ * agent dir only: two agents can own an instance of the same name (dev --purpose foo-1 and agent
8312
+ * dev-foo). Retirement is destructive, so a name that resolves to several homes is refused unless
8313
+ * the caller says which home (--home), and a home is accepted only when it is one of that name's
8314
+ * homes under this root. */
8315
+ function resolveRetireHome(root, name, o) {
8274
8316
  const matches = findInstanceHomes(root, name);
8275
8317
  if (!matches.length) throw oatsError("E_SESSION_UNKNOWN", `no instance named "${name}"`);
8276
8318
  const sameHome = (a, b) => { try { return realpathSync(a) === realpathSync(b); } catch { return resolve(a) === resolve(b); } };
8277
- let found;
8278
8319
  if (o.home) {
8279
- found = matches.find((m) => sameHome(m.home, o.home));
8320
+ const found = matches.find((m) => sameHome(m.home, o.home));
8280
8321
  if (!found) throw oatsError("E_HOME_MISMATCH", `instance "${name}" has no home at ${o.home} under this agents root (its home${matches.length === 1 ? " is" : "s are"} ${matches.map((m) => m.home).join(", ")})`);
8281
- } else if (matches.length > 1) {
8322
+ return found;
8323
+ }
8324
+ if (matches.length > 1) {
8282
8325
  throw oatsError("E_AMBIGUOUS_INSTANCE", `"${name}" names ${matches.length} instances under this agents root (${matches.map((m) => `${m.agent.name}: ${m.home}`).join("; ")}); retire with --home <path> to say which`);
8283
- } else {
8284
- found = matches[0];
8285
8326
  }
8327
+ return matches[0];
8328
+ }
8329
+
8330
+ /** `name` has no home under `root`: remove a retire claim of that name whose holder is gone, in
8331
+ * each instances directory the lookup searches (a retire killed after it removed the home and
8332
+ * before it released). One whose holder is alive, unknown or unreadable is left as it is. `name`
8333
+ * is the caller's: no path is built from one outside the instance-name grammar. */
8334
+ function removeAbandonedRetireClaims(root, name) {
8335
+ if (typeof name !== "string" || !INSTANCE_NAME_RE.test(name)) return;
8336
+ const dirs = new Set([...listAgents(root).map((a) => a._dir), ...capabilityAgentDirs(root).map((c) => c.dir)]);
8337
+ for (const dir of dirs) {
8338
+ const home = join(dir, "instances", name);
8339
+ const lock = retireClaimPath(home);
8340
+ // Whatever stops the removal, the answer is the same: there is no such instance.
8341
+ try { removeGoneClaim(lock, { ...retireClaimRefusals(name, home, lock), waitMs: 0 }); } catch { /* left as it is */ }
8342
+ }
8343
+ }
8344
+
8345
+ /** A deferred self-retire is scheduled for `home` and its completion has not started: every other
8346
+ * retire of the home is refused while that completion lives. The pending marker
8347
+ * (scheduleDeferredSelfRetirement) names it. Nothing refuses when there is no marker, when the
8348
+ * completion left its outcome (it failed: this retire retries it), when the marker names no
8349
+ * completion (an older kernel wrote it), when this process is that completion, or when that
8350
+ * process is gone (it died: this retire does what it owed). */
8351
+ function refusePendingCompletion(name, home) {
8352
+ const marker = retirePendingMarkerPath(home);
8353
+ if (!existsSync(marker) || existsSync(deferredRetireResultPath(home))) return;
8354
+ const pending = readJsonOrUndefined(marker);
8355
+ const pid = pending?.completionPid;
8356
+ if (!Number.isSafeInteger(pid) || pid === process.pid) return;
8357
+ const live = processLiveness({ pid, processStart: pending.completionStart });
8358
+ if (live.state === "gone") return;
8359
+ const start = typeof pending.completionStart === "string" ? pending.completionStart : "none";
8360
+ const details = { instance: name, home, lock: marker, pid, since: pending.requestedAt ?? null };
8361
+ if (live.state === "alive") throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `a retire of ${name} is already scheduled (its completion, pid ${pid}, requested at ${pending.requestedAt ?? "?"}); nothing was done — wait for it to finish`), { details });
8362
+ throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `whether the completion of the scheduled retire of ${name} that ${marker} names (pid ${pid}, recorded start ${start}) still runs cannot be read (${live.reason}); nothing was done — check that pid by hand, and if it is not an oats retire, remove ${marker}, then retry`), { details: { ...details, unknown: live.reason } });
8363
+ }
8364
+
8365
+ /** Retire one instance. One retire of a home at a time (awebai/oats#863): the home's claim
8366
+ * (retireClaimPath; lib/claim.mjs) is taken as soon as the home is resolved, before anything the
8367
+ * retire acts on is read, and held until this returns or throws. Any other retire of that home
8368
+ * is refused at once (E_LIFECYCLE_BUSY) before it stops, copies or runs anything; `--force` does
8369
+ * not bypass it. A claim left by a killed retire is taken over. Every apply path runs this
8370
+ * function: the CLI, the deferred completion, and `--server` on the host. Synchronous. */
8371
+ export function retireInstance(root, name, o = {}) {
8372
+ if (o.deleteBranch) throw oatsError("E_BAD_ARGS", RETIRE_DELETE_BRANCH_REFUSED);
8373
+ let found;
8374
+ try { found = resolveRetireHome(root, name, o); }
8375
+ catch (e) {
8376
+ if (e.code === "E_SESSION_UNKNOWN") removeAbandonedRetireClaims(root, name);
8377
+ throw e;
8378
+ }
8379
+ for (let restarts = 0; ; restarts++) {
8380
+ const lock = retireClaimPath(found.home);
8381
+ const refusals = retireClaimRefusals(name, found.home, lock);
8382
+ // The retirement root as retire makes it for its recovery copies; the claims are private.
8383
+ mkdirSync(instancesRetirementRoot(dirname(found.home)), { recursive: true });
8384
+ mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
8385
+ // No waiting: a live holder is refused at once. Only a deferred completion waits, for the
8386
+ // retire that scheduled it to return.
8387
+ const me = acquireClaim(lock, { ...refusals, waitMs: o[COMPLETES_DEFERRED] ? CLAIM_WAIT_MS : 0 });
8388
+ try {
8389
+ // Resolved again under the claim: another retire may have removed the home between the
8390
+ // first resolution and the claim. Gone is what a retire of a retired instance answers.
8391
+ const now = resolveRetireHome(root, name, o);
8392
+ if (retireClaimPath(now.home) !== lock) {
8393
+ // The name is another home's now, whose claim this does not hold: start over on that one.
8394
+ if (restarts >= RETIRE_CLAIM_RESTARTS) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `the home of ${name} changed while its claim was being taken (it is now ${now.home}); nothing was done — retry`), { details: { instance: name, home: now.home, lock: retireClaimPath(now.home) } });
8395
+ found = now;
8396
+ continue;
8397
+ }
8398
+ // Every retire that runs here, in this process: a `--self` that only schedules answers that
8399
+ // one is already scheduled (scheduleDeferredSelfRetirement).
8400
+ if (o.self !== true || o.keepDir) refusePendingCompletion(name, now.home);
8401
+ // What the caller confirms once nobody else can be retiring this home (a guarded apply reads
8402
+ // its plan and checks the revision): after the two answers above, before the retire reads
8403
+ // anything of the home. What it returns of the plan binds the retire.
8404
+ const confirmed = o[RETIRE_UNDER_CLAIM]?.();
8405
+ const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}) } : o;
8406
+ return retireClaimed(root, name, bound, now);
8407
+ } finally {
8408
+ releaseClaim(lock, me);
8409
+ }
8410
+ }
8411
+ }
8412
+
8413
+ /** The retire of the home `found`, under its claim (retireInstance). */
8414
+ function retireClaimed(root, name, o, found) {
8415
+ const session = o.tmuxSession || DEFAULT_TMUX_SESSION;
8416
+ // self-retire: the caller IS the instance. Without --keep-dir the whole
8417
+ // retirement is deferred to a detached external completion (below); with
8418
+ // --keep-dir the old in-process path runs and kills the window LAST.
8419
+ const self = o.self === true;
8286
8420
  const metaPath = join(found.home, "instance.json");
8287
8421
  // A QUARANTINED home (spawn failed after a required hook and compensation did
8288
8422
  // not finish) has no instance.json — it never got that far. Its marker carries