@awebai/oats 0.57.1 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/bin/oats.mjs +24 -11
  2. package/docs/configuration.md +2 -1
  3. package/docs/desktop-cli-api.md +105 -17
  4. package/docs/desktop.md +30 -3
  5. package/docs/execution-targets.md +15 -0
  6. package/docs/implementation.md +2 -0
  7. package/docs/integrations.md +2 -2
  8. package/docs/knowledge.md +4 -4
  9. package/docs/official-catalog.md +4 -4
  10. package/docs/packages.md +14 -14
  11. package/docs/release-notes/v0.58.0.md +107 -0
  12. package/docs/release-notes/v0.59.0.md +288 -0
  13. package/docs/servers.md +4 -1
  14. package/docs/souls-and-instances.md +30 -0
  15. package/docs/tui.md +653 -117
  16. package/docs/workspaces.md +2 -2
  17. package/lib/core.mjs +227 -46
  18. package/lib/read-ahead-worker.mjs +119 -0
  19. package/lib/read-ahead.mjs +115 -0
  20. package/lib/retire-state.mjs +33 -0
  21. package/lib/servers.mjs +9 -1
  22. package/lib/session-input.mjs +14 -4
  23. package/package-catalog.json +3 -3
  24. package/package.json +1 -1
  25. package/packages/client/cli-locator.mjs +2 -2
  26. package/packages/client/deployment-data.mjs +4 -0
  27. package/packages/client/deployment-panel.mjs +3 -0
  28. package/packages/client/instance-acts.mjs +23 -8
  29. package/packages/client/instance-presentation.mjs +3 -2
  30. package/packages/client/instance-tree.mjs +84 -39
  31. package/packages/client/lifecycle-confirmation.mjs +9 -3
  32. package/packages/client/panel-views.mjs +1 -1
  33. package/packages/client/remote-roster.mjs +4 -1
  34. package/packages/client/retire-in-flight.mjs +65 -0
  35. package/packages/client/retire-state.mjs +30 -0
  36. package/packages/client/spawn-apply-cli.mjs +8 -2
  37. package/packages/client/spawn-apply.mjs +20 -7
  38. package/packages/client/spawn-preview-cli.mjs +2 -1
  39. package/packages/client/spawn-preview.mjs +30 -18
  40. package/packages/record/lib/directory-identity.mjs +14 -0
  41. package/packages/record/lib/native-history.mjs +6 -5
  42. package/packages/tui/README.md +23 -10
  43. package/packages/tui/lib/actions.mjs +63 -5
  44. package/packages/tui/lib/client.mjs +12 -1
  45. package/packages/tui/lib/config.mjs +7 -2
  46. package/packages/tui/lib/main.mjs +315 -82
  47. package/packages/tui/lib/model.mjs +523 -56
  48. package/packages/tui/lib/panel.mjs +519 -144
  49. package/packages/tui/lib/read.mjs +52 -26
  50. package/packages/tui/lib/store.mjs +908 -65
  51. package/packages/tui/lib/term/keys.mjs +9 -2
  52. package/packages/tui/lib/term/text.mjs +4 -0
  53. package/packages/tui/lib/term/through.mjs +12 -1
  54. package/packages/tui/lib/views/frame.mjs +394 -95
  55. package/packages/tui/lib/views/help.mjs +54 -13
  56. package/packages/tui/lib/views/instances.mjs +43 -25
  57. package/packages/tui/lib/views/palette.mjs +61 -0
  58. package/packages/tui/lib/views/souls.mjs +268 -0
  59. package/packages/tui/lib/views/spawn.mjs +299 -0
  60. package/packages/tui/lib/views/split.mjs +29 -0
  61. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -4,6 +4,8 @@
4
4
  * no element: a client draws from these answers with its own means. */
5
5
  import { waitingClaim } from './waiting-on-you.mjs';
6
6
  import { byRuntimeState } from './instance-presentation.mjs';
7
+ import { retireData } from './retire-state.mjs';
8
+ import { displayLine } from './display-text.mjs';
7
9
 
