@awebai/oats 0.58.0 → 0.60.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 (63) hide show
  1. package/bin/oats.mjs +1 -1
  2. package/docs/desktop-cli-api.md +80 -8
  3. package/docs/desktop.md +30 -3
  4. package/docs/execution-targets.md +18 -2
  5. package/docs/implementation.md +3 -0
  6. package/docs/integrations.md +2 -2
  7. package/docs/knowledge.md +4 -4
  8. package/docs/official-catalog.md +4 -4
  9. package/docs/packages.md +14 -14
  10. package/docs/release-notes/v0.59.0.md +288 -0
  11. package/docs/release-notes/v0.60.0.md +104 -0
  12. package/docs/servers.md +4 -1
  13. package/docs/souls-and-instances.md +21 -0
  14. package/docs/tui.md +753 -119
  15. package/docs/workspaces.md +2 -2
  16. package/lib/core.mjs +258 -57
  17. package/lib/read-ahead-worker.mjs +119 -0
  18. package/lib/read-ahead.mjs +115 -0
  19. package/lib/retire-state.mjs +33 -0
  20. package/lib/servers.mjs +9 -1
  21. package/lib/session-input.mjs +53 -26
  22. package/package-catalog.json +3 -3
  23. package/package.json +1 -1
  24. package/packages/client/capability-catalog.mjs +93 -0
  25. package/packages/client/capability-facts.mjs +59 -0
  26. package/packages/client/capability-rows.mjs +121 -0
  27. package/packages/client/catalog-messages.mjs +12 -0
  28. package/packages/client/cli-locator.mjs +2 -2
  29. package/packages/client/deployment-data.mjs +4 -0
  30. package/packages/client/deployment-panel.mjs +3 -0
  31. package/packages/client/instance-acts.mjs +23 -8
  32. package/packages/client/instance-presentation.mjs +3 -2
  33. package/packages/client/instance-tree.mjs +84 -39
  34. package/packages/client/lifecycle-confirmation.mjs +9 -3
  35. package/packages/client/remote-roster.mjs +4 -1
  36. package/packages/client/retire-in-flight.mjs +65 -0
  37. package/packages/client/retire-state.mjs +30 -0
  38. package/packages/client/soul-catalog.mjs +8 -0
  39. package/packages/client/soul-facts.mjs +7 -0
  40. package/packages/client/spawn-apply.mjs +13 -4
  41. package/packages/client/spawn-messages.mjs +8 -0
  42. package/packages/client/subsequence-score.mjs +15 -0
  43. package/packages/tui/README.md +23 -10
  44. package/packages/tui/lib/actions.mjs +63 -5
  45. package/packages/tui/lib/client.mjs +17 -1
  46. package/packages/tui/lib/config.mjs +7 -2
  47. package/packages/tui/lib/main.mjs +364 -82
  48. package/packages/tui/lib/model.mjs +614 -57
  49. package/packages/tui/lib/panel.mjs +436 -125
  50. package/packages/tui/lib/read.mjs +52 -26
  51. package/packages/tui/lib/store.mjs +1025 -65
  52. package/packages/tui/lib/term/keys.mjs +9 -2
  53. package/packages/tui/lib/term/text.mjs +4 -0
  54. package/packages/tui/lib/term/through.mjs +12 -1
  55. package/packages/tui/lib/views/capabilities.mjs +239 -0
  56. package/packages/tui/lib/views/frame.mjs +433 -99
  57. package/packages/tui/lib/views/help.mjs +61 -15
  58. package/packages/tui/lib/views/instances.mjs +43 -25
  59. package/packages/tui/lib/views/palette.mjs +66 -0
  60. package/packages/tui/lib/views/souls.mjs +270 -0
  61. package/packages/tui/lib/views/spawn.mjs +301 -0
  62. package/packages/tui/lib/views/split.mjs +29 -0
  63. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -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.12.0 # bare version → resolves through the official catalog
58
- oats.okf: v5.2.0
57
+ oats.framework: v1.12.3 # bare version → resolves through the official catalog
58
+ oats.okf: v5.2.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/core.mjs CHANGED
@@ -38,7 +38,7 @@ import {
38
38
  } from "node:fs";
39
39
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
40
40
  import { homedir } from "node:os";
41
- import { accessSync, constants as fsConstants } from "node:fs";
41
+ import { accessSync, constants as fsConstants, fstatSync } from "node:fs";
42
42
  import { recordLocalInput } from "./local-inputs.mjs";
43
43
  import { createHash, randomUUID } from "node:crypto";
44
44
  import { fileURLToPath } from "node:url";
@@ -46,11 +46,12 @@ import { initializeNativeHistory, prepareNativeStart } from "../packages/record/
46
46
  import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
47
47
  import { noteRuntimeName } from "./deprecation.mjs";