8
10
  export function collapseKey(workspace, instance) {
9
11
  return `${workspace || ""}\u0000${instance}`;
@@ -54,6 +56,15 @@ export function resolveLinkId(fromInstance, name, byName) {
54
56
  return sameRoot.length === 1 ? instanceId(sameRoot[0]) : null;
55
57
  }
56
58
 
59
+ /** The roster's order, a comparator for `sort`: by instance name, ties broken by `instanceId`, so it is total and
60
+ * deterministic. It ranks roots, siblings under one parent, and so clusters (by their first root). A start or a
61
+ * stop moves no row; only adding or removing one does (Pepe's decision on #1262, comment 6196531154, which
62
+ * replaces #1083's running-first order for the roster). The one place the roster's order is decided. */
63
+ function rosterOrder(a, b) {
64
+ const ia = instanceId(a), ib = instanceId(b);
65
+ return String(a.instance).localeCompare(String(b.instance)) || (ia < ib ? -1 : ia > ib ? 1 : 0);
66
+ }
67
+
57
68
  /** Group instances into agent CLUSTERS — connected components of the
58
69
  * undirected relation graph (parent/child spawn edges + sibling links).
59
70
  * Unrelated instances are single-node clusters. Within a cluster the
@@ -62,7 +73,9 @@ export function resolveLinkId(fromInstance, name, byName) {
62
73
  * Nodes are keyed by instanceId (composite identity), never bare name —
63
74
  * duplicate names across repos render as distinct nodes.
64
75
  * Returns [{ key, instances: [{...instance, depth}] }] with clusters ranked by
65
- * their first member in the roster's order (`byRuntimeState`), as the panel is. */
76
+ * their first ROOT in the roster's order (`rosterOrder`), never by another member (#1262): a bundle sits where
77
+ * its root sits, and gaining or losing a child, or a start or a stop, moves nothing. A cluster without a root
78
+ * (a malformed cycle) ranks by its first member in that order. */
66
79
  export function clusterInstances(instances, { links = instanceLinks } = {}) {
67
80
  const byId = new Map(instances.map((i) => [instanceId(i), i]));
68
81
  const byName = new Map();
@@ -86,7 +99,7 @@ export function clusterInstances(instances, { links = instanceLinks } = {}) {
86
99
  adj.get(oid).add(id);
87
100
  }
88
101
  }
89
- const rank = byRuntimeState;
102
+ const rank = rosterOrder;
90
103
  const seen = new Set();
91
104
  const clusters = [];
92
105
  for (const start of [...instances].sort(rank)) {
@@ -122,11 +135,12 @@ export function clusterInstances(instances, { links = instanceLinks } = {}) {
122
135
  // Deterministic cluster label: the lexically-smallest ROOT name —
123
136
  // independent of liveness, so the visible cluster name does not flip
124
137
  // when a different member starts/stops running (review f921f7d nit).
125
- // `rank` (running, unknown, stopped) still governs display ORDER within the cluster.
138
+ // `rank` (rosterOrder: by name) governs display ORDER within the cluster.
126
139
  const rootNames = (roots.length ? roots : members).map((i) => i.instance).sort();
127
- clusters.push({ key: rootNames[0], instances: ordered });
140
+ clusters.push({ key: rootNames[0], instances: ordered, head: roots[0] ?? [...members].sort(rank)[0] });
128
141
  }
129
- return clusters;
142
+ // Stable: clusters whose heads rank equal keep the order they were found in (the roster's order of members).
143
+ return clusters.sort((a, b) => rank(a.head, b.head)).map(({ head: _head, ...c }) => c);
130
144
  }
131
145
 
132
146
  /** Find the roster instance a UI reference means. References carry the
@@ -214,22 +228,52 @@ const HELD_HOMES = Object.freeze({
214
228
  sentence: name => `${name} is setting up its worktree. It can't be used until the spawn finishes.` },
215
229
  "spawn-incomplete": { state: "Spawn didn't finish", hint: "Retire it to clean up", status: "Spawn didn't finish", retire: true,
216
230
  sentence: name => `The spawn of ${name} didn't finish. Retire it to clean up.` },
231
+ // #1247: a retire that runs (or whose holder's liveness can't be read): Retire stays offered, secondary.
232
+ retiring: { state: "Retiring…", status: "Retiring…", retire: "secondary",
233
+ sentence: name => `${name} is being retired.` },
234
+ "retire-failed": { state: "Retire failed", hint: "Retire it again to finish", status: "Retire failed", retire: true,
235
+ sentence: name => `The retire of ${name} failed. Retire it again to finish.` },
217
236
  "retire-incomplete": { state: "Retire didn't finish", hint: "Retire it again to complete", status: "Retire didn't finish", retire: true,
218
237
  sentence: name => `The retire of ${name} didn't finish. Retire it again to complete.` },
219
238
  });
220
- /** What the kernel's roster row says holds this home, or null (#802): `spawning` while a spawn that
221
- * runs its worktree hooks is verifiably alive (`spawnInProgress: true`), `spawn-incomplete` when a
222
- * spawn left it for retire to clean up (`rollbackIncomplete`), `retire-incomplete` when a retire did
223
- * (`retirePending`). rollbackIncomplete wins over spawnInProgress (the spawn is gone, not live), and a
224
- * live spawn over retirePending (the kernel refuses to retire it). Every surface draws such a row from
225
- * this: a spawning one starts, stops, retires and splits nothing; a quarantined one (`retire`) offers
226
- * Retire only. `state` is the row's text, `hint` its muted line, `status` the hover card's Status.
227
- * `sentence` is every client's, so it promises no act of one client: a spawning home "can't be used
228
- * until the spawn finishes", whoever started the spawn and whether or not it ends finished. */
239
+ /** Which retire kind a row's kernel facts are (#1247), or null: the kernel's `retire` (retire-state.mjs, read
240
+ * again here: a value out of the contract is absent); a row with no `retire` but `retirePending` (a kernel or a
241
+ * host before `status-retire-state`) reads `retiring`. */
242
+ function retireKind(instance) {
243
+ const retire = retireData(instance.retire);
244
+ if (retire) return retire.state === "failed" ? "retire-failed" : retire.state === "interrupted" ? "retire-incomplete" : "retiring";
245
+ return instance.retirePending ? "retiring" : null;
246
+ }
247
+ /** What the kernel's roster row says holds this home, or null (#802, #1247): `spawning` while a spawn
248
+ * that runs its worktree hooks is verifiably alive (`spawnInProgress: true`), `spawn-incomplete` when a
249
+ * spawn left it for retire to clean up (`rollbackIncomplete`); then the retire kinds (`retireKind`):
250
+ * `retiring` while a retire runs, its holder can't be read, the row is an older kernel's `retirePending`
251
+ * or this client's own retire is in flight; `retire-failed` when a self-retire's completion recorded an
252
+ * error; `retire-incomplete` when a scheduled completion is gone without an outcome. A retire this client
253
+ * started and has not read the roster after (retire-in-flight.mjs `retireInFlight`) is `retiring` whatever
254
+ * the row says: it is the newest fact, and the kernel refuses it (letting the row go) where a live spawn
255
+ * holds the home. Of the kernel's facts, rollbackIncomplete wins over spawnInProgress (the spawn is gone,
256
+ * not live), and a live spawn over a retire (the kernel refuses to retire it). Every surface draws such a row from this: a spawning or retiring one starts,
257
+ * stops, restarts and opens nothing new; one with `retire` offers Retire only, and `retire: "secondary"`
258
+ * (retiring: a second retire is refused while one runs, and safe) offers it out of the way (instance-acts.mjs).
259
+ * `state` is the row's text, `hint` its muted line (none while retiring), `status` the hover card's Status.
260
+ * `sentence` is every client's, so it promises no act of one client: a spawning home "can't be used until
261
+ * the spawn finishes", whoever started the spawn and whether or not it ends finished. `said` is what the
262
+ * row's reason says (instance-acts.mjs): the sentence, or for a failed retire with a recorded message or code the
263
+ * kernel's words (`message`, `code`, or `message (code)`) with `origin: "kernel"`, shown only through the display
264
+ * filter. */
229
265
  export function heldHome(instance) {
230
- const kind = !instance ? null : instance.rollbackIncomplete ? "spawn-incomplete"
231
- : instance.spawnInProgress === true ? "spawning" : instance.retirePending ? "retire-incomplete" : null;
232
- return kind ? { kind, ...HELD_HOMES[kind] } : null;
266
+ const kind = !instance ? null : instance.retireInFlight === true ? "retiring" : instance.rollbackIncomplete ? "spawn-incomplete"
267
+ : instance.spawnInProgress === true ? "spawning" : retireKind(instance);
268
+ if (!kind) return null;
269
+ const held = HELD_HOMES[kind], retire = kind === "retire-failed" ? retireData(instance.retire) : null;
270
+ // The kernel's words, message or code, are said as the kernel's, and shown only through the display filter; one the
271
+ // filter reduces to nothing (blank) says nothing; one it withholds is said, and shown withheld. With neither, the row's own words stand.
272
+ const shown = text => (text && displayLine(text) !== null ? text : null);
273
+ const message = shown(retire?.message), code = shown(retire?.code);
274
+ const said = message || code ? { sentence: message && code ? `${message} (${code})` : message || code, origin: "kernel" }
275
+ : { sentence: held.sentence(instance.instance) };
276
+ return { kind, ...held, said };
233
277
  }
234
278
 
235
279
  /* ── roster grouping: repo → agent family (soul), with sort modes ── */
@@ -239,9 +283,8 @@ export const ROSTER_SORTS = Object.freeze([
239
283
  Object.freeze({ id: "name", label: "Name" }),
240
284
  ]);
241
285
 
242
- /** Comparator for one sibling level. "status" is the roster's one order
243
- * (`byRuntimeState`: running, unknown, stopped, then by name); "name" is purely
244
- * alphabetical. Unknown ids fall back to "status" so a stale persisted choice
286
+ /** Comparator for one sibling level. "status" is `byRuntimeState` (running, unknown, stopped, then by name:
287
+ * #1083's order, which the roster no longer uses, #1262); "name" is purely alphabetical. No client calls it. Unknown ids fall back to "status" so a stale persisted choice
245
288
  * can never break rendering. */
246
289
  export function rosterRank(sortBy) {
247
290
  const byName = (a, b) => String(a.instance).localeCompare(String(b.instance));
@@ -355,30 +398,32 @@ export function visibleClusters(allInstances, visibleInstances, { links = instan
355
398
  .filter((c) => c.instances.length);
356
399
  }
357
400
 
358
- /** The sidebar roster's groups (Redesign v3), shared with the command palette:
359
- * each multi-member relation cluster under its deterministic name, then every
360
- * unrelated instance under "independent". A cluster's group is decided on the
361
- * FULL roster: more than one member there is a group under the cluster's name,
362
- * exactly one goes under "independent". A filter or a collapse decides which
363
- * rows are listed and never moves a row to another group; a group with no
364
- * visible row is left out. Returns [{ key, label, clusters: [{ key, instances }] }]
365
- * in the full roster's cluster order, each cluster projected to its visible
366
- * members, which carry their tree depth. A group's key is unique even when two
367
- * roots share a name (other agents roots or hosts), and does not depend on what
368
- * is visible: the label is the name, the key adds the cluster's place among the
369
- * multi-member clusters of the full roster. */
401
+ /** The sidebar roster's groups (Redesign v3), shared with the command palette and the TUI: the full roster's
402
+ * clusters in their one order (#1262), each multi-member relation cluster a group under its deterministic name,
403
+ * and each RUN of consecutive single-instance clusters one "independent" group, in place. So an instance that
404
+ * gains its first child stays where it was and becomes a group there; losing its last child, it rejoins the run
405
+ * at the same place. A cluster's group is decided on the FULL roster: a filter or a collapse decides which rows
406
+ * are listed and never moves a row to another group; a group with no visible row is left out. Returns
407
+ * [{ key, label, clusters: [{ key, instances }] }], each cluster projected to its visible members, which carry
408
+ * their tree depth. A group's key is unique even when two roots share a name (other agents roots or hosts), and
409
+ * does not depend on what is visible: a cluster's is `cluster:<its place among the full roster's multi-member
410
+ * clusters>:<name>`, a run's `independent:<instanceId of its first member in the full roster>`. */
370
411
  export function rosterGroups(allInstances, visibleInstances, { links = instanceLinks } = {}) {
371
412
  const visibleIds = new Set(visibleInstances.map((i) => instanceId(i)));
372
- const named = [], independent = [];
373
- let place = 0;
413
+ const groups = [];
414
+ let place = 0, run = null;
374
415
  for (const c of clusterInstances(allInstances, { links })) {
375
- const at = c.instances.length > 1 ? place++ : -1;
376
416
  const shown = { ...c, instances: c.instances.filter((i) => visibleIds.has(instanceId(i))) };
377
- if (!shown.instances.length) continue;
378
- if (at < 0) independent.push(shown);
379
- else named.push({ key: `cluster:${at}:${c.key}`, label: c.key, clusters: [shown] });
417
+ if (c.instances.length > 1) {
418
+ run = null;
419
+ const at = place++;
420
+ if (shown.instances.length) groups.push({ key: `cluster:${at}:${c.key}`, label: c.key, clusters: [shown] });
421
+ continue;
422
+ }
423
+ if (!run) { run = { key: `independent:${instanceId(c.instances[0])}`, label: "independent", clusters: [] }; groups.push(run); }
424
+ if (shown.instances.length) run.clusters.push(shown);
380
425
  }
381
- return [...named, ...(independent.length ? [{ key: "independent", label: "independent", clusters: independent }] : [])];
426
+ return groups.filter((g) => g.clusters.length);
382
427
  }
383
428
 
384
429
  /** Whether an item remains visible under VS Code-style collapsed ancestors.
@@ -28,7 +28,7 @@
28
28
  * { type: 'rows', rows: [{ text, quote? }] } a stop's results or a retire's children
29
29
  * { type: 'lines', lines: [{ text, path? }] } what a retire did
30
30
  * applyRunningSentence(running, terms) -> the sentence for an apply of this client that is still running
31
- * createLifecycleConfirmation({ request, target, operation, terms, onSettled, onChange, label, leftover })
31
+ * createLifecycleConfirmation({ request, target, operation, terms, onSettled, onChange, label, leftover, retires })
32
32
  * -> { state(), view(), setChoice(id, value), refresh(), apply(), checkAgain(), close() }
33
33
  */
34
34
  import { lifecyclePlan, lifecycleOptions, planReference, lifecycleReason, lifecycleDetailCode, publicLifecycleReceipt, decodedStoppedTargets,
@@ -325,8 +325,11 @@ const SETTLED_OFFERS = Object.freeze({ complete: ['close'], partial: ['refresh',
325
325
  * `onSettled(result, target)` is called once for every apply answer that reads and is not a return to review;
326
326
  * what it does or throws changes nothing here. `label`: the server's label for a routed row; `leftover`: the row
327
327
  * is a home a failed spawn left. Each step carries this confirmation's latest-intent token: an answer to an
328
- * earlier step, or one after close, changes nothing and is not told. Nothing is kept beyond the instance. */
329
- export function createLifecycleConfirmation({ request, target, operation, terms, onSettled = () => {}, onChange = () => {}, label = null, leftover = false, choices: initial = null } = {}) {
328
+ * earlier step, or one after close, changes nothing and is not told. Nothing is kept beyond the instance.
329
+ * `retires` (#1247): the client's retires in flight (retire-in-flight.mjs). Every apply of a retire is begun
330
+ * there before it is sent and settled with its answer's kind, whether or not the confirmation is still open
331
+ * or that answer is still the latest: the row reads Retiring… from the send until the roster was read after it. */
332
+ export function createLifecycleConfirmation({ request, target, operation, terms, onSettled = () => {}, onChange = () => {}, label = null, leftover = false, choices: initial = null, retires = null } = {}) {
330
333
  requireTerms(terms, 'createLifecycleConfirmation');
331
334
  if (typeof request !== 'function' || !target?.instance || !['stop', 'retire'].includes(operation)) throw new TypeError('createLifecycleConfirmation: a request, a target and an operation (stop or retire)');
332
335
  let choices = lifecycleOptions(operation, initial) ?? (operation === 'stop' ? { recursive: true } : { discardWorktree: false });
@@ -372,9 +375,12 @@ export function createLifecycleConfirmation({ request, target, operation, terms,
372
375
  current = { kind: 'applying', title: `${operation === 'retire' ? 'Retiring' : 'Stopping'} ${target.instance}…`,
373
376
  message: operation === 'retire' ? `Retiring ${target.instance}. This can take up to a minute while sessions stop.` : `Stopping ${target.instance}. This can take up to a minute.` };
374
377
  tell('applying', { view: current });
378
+ let own = null;
379
+ if (operation === 'retire') { try { own = retires?.begin(target) ?? null; } catch { /* the hold is a drawing aid only */ } }
375
380
  let result = null, view;
376
381
  try { result = await request({ action: 'apply', planRef: reference }); view = outcomeView(result, { target, operation, choices, plan: snapshot, leftover }, terms); }
377
382
  catch { view = outcomeView(null, { target, operation, choices, plan: snapshot, leftover }, terms); }
383
+ try { own?.settle(view.kind); } catch { /* as above */ }
378
384
  if (mine !== ticket || closed) return;
379
385
  if (view.kind === 'stale') {
380
386
  plan = view.plan; planRef = view.planRef; shown = view.plan; notice = view.notice; phase = 'review';
@@ -14,7 +14,7 @@
14
14
  * rosterAnswered, // boolean: a roster answer arrived under the current CLI
15
15
  * rosterFailure, // string | null: the roster read's failure while no answer has arrived
16
16
  * cli, // the kernel record (cli-locator.mjs)
17
- * observing, // Set<deployment id>: a read in flight
17
+ * observing, // keyed by deployment id (`has`): a read in flight
18
18
  * remoteCollecting, // boolean: the remote roster is being read
19
19
  * home, // string: the user's home directory, for the short label
20
20
  * at, // string: the ISO time of this call
@@ -2,6 +2,7 @@ import { harnessOf } from "./harness-names.mjs";
2
2
  import { unsupportedSession, unsupportedSessionOrigin, hasRuntimeError } from "./instance-presentation.mjs";
3
3
  import { madeByKernel } from "./kernel-made.mjs";
4
4
  import { waitingOnYouData } from "./waiting-on-you.mjs";
5
+ import { retireData } from "./retire-state.mjs";
5
6
  import { readIdentity } from "./workspace-views.mjs";
6
7
  /** Projection of the installed CLI's remote roster. Never reads remote paths locally. */
7
8
  export function remoteWorkspace(group) {
@@ -43,7 +44,7 @@ export function remotePanel(group, at) {
43
44
  // A row's soul subtitle: its own group's soul list only, a string as the host reported it, never synthesized.
44
45
  const described = name => { const soul = (group.souls || []).find((a) => a?.name === name); return typeof soul?.description === "string" ? soul.description : null; };
45
46
  // A Herdr-recorded row is unsupported whatever the host's probe said: it cannot open or start.
46
- const instances = (group.instances || []).map(({ runtime: _released, runtimeErrorOrigin: _sent, ...i }) => {
47
+ const instances = (group.instances || []).map(({ runtime: _released, runtimeErrorOrigin: _sent, retire: sentRetire, ...i }) => {
47
48
  const unsupported = unsupportedSession(i);
48
49
  const origin = unsupported ? unsupportedSessionOrigin(i) : group.probe.ok || (group.probe.error?.message && madeByKernel(group.probe.error)) ? "kernel" : "roster-read";
49
50
  const row = {
@@ -58,6 +59,8 @@ export function remotePanel(group, at) {
58
59
  tmux: i.tmux || null, git: i.git || null, task: i.task || "", next: i.next || "",
59
60
  // Needs input: only a remote kernel with the feature reports it — validated, never synthesized when absent.
60
61
  ...(Object.hasOwn(i, "waitingOnYou") ? { waitingOnYou: waitingOnYouData(i.waitingOnYou) } : {}),
62
+ // #1247: the host's retire state, relayed unchanged when it is in the contract (retire-state.mjs), else absent.
63
+ ...(retireData(sentRetire) ? { retire: retireData(sentRetire) } : {}),
61
64
  ...(unsupported ? { running: null, runtimeState: "unsupported", runtimeError: unsupported } : {}),
62
65
  };
63
66
  return hasRuntimeError(row) && origin ? { ...row, runtimeErrorOrigin: origin } : row;
@@ -0,0 +1,65 @@
1
+ /** Retires this client started, read as Retiring… before the roster says so (#1247). One per client: the
2
+ * Desktop's window and the TUI's run each keep one, and their lifecycle confirmations tell it
3
+ * (lifecycle-confirmation.mjs `retires`).
4
+ *
5
+ * createRetiresInFlight({ mark, onChange }) -> { begin, landed, ids, holds }
6
+ * mark() the client's read mark now: a value that grows with every roster read the client
7
+ * begins (a counter, a clock); compared with `>` only
8
+ * onChange() the set changed: the client draws its rows again
9
+ * begin(target) an apply of a retire of `target` (a row's identity: server and home) starts. The row
10
+ * is held from now. Answers `{ settle(kind) }`, for the apply's answer: an outcome kind
11
+ * of lifecycle-confirmation.mjs `outcomeView`
12
+ * landed(at, covers?) an owned roster read the client began at mark `at` was read. A held row whose
13
+ * retire has answered, and whose answer came before that read began, is let go, when
14
+ * `covers(target)` says this read covers its row (default: every row)
15
+ * ids() the held rows' instanceIds
16
+ * holds(row) whether `row` is held
17
+ *
18
+ * retiringRows(rows, ids) -> rows, each held one copied with `retireInFlight: true`
19
+ *
20
+ * A row is held from the moment an apply starts until its answer is in and the roster was read after it, and
21
+ * while any other apply of a retire of it is held (a second Retire, offered while one runs, is one).
22
+ * An answer that ran nothing (a refusal, `refused`; a plan that changed under it, `stale`) lets its apply go at
23
+ * once: with no other apply held, the row reads again as the roster says. Any other answer (complete, partial, unknown, pending, unreadable)
24
+ * holds it until a read: that read says what the retire left. instance-tree.mjs `heldHome` reads
25
+ * `retireInFlight` as `retiring`. Nothing is kept beyond the client's run. */
26
+ import { instanceId } from './instance-tree.mjs';
27
+
28
+ const RAN_NOTHING = new Set(['refused', 'stale']);
29
+
30
+ export function createRetiresInFlight({ mark, onChange = () => {} } = {}) {
31
+ if (typeof mark !== 'function') throw new TypeError('createRetiresInFlight: a mark of the client\'s roster reads');
32
+ // instanceId -> { target, applies }: every apply of a retire of that row, each `{ settled, after }`. The row is
33
+ // held while any one holds it, so an answer to a later apply (a refusal: one is still running) never lets go
34
+ // of an earlier one that has not answered or was not read after.
35
+ const held = new Map();
36
+ const changed = () => { try { onChange(); } catch { /* a client's drawing changes nothing here */ } };
37
+ const drop = (id, entry, apply) => { entry.applies.delete(apply); if (!entry.applies.size && held.get(id) === entry) held.delete(id); };
38
+ return {
39
+ begin(target) {
40
+ const id = instanceId(target), entry = held.get(id) ?? { target, applies: new Set() }, apply = { settled: false, after: undefined };
41
+ entry.applies.add(apply); held.set(id, entry); changed();
42
+ return {
43
+ settle(kind) {
44
+ if (apply.settled || !entry.applies.has(apply)) return;
45
+ apply.settled = true;
46
+ if (RAN_NOTHING.has(kind)) { drop(id, entry, apply); changed(); } else apply.after = mark();
47
+ },
48
+ };
49
+ },
50
+ landed(at, covers = () => true) {
51
+ const before = held.size;
52
+ for (const [id, entry] of held) {
53
+ if (!covers(entry.target)) continue;
54
+ for (const apply of [...entry.applies]) if (apply.settled && at > apply.after) drop(id, entry, apply);
55
+ }
56
+ if (held.size !== before) changed();
57
+ },
58
+ ids: () => new Set(held.keys()),
59
+ holds: row => !!row && held.has(instanceId(row)),
60
+ };
61
+ }
62
+
63
+ export function retiringRows(rows, ids) {
64
+ return ids?.size ? rows.map(row => ids.has(instanceId(row)) ? { ...row, retireInFlight: true } : row) : rows;
65
+ }
@@ -0,0 +1,30 @@
1
+ /** A retire of a home, as the kernel's roster row reports it (#1247, feature `status-retire-state`): the
2
+ * row's `retire`, absent while no retire runs, is scheduled or is owed.
3
+ *
4
+ * retire: { state, since, self, code?, message? }
5
+ * state 'running' a retire holds the home's claim with a live holder, or a self-retire's
6
+ * completion is alive (its 8 s wait counts)
7
+ * 'unknown' that holder's liveness cannot be read
8
+ * 'failed' a self-retire's completion recorded an error (`code`, `message`)
9
+ * 'interrupted' a scheduled completion is gone and left no outcome
10
+ * since a string (the kernel's ISO time)
11
+ * self a boolean: a self-retire
12
+ * code an `E_…` code; message: a string: what a failed completion recorded
13
+ *
14
+ * `retireData` is the one reading of it every place that carries row facts uses (deployment-data.mjs,
15
+ * deployment-panel.mjs, remote-roster.mjs, the Desktop's active-observation.mjs): the value when it is the
16
+ * contract's, else null, and a client then holds the row as if it had none. Never guessed, never repaired: one
17
+ * field out of the contract drops the whole value (an optional field is absent or a string, never null).
18
+ * `retirePending` is a fact of its own and stays as the kernel reports it. Text in `message` and `code` is the kernel's: a client
19
+ * shows it only through display-text.mjs `displayLine`, as instance-acts.mjs says for a reason with an `origin`. */
20
+ export const RETIRE_STATES = Object.freeze(['running', 'unknown', 'failed', 'interrupted']);
21
+ const CODE = /^E_[A-Z0-9_]+$/;
22
+
23
+ export function retireData(value) {
24
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
25
+ if (!RETIRE_STATES.includes(value.state) || typeof value.since !== 'string' || typeof value.self !== 'boolean') return null;
26
+ const { code, message } = value;
27
+ if (code !== undefined && !(typeof code === 'string' && CODE.test(code))) return null;
28
+ if (message !== undefined && typeof message !== 'string') return null;
29
+ return { state: value.state, since: value.since, self: value.self, ...(code !== undefined ? { code } : {}), ...(message !== undefined ? { message } : {}) };
30
+ }
@@ -45,7 +45,13 @@ function refusal(doc, cli) {
45
45
  export async function cliSpawnApply(cli, options = {}, io = {}) {
46
46
  // Repeat the complete positive mode fence here, before even creating inputs.
47
47
  if (!spawnApplySupported(cli)) return failure('E_APPLY_UNAVAILABLE');
48
- if (!record(options) || Object.keys(options).some(k => !['target', 'choices', 'task', 'wake', 'decision', 'key', 'deadlineMs'].includes(k))) return failure('E_BAD_ARGS');
48
+ if (!record(options) || Object.keys(options).some(k => !['target', 'choices', 'task', 'wake', 'decision', 'key', 'deadlineMs', 'maxAge'].includes(k))) return failure('E_BAD_ARGS');
49
+ // Feature spawn-apply-max-age (#1246 K1): the kernel may reuse deployment observations up to maxAge seconds old.
50
+ // Only beside --expect-decision, which fences a drifted decision, and only where the CLI lists it (an older
51
+ // kernel refuses the flag).
52
+ const maxAge = options.maxAge;
53
+ if (maxAge !== undefined && (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 3600)) return failure('E_BAD_ARGS');
54
+ const reuse = maxAge !== undefined && Array.isArray(cli.features) && cli.features.includes('spawn-apply-max-age') ? ['--max-age', String(maxAge)] : [];
49
55
  // The broker derives the deadline from the confirmed preview (spawnApplyDeadlineMs); 60 s without one.
50
56
  const timeout = options.deadlineMs ?? SPAWN_APPLY_MS;
51
57
  if (!spawnApplyDeadline(timeout)) return failure('E_BAD_ARGS');
@@ -60,7 +66,7 @@ export async function cliSpawnApply(cli, options = {}, io = {}) {
60
66
  if (input.wake) wakeFile = writeTaskFile(JSON.stringify(input.wake), io);
61
67
  const choices = input.choices;
62
68
  const argv = ['spawn', target.selector.soul, '--dir', target.context, '--agents-root', target.selector.agentsRoot, ...choiceArgv(choices, cli)];
63
- argv.push('--expect-decision', decision.revision, '--idempotency-key', options.key, '--task-file', taskFile.file);
69
+ argv.push('--expect-decision', decision.revision, ...reuse, '--idempotency-key', options.key, '--task-file', taskFile.file);
64
70
  if (wakeFile) argv.push('--wake-file', wakeFile.file);
65
71
  argv.push('--json');
66
72
  const env = { ...(io.env ?? process.env) };
@@ -12,7 +12,7 @@ import { retainedSpawnDetails, LAUNCH_DIAGNOSTIC_BYTES, FLAG_IGNORED_BYTES } fro
12
12
  import { randomBytes } from 'node:crypto';
13
13
  import { performance } from 'node:perf_hooks';
14
14
  import { cliSpawnApply } from './spawn-apply-cli.mjs';
15
- import { admitSpawnSelection } from './spawn-preview.mjs';
15
+ import { admitSpawnSelection, PREVIEW_MAX_AGE_S } from './spawn-preview.mjs';
16
16
  import { record } from './spawn-preview-contract.mjs';
17
17
  import { spawnApplySupported, spawnApplyChoicesSupported, spawnPrepareInput, spawnRefInput, spawnPreparedData, spawnReference,
18
18
  spawnCreationReceipt, spawnApplyFailure, spawnApplyDeadlineMs, ROLLED_BACK_CODES, WAKE_OUTCOME_UNKNOWN } from './spawn-apply-contract.mjs';
@@ -27,19 +27,31 @@ const scopeKey = c => JSON.stringify([c?.workspace?.id, c?.workspace?.scope, c?.
27
27
  * reads through the dialog's cache: a fresh held answer for exactly these choices is the decision (no second
28
28
  * CLI read); apply's --expect-decision is the drift guard. No held answer: a fresh read.
29
29
  * exec optional: the client's own execFile, passed to `invoke` as `invoke(cli, options, { exec })` for every
30
- * apply (cli-adapter.mjs `runJson` has the rule); without it `invoke` is given no third argument and
31
- * cliSpawnApply's own default runs. An apply is a change: its options carry `detached: true`
30
+ * apply (cli-adapter.mjs `runJson` has the rule); without it (and without `applyTimer`) `invoke` is
31
+ * given no third argument and cliSpawnApply's own default runs. An apply is a change: its options carry `detached: true`
32
32
  * whatever exec is given, which runs it in a session of its own (as execFileInSession does). On a
33
33
  * worktree-event kernel cliSpawnApply ends the child at the deadline through what exec returns
34
34
  * (`child.kill`): a given exec must return the child. One that returns nothing leaves that apply
35
35
  * unended at its deadline; there is no fallback here. On a kernel without worktree-event the options'
36
36
  * `timeout` is the apply's only deadline: exec must honour it as execFileInSession does, killing the
37
- * child when it passes and reporting `killed` even if the child then exits cleanly. */
38
- export function createSpawnApplyBoundary({ read, invoke = cliSpawnApply, exec,
37
+ * child when it passes and reporting `killed` even if the child then exits cleanly.
38
+ * applyTimer optional: the timer the apply's own deadline and its SIGTERM grace are armed on, passed to
39
+ * `invoke` as `io.timer` beside `exec` (cliSpawnApply's `timer(fn, ms)`, which returns its cancel).
40
+ * Without it `invoke` is given none, and cliSpawnApply arms them on setTimeout, as before. It is for
41
+ * a client that lets go of an apply when it ends (the TUI on quit): it gives its own timer and clears
42
+ * it then, so its process neither signals the apply nor is kept alive by its deadline, and the apply
43
+ * runs to its own end, unsupervised (the kernel's own limits bound it). `timer` is the boundary's own
44
+ * wait for an answer (answerWithinMs), which it does not pass on.
45
+ * maxAge seconds the kernel may reuse its deployment observations for the apply (#1246 K1: the member heads'
46
+ * ls-remote wave at the press). Passed to `invoke` only where the apply's CLI lists spawn-apply-max-age;
47
+ * null never. The fence is unchanged: apply's --expect-decision refuses a drifted decision (E_DECISION_STALE). */
48
+ export function createSpawnApplyBoundary({ read, invoke = cliSpawnApply, exec, applyTimer, maxAge = PREVIEW_MAX_AGE_S,
39
49
  now = () => performance.now(), mint = () => randomBytes(32).toString('hex'), answerWithinMs = ANSWER_WITHIN_MS,
40
50
  timer = (fn, ms) => { const t = setTimeout(fn, ms); return () => clearTimeout(t); } } = {}) {
41
51
  if (typeof read !== 'function') throw new TypeError('createSpawnApplyBoundary: read (the client\'s prepareRead) is required');
42
- const prepared = new Map(), submitted = new Map(), active = new Set(), io = exec ? [{ exec }] : [];
52
+ if (applyTimer !== undefined && typeof applyTimer !== 'function') throw new TypeError('createSpawnApplyBoundary: applyTimer, when given, is a timer(fn, ms) that returns its cancel');
53
+ const given = { ...(exec ? { exec } : {}), ...(applyTimer ? { timer: applyTimer } : {}) };
54
+ const prepared = new Map(), submitted = new Map(), active = new Set(), io = Object.keys(given).length ? [given] : [];
43
55
  let preparing = 0, reservedBytes = 0;
44
56
  const denied = (code, entry = null, status = 'unavailable', message) => spawnApplyFailure(code, { target: entry?.target, spawnRef: entry?.ref, status, message });
45
57
  const sweep = () => { for (const map of [prepared, submitted]) for (const [ref, entry] of map) if (!entry.pending && entry.expires <= now()) map.delete(ref); };
@@ -170,7 +182,8 @@ export function createSpawnApplyBoundary({ read, invoke = cliSpawnApply, exec,
170
182
  if (!same(entry, latest)) reply = denied('E_PLAN_CHANGED', entry, 'refused');
171
183
  else {
172
184
  const result = await invoke(latest.cli, { target: clone(entry.target), choices: clone(entry.input.choices), task: entry.input.task,
173
- ...(entry.input.wake ? { wake: clone(entry.input.wake) } : {}), decision: clone(entry.preview.decision), key: entry.key, deadlineMs: entry.deadlineMs }, ...io);
185
+ ...(entry.input.wake ? { wake: clone(entry.input.wake) } : {}), decision: clone(entry.preview.decision), key: entry.key, deadlineMs: entry.deadlineMs,
186
+ ...(maxAge !== null && latest.cli?.features?.includes('spawn-apply-max-age') ? { maxAge } : {}) }, ...io);
174
187
  reply = interpret(result, entry, latest.cli);
175
188
  }
176
189
  } catch { reply = denied('E_OUTCOME_UNKNOWN', entry, 'unknown'); }
@@ -16,7 +16,8 @@ export function cliSpawnPreview(cli, options = {}, io = {}) {
16
16
  const target = previewTarget(options.target), choices = previewChoices(options.choices);
17
17
  if (!target || !choices || Object.keys(options).some(k => !['target', 'choices', 'maxAge'].includes(k))) return Promise.resolve(failure('E_BAD_ARGS'));
18
18
  // Feature spawn-preview-max-age: reuse member heads the kernel observed within maxAge seconds. Only
19
- // where the CLI advertises it (an older kernel refuses the flag); prepare and apply never pass it.
19
+ // where the CLI advertises it (an older kernel refuses the flag); prepare never passes it. The apply's own
20
+ // --max-age is spawn-apply-max-age's (spawn-apply-cli.mjs).
20
21
  const maxAge = options.maxAge;
21
22
  if (maxAge !== undefined && (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 3600)) return Promise.resolve(failure('E_BAD_ARGS'));
22
23
  const reuse = maxAge !== undefined && Array.isArray(cli.features) && cli.features.includes('spawn-preview-max-age') ? ['--max-age', String(maxAge)] : [];
@@ -3,12 +3,14 @@
3
3
  *
4
4
  * A client makes its own preview (createSpawnPreview) and owns it: nothing here is
5
5
  * held at module level, so two clients' budgets, caches and flights never meet.
6
- * The cache (60 s, keyed by the admission identity) serves the dialog's preview
7
- * read and prepare's: an answer is still admitted against the current context
8
- * before it is returned, and a workspace's entries go when the client observes a
9
- * change that can alter a preview (the Desktop's: server/oats-web.mjs). Prepare taking
10
- * a held decision is safe because apply binds it with the kernel's --expect-decision:
11
- * a decision the kernel no longer makes is refused there (E_DECISION_STALE), never applied. */
6
+ * The cache (keyed by the admission identity) serves the dialog's preview read for
7
+ * 60 s and prepare's for PREPARE_REUSE_MS (#1246: the prepared intent's own lifetime,
8
+ * so a press after the operator lingered over the form runs no second kernel preview):
9
+ * an answer is still admitted against the current context before it is returned, and a
10
+ * workspace's entries go when the client observes a change that can alter a preview (the
11
+ * Desktop's: server/oats-web.mjs). Prepare taking a held decision is safe because apply
12
+ * binds it with the kernel's --expect-decision: a decision the kernel no longer makes is
13
+ * refused there (E_DECISION_STALE, read as drifted), never applied. */
12
14
  import { dirname } from 'node:path';
13
15
  import { performance } from 'node:perf_hooks';
14
16
  import { cliSpawnPreview } from './spawn-preview-cli.mjs';
@@ -24,24 +26,31 @@ export function createSpawnPreviewFlights() {
24
26
  }
25
27
  const missing = (factory, what) => new TypeError(`${factory}: ${what} is required`);
26
28
  export const PREVIEW_CACHE_TTL_MS = 60000;
29
+ /** How old a held answer prepare may take (#1246): the lifetime of the intent it prepares. */
30
+ export const PREPARE_REUSE_MS = 300000;
27
31
  // A name refusal answers the same name the same way until something changes.
28
32
  const CACHED_REFUSALS = ['E_INSTANCE_NAME_TAKEN', 'E_INSTANCE_NAME_INVALID'];
29
33
  const cacheable = result => result?.status === 'available' || result?.status === 'unavailable' && CACHED_REFUSALS.includes(result.reason?.code);
30
- /** `clock` is the flights' clock (createSpawnPreviewFlights): required, never a clock of its own. */
31
- export function createSpawnPreviewCache({ ttlMs = PREVIEW_CACHE_TTL_MS, limit = 64, now = () => performance.now(), clock } = {}) {
34
+ /** `clock` is the flights' clock (createSpawnPreviewFlights): required, never a clock of its own. An entry is kept
35
+ * for `keepMs` (at least `ttlMs`) from when it was read; `get(identity, maxAgeMs)` answers it only while it is
36
+ * younger than `maxAgeMs` (default `ttlMs`): the dialog's reads take 60 s, prepare's PREPARE_REUSE_MS. */
37
+ export function createSpawnPreviewCache({ ttlMs = PREVIEW_CACHE_TTL_MS, keepMs = ttlMs, limit = 64, now = () => performance.now(), clock } = {}) {
32
38
  if (typeof clock !== 'function') throw missing('createSpawnPreviewCache', 'clock (the flights\' clock)');
33
39
  const entries = new Map(), invalidatedAt = new Map();
34
40
  let clearedAt = 0;
41
+ const kept = Math.max(ttlMs, keepMs);
35
42
  return {
36
- get(identity) {
43
+ get(identity, maxAgeMs = ttlMs) {
37
44
  const entry = entries.get(identity);
38
45
  if (!entry) return null;
39
46
  if (now() >= entry.expires) { entries.delete(identity); return null; }
47
+ if (now() - entry.readAt >= maxAgeMs) return null; // too old for this reader; a longer-lived one may still take it
40
48
  return structuredClone(entry.result);
41
49
  },
42
50
  set(identity, workspace, result, startedAt) {
43
51
  if (!cacheable(result) || typeof startedAt !== 'number' || startedAt <= clearedAt || startedAt <= (invalidatedAt.get(workspace) ?? 0)) return;
44
- entries.delete(identity); entries.set(identity, { workspace, result: structuredClone(result), expires: now() + ttlMs });
52
+ const readAt = now();
53
+ entries.delete(identity); entries.set(identity, { workspace, result: structuredClone(result), readAt, expires: readAt + kept });
45
54
  for (const [key, entry] of entries) if (now() >= entry.expires) entries.delete(key);
46
55
  while (entries.size > limit) entries.delete(entries.keys().next().value);
47
56
  },
@@ -93,8 +102,9 @@ export function admitSpawnSelection(selector, choices, { workspace: w, cli, agen
93
102
  /** One read of a preview. `flights` (createSpawnPreviewFlights) is required: the reads of one preview share it,
94
103
  * and a cache given here must run on its clock. maxAge: the dialog's reads may reuse member heads the kernel
95
104
  * observed within that many seconds (feature spawn-preview-max-age, passed only when the admitted CLI
96
- * advertises it). Prepare's reads never do. exec: as createSpawnPreview's. */
97
- export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = null, maxAge = null, flights, exec } = {}) {
105
+ * advertises it). Prepare's reads never do. heldMs: how old a held answer this read takes (default: the cache's
106
+ * TTL). exec: as createSpawnPreview's. */
107
+ export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = null, maxAge = null, heldMs, flights, exec } = {}) {
98
108
  if (!flights?.slots || !flights.byInvoker || !flights.started || typeof flights.clock !== 'function') throw missing('createSpawnPreviewBoundary', 'flights (createSpawnPreviewFlights)');
99
109
  if (cache && cache.clock !== flights.clock) throw new TypeError('createSpawnPreviewBoundary: the cache must run on the flights\' clock');
100
110
  const { slots, byInvoker, started } = flights, io = exec ? [{ exec }] : [];
@@ -106,7 +116,7 @@ export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = n
106
116
  const selected = admitSpawnSelection(selector, choices, getContext());
107
117
  if (selected.error) return previewFailure(selected.error);
108
118
  const { target, identity, cli } = selected;
109
- const held = cache?.get(identity);
119
+ const held = cache?.get(identity, heldMs);
110
120
  if (held) return held; // admitted above against the current context, like a fresh answer
111
121
  let pending = byInvoker.get(invoke); if (!pending) { pending = new Map(); byInvoker.set(invoke, pending); }
112
122
  const reuse = maxAge !== null && cli.features.includes('spawn-preview-max-age') ? { maxAge } : {};
@@ -134,19 +144,21 @@ export const PREVIEW_MAX_AGE_S = 60;
134
144
  * read the dialog's read, through the cache; its kernel reads may reuse recent member heads (maxAge,
135
145
  * where the CLI declares spawn-preview-max-age)
136
146
  * prepareRead prepare's read (spawn-apply.mjs createSpawnApplyBoundary's `read`), through the same cache,
137
- * never with maxAge; a reusing read and a live one never coalesce
147
+ * taking a held answer up to `prepareReuseMs` old (PREPARE_REUSE_MS), never with maxAge; a reusing
148
+ * read and a live one never coalesce
138
149
  * cache `invalidate(workspace?)` (no argument: every workspace's answers) and `size()`
139
150
  * The two reads share one two-slot budget, one set of coalesced flights and one clock, the cache's too.
140
151
  * exec optional: the client's own execFile, passed to `invoke` as `invoke(cli, options, { exec })` for both
141
152
  * reads (cli-adapter.mjs `runJson` has the rule); without it `invoke` is given no third argument and
142
153
  * cliSpawnPreview's own default runs. A read is a read: its options carry no `detached` and a 30 s
143
154
  * deadline, and it ends with its caller. */
144
- export function createSpawnPreview({ invoke = cliSpawnPreview, exec, now = () => performance.now(), ttlMs = PREVIEW_CACHE_TTL_MS, limit = 64, maxAge = PREVIEW_MAX_AGE_S } = {}) {
155
+ export function createSpawnPreview({ invoke = cliSpawnPreview, exec, now = () => performance.now(), ttlMs = PREVIEW_CACHE_TTL_MS,
156
+ prepareReuseMs = PREPARE_REUSE_MS, limit = 64, maxAge = PREVIEW_MAX_AGE_S } = {}) {
145
157
  const flights = createSpawnPreviewFlights();
146
- const cache = createSpawnPreviewCache({ ttlMs, limit, now, clock: flights.clock });
158
+ const cache = createSpawnPreviewCache({ ttlMs, keepMs: prepareReuseMs, limit, now, clock: flights.clock });
147
159
  return {
148
- read: createSpawnPreviewBoundary({ invoke, cache, maxAge, flights, exec }),
149
- prepareRead: createSpawnPreviewBoundary({ invoke, cache, flights, exec }),
160
+ read: createSpawnPreviewBoundary({ invoke, cache, maxAge, heldMs: ttlMs, flights, exec }),
161
+ prepareRead: createSpawnPreviewBoundary({ invoke, cache, heldMs: prepareReuseMs, flights, exec }),
150
162
  cache: { invalidate: workspace => cache.invalidate(workspace), size: () => cache.size() },
151
163
  };
152
164
  }
@@ -0,0 +1,14 @@
1
+ /** Whether `actual` ({dev, ino, birthtimeNs?}, read now) is the directory `recorded` names.
2
+ * The inode is the identity: on one volume a different directory has a different inode.
3
+ * macOS gives an APFS volume a new `dev` each time it is mounted, so after a reboot `dev`
4
+ * no longer matches; there an equal inode is enough, unless the record holds a birth time
5
+ * (a decimal string of ns), which must then match too. Birth time is not an identity (it can
6
+ * be set, and copies keep it): it closes only the gap a dropped `dev` opens, another volume
7
+ * showing the same inode. A record without one, or with "0" (no birth times on that volume),
8
+ * is judged by the inode alone. Elsewhere `dev` and `ino` must both match. */
9
+ export function sameDirectory(recorded, actual, platform = process.platform) {
10
+ if (!recorded || !actual || recorded.ino !== actual.ino) return false;
11
+ if (recorded.dev === actual.dev) return true;
12
+ if (platform !== "darwin") return false;
13
+ return recorded.birthtimeNs === undefined || recorded.birthtimeNs === "0" || recorded.birthtimeNs === actual.birthtimeNs;
14
+ }