48
48
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
49
- import { inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
49
+ import { createSessionPaneInspector, inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
50
50
  import { appendEvent, incarnationOf, liveWaiting, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
51
51
  import { killGroup } from "./process-group.mjs";
52
52
  import { interruptExitStatus, isStartToken, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
53
53
  import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
54
+ import { isInstant as isInstantString, readRetireState } from "./retire-state.mjs";
54
55
  import { captureLoginEnvironment } from "./login-environment.mjs";
55
56
  import { kernelNode } from "./stable-node.mjs";
56
57
 
@@ -76,12 +77,14 @@ import { validateBindingInterface } from "./provider-binding.mjs";
76
77
  /** Retirement/rollback tree fingerprint (exported for scope tests: kernel-field neutrality is opt-in per instance home),
77
78
  * the exact digest a copied path is compared with (exported so a test holds it to the copier),
78
79
  * a worktree's byte digest and the Git directories it leaves out (exported so a test holds them to exact paths),
79
- * and the receipts the stored digest passes over in a home (exported so a test holds the manifest grammar to refusing each of them). */
80
- export { exactTreeDigest, fingerprintTree, KERNEL_HOME_RECEIPTS, storedTreeDigest, worktreeBytes, worktreeGitPaths };
80
+ * the receipts the stored digest passes over in a home (exported so a test holds the manifest grammar to refusing each of them),
81
+ * and a worktree's untracked and ignored digest, alone and with its bytes from one read (exported so a test holds the one read to the two apart). */
82
+ export { exactTreeDigest, fingerprintTree, generatedWorkDigest, KERNEL_HOME_RECEIPTS, storedTreeDigest, worktreeBytes, worktreeDigests, worktreeGitPaths };
81
83
 
82
84
  import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
83
85
  import { readPortableBytes } from "./bounded-read.mjs";
84
86
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.mjs";
87
+ import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
85
88
  import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
86
89
  import { systemTool } from "./system-tools.mjs";
87
90
  import { creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
@@ -5167,8 +5170,8 @@ export function servedIdentityLine(identity) {
5167
5170
  /** The window names of `session` on the tmux server at `socket`: `{ windows }`, empty when the server
5168
5171
  * or the session is gone, with `missingSocket` (tmux's words) when the socket file is missing, which
5169
5172
  * alone does not say the server is gone (#624); `{ error }` when the server could not be read. */
5170
- function recordedTmuxWindows(socket, session) {
5171
- try { return { windows: tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"]).split("\n").filter(Boolean) }; }
5173
+ function recordedTmuxWindows(socket, session, io) {
5174
+ try { return { windows: tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], io).split("\n").filter(Boolean) }; }
5172
5175
  catch (e) {
5173
5176
  const absence = tmuxServerAbsence(e);
5174
5177
  if (absence === "missing-socket") return { windows: [], missingSocket: tmuxFailure(e, "tmux list-windows failed") };
@@ -5176,20 +5179,46 @@ function recordedTmuxWindows(socket, session) {
5176
5179
  return { error: String(e.stderr ?? e.message ?? "").trim() || "tmux list-windows failed" };
5177
5180
  }
5178
5181
  }
5179
- /** A status row's liveness from its session's windows: unknown (not false) when the server could not
5182
+ /** A status row's harness liveness from its session's panes: unknown (not false) when the server could not
5180
5183
  * be read, and, for a row whose server holds its endpoint (`endpoint`), when its socket file is
5181
5184
  * missing while a process works in the home or the scan (`scanHome()`, processesInHome's answer for
5182
5185
  * it) cannot tell (#624). */
5183
- function tmuxLiveness({ windows, error, missingSocket }, window, scanHome, endpoint) {
5186
+ function tmuxLiveness({ windows, error, missingSocket, panes }, window, scanHome, endpoint, inspectPanes) {
5184
5187
  if (error) return { running: null, runtimeState: "unreachable", runtimeError: error };
5185
5188
  const running = windows.includes(window);
5186
5189
  const why = !running && missingSocket && endpoint ? missingSocketUnestablished(missingSocket, scanHome()) : null;
5187
- return why ? { running: null, runtimeState: "unreachable", runtimeError: why } : { running };
5190
+ if (why) return { running: null, runtimeState: "unreachable", runtimeError: why };
5191
+ if (!running) return { running: false };
5192
+ try {
5193
+ const observed = inspectPanes(panes.get(window) ?? []);
5194
+ return { running: harnessRunning(observed), ...(observed.state === "shell" ? { runtimeState: "shell" } : {}) };
5195
+ } catch (e) { return { running: null, runtimeState: "unreachable", runtimeError: tmuxFailure(e, "tmux pane inspection failed") }; }
5196
+ }
5197
+ /** One extra read per socket/session, never per row. Keep window discovery's missing-socket
5198
+ * handling; a failed pane read after successful discovery is unknown, not proof of a stop. */
5199
+ function statusTmuxPanes(snapshot, socket, session, io) {
5200
+ if (!snapshot.windows?.length) return snapshot;
5201
+ try {
5202
+ const args = ["list-panes", "-s", "-t", `=${session}`, "-F", "#{window_name}\t#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"];
5203
+ const output = socket ? tmuxOn(socket, args, io) : (io?.exec || execFileSync)("tmux", ["-u", ...args], {
5204
+ encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
5205
+ });
5206
+ const panes = new Map();
5207
+ for (const line of output.split("\n").filter(Boolean)) {
5208
+ const tab = line.indexOf("\t");
5209
+ if (tab < 0) throw new Error("invalid tmux pane response");
5210
+ const window = line.slice(0, tab);
5211
+ if (!panes.has(window)) panes.set(window, []);
5212
+ panes.get(window).push(line.slice(tab + 1));
5213
+ }
5214
+ return { ...snapshot, panes };
5215
+ } catch (e) { return { error: tmuxFailure(e, "tmux list-panes failed") }; }
5188
5216
  }
5189
5217
  export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5190
5218
  // Liveness reads each home's RECORDED endpoint (a pre-0.31 home records pi-agents): the recorded
5191
- // socket, never the ambient $TMUX server, once per socket and session per call, so status costs no
5192
- // more child processes as homes grow. A home without a recorded socket reads the default server.
5219
+ // socket, never the ambient $TMUX server: one window read and one pane read per socket/session,
5220
+ // plus one lazy process scan for shell descendants, independent of the number of homes.
5221
+ // A home without a recorded socket reads the default server.
5193
5222
  // A row whose socket file is missing is checked against one process scan of the host, made the
5194
5223
  // first time a row needs it and shared by every row (`io` reaches it: processesInHome).
5195
5224
  let hostScan;
@@ -5197,10 +5226,12 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5197
5226
  hostScan ??= hostProcesses(io);
5198
5227
  return hostScan.ok ? { ok: true, processes: processesWorkingIn(hostScan.processes, home) } : hostScan;
5199
5228
  };
5229
+ const inspectPanes = createSessionPaneInspector(io);
5200
5230
  const tmuxByEndpoint = new Map();
5201
5231
  const windowsOf = (session, socket) => {
5202
5232
  const key = JSON.stringify([socket ?? null, session]);
5203
- if (!tmuxByEndpoint.has(key)) tmuxByEndpoint.set(key, socket ? recordedTmuxWindows(socket, session) : defaultTmuxWindows(session));
5233
+ if (!tmuxByEndpoint.has(key)) tmuxByEndpoint.set(key, statusTmuxPanes(
5234
+ socket ? recordedTmuxWindows(socket, session, io) : defaultTmuxWindows(session), socket, session, io));
5204
5235
  return tmuxByEndpoint.get(key);
5205
5236
  };
5206
5237
  const readInstancesOf = (agentDir) => {
@@ -5236,11 +5267,12 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5236
5267
  // owed a retirement, not live work. Read-only here — completion is the
5237
5268
  // detached child's or an operator's `oats retire`, never status.
5238
5269
  const pending = retirePendingMarkerPath(home);
5239
- let retirePending;
5270
+ let retirePending, marker;
5240
5271
  if (existsSync(pending)) {
5241
- try { retirePending = JSON.parse(readFileSync(pending, "utf8")); }
5242
- catch { retirePending = { reason: "retire pending" }; }
5272
+ try { retirePending = JSON.parse(readFileSync(pending, "utf8")); marker = { read: retirePending }; }
5273
+ catch { retirePending = { reason: "retire pending" }; marker = { read: undefined }; }
5243
5274
  }
5275
+ const retire = retireStateOf(home, marker);
5244
5276
  // A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
5245
5277
  // A home whose record cannot be read is listed, never observed: where its session is, is in the record.
5246
5278
  const liveness = record.state === "unreadable" ? { running: null, runtimeState: "unreachable", runtimeError: `E_UNIDENTIFIED_INSTANCE_HOME: ${unreadableRecordSaid(record)}` }
@@ -5249,7 +5281,7 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5249
5281
  : tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name, scanOf(home),
5250
5282
  // A home that records no socket and no launch (--no-launch) reads the default server only
5251
5283
  // by default: that server's missing socket says nothing about it, and stays "not running".
5252
- !!meta.tmux?.socket || meta.launched === true);
5284
+ !!meta.tmux?.socket || meta.launched === true, inspectPanes);
5253
5285
  const identity = servedIdentityOf(meta);
5254
5286
  // Feature desktop-facts: `startedAt` — the last session start or restart (the receipt's restarts[]),
5255
5287
  // else the spawn's own launch (createdAt), else null (never launched); `identityAddress` — the
@@ -5268,16 +5300,18 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5268
5300
  };
5269
5301
  // Feature waiting-on-you: a producer's live claim that the instance is
5270
5302
  // blocked on a human, read only for a running row (one bounded read of
5271
- // its home log); null otherwise, and null means unknown. `running` is
5272
- // the window's presence, which a crashed harness's fallback shell or a
5273
- // retained dead pane keeps: a row with a claim is shown only when its
5274
- // session is observed running a harness, as session inspect reports it.
5303
+ // its home log); null otherwise, and null means unknown. Pane liveness is
5304
+ // already observed in the batch; still require the independent receipt
5305
+ // to agree before showing a claim, just as session inspect does.
5275
5306
  let waitingOnYou = liveness.running === true ? liveWaiting(home) : null;
5276
5307
  if (waitingOnYou) {
5277
- try { const s = instanceSessionTarget(home); if (!s.target || !harnessRunning(inspectSessionTarget(s.target))) waitingOnYou = null; }
5308
+ try { const s = instanceSessionTarget(home); if (!s.target) waitingOnYou = null; }
5278
5309
  catch { waitingOnYou = null; }
5279
5310
  }
5280
- return { ...meta, ...claims, home, instance: e.name, ...facts, ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}) };
5311
+ // `retire` is only ever the value read above: a record that carries one (hand-edited, or
5312
+ // copied from a row) never stands in for it.
5313
+ const { retire: _recordedRetire, ...recorded } = meta;
5314
+ return { ...recorded, ...claims, home, instance: e.name, ...facts, ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
5281
5315
 
5282
5316
  });
5283
5317
  };
@@ -5908,14 +5942,34 @@ const GIT_NAME = Buffer.from(".git");
5908
5942
  * `children` is for a root the copier creates itself (a home, a worktree):
5909
5943
  * its copy is made inside a directory the copier creates, so the root's bits
5910
5944
  * are no part of what it carries, and the root is compared through its
5911
- * children alone. The stored digest never holds the root's bits. */
5912
- function fingerprintTrees(root, { excludeRoot = new Set(), excludePaths = [], instanceHome = false, stored = true, digestVersion = 1, exact = false, children = false } = {}) {
5945
+ * children alone. The stored digest never holds the root's bits.
5946
+ *
5947
+ * `taps` (paths under the root, as bytes; not with the legacy digest) are
5948
+ * entries read into a digest of their own from the same read: each one's
5949
+ * stored digest of version 2, as storedTreeDigest takes it of that path
5950
+ * alone, in `taps` of the answer (a Map by the hex of the path). A tap the
5951
+ * walk does not read whole has none there: one it passes over or does not
5952
+ * reach, one inside another tap, and one that holds a path it passes over
5953
+ * (the caller does not ask for those; worktreeDigests).
5954
+ *
5955
+ * The walk reads every byte it hashes itself, in this order. While it does,
5956
+ * worker threads read the files it reads next into the page cache
5957
+ * (read-ahead.mjs), which changes nothing it computes or throws. */
5958
+ function fingerprintTrees(root, options = {}) {
5959
+ const { excludeRoot = new Set(), excludePaths = [], stored = true, digestVersion = 1 } = options;
5960
+ // The files are read ahead in this walk's order (read-ahead.mjs); the digest is the read below, alone.
5961
+ return readingAhead([root], { order: stored && digestVersion === 1 ? "locale" : "bytes", excludeRoot, excludePaths }, () => treeDigests(root, options));
5962
+ }
5963
+ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanceHome = false, stored = true, digestVersion = 1, exact = false, children = false, taps = [] } = {}) {
5913
5964
  if (stored && digestVersion !== 1 && digestVersion !== BASELINE_DIGEST_VERSION) throw new Error(`no stored digest of version ${digestVersion}`);
5914
5965
  const legacy = stored && digestVersion === 1;
5966
+ if (taps.length && legacy) throw new Error("taps are read in the order of the names' bytes, which the legacy digest does not take");
5967
+ // Each tap's digest, by the hex of its path; undefined until the walk has read it.
5968
+ const tapDigests = new Map(taps.map((tap) => [tap.toString("hex"), undefined]));
5915
5969
  const excluded = new Set(excludePaths.map((path) => path.toString("hex")));
5916
5970
  // The stored digest: `s` when it is the legacy one, `v` when it is version 2.
5917
5971
  const s = legacy ? createHash("sha256") : null, v = stored && !legacy ? createHash("sha256") : null, x = exact ? createHash("sha256") : null;
5918
- const digests = () => ({ stored: s || v ? `sha256:${(s || v).digest("hex")}` : undefined, exact: x ? `sha256:${x.digest("hex")}` : undefined });
5972
+ const digests = () => ({ stored: s || v ? `sha256:${(s || v).digest("hex")}` : undefined, exact: x ? `sha256:${x.digest("hex")}` : undefined, ...(taps.length ? { taps: tapDigests } : {}) });
5919
5973
  /** A field whose length is not fixed, in the exact digest or in version 2: its length, NUL, its bytes. */
5920
5974
  const sizedIn = (hash, bytes) => { hash.update(String(bytes.length)); hash.update("\0"); hash.update(bytes); };
5921
5975
  const sized = (bytes) => sizedIn(x, bytes);
@@ -5926,7 +5980,7 @@ function fingerprintTrees(root, { excludeRoot = new Set(), excludePaths = [], in
5926
5980
  v?.update("entry\0"); v?.update(mode); v?.update("\0");
5927
5981
  x?.update("entry\0"); x?.update(mode); x?.update("\0");
5928
5982
  if (rootStat.isSymbolicLink()) { const target = readlinkSync(root, "buffer"); s?.update("link\0"); s?.update(target); if (v) { v.update("link\0"); sizedIn(v, target); } if (x) { x.update("link\0"); sized(target); } }
5929
- else if (rootStat.isFile()) { const bytes = readFileSync(root); s?.update("file\0"); s?.update(bytes); if (v) { v.update("file\0"); sizedIn(v, bytes); } if (x) { x.update("file\0"); sized(bytes); } }
5983
+ else if (rootStat.isFile()) { const bytes = readFileSync(root); readAheadConsumed(bytes.length); s?.update("file\0"); s?.update(bytes); if (v) { v.update("file\0"); sizedIn(v, bytes); } if (x) { x.update("file\0"); sized(bytes); } }
5930
5984
  else throw unsupportedEntry(String(root));
5931
5985
  return digests();
5932
5986
  }
@@ -5935,7 +5989,8 @@ function fingerprintTrees(root, { excludeRoot = new Set(), excludePaths = [], in
5935
5989
  // `dir` and `rel` are bytes: the directory, and its path under the root
5936
5990
  // (empty at the root). `relText` is `rel` as text, for the name tests.
5937
5991
  // `storedOn` is false inside an entry the stored digest passes over.
5938
- const walk = (dir, rel, relText, storedOn) => {
5992
+ // `tap`: inside a tap, its hash and where its paths start in `rel`.
5993
+ const walk = (dir, rel, relText, storedOn, tap) => {
5939
5994
  // The legacy order is the one it has always been: the names as text,
5940
5995
  // compared by localeCompare, on the listing as readdirSync returns it.
5941
5996
  // The sort is stable and the listing is the same whether its names come
@@ -5964,25 +6019,39 @@ function fingerprintTrees(root, { excludeRoot = new Set(), excludePaths = [], in
5964
6019
  s?.update(childRel); s?.update("\0"); s?.update(mode); s?.update("\0");
5965
6020
  if (v) { sizedIn(v, childRel); v.update(mode); v.update("\0"); }
5966
6021
  if (x) { sized(childRel); x.update(mode); x.update("\0"); }
6022
+ // A tap is framed as the stored digest of version 2 frames a root of its own: a directory
6023
+ // as "tree", anything else as one entry without a path. Not one inside another: the inner
6024
+ // one is read apart.
6025
+ if (tap) { sizedIn(tap.hash, childRel.subarray(tap.at)); tap.hash.update(mode); tap.hash.update("\0"); }
6026
+ const opens = !tap && tapDigests.size && tapDigests.has(childRel.toString("hex")) ? createHash("sha256") : null;
6027
+ if (opens) opens.update(st.isDirectory() ? "tree\0" : `entry\0${mode}\0`);
6028
+ const t = tap?.hash ?? opens;
5967
6029
  if (st.isSymbolicLink()) {
5968
6030
  const target = readlinkSync(path, "buffer");
5969
6031
  s?.update("link\0"); s?.update(target); s?.update("\0");
5970
6032
  if (v) { v.update("link\0"); sizedIn(v, target); }
5971
6033
  if (x) { x.update("link\0"); sized(target); }
6034
+ if (t) { t.update("link\0"); sizedIn(t, target); }
5972
6035
  } else if (st.isFile()) {
5973
6036
  const bytes = readFileSync(path);
6037
+ readAheadConsumed(bytes.length);
5974
6038
  // Kernel-field neutrality applies ONLY when the tree IS an instance home, and only to the
5975
6039
  // stored digest; a work tree's instance.json is the agent's bytes.
5976
6040
  const storedBytes = s || v ? (instanceHome && !relText && name === "instance.json" ? kernelNeutralInstanceJson(bytes) : bytes) : undefined;
5977
6041
  s?.update("file\0"); s?.update(storedBytes); s?.update("\0");
5978
6042
  if (v) { v.update("file\0"); sizedIn(v, storedBytes); }
5979
6043
  if (x) { x.update("file\0"); sized(bytes); }
5980
- } else if (st.isDirectory()) { s?.update("dir\0"); v?.update("dir\0"); x?.update("dir\0"); walk(path, childRel, childRelText, on); }
6044
+ if (t) { t.update("file\0"); sizedIn(t, bytes); }
6045
+ } else if (st.isDirectory()) {
6046
+ s?.update("dir\0"); v?.update("dir\0"); x?.update("dir\0"); tap?.hash.update("dir\0");
6047
+ walk(path, childRel, childRelText, on, tap ?? (opens ? { hash: opens, at: childRel.length + PATH_SEPARATOR_BYTES.length } : null));
6048
+ }
5981
6049
  else throw unsupportedEntry(join(String(root), childRelText));
6050
+ if (opens) tapDigests.set(childRel.toString("hex"), `sha256:${opens.digest("hex")}`);
5982
6051
  }
5983
6052
  };
5984
6053
  const outerS = s, outerV = v;
5985
- walk(Buffer.from(root), Buffer.alloc(0), "", true);
6054
+ walk(Buffer.from(root), Buffer.alloc(0), "", true, null);
5986
6055
  return digests();
5987
6056
  }
5988
6057
  /** The legacy stored digest of a tree (fingerprintTrees, version 1): what a spawn baseline without
@@ -6090,13 +6159,28 @@ function generatedWorkFingerprintIn(digestVersion, work, statusBytes, disposable
6090
6159
  * (an entry under it without permission, for example) is no path the digest can prove anything
6091
6160
  * of: it throws E_WORK_INSPECTION_FAILED, `could not inspect <path>: <reason>`, the path as text. */
6092
6161
  function generatedWorkDigest(work, statusBytes, disposableRoots = []) {
6162
+ const paths = generatedWorkPaths(statusBytes, disposableRoots);
6163
+ return readingAhead(paths.map((rel) => generatedWorkPath(work, rel)), {}, () => generatedWorkDigestOf(work, paths));
6164
+ }
6165
+ /** The paths generatedWorkDigest reads, under the worktree, in its order: the
6166
+ * untracked and ignored ones, outside the disposable roots, as bytes. */
6167
+ function generatedWorkPaths(statusBytes, disposableRoots) {
6093
6168
  const roots = disposableRoots.map((root) => [Buffer.from(root), Buffer.from(`${root}${sep}`)]);
6094
6169
  const owned = (path) => roots.some(([root, under]) => path.equals(root) || (path.length >= under.length && path.subarray(0, under.length).equals(under)));
6095
- const paths = untrackedOrIgnoredPaths(statusBytes).filter((path) => !owned(path)).sort(Buffer.compare);
6170
+ return untrackedOrIgnoredPaths(statusBytes).filter((path) => !owned(path)).sort(Buffer.compare);
6171
+ }
6172
+ /** Where generatedWorkDigest reads the status's path `rel`: without the `/` an ignored directory's row ends in. */
6173
+ const generatedWorkPath = (work, rel) => joinBytes(work, rel.length > 1 && rel[rel.length - 1] === 0x2f ? rel.subarray(0, -1) : rel);
6174
+ /** generatedWorkDigest of `paths` (generatedWorkPaths), each read as it is in
6175
+ * there, or as `read` has it already: a Map of a path's stored digest by the
6176
+ * hex of where it is read (worktreeDigests). */
6177
+ function generatedWorkDigestOf(work, paths, read = new Map()) {
6096
6178
  const hash = createHash("sha256");
6097
6179
  for (const rel of paths) {
6098
6180
  hash.update(String(rel.length)); hash.update("\0"); hash.update(rel);
6099
- const path = joinBytes(work, rel.length > 1 && rel[rel.length - 1] === 0x2f ? rel.subarray(0, -1) : rel);
6181
+ const path = generatedWorkPath(work, rel);
6182
+ const known = read.get(path.subarray(pathBytes(work).length + PATH_SEPARATOR_BYTES.length).toString("hex"));
6183
+ if (known !== undefined) { hash.update(known); hash.update("\0"); continue; }
6100
6184
  const uninspectable = (e) => (e?.code === "E_WORK_INSPECTION_FAILED" ? e : oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path.toString()}: ${e.message}`));
6101
6185
  try { lstatSync(path); }
6102
6186
  catch (e) {
@@ -6110,6 +6194,29 @@ function generatedWorkDigest(work, statusBytes, disposableRoots = []) {
6110
6194
  }
6111
6195
  return `sha256:${hash.digest("hex")}`;
6112
6196
  }
6197
+ /** A worktree's generatedWorkDigest and its bytes (worktreeBytes) from one
6198
+ * read of each file (#1247): one walk of the worktree for its bytes, in
6199
+ * which each path of the digest that the walk reads whole is a tap
6200
+ * (fingerprintTrees), read into its stored digest from the same bytes. A
6201
+ * path it cannot read whole (one under a link or a Git directory the bytes
6202
+ * leave out, one that holds such a directory, one inside another path, one
6203
+ * that is not there) is read apart, as generatedWorkDigest reads it.
6204
+ * → { generated, bytes, gitPaths }, the values the two give apart; or
6205
+ * undefined when anything fails: the caller then takes them apart, as
6206
+ * before, so that whatever fails fails in their order, with their words. */
6207
+ function worktreeDigests(work, statusBytes, disposableRoots = []) {
6208
+ try {
6209
+ const gitPaths = worktreeGitPaths(work);
6210
+ const paths = generatedWorkPaths(statusBytes, disposableRoots);
6211
+ const under = pathBytes(work).length + PATH_SEPARATOR_BYTES.length;
6212
+ const holdsLeftOut = (rel) => gitPaths.some((git) => git.length > rel.length && git[rel.length] === PATH_SEPARATOR_BYTES[0] && git.subarray(0, rel.length).equals(rel));
6213
+ const taps = paths.map((rel) => generatedWorkPath(work, rel).subarray(under)).filter((rel) => rel.length && !holdsLeftOut(rel));
6214
+ const { exact, taps: read } = fingerprintTrees(work, { stored: false, exact: true, excludePaths: gitPaths, children: true, taps });
6215
+ return { generated: generatedWorkDigestOf(work, paths, read ?? new Map()), bytes: exact, gitPaths };
6216
+ } catch {
6217
+ return undefined;
6218
+ }
6219
+ }
6113
6220
  /** The legacy generatedWorkFingerprint (digest version 1), for a baseline without `digestVersion`.
6114
6221
  * It never changes: the decoded status's paths, tested with existsSync, which follows a link. */
6115
6222
  function generatedWorkFingerprint(work, status, disposableRoots = []) {
@@ -6117,14 +6224,16 @@ function generatedWorkFingerprint(work, status, disposableRoots = []) {
6117
6224
  const paths = status.split("\0").filter(Boolean)
6118
6225
  .filter((row) => row.startsWith("?? ") || row.startsWith("!! "))
6119
6226
  .map((row) => row.slice(3)).filter((path) => !owned(path)).sort();
6120
- const hash = createHash("sha256");
6121
- for (const rel of paths) {
6122
- const path = join(work, rel);
6123
- hash.update(rel); hash.update("\0");
6124
- if (!existsSync(path)) { hash.update("missing\0"); continue; }
6125
- hash.update(fingerprintTree(path)); hash.update("\0");
6126
- }
6127
- return `sha256:${hash.digest("hex")}`;
6227
+ return readingAhead(paths.map((rel) => join(work, rel)), { order: "locale" }, () => {
6228
+ const hash = createHash("sha256");
6229
+ for (const rel of paths) {
6230
+ const path = join(work, rel);
6231
+ hash.update(rel); hash.update("\0");
6232
+ if (!existsSync(path)) { hash.update("missing\0"); continue; }
6233
+ hash.update(fingerprintTree(path)); hash.update("\0");
6234
+ }
6235
+ return `sha256:${hash.digest("hex")}`;
6236
+ });
6128
6237
  }
6129
6238
 
6130
6239
  function retirementDisposableRoots(work, capabilities) {
@@ -6558,7 +6667,7 @@ export function inspectInstanceSession(home) {
6558
6667
  const s = instanceSessionTarget(home);
6559
6668
  if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", waitingOnYou: null };
6560
6669
  let observed;
6561
- try { observed = inspectSessionTarget(s.target); }
6670
+ try { observed = inspectSessionTarget(s.target, undefined, { includeSize: true }); }
6562
6671
  // The tmux failure stays the cause: sessionServerGone judges it.
6563
6672
  catch (e) { throw Object.assign(oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`), { cause: e }); }
6564
6673
  // Feature waiting-on-you: beside `state`, whose enum is unchanged.
@@ -7987,7 +8096,8 @@ const worktreeBytes = (work, gitPaths = worktreeGitPaths(work)) => exactTreeDige
7987
8096
  /** The byte part of an observed worktree's work state, read at most once per
7988
8097
  * observation and kept on it with the Git directories it leaves out
7989
8098
  * (`workGitPaths`, for the copy's verification); undefined where the
7990
- * observation saw no worktree. An inspection never reads it. The retire reads it before it
8099
+ * observation saw no worktree. An inspection reads it only with its own walk,
8100
+ * for inspectedWorkBytes, and never sets it. The retire reads it before it
7991
8101
  * writes the pre-hook recovery, the copy's verification uses it (so a pass
7992
8102
  * that copies the work costs no extra read), and so does the proof that the
7993
8103
  * retire hooks left the work as it was (movedByHooks). */
@@ -8007,6 +8117,18 @@ function observedWorkBytes(observation) {
8007
8117
  }
8008
8118
  return observation.workBytes;
8009
8119
  }
8120
+ /** observedWorkBytes, taken from the inspection's own read where it took one
8121
+ * (`inspectedWorkBytes`, worktreeDigests): it read the worktree whole for its
8122
+ * untracked and ignored digest, and nothing has written the worktree since.
8123
+ * Asked only where the retire reads the bytes right after that inspection
8124
+ * (#1247): before the pre-hook recovery, and in movedByHooks. */
8125
+ function inspectedWorkBytes(observation) {
8126
+ if (observation.workBytes === undefined && observation.inspectedWorkBytes) {
8127
+ observation.workBytes = observation.inspectedWorkBytes.bytes;
8128
+ observation.workGitPaths = observation.inspectedWorkBytes.gitPaths;
8129
+ }
8130
+ return observedWorkBytes(observation);
8131
+ }
8010
8132
  /** What the retire hooks moved, between the observation before them and the
8011
8133
  * one after → { home, work }. Nothing when the later observation has nothing
8012
8134
  * to preserve. The home moved when its exact digest did: that is its bytes,
@@ -8025,7 +8147,7 @@ function movedByHooks(before, after) {
8025
8147
  if (!after.classes.length) return { home: false, work: false };
8026
8148
  const home = after.homeBytes !== before.homeBytes;
8027
8149
  let work = after.workFingerprint !== before.workFingerprint;
8028
- if (!work && after.worktree) work = !before.workProvable || !after.workProvable || before.workBytes === undefined || observedWorkBytes(after) !== before.workBytes;
8150
+ if (!work && after.worktree) work = !before.workProvable || !after.workProvable || before.workBytes === undefined || inspectedWorkBytes(after) !== before.workBytes;
8029
8151
  return { home, work };
8030
8152
  }
8031
8153
 
@@ -8048,7 +8170,7 @@ function assertWorktreeTopLevel(work, disclosure) {
8048
8170
  }
8049
8171
  }
8050
8172
 
8051
- function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, directoryMode = directory, link = false, instance, orphanedWork = false, disclosure } = {}) {
8173
+ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, directoryMode = directory, link = false, instance, orphanedWork = false, disclosure, readWorkBytes = false } = {}) {
8052
8174
  // `directory`: work/ is read, copied and checked as a directory's bytes. `directoryMode`: the
8053
8175
  // record says `directory`. They differ for a directory of the home (instanceWork, #962), which
8054
8176
  // is copied the same way and is no directory instance: it has no receipt of its roots.
@@ -8110,7 +8232,7 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
8110
8232
  const unreached = worktreeRemoval?.removes && worktreeRemoval.repo && !directory && isWorktree && existsSync(work) ? worktreeCommitUnreached(worktreeRemoval.repo, work) : undefined;
8111
8233
  if (unreached?.unreached) classes.push("worktree commits no ref reaches");
8112
8234
  const worktree = isWorktree && existsSync(work);
8113
- let gitState = "", workProvable = true;
8235
+ let gitState = "", workProvable = true, inspectedBytes;
8114
8236
  if (worktree) {
8115
8237
  // Read once, as bytes. The bytes go into the Git state and into the
8116
8238
  // comparison with the spawn baseline (its legacy digest reads them as
@@ -8122,8 +8244,14 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
8122
8244
  const disposableRoots = baseline?.disposableReceipts?.map((r) => r.root) || [];
8123
8245
  // A path the digest cannot inspect refuses, with what this retire has
8124
8246
  // and has not done by now, as the other refusals of an inspection do.
8125
- let generated;
8126
- try { generated = baseline && digestVersion !== undefined ? generatedWorkFingerprintIn(digestVersion, work, statusBytes, disposableRoots) : undefined; }
8247
+ // `readWorkBytes`: the retire will read the worktree's bytes right after
8248
+ // this inspection, so both digests come from one read (worktreeDigests),
8249
+ // or, where that cannot be done, apart as before.
8250
+ let generated, both;
8251
+ try {
8252
+ if (readWorkBytes && baseline && digestVersion === BASELINE_DIGEST_VERSION) both = worktreeDigests(work, statusBytes, disposableRoots);
8253
+ generated = both ? both.generated : baseline && digestVersion !== undefined ? generatedWorkFingerprintIn(digestVersion, work, statusBytes, disposableRoots) : undefined;
8254
+ }
8127
8255
  catch (e) {
8128
8256
  if (e?.code !== "E_WORK_INSPECTION_FAILED") throw e;
8129
8257
  throw oatsError(e.code, `${e.message}.${disclosure ? ` ${disclosure}.` : ""}`);
@@ -8159,12 +8287,16 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
8159
8287
  // branch, and a worktree commit no ref reaches is preserved (the class
8160
8288
  // above, `unreached`).
8161
8289
  if (found.length) workProvable = false;
8290
+ if (both && workProvable) inspectedBytes = { bytes: both.bytes, gitPaths: both.gitPaths };
8162
8291
  }
8163
8292
  // Two values, so the post-hook pass can tell which part a hook moved: the
8164
8293
  // home's bytes (its exact digest), and the work state's fingerprint. A
8165
8294
  // directory's work state is its bytes (`directoryFingerprint`, an exact
8166
- // digest too). A worktree's is its Git state here, and its bytes, which an
8167
- // inspection does not read (observedWorkBytes). `workProvable`: whether
8295
+ // digest too). A worktree's is its Git state here, and its bytes, which the
8296
+ // observation holds apart (observedWorkBytes): an inspection asked to
8297
+ // (`readWorkBytes`) reads them with its untracked and ignored digest, and
8298
+ // keeps them as `inspectedWorkBytes` for inspectedWorkBytes to adopt; it
8299
+ // never sets them. `workProvable`: whether
8168
8300
  // that state could be read and covers everything a copy of the work would
8169
8301
  // carry. None of these is kept in a baseline, a receipt or recovery.json.
8170
8302
  // When the worktree will be removed, its HEAD (the commit and the ref's
@@ -8176,7 +8308,7 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
8176
8308
  .update("\0").update(unreached ? `${unreached.head.commit}\0${unreached.unreached ? "unreached" : "reached"}\0` : "")
8177
8309
  .update(unreached?.head.ref ?? "")
8178
8310
  .digest("hex");
8179
- return { classes: [...new Set(classes)], home, work, directory, orphanedWork, worktree, workProvable, directoryFingerprint, homeBytes: homeDigests.exact, workFingerprint, homeExclude: homeExclusions.excludeRoot, notCopied: homeExclusions.notCopied, extraTrees, branchExists, head: unreached?.head, runtimeAuthority: baselineValid ? runtimeAuthorityOf(baseline) : undefined };
8311
+ return { classes: [...new Set(classes)], home, work, directory, orphanedWork, worktree, workProvable, directoryFingerprint, homeBytes: homeDigests.exact, workFingerprint, inspectedWorkBytes: inspectedBytes, homeExclude: homeExclusions.excludeRoot, notCopied: homeExclusions.notCopied, extraTrees, branchExists, head: unreached?.head, runtimeAuthority: baselineValid ? runtimeAuthorityOf(baseline) : undefined };
8180
8312
  }
8181
8313
 
8182
8314
  /** Copy the entries of `src` into `dest` (created), names as bytes, except
@@ -8941,7 +9073,7 @@ function copyRecoveryHome(observation, dest) {
8941
9073
  * cannot be read is an inspection failure, not a failed copy: its error is
8942
9074
  * put in `unreadableHeads`, and the callers throw it as it is. */
8943
9075
  const unreadableHeads = new WeakSet();
8944
- function copyRecoveryWork(observation, meta, parent) {
9076
+ function copyRecoveryWork(observation, meta, parent, { rereadSource = true } = {}) {
8945
9077
  let branchDrift, excludes, statusConfig, copied = false;
8946
9078
  // A worktree that is there is copied from itself: only one that is gone needs the recorded
8947
9079
  // branch, to be copied from the repository. (An own tree whose record holds no branch, #962.)
@@ -9003,7 +9135,15 @@ function copyRecoveryWork(observation, meta, parent) {
9003
9135
  if (observation.directory && observation.directoryFingerprint) {
9004
9136
  const recoveredWork = join(parent, "work");
9005
9137
  copyTreeSafe(observation.work, recoveredWork);
9006
- if (directoryBytes(observation.work) !== observation.directoryFingerprint || directoryBytes(recoveredWork) !== observation.directoryFingerprint) {
9138
+ // The copy is read back and held against the inspected bytes. A change to
9139
+ // the source before the copy read it is in the copy, and refuses here. One
9140
+ // made during the copy, to a file already copied, is not: the source is
9141
+ // read again for that unless `rereadSource` is false, which only the
9142
+ // retire's pre-hook copy passes. There the inspection after the hooks
9143
+ // reads the source again in any case, sees the change and copies the work
9144
+ // again, verified, under after-hooks/ (#1247). Every other copy is the
9145
+ // last read of its source before the home is removed.
9146
+ if ((rereadSource && directoryBytes(observation.work) !== observation.directoryFingerprint) || directoryBytes(recoveredWork) !== observation.directoryFingerprint) {
9007
9147
  throw new Error("directory recovery verification disagreed with the inspected source");
9008
9148
  }
9009
9149
  copied = true;
@@ -9081,7 +9221,7 @@ function writeRetirementRecovery(observation, meta, instance, phase) {
9081
9221
  const homeOnly = homeOnlyRecovery(observation, meta);
9082
9222
  const recoveredHome = join(staging, "home");
9083
9223
  copyRecoveryHome(observation, recoveredHome);
9084
- const { branchDrift, excludes, statusConfig } = homeOnly ? {} : copyRecoveryWork(observation, meta, staging);
9224
+ const { branchDrift, excludes, statusConfig } = homeOnly ? {} : copyRecoveryWork(observation, meta, staging, { rereadSource: phase !== "before-hooks" });
9085
9225
  const repoCopy = homeOnly ? { copied: false, reason: "Only instance-home bytes changed; no work state requires a repository copy", source: meta.repo, branch: meta.branch } : undefined;
9086
9226
  // What the copy cost: the home entries it carries and the untracked/ignored (or directory) outputs, named.
9087
9227
  const home = preservedHome(recoveredHome);
@@ -9227,6 +9367,62 @@ export function retirePendingMarkerPath(home) {
9227
9367
  return join(dirname(home), `.oats-retire-pending-${basename(home)}.json`);
9228
9368
  }
9229
9369
 
9370
+ /** A status row's `retire` (feature status-retire-state, lib/retire-state.mjs): whether a retire of
9371
+ * `home` runs, could not be told, failed or was interrupted, read from what is beside the home
9372
+ * (`marker`: `{ read }` when its retire marker is there, `read` what its file parsed as, undefined
9373
+ * when it did not parse; the row's own read, so `retirePending` and this agree). Only read: no
9374
+ * claim is taken, no file removed, no process signalled. → the value, or undefined when no retire
9375
+ * runs, is scheduled or is owed.
9376
+ * - The marker of a self-retire comes first, whatever the claim says (its completion holds the
9377
+ * claim for its own retire), and gives `self: true`. A completion's result that says `ok:
9378
+ * false` is `failed`, with its time, code and message. Otherwise, a result that says anything
9379
+ * else included, the marker's completion decides: `running` while it lives (pid and recorded
9380
+ * start), `interrupted` once it is gone, and `unknown` when that cannot be read or the marker
9381
+ * names no completion. A marker that does not parse is `unknown`.
9382
+ * - Without a marker, the home's claim held for a retire is `running` while its holder lives and
9383
+ * `unknown` when that cannot be read, with `self: false`. A holder that is gone, a stop's claim
9384
+ * or no claim gives no value.
9385
+ * `since` is required (a reader drops a value without one): the recorded time when it is an
9386
+ * instant as `toISOString()` gives it (the result's `completedAt`, then the marker's
9387
+ * `requestedAt`; the claim's `at`), else the marker's or the claim file's mtime. When none can be
9388
+ * read there is no value at all. */
9389
+ function retireStateOf(home, marker) {
9390
+ const mtimeOf = (path) => { try { return statSync(path).mtime.toISOString(); } catch { return undefined; } };
9391
+ // A file beside the home as JSON, only when it is a regular file: opened without blocking and
9392
+ // checked on the open descriptor, so a pipe (whose open or read would not return) or a device put
9393
+ // there is no value, never a status that hangs. Anything that does not read is undefined.
9394
+ const regularJson = (path) => {
9395
+ let fd;
9396
+ try {
9397
+ fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
9398
+ return fstatSync(fd).isFile() ? JSON.parse(readFileSync(fd, "utf8")) : undefined;
9399
+ } catch { return undefined; } finally { if (fd !== undefined) closeSync(fd); }
9400
+ };
9401
+ const instantOr = (...times) => times.find((t) => isInstantString(t));
9402
+ if (marker) {
9403
+ const pending = marker.read, markerTime = () => mtimeOf(retirePendingMarkerPath(home));
9404
+ if (!isPlainObject(pending)) return readRetireState({ state: "unknown", self: true, since: markerTime() });
9405
+ const result = regularJson(deferredRetireResultPath(home));
9406
+ if (isPlainObject(result) && result.ok === false) {
9407
+ return readRetireState({ state: "failed", self: true, since: instantOr(result.completedAt, pending.requestedAt) ?? markerTime(), code: result.error?.code, message: result.error?.message });
9408
+ }
9409
+ const pid = pending.completionPid;
9410
+ const state = !Number.isSafeInteger(pid) || pid <= 0 ? "unknown"
9411
+ : { alive: "running", gone: "interrupted" }[processLiveness({ pid, processStart: pending.completionStart }).state] ?? "unknown";
9412
+ return readRetireState({ state, self: true, since: instantOr(pending.requestedAt) ?? markerTime() });
9413
+ }
9414
+ // Most rows have no claim: asked without the throw of a read that finds none, which is most of
9415
+ // what reading it costs. A path that is not there (a dangling link too) reads as no claim either way.
9416
+ // The claim is read as homeClaimHolder reads it (claimAction, processLiveness), through regularJson.
9417
+ const lock = retireClaimPath(home);
9418
+ if (!existsSync(lock)) return undefined;
9419
+ const holder = regularJson(lock);
9420
+ if (!isPlainObject(holder) || claimAction(holder) !== "retire") return undefined;
9421
+ const { state } = processLiveness(holder);
9422
+ if (state !== "alive" && state !== "unknown") return undefined;
9423
+ return readRetireState({ state: state === "alive" ? "running" : "unknown", self: false, since: shownHolder(holder).since ?? mtimeOf(lock) });
9424
+ }
9425
+
9230
9426
  /** Where a deferred self-retirement writes its explicit outcome: a FILE beside
9231
9427
  * the (former) home, so it survives the home's removal and never reads as an
9232
9428
  * instance directory. */
@@ -10083,8 +10279,10 @@ function retireSteps(root, name, o, found, at) {
10083
10279
  // cannot read or that is gone included, is an inspection that failed (E_WORK_INSPECTION_FAILED),
10084
10280
  // and says what the retire has and has not done by then (`disclosure`), once. Classified here,
10085
10281
  // at the retire's own calls: the digests' other callers do not answer that code for it.
10086
- const inspect = (disclosure) => {
10087
- try { return inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, directoryMode, link, instance: name, orphanedWork, disclosure }); }
10282
+ // `readWorkBytes`: whether the worktree's bytes are likely to be read right after this inspection,
10283
+ // so that it takes them in its own read (worktreeDigests). A guess either way costs time, never a proof.
10284
+ const inspect = (disclosure, readWorkBytes = false) => {
10285
+ try { return inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, directoryMode, link, instance: name, orphanedWork, disclosure, readWorkBytes }); }
10088
10286
  catch (e) { throw statedFailure(e, "E_WORK_INSPECTION_FAILED", `${disclosure}.`, `could not inspect the home of ${name} or its work`); }
10089
10287
  };
10090
10288
  const initialObservation = inspect(nothingYet());
@@ -10190,7 +10388,9 @@ function retireSteps(root, name, o, found, at) {
10190
10388
  }
10191
10389
  ownSession = "stopped";
10192
10390
  }
10193
- const stableObservation = inspect(beforeHooks());
10391
+ // Its bytes are read before the pre-hook recovery when it has something to preserve, which the
10392
+ // first inspection, of the same work before the stop, foretells.
10393
+ const stableObservation = inspect(beforeHooks(), initialObservation.classes.length > 0 && initialObservation.workProvable);
10194
10394
  // The bytes of the worktree as they are before the hooks: after the hooks,
10195
10395
  // "the work did not move" is then proven, never taken from a status text.
10196
10396
  // Read before the recovery is written, so that a worktree that cannot be
@@ -10203,7 +10403,7 @@ function retireSteps(root, name, o, found, at) {
10203
10403
  // before the hooks there is nothing to prove: any class after them is
10204
10404
  // preserved.
10205
10405
  if (stableObservation.classes.length && stableObservation.workProvable) {
10206
- try { observedWorkBytes(stableObservation); }
10406
+ try { inspectedWorkBytes(stableObservation); }
10207
10407
  catch (e) {
10208
10408
  throw statedFailure(e, "E_WORK_INSPECTION_FAILED", `No recovery was written and nothing was deleted: ${soFar("its home is kept")}`);
10209
10409
  }
@@ -10313,7 +10513,8 @@ function retireSteps(root, name, o, found, at) {
10313
10513
  // step and before the home is removed.
10314
10514
  // A refusal here says what has and has not happened, as one before the hooks
10315
10515
  // does: the hooks have run, and what is kept (#659).
10316
- const finalObservation = inspect(afterHooks());
10516
+ // Its bytes are read when movedByHooks compares them with the bytes read before the hooks.
10517
+ const finalObservation = inspect(afterHooks(), !!preHookRecovery && stableObservation.workBytes !== undefined);
10317
10518
  try {
10318
10519
  if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, workMeta);
10319
10520
  else if (finalObservation.classes.length) {