@awebai/oats 0.48.0 → 0.49.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 (41) hide show
  1. package/bin/oats.mjs +226 -14
  2. package/docs/capabilities.md +256 -8
  3. package/docs/capability-manifest.schema.json +18 -5
  4. package/docs/configuration.md +6 -0
  5. package/docs/desktop-cli-api.md +368 -31
  6. package/docs/desktop.md +72 -5
  7. package/docs/execution-targets.md +17 -2
  8. package/docs/implementation.md +62 -1
  9. package/docs/integrations.md +7 -5
  10. package/docs/knowledge.md +167 -197
  11. package/docs/official-catalog.md +2 -2
  12. package/docs/packages.md +8 -8
  13. package/docs/release-notes/v0.49.0.md +770 -0
  14. package/docs/schedules.md +62 -39
  15. package/docs/servers.md +7 -0
  16. package/docs/souls-and-instances.md +381 -53
  17. package/docs/workspaces.md +2 -2
  18. package/injects/work-checkout.md +17 -11
  19. package/injects/work-worktree.md +19 -13
  20. package/lib/capability-contract.mjs +100 -11
  21. package/lib/capability-show.mjs +5 -2
  22. package/lib/core.mjs +1109 -321
  23. package/lib/instance-events.mjs +6 -3
  24. package/lib/instance-git.mjs +11 -5
  25. package/lib/instance-inspect.mjs +14 -3
  26. package/lib/instance-lifecycle.mjs +106 -16
  27. package/lib/instance-resolution.mjs +15 -3
  28. package/lib/launch-prompt-policy.mjs +17 -3
  29. package/lib/packages.mjs +1 -0
  30. package/lib/real-path.mjs +27 -0
  31. package/lib/resolve.mjs +4 -4
  32. package/lib/retire-output.mjs +6 -1
  33. package/lib/schedule.mjs +1 -0
  34. package/lib/servers.mjs +32 -6
  35. package/lib/tree-copy.mjs +18 -7
  36. package/lib/triggers.mjs +201 -65
  37. package/lib/workspace.mjs +20 -5
  38. package/lib/worktree-hooks.mjs +392 -0
  39. package/lib/worktree.mjs +655 -0
  40. package/package-catalog.json +1 -1
  41. package/package.json +1 -1
package/lib/core.mjs CHANGED
@@ -28,6 +28,7 @@
28
28
  * (attached as soul default is for service agents — spawn must supply workDir)
29
29
  */
30
30
  import { effectiveLaunchPromptPolicy } from "./launch-prompt-policy.mjs";
31
+ import { canonicalHomePath, realPathOrNearest } from "./real-path.mjs";
31
32
  import { createLaunchPromptController } from "./launch-prompts.mjs";
32
33
  import { retainLaunchPromptFrame } from "./launch-prompt-evidence.mjs";
33
34
  import { qualifyLaunchPromptFixtures } from "./launch-prompt-fixtures.mjs";
@@ -48,6 +49,7 @@ import { attachSessionTarget } from "./session-viewer.mjs";
48
49
  import { inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
49
50
  import { appendEvent, liveWaiting, recordStartBoundary } from "./instance-events.mjs";
50
51
  import { killGroup } from "./process-group.mjs";
52
+ import { interruptExitStatus, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
51
53
  import { captureLoginEnvironment } from "./login-environment.mjs";
52
54
 
53
55
  import { oatsError, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
@@ -61,21 +63,22 @@ async function materializePreparedDefault(prepared, home) { const m = await impo
61
63
  // (manifest, settings, origin, trust; no skills/inject since the copies are not
62
64
  // there yet) and REBUILT after materialize against what actually landed. Static
63
65
  // import: instance-resolution.mjs does not depend on core.mjs (no cycle).
64
- import { cloneRemoteFor, toCapabilityRows } from "./instance-resolution.mjs";
66
+ import { cloneRemoteFor, resolutionContractWarnings, toCapabilityRows, verifyMemberClone } from "./instance-resolution.mjs";
65
67
  import { GIT_FETCH_TIMEOUT_MS, GIT_TIMEOUT_MS, gitEnv } from "./remote.mjs";
66
68
  import { loadLocal } from "./workspace.mjs";
67
69
  import { parseConfigData } from "./config-data.mjs";
68
70
  import { renderInstructionText } from "./instruction-composition.mjs";
69
- import { APPROVED_HOOKS, PORTABLE_ENV_NAME_RE, CORE_LAUNCH_ENV, PROCESS_BOOTSTRAP_ENV, PROCESS_BOOTSTRAP_PREFIXES, manifestContractProblems, disposableHomeRootProblem, disposableHomeRootMatches } from "./capability-contract.mjs";
71
+ import { APPROVED_HOOKS, PORTABLE_ENV_NAME_RE, CORE_LAUNCH_ENV, PROCESS_BOOTSTRAP_ENV, PROCESS_BOOTSTRAP_PREFIXES, manifestContractProblems, disposableHomeRootProblem, disposableHomeRootMatches, contractWarningMessages, locatedContractWarnings } from "./capability-contract.mjs";
70
72
  import { validateBindingInterface } from "./provider-binding.mjs";
71
73
  /** Retirement/rollback tree fingerprint (exported for scope tests: kernel-field neutrality is opt-in per instance home),
72
74
  * the exact digest a copied path is compared with (exported so a test holds it to the copier),
75
+ * a worktree's byte digest and the Git directories it leaves out (exported so a test holds them to exact paths),
73
76
  * and the receipts the stored digest passes over in a home (exported so a test holds the manifest grammar to refusing each of them). */
74
- export { exactTreeDigest, fingerprintTree, KERNEL_HOME_RECEIPTS };
77
+ export { exactTreeDigest, fingerprintTree, KERNEL_HOME_RECEIPTS, storedTreeDigest, worktreeBytes, worktreeGitPaths };
75
78
 
76
79
  import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
77
80
  import { readPortableBytes } from "./bounded-read.mjs";
78
- import { copyTreeSafe } from "./tree-copy.mjs";
81
+ import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.mjs";
79
82
  import { assertSameWorktreeHead, gitRead, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
80
83
  /** The package and capability id grammar (namespaced, lowercase): an id names a
81
84
  * directory (a home's module copy), so no path spelling fits it. */
@@ -186,6 +189,11 @@ export const PACKAGED_SKILLS_DIR = join(PKG_ROOT, "skills");
186
189
  // ---------- shell helpers ----------
187
190
  function sh(cmdline) { return execSync(cmdline, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); }
188
191
  function shTry(cmdline) { try { return sh(cmdline); } catch { return undefined; } }
192
+ /** The branch spawn records for an attached or checkout instance (#641): the
193
+ * name HEAD carries as headName reads it, or null when HEAD is detached or
194
+ * names a ref OATS carries no branch name for. Never the word "HEAD". A HEAD
195
+ * that cannot be read (not a Git tree) records none, as before. */
196
+ function recordedHeadBranch(dir) { try { return headName(dir).branch; } catch { return undefined; } }
189
197
  /** A native PROBE (a harness binary asked about its catalogue or packages) under
190
198
  * a preview: bounded by what is left of the shared preflight budget, run in its
191
199
  * own process group and group-killed on timeout. Cheap lookups (`command -v`)
@@ -415,18 +423,6 @@ export function findRoot(cwd = process.cwd()) {
415
423
  d = parent;
416
424
  }
417
425
  }
418
- /** realpath of `p`, or — when `p` does not exist yet — the realpath of its
419
- * nearest existing ancestor with the remaining segments re-appended. Any path
420
- * decision about WHERE something will be created has to go through this: a
421
- * lexical path says nothing about the destination once a symlink sits anywhere
422
- * along it. */
423
- function realPathOrNearest(p) {
424
- try { return realpathSync(p); } catch { /* not created yet — resolve what exists */ }
425
- let d = resolve(p); const tail = [];
426
- while (!existsSync(d) && dirname(d) !== d) { tail.unshift(basename(d)); d = dirname(d); }
427
- try { return join(realpathSync(d), ...tail); } catch { return resolve(p); }
428
- }
429
-
430
426
  /** Is there a Git marker (`.git` dir or worktree pointer file) at or above `dir`?
431
427
  * Filesystem-only: it answers "does Git own this location" even when the git
432
428
  * binary is missing, refuses the repo (dubious ownership), or cannot read its
@@ -489,10 +485,12 @@ export function canonicalDeploymentPath(p) {
489
485
  // Git reports CANONICAL paths, so every comparison and every relative()
490
486
  // below must be realpath-based: on macOS a temp/agents root reached through
491
487
  // /var while Git reports /private/var would otherwise look "outside" the
492
- // work tree and silently skip canonicalization. The agents dir itself may
493
- // not exist yet (local-only scopes), so resolve the nearest existing
488
+ // work tree and silently skip canonicalization. So would a root given in
489
+ // another letter case on a case-insensitive filesystem: Git's paths are in
490
+ // their on-disk spelling, and so are both sides here. The agents dir itself
491
+ // may not exist yet (local-only scopes), so resolve the nearest existing
494
492
  // ancestor and re-append the remainder.
495
- const realOf = realPathOrNearest;
493
+ const realOf = canonicalHomePath;
496
494
  const same = (a, b) => realOf(a) === realOf(b);
497
495
  // Linked or main? `--git-dir` equals `--git-common-dir` in the MAIN worktree
498
496
  // and points at <common>/worktrees/<name> in a linked one. This settles it
@@ -582,7 +580,11 @@ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
582
580
  * its reference aliases: a configuration may not name them. */
583
581
  export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "OATS_AGENT", "OATS_SOUL", "OATS_SOUL_ID", "OATS_ROOT", "OATS_CONTEXT", "OATS_WORKSPACE", "OATS_EVENT", "OATS_SETTINGS", "OATS_SETTINGS_ORIGINS", "OATS_CLI_BIN", "PI_AGENT_INSTANCE", "PI_AGENT_HOME", "PI_AGENTS_ROOT",
584
582
  // The test seam that replaces the login shell (lib/login-environment.mjs): never a launch's to set.
585
- "OATS_TEST_LOGIN_SHELL"]);
583
+ "OATS_TEST_LOGIN_SHELL",
584
+ // The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
585
+ // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
586
+ // process's start time on a host with procfs (lib/worktree-hooks.mjs processStart).
587
+ "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS"]);
586
588
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
587
589
  const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
588
590
  export function validateLaunchConfig(name, entry, where) {
@@ -725,6 +727,14 @@ function manifestHookCommands(manifest) {
725
727
 
726
728
  const PACKAGED_INJECTS_DIR = join(PKG_ROOT, "injects");
727
729
 
730
+ /** A replayed spawn's contract warnings (contractWarningMessages), from the home's module copies in
731
+ * module-name order; none when they cannot be read (the replay answers what it can, as before). */
732
+ function replayedContractWarnings(home) {
733
+ let manifests;
734
+ try { manifests = typeof home === "string" ? capabilityManifests(home) : {}; } catch { return []; }
735
+ return contractWarningMessages(Object.keys(manifests).sort().flatMap((name) => locatedContractWarnings(manifests[name], `.oats/modules/${name}/oats.json`)));
736
+ }
737
+
728
738
  function validateCapabilityManifest(m, mf) {
729
739
  const id = m.capability;
730
740
  if (!id) throw new Error(`capability manifest needs "capability": ${mf}`);
@@ -1072,7 +1082,7 @@ function plannedCapabilityRows(resolution) {
1072
1082
  * `node <abs script> <args>`, exactly as `manifestHookCommands` renders a classic
1073
1083
  * capability. The script must exist inside the module's copy under
1074
1084
  * <home>/.oats/modules/<cap>/ — a path escaping it is a manifest defect. Only
1075
- * the events the kernel approves (soul-scaffold, spawn, retire, launch) are kept. */
1085
+ * the events the kernel approves (soul-scaffold, spawn, retire, launch, worktree) are kept. */
1076
1086
  function materializedHookCommands(row, home) {
1077
1087
  const out = {};
1078
1088
  const moduleDir = row.dir || join(home, ".oats", "modules", row.id);
@@ -1389,7 +1399,8 @@ export const HARNESS_PACKAGE_MANAGERS = {
1389
1399
  let rows;
1390
1400
  try { rows = JSON.parse(out); } catch { return []; }
1391
1401
  if (!Array.isArray(rows)) return [];
1392
- const target = opts.context ? realPathOrNearest(opts.context) : undefined;
1402
+ // Claude reports projectPath in its on-disk spelling: the context is compared in it too.
1403
+ const target = opts.context ? canonicalHomePath(opts.context) : undefined;
1393
1404
  return rows
1394
1405
  .filter((r) => r && typeof r.id === "string")
1395
1406
  // A user-scope install applies everywhere. A project/local install
@@ -1397,7 +1408,7 @@ export const HARNESS_PACKAGE_MANAGERS = {
1397
1408
  .filter((r) => {
1398
1409
  if (r.scope === "user") return true;
1399
1410
  if (!r.projectPath || !target) return false;
1400
- const owner = realPathOrNearest(r.projectPath);
1411
+ const owner = canonicalHomePath(r.projectPath);
1401
1412
  return target === owner || target.startsWith(owner + sep);
1402
1413
  })
1403
1414
  // verifiedPresent is the "this harness confirms presence without naming a
@@ -1629,6 +1640,39 @@ function withoutAmbientLaunchPreview(env) {
1629
1640
  const { OATS_LAUNCH_PREVIEW: _ambient, ...rest } = env;
1630
1641
  return rest;
1631
1642
  }
1643
+ /** The environment one capability's lifecycle hook runs with: the invoker's own
1644
+ * (inherited, as for every hook; the kernel adds no credentials), plus the
1645
+ * standard OATS_* variables (docs/capabilities.md, Commands and hooks) and the
1646
+ * caller's `extraEnv`. One builder for every event, so the `worktree` runner
1647
+ * (lib/worktree-hooks.mjs) hands its hooks exactly what every other hook gets. */
1648
+ export function lifecycleHookEnv(event, cap, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta = {}, extraEnv = {} }) {
1649
+ return {
1650
+ // OATS_LAUNCH_PREVIEW is the kernel's to give (prepareLaunchHooks), never
1651
+ // inherited: a real start's hook must not read an ambient one as a preview.
1652
+ ...withoutAmbientLaunchPreview(process.env),
1653
+ // OATS_INSTANCE_HOME is the runtime-neutral contract name for the
1654
+ // instance home (absolute). OATS_HOME predates it and stays as a
1655
+ // compatibility alias: shipped capability hooks read it
1656
+ // (the official oats.aweb and oats.okf packages) and are versioned
1657
+ // independently of this kernel. Neither is OATS_HOME_DIR, which is
1658
+ // the package STORE root — do not conflate them.
1659
+ OATS_EVENT: event, OATS_INSTANCE: instance, OATS_INSTANCE_HOME: home, OATS_HOME: home, OATS_AGENT: agentName,
1660
+ OATS_CAPABILITY: cap.id, OATS_LAYER: cap.layer || "", OATS_ROOT: rootDir || "",
1661
+ OATS_SOUL: soulDir || "", OATS_SOUL_ID: stableSoulId({ soulId, home, soulDir, agentName }), OATS_CONTEXT: contextDir, OATS_WORKSPACE: workspaceDir || "", OATS_LEVEL: cap.level || "",
1662
+ ...teamEnv(resolved),
1663
+ ...extraEnv,
1664
+ // Hooks also run through direct core callers (not only bin/oats).
1665
+ // Author this from the running kernel, never PATH, ambient env or
1666
+ // a caller's extraEnv: those may point at a different executable.
1667
+ OATS_CLI_BIN: kernelBin(),
1668
+ OATS_SETTINGS: JSON.stringify(cap.settings || {}),
1669
+ // Where each leaf of OATS_SETTINGS came from (JSON pointer → { kind, at }; kind is
1670
+ // manifest-default | workspace | soul | host | spawn | anchor), so a provider can tell a
1671
+ // soul-set value from a host-set one. {} when the home recorded none (spawned before 0.29).
1672
+ OATS_SETTINGS_ORIGINS: JSON.stringify(cap.settingsOrigins || {}),
1673
+ OATS_META: JSON.stringify(priorMeta[cap.id] || {}),
1674
+ };
1675
+ }
1632
1676
  export function runLifecycleHooks(event, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta = {}, extraEnv = {}, assertRoots }) {
1633
1677
  const results = { meta: {}, briefs: [], warnings: [], order: [], launch: {}, env: {}, failures: [], contributions: [], volatileEnv: {} };
1634
1678
  // OATS_SOUL is set for EVERY hook: a caller that does not name the soul (launch,
@@ -1650,32 +1694,7 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1650
1694
  try {
1651
1695
  const stdout = execSync(cmd, {
1652
1696
  cwd: home, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 120000,
1653
- env: {
1654
- // OATS_LAUNCH_PREVIEW is the kernel's to give (prepareLaunchHooks), never
1655
- // inherited: a real start's hook must not read an ambient one as a preview.
1656
- ...withoutAmbientLaunchPreview(process.env),
1657
- // OATS_INSTANCE_HOME is the runtime-neutral contract name for the
1658
- // instance home (absolute). OATS_HOME predates it and stays as a
1659
- // compatibility alias: shipped capability hooks read it
1660
- // (the official oats.aweb and oats.okf packages) and are versioned
1661
- // independently of this kernel. Neither is OATS_HOME_DIR, which is
1662
- // the package STORE root — do not conflate them.
1663
- OATS_EVENT: event, OATS_INSTANCE: instance, OATS_INSTANCE_HOME: home, OATS_HOME: home, OATS_AGENT: agentName,
1664
- OATS_CAPABILITY: cap.id, OATS_LAYER: cap.layer || "", OATS_ROOT: rootDir || "",
1665
- OATS_SOUL: soulDir || "", OATS_SOUL_ID: stableSoulId({ soulId, home, soulDir, agentName }), OATS_CONTEXT: contextDir, OATS_WORKSPACE: workspaceDir || "", OATS_LEVEL: cap.level || "",
1666
- ...teamEnv(resolved),
1667
- ...extraEnv,
1668
- // Hooks also run through direct core callers (not only bin/oats).
1669
- // Author this from the running kernel, never PATH, ambient env or
1670
- // a caller's extraEnv: those may point at a different executable.
1671
- OATS_CLI_BIN: kernelBin(),
1672
- OATS_SETTINGS: JSON.stringify(cap.settings || {}),
1673
- // Where each leaf of OATS_SETTINGS came from (JSON pointer → { kind, at }; kind is
1674
- // manifest-default | workspace | soul | host | spawn | anchor), so a provider can tell a
1675
- // soul-set value from a host-set one. {} when the home recorded none (spawned before 0.29).
1676
- OATS_SETTINGS_ORIGINS: JSON.stringify(cap.settingsOrigins || {}),
1677
- OATS_META: JSON.stringify(priorMeta[cap.id] || {}),
1678
- },
1697
+ env: lifecycleHookEnv(event, cap, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta, extraEnv }),
1679
1698
  }).trim();
1680
1699
  const lastLine = stdout.split("\n").filter(Boolean).pop() || "{}";
1681
1700
  let o = {};
@@ -2021,7 +2040,9 @@ const KERNEL_ENV_NAMES = new Set([...RESERVED_LAUNCH_ENV, "COLORFGBG", "TMUX", "
2021
2040
  "OATS_REPO", "OATS_BRANCH", "OATS_WORK", "OATS_KIND", "OATS_TASK", "OATS_HARNESS", "OATS_PREVIOUS_HARNESS", "OATS_RUNTIME", "OATS_PREVIOUS_RUNTIME",
2022
2041
  "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
2023
2042
  "OATS_TEAM_NAME", "OATS_TEAM_SCOPE", "OATS_TEAM_ID", "OATS_TEAM_LABEL", "OATS_TEAM_LABELS", "OATS_TEAMS", "OATS_TEAMS_SOURCE",
2024
- "OATS_DEFAULT_TEAM", "OATS_DEFAULT_TEAM_ID", "OATS_DEFAULT_TEAM_FROM", "OATS_WORKSPACE_NAME", "OATS_WORKSPACE_KEY"]);
2043
+ "OATS_DEFAULT_TEAM", "OATS_DEFAULT_TEAM_ID", "OATS_DEFAULT_TEAM_FROM", "OATS_WORKSPACE_NAME", "OATS_WORKSPACE_KEY",
2044
+ // A worktree hook's tree (#796): never inherited by what such a hook starts.
2045
+ "OATS_TREE", "OATS_TREE_CLONE", "OATS_TREE_REMOTE", "OATS_TREE_MEMBER", "OATS_TREE_BASE", "OATS_TREE_BASE_OID", "OATS_PURPOSE", "OATS_TREE_ORIGIN"]);
2025
2046
  function withoutKernelEnvironment(source) {
2026
2047
  const env = { ...source };
2027
2048
  for (const name of Object.keys(env)) {
@@ -2924,7 +2945,8 @@ export function renderLaunchRecipe(recipe, { home, instance, redact = false, tru
2924
2945
  if (harness === "claude") {
2925
2946
  cmdline = `${shq(executable)}${yolo ? " --dangerously-skip-permissions" : ""}${model ? ` --model ${shq(model)}` : ""}${tail} -- ${shq(TASK_PROMPT.claude)}`;
2926
2947
  } else if (harness === "codex") {
2927
- const codexTrust = `projects={${JSON.stringify(realPathOrNearest(home))}={trust_level="trusted"}}`;
2948
+ // Codex compares the key with its own working directory, in its on-disk spelling.
2949
+ const codexTrust = `projects={${JSON.stringify(canonicalHomePath(home))}={trust_level="trusted"}}`;
2928
2950
  // Codex may run tool commands outside the session's process (its shared app-server daemon),
2929
2951
  // so the env the prefix below gives the session is also set for them. A reference's value
2930
2952
  // never goes on argv, and PATH is the execution's (CODEX_TOOL_PATH: the shim first).
@@ -3275,7 +3297,9 @@ function* spawnBody(root, agent, o = {}) {
3275
3297
  // happened (crash in the interval). Say which, never replay a half-spawn.
3276
3298
  if (["blocked", "incomplete"].includes(prior.launchPrompts?.status)) throw retainedPromptError(prior.home, prior.instance, prior.launchPromptTarget ?? prior.tmux, prior.parentLineageCommitted === true, prior.launchPrompts);
3277
3299
  if (prior.spawnCompleted !== true) throw unconfirmedSpawn(Object.assign(oatsError("E_SPAWN_INCOMPLETE", `${prior.instance} was created for this key but its spawn did not complete (launch or lineage unfinished); inspect it with oats session inspect --home ${prior.home} — do not spawn again`), { instance: prior.instance, home: prior.home, launched: prior.launched === true ? "unknown" : false }));
3278
- return { ...prior, replayed: true, launch: undefined, command: undefined, wake: prior.wake ?? { requested: null, saved: null, error: null } };
3300
+ // The receipt's warnings that are facts of the composition (a hook event this kernel ignores),
3301
+ // from the home's module copies: nothing runs again, and the captured composition is unchanged.
3302
+ return { ...prior, replayed: true, launch: undefined, command: undefined, wake: prior.wake ?? { requested: null, saved: null, error: null }, warnings: replayedContractWarnings(prior.home) };
3279
3303
  }
3280
3304
  }
3281
3305
 
@@ -3669,18 +3693,22 @@ function* spawnBody(root, agent, o = {}) {
3669
3693
  // Addendum 5: where each leaf of `settings.<cap>` came from (JSON pointer → { kind, at }):
3670
3694
  // manifest-default | workspace | soul | host | spawn, the last layer that set it.
3671
3695
  const preparedSettingsOrigins = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloadOrigins?.[m.name] ?? {})]));
3696
+ // The preview's warnings are strings: the launch-prompt notice, then what a module declares and this kernel ignores.
3697
+ const previewWarnings = [...(promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution))];
3672
3698
  const preparedSettings = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloads?.[m.name] && typeof o.prepared.resolution.payloads[m.name] === "object" ? o.prepared.resolution.payloads[m.name] : {})]));
3673
3699
  return deliver({
3674
3700
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
3675
3701
  // Desktop offers before anything is minted; joining any but the default is the provider's explicit act.
3676
3702
  ...{ modules: o.prepared.preview ?? null, teams: structuredClone(o.prepared.resolution.teams ?? []), defaultTeam: structuredClone(o.prepared.resolution.defaultTeam ?? null), resolution: o.prepared.resolution.revision, declRevision: o.prepared.resolution.declRevision ?? null, payloadRevision: o.prepared.resolution.payloadRevision ?? null, workspace: o.prepared.discovery?.key ?? null, standalone: o.prepared.discovery?.standalone === true, providers: preparedProviders, settings: preparedSettings, settingsOrigins: preparedSettingsOrigins },
3677
- spawnPreviewApi: 2, preview: true, launchPromptAnswers, ...(promptOptedIn(launchPromptAnswers) ? { warnings: [LAUNCH_PROMPT_UPDATE_WARNING] } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
3703
+ spawnPreviewApi: 2, preview: true, launchPromptAnswers, ...(previewWarnings.length ? { warnings: previewWarnings } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
3678
3704
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
3679
3705
  decision, preflight,
3680
3706
  backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
3681
3707
  harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
3682
3708
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
3683
3709
  branch: plannedBranch, base: plannedBase, worktree: work === "worktree" ? join(home, "work") : null,
3710
+ // #796: the `worktree` hooks a worktree-mode spawn would fire, in the order they run; null in other modes.
3711
+ worktreeHooks: work === "worktree" ? worktreeHooksOf(resolvedCfg.capabilities).map((h) => ({ capability: h.id, required: h.required })) : null,
3684
3712
  relation: relation || null, parentInstance: parentInstance && parentInstance !== instance ? parentInstance : null,
3685
3713
  policy: { childSpawns: ownChildPolicy }, executable: bin, capabilities: preparedCapabilities,
3686
3714
  skills: [...expectedResources.filter((r) => r.type === "skill-tree" && !r.deferred).flatMap((r) => r.entries || []), ...preparedSkills], task: task || null,
@@ -3977,7 +4005,7 @@ function* spawnBody(root, agent, o = {}) {
3977
4005
  // The tree belongs to its owner — retire never removes it (work/ is a symlink).
3978
4006
  if (!o.workDir || !existsSync(o.workDir)) { rmSync(home, { recursive: true, force: true }); throw new Error(`attached mode needs workDir (got: ${o.workDir})`); }
3979
4007
  symlinkSync(resolve(o.workDir), join(home, "work"));
3980
- branch = shTry(`git -C ${shq(o.workDir)} rev-parse --abbrev-ref HEAD`);
4008
+ branch = recordedHeadBranch(o.workDir);
3981
4009
  } else if (work === "workspace") {
3982
4010
  // Cross-repo coordinator: ./work is the deployment boundary (the directory
3983
4011
  // holding oats-local.yaml, prepared.deployment), not a repo — member repos are
@@ -3991,10 +4019,11 @@ function* spawnBody(root, agent, o = {}) {
3991
4019
  branch = undefined; // no repo identity: the workspace is not a git tree
3992
4020
  } else {
3993
4021
  symlinkSync(repoAbs, join(home, "work"));
3994
- branch = shTry(`git -C ${shq(repoAbs)} rev-parse --abbrev-ref HEAD`);
4022
+ branch = recordedHeadBranch(repoAbs);
3995
4023
  }
3996
4024
 
3997
- const warnings = promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : [];
4025
+ // What the composed modules declare and this kernel ignores (an unknown hook event), as the preview said.
4026
+ const warnings = [...(promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared?.resolution))];
3998
4027
 
3999
4028
  // Establish directory ownership while these are still the kernel's own roots.
4000
4029
  // A hook may replace either path; it must never mint authority for that target.
@@ -4049,6 +4078,32 @@ function* spawnBody(root, agent, o = {}) {
4049
4078
  throw new Error(`relation "parent": failed to re-point anchor "${relativeTo}" (${e.message})`);
4050
4079
  }
4051
4080
  };
4081
+ // #796: the `worktree` hooks this spawn fires (work: worktree only), their run, and the
4082
+ // in-progress marker that covers a parent killed while they run.
4083
+ const treeHooks = work === "worktree" ? worktreeHooksOf(resolvedCfg.capabilities) : [];
4084
+ let worktreeRun = null, treeGuard = null, inProgressMarker = false;
4085
+ const writeSpawnInProgressMarker = (hook) => {
4086
+ const retireOwed = new Set((hookRes.order || []).filter((id) => resolvedCfg.capabilities.find((c) => c.id === id)?.hooks?.retire));
4087
+ writeQuarantineMarker(home, buildQuarantineMarker({
4088
+ instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId,
4089
+ incomplete: ["the spawn is running its worktree hooks; until its process is gone this home is a spawn in progress"],
4090
+ failed: [{ capability: "oats.kernel", event: "worktree" }],
4091
+ outstandingHooks: retireOwed, outstandingGit: new Set(branch ? ["worktree", "branch"] : ["worktree"]),
4092
+ repoAbs, work, branch, resolvedCfg, hookMeta: hookRes.meta || {}, launched: false, tmux: { session, window: instance },
4093
+ reason: "spawn interrupted while its worktree hooks ran",
4094
+ }), { inProgress: { ...selfIdentity(), startedAt: inProgressStartedAt, branch, baseOid: plannedBase.oid, ...hook } });
4095
+ if (!inProgressMarker) {
4096
+ inProgressMarker = true;
4097
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: { session, window: instance } });
4098
+ }
4099
+ };
4100
+ const inProgressStartedAt = new Date().toISOString();
4101
+ // The spawn's commit point for the marker: the final instance.json and baseline are written.
4102
+ const clearSpawnInProgressMarker = () => {
4103
+ if (!inProgressMarker) return;
4104
+ rmSync(join(home, ".oats-rollback-incomplete.json"), { force: true });
4105
+ inProgressMarker = false;
4106
+ };
4052
4107
  let promptDispatched = false, promptTarget, promptResult, promptStartId;
4053
4108
  let windowMayExist = false;
4054
4109
  let spawnTmux;
@@ -4203,8 +4258,58 @@ function* spawnBody(root, agent, o = {}) {
4203
4258
  if (requiredFailures.length) {
4204
4259
  const detail = requiredFailures.map((f) => ` ${f.capability} ${f.event} ${f.contract === "environment" ? "environment contract" : "hook (declared required)"}: ${f.message}`).join("\n");
4205
4260
  const code = requiredFailures.some((f) => f.contract === "environment") ? "E_HOOK_ENVIRONMENT_CONTRACT" : "E_REQUIRED_HOOK_FAILED";
4206
- throw oatsError(code, `a capability this soul activates could not configure itself:\n${detail}\n\nThe instance would have started with an invalid or missing capability configuration`);
4261
+ // The spawn hooks that ran, in the worktree receipt's shape. A spawn hook keeps no log (`log: null`),
4262
+ // and nothing of its output is carried here.
4263
+ const hooks = (hookRes.order || []).map((id) => {
4264
+ const f = (hookRes.failures || []).find((x) => x.capability === id);
4265
+ const cap = resolvedCfg.capabilities.find((c) => c.id === id);
4266
+ return { capability: id, ok: !f, required: (cap?.requiredHooks || []).includes("spawn") || f?.contract === "environment", log: null, ...(f?.contract ? { contract: f.contract } : {}) };
4267
+ });
4268
+ throw Object.assign(oatsError(code, `a capability this soul activates could not configure itself:\n${detail}\n\nThe instance would have started with an invalid or missing capability configuration`), { details: { hooks } });
4269
+ }
4270
+ // #796: the `worktree` event, once, for the ./work this spawn created, after the spawn hooks
4271
+ // succeeded and inside this transaction (lib/worktree-hooks.mjs says how it runs). A killed
4272
+ // parent is recovered by `oats retire` from the in-progress marker written before the first hook.
4273
+ if (treeHooks.length) {
4274
+ const tree = worktreeCanonical || realpathSync(join(home, "work"));
4275
+ const cloneReal = realPathOrNearest(repoAbs);
4276
+ // The marker names this process by pid and start; one whose start cannot be read could not be told
4277
+ // apart from a dead one after a kill, so the spawn does not run its worktree hooks without it.
4278
+ if (!processStartToken(process.pid)) throw oatsError("E_SPAWN_FAILED", `this process's start time cannot be read, so a spawn killed while its worktree hooks ran could not be recovered safely; no worktree hook ran`);
4279
+ writeSpawnInProgressMarker({});
4280
+ treeGuard = signalGuard();
4281
+ const treeEnv = {
4282
+ OATS_TREE: tree, OATS_TREE_CLONE: cloneReal, OATS_TREE_REMOTE: originRemoteOf(cloneReal),
4283
+ OATS_TREE_MEMBER: o.prepared?.soulEntry?.repoKey && cloneOfMember(cloneReal, o.prepared.soulEntry.repoKey) ? o.prepared.soulEntry.repoKey : "",
4284
+ OATS_BRANCH: branch, OATS_TREE_BASE: plannedBase.ref, OATS_TREE_BASE_OID: plannedBase.oid, OATS_PURPOSE: "", OATS_TREE_ORIGIN: "spawn",
4285
+ };
4286
+ worktreeRun = yield () => runWorktreeHooks(treeHooks, {
4287
+ envFor: (cap) => lifecycleHookEnv("worktree", cap, { home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs, workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg, priorMeta: hookRes.meta || {}, extraEnv: treeEnv }),
4288
+ cwd: tree, home, purpose: "", guard: treeGuard,
4289
+ onStart: ({ pgid, hookStart }) => writeSpawnInProgressMarker({ hookPgid: pgid, hookStart }),
4290
+ });
4291
+ warnings.push(...worktreeRun.warnings);
4292
+ if (worktreeRun.interrupted) {
4293
+ throw Object.assign(oatsError("E_INTERRUPTED", `the spawn was interrupted by ${worktreeRun.interrupted} while its worktree hooks ran; the running hook's process group was ended`),
4294
+ { exitStatus: interruptExitStatus(worktreeRun.interrupted), details: { signal: worktreeRun.interrupted, hooks: worktreeRun.receipt } });
4295
+ }
4296
+ // A hook may itself remove or move the tree: the tree must still be this worktree.
4297
+ if (!treeStillThere(tree)) {
4298
+ const msg = `the tree ${tree} is no longer there (or no longer this worktree) after the worktree hooks ran`;
4299
+ if (treeHooks.some((h) => h.required)) worktreeRun.failures.push({ capability: "oats.kernel", event: "worktree", message: msg, required: true });
4300
+ else warnings.push(msg);
4301
+ }
4302
+ const logOf = (id) => worktreeRun.receipt.find((r) => r.capability === id)?.log;
4303
+ for (const f of worktreeRun.failures.filter((x) => !x.required)) warnings.push(`${f.capability} worktree hook failed (continuing): ${f.message}${logOf(f.capability) ? ` (log: ${logOf(f.capability)})` : ""}`);
4304
+ const treeFailures = worktreeRun.failures.filter((x) => x.required);
4305
+ if (treeFailures.length) {
4306
+ requiredFailures.push(...treeFailures);
4307
+ // The logs are in the home, which the rollback may remove: where they are is said after it (below).
4308
+ const detail = treeFailures.map((f) => ` ${f.capability} worktree ${f.contract === "environment" ? "environment contract" : "hook (declared required)"}: ${f.message}`).join("\n");
4309
+ throw Object.assign(oatsError(treeFailures.some((f) => f.contract === "environment") ? "E_HOOK_ENVIRONMENT_CONTRACT" : "E_REQUIRED_HOOK_FAILED", `a capability could not set up the new worktree:\n${detail}`), { details: { hooks: worktreeRun.receipt } });
4310
+ }
4207
4311
  }
4312
+ treeGuard?.restore();
4208
4313
  // Hooks have finished, but no TASK, launch recipe, successful scaffold, or
4209
4314
  // backend operation may be published until the owned roots are revalidated.
4210
4315
  if (work === "directory") assertDirectoryRoots(home, homeReal);
@@ -4216,15 +4321,18 @@ function* spawnBody(root, agent, o = {}) {
4216
4321
  }
4217
4322
  }
4218
4323
  const briefLines = hookRes.briefs.length ? `\n${hookRes.briefs.join("\n")}` : "";
4324
+ // A checkout or attached tree may be on no branch OATS can name (#641): a detached HEAD. With a
4325
+ // branch the text is as it always was; only a missing one is said another way.
4326
+ const noBranch = "no branch that OATS can name, e.g. a detached HEAD";
4219
4327
  const workDesc = work === "worktree"
4220
4328
  ? `a dedicated git worktree of ${repoAbs} on branch "${branch}" — commit freely there`
4221
4329
  : work === "attached"
4222
- ? `ATTACHED to another instance's work tree (${o.workDir}, branch ${branch}) — you share it with that instance; make your changes and commits focused, and never switch branches`
4330
+ ? `ATTACHED to another instance's work tree (${o.workDir}, ${branch ? `branch ${branch}` : noBranch}) — you share it with that instance; make your changes and commits focused, and never switch branches`
4223
4331
  : work === "directory"
4224
4332
  ? `an instance-owned execution directory — not a Git worktree or a link to ${repoAbs}; that path supplies configuration only`
4225
4333
  : work === "workspace"
4226
4334
  ? `the WHOLE WORKSPACE (${realpathSync(join(home, "work"))}) — every member repo is read-context; you coordinate, you do not edit member repos (see your work-mode briefing)`
4227
- : `a symlink to the ${repoAbs} checkout — you share it; work on the currently checked-out branch (${branch}) and do not switch branches without being asked`;
4335
+ : `a symlink to the ${repoAbs} checkout — you share it; ${branch ? `work on the currently checked-out branch (${branch})` : `work on what is checked out (${noBranch})`} and do not switch branches without being asked`;
4228
4336
  writeFileSync(join(home, "TASK.md"), `# Instance briefing: ${instance}
4229
4337
 
4230
4338
  You are instance "${instance}" of agent "${agent.name}".
@@ -4269,7 +4377,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4269
4377
  relativeTo: relation ? relativeTo : undefined,
4270
4378
  spawnOrigin: relation || (parentInstance && parentInstance !== instance) ? "instance" : "operator",
4271
4379
  policy: { childSpawns: ownChildPolicy },
4272
- ...(triggerEventFile ? { trigger: { id: o.triggerEvent.trigger, key: o.triggerEvent.key ?? null, source: o.triggerEvent.source, repo: o.triggerEvent.repo, number: o.triggerEvent.number, url: o.triggerEvent.url ?? null, event: o.triggerEvent.event, headSha: o.triggerEvent.headSha ?? null, observedAt: o.triggerEvent.observedAt ?? null, eventFile: triggerEventFile } } : {}),
4380
+ ...(triggerEventFile ? { trigger: { id: o.triggerEvent.trigger, key: o.triggerEvent.key ?? null, source: o.triggerEvent.source, repo: o.triggerEvent.repo, number: o.triggerEvent.number, subject: o.triggerEvent.subject ?? null, url: o.triggerEvent.url ?? null, event: o.triggerEvent.event, headSha: o.triggerEvent.headSha ?? null, observedAt: o.triggerEvent.observedAt ?? null, eventFile: triggerEventFile } } : {}),
4273
4381
  // K6c: a decision-bound spawn records what bound it, so a retry with the
4274
4382
  // same key replays this receipt instead of spawning again.
4275
4383
  // The FULL bound decision (placement + effective), exactly as the fence
@@ -4380,6 +4488,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4380
4488
  // the managed harness can write. No child-home transition follows launch.
4381
4489
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
4382
4490
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: true, tmux: meta.tmux });
4491
+ clearSpawnInProgressMarker();
4383
4492
  // Wrap the command so the window drops into an interactive shell when the
4384
4493
  // agent exits (e.g. Ctrl-C) instead of tmux killing the window.
4385
4494
  const windowCmd = paneCommand(executionCommand);
@@ -4415,20 +4524,21 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4415
4524
  meta.launched = false;
4416
4525
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
4417
4526
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: meta.tmux });
4527
+ clearSpawnInProgressMarker();
4418
4528
  }
4419
4529
 
4420
4530
  // Ordinary launches and scaffolds commit here; opted-in launches already
4421
4531
  // committed before dispatch so retained prompt failures keep their lineage.
4422
4532
  commitParentLineage();
4423
4533
 
4424
- appendEvent(home, { kind: "spawned", data: { agent: agent.name, work, branch: branch ?? null, harness, model: model || null, parentInstance: meta.parentInstance ?? null, relation: relation ?? null, launched: launch, hooks: hookReceipt(hookRes) } });
4534
+ appendEvent(home, { kind: "spawned", data: { agent: agent.name, work, branch: branch ?? null, harness, model: model || null, parentInstance: meta.parentInstance ?? null, relation: relation ?? null, launched: launch, hooks: hookReceipt(hookRes), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}) } });
4425
4535
  if (launch) appendEvent(home, { kind: "launched", data: { harness, backend, launchConfig: launchConfig?.name ?? null } });
4426
4536
  if (o.idempotencyKey !== undefined) {
4427
4537
  // Only now is the spawn a finished receipt a same-key retry may replay.
4428
4538
  meta.spawnCompleted = true;
4429
4539
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n"); // a kernel-owned field: the baseline fingerprint ignores it
4430
4540
  }
4431
- return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined });
4541
+ return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined });
4432
4542
  } catch (error) {
4433
4543
  if (promptDispatched) {
4434
4544
  // Once opted-in launch dispatch occurred, uncertainty retains all effects.
@@ -4465,6 +4575,20 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4465
4575
  // An interrupted compensation pass cannot establish that effects ended.
4466
4576
  error.message += ` — rollback INCOMPLETE: cleanup could not be completed: ${cleanupError.message}`;
4467
4577
  unconfirmedSpawn(error);
4578
+ } finally {
4579
+ // Interrupts were held through the rollback of a spawn that ran worktree hooks (#796).
4580
+ treeGuard?.restore();
4581
+ }
4582
+ // #796: the worktree hooks' logs are in the home. A rollback that removed it removed them: no
4583
+ // answer names a path that is gone (each entry's `log` is null); a retained home keeps them.
4584
+ if (worktreeRun && error?.details?.hooks === worktreeRun.receipt) {
4585
+ if (existsSync(home)) {
4586
+ const logs = error.details.hooks.map((h) => h.log).filter(Boolean);
4587
+ if (logs.length) error.message += `; the worktree hooks' logs are kept in the retained home: ${logs.join(", ")}`;
4588
+ } else {
4589
+ error.details = { ...error.details, hooks: error.details.hooks.map((h) => ({ ...h, log: null })) };
4590
+ error.message += "; the worktree hooks' output was logged in the instance home, which the rollback removed: run the setup in an existing instance with `oats worktree add` to see it";
4591
+ }
4468
4592
  }
4469
4593
  throw error;
4470
4594
  }
@@ -4529,10 +4653,17 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION) {
4529
4653
  // is preserved state awaiting cleanup, and must read that way.
4530
4654
  const fallback = directoryRollbackPath(home);
4531
4655
  const quarantine = existsSync(fallback) ? fallback : join(home, ".oats-rollback-incomplete.json");
4532
- let rollbackIncomplete;
4656
+ let rollbackIncomplete, spawnInProgress;
4533
4657
  if (existsSync(quarantine)) {
4534
4658
  try { rollbackIncomplete = JSON.parse(readFileSync(quarantine, "utf8")); }
4535
4659
  catch { rollbackIncomplete = { reason: "rollback incomplete" }; }
4660
+ // #796: a spawn still running its worktree hooks keeps a marker that names it
4661
+ // (`inProgress`). While that process is verifiably alive the home is a spawn in
4662
+ // progress, not a failed one; otherwise the marker reads as the quarantine. A process whose
4663
+ // start cannot be read is not shown in progress either: on a host that never reads it, the
4664
+ // row would say "setting up" forever. It reads as the quarantine (its `inProgress` names
4665
+ // the pid), and retire, which never takes it for gone, refuses it with the way out.
4666
+ if (rollbackIncomplete?.inProgress && processLiveness(rollbackIncomplete.inProgress).state === "alive") { rollbackIncomplete = undefined; spawnInProgress = true; }
4536
4667
  }
4537
4668
  // A self-retire that has been requested but not completed: the home is
4538
4669
  // owed a retirement, not live work. Read-only here — completion is the
@@ -4544,7 +4675,7 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION) {
4544
4675
  catch { retirePending = { reason: "retire pending" }; }
4545
4676
  }
4546
4677
  // A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
4547
- const liveness = recordsHerdr(meta, readJsonOrUndefined(retirementBaselinePath(home)))
4678
+ const liveness = recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(home)))
4548
4679
  ? { running: null, runtimeState: "unsupported", runtimeError: `E_HERDR_REMOVED: ${herdrInstanceRemoved(e.name).message}` }
4549
4680
  : tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name);
4550
4681
  const identity = servedIdentityOf(meta);
@@ -4574,7 +4705,7 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION) {
4574
4705
  try { const s = instanceSessionTarget(home); if (!s.target || !harnessRunning(inspectSessionTarget(s.target))) waitingOnYou = null; }
4575
4706
  catch { waitingOnYou = null; }
4576
4707
  }
4577
- 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 } : {}), ...(retirePending ? { retirePending } : {}) };
4708
+ 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 } : {}) };
4578
4709
 
4579
4710
  });
4580
4711
  };
@@ -4738,12 +4869,12 @@ function directoryIdentity(path) {
4738
4869
  // lock creation or backend observation. A metadata mode edit cannot disable it.
4739
4870
  function sessionDirectoryGuard(home) {
4740
4871
  let baseline;
4741
- try { baseline = JSON.parse(readFileSync(retirementBaselinePath(home), "utf8")); }
4872
+ try { baseline = JSON.parse(readFileSync(findRetirementBaseline(home), "utf8")); }
4742
4873
  catch (e) { if (e.code === "ENOENT") return () => {}; throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", "independent session receipt is unreadable"); }
4743
4874
  const expected = join(realPathOrNearest(dirname(home)), basename(home));
4744
4875
  const check = () => {
4745
4876
  if (baseline.directoryWork === true) {
4746
- if (baseline.version !== RETIRE_BASELINE_VERSION || baseline.home !== expected) throw oatsError("E_WORK_INSPECTION_FAILED", "invalid independent directory home authority");
4877
+ if (baseline.version !== RETIRE_BASELINE_VERSION || !receiptRecordsHome(baseline, receiptHomeIdentity(home))) throw oatsError("E_WORK_INSPECTION_FAILED", "invalid independent directory home authority");
4747
4878
  assertDirectoryRoots(home, expected);
4748
4879
  for (const [name, path] of [["home", home], ["work", join(home, "work")]]) {
4749
4880
  const actual = directoryIdentity(path), recorded = baseline.directoryRoots?.[name];
@@ -4789,6 +4920,12 @@ function fetchObservedBase(repoAbs, { key, oid, remote }) {
4789
4920
  { details: { repo: repoAbs, repoKey: key, commit: oid, remote } });
4790
4921
  }
4791
4922
 
4923
+ /** Whether `clone` is a clone of the member `key`, read from its local remotes only (never the network):
4924
+ * OATS_TREE_MEMBER names a member only when this holds. */
4925
+ export function cloneOfMember(clone, key) {
4926
+ try { verifyMemberClone(clone, key); return true; } catch { return false; }
4927
+ }
4928
+
4792
4929
  /** A failed spawn's compare-and-delete of the branch it created at `oid`: `git update-ref -d` refuses
4793
4930
  * atomically if the tip moved (something was committed there), and the branch is then kept. `run`
4794
4931
  * answers { ok, out, status, err }. → what is still owed, as messages ([] when the branch is gone). */
@@ -4802,8 +4939,11 @@ function deleteBranchAsCreated(run, repoAbs, branch, oid) {
4802
4939
  }
4803
4940
  /** Retain the home and its cleanup receipt when spawn compensation or retirement
4804
4941
  * cannot finish. Keeping the original credentials makes cleanup retryable. */
4805
- function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, recordRetirementBaseline = false, reason, directoryPreservation = false, orphanedWork = false, directoryHome = realPathOrNearest(home) }) {
4806
- const marker = {
4942
+ /** The quarantine marker (`.oats-rollback-incomplete.json`) a rollback that cannot finish leaves:
4943
+ * the cleanup descriptor a retry consumes (usableCleanupDescriptor). One builder for the
4944
+ * rollback below and for a spawn's in-progress marker (#796), which adds `inProgress`. */
4945
+ function buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, reason, directoryPreservation = false, orphanedWork = false }) {
4946
+ return {
4807
4947
  // `reason` is optional and DEFAULTS to the spawn wording, so every existing
4808
4948
  // caller is byte-identical; only a caller that supplies one differs. The
4809
4949
  // quarantine shape is now reached from two events and a fixed "spawn"
@@ -4833,12 +4973,20 @@ function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomp
4833
4973
  },
4834
4974
  createdAt: new Date().toISOString(),
4835
4975
  };
4976
+ }
4977
+ /** Write a quarantine marker by rename, so a marker that replaces another (a spawn's
4978
+ * compensation over its in-progress marker) never leaves two files or a moment with none.
4979
+ * `extra` adds top-level fields (`inProgress`). */
4980
+ function writeQuarantineMarker(home, marker, extra = {}, mode) {
4981
+ writeJsonAtomic(join(home, ".oats-rollback-incomplete.json"), { ...marker, ...extra }, mode);
4982
+ }
4983
+ function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, recordRetirementBaseline = false, reason, directoryPreservation = false, orphanedWork = false, directoryHome = realPathOrNearest(home) }) {
4984
+ const marker = buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, reason, directoryPreservation, orphanedWork });
4836
4985
  try {
4837
- const path = join(home, ".oats-rollback-incomplete.json");
4838
4986
  if (work === "directory") {
4839
4987
  assertDirectoryHome(home, directoryHome);
4840
- writeJsonAtomic(path, marker, 0o600);
4841
- } else writeFileSync(path, JSON.stringify(marker, null, 2) + "\n");
4988
+ writeQuarantineMarker(home, marker, {}, 0o600);
4989
+ } else writeQuarantineMarker(home, marker);
4842
4990
  } catch {
4843
4991
  if (work === "directory") {
4844
4992
  // Never write through a substituted home (even its metadata paths).
@@ -4918,7 +5066,19 @@ function usableCleanupDescriptor(marker) {
4918
5066
  return true;
4919
5067
  }
4920
5068
 
5069
+ // The stored digests are versioned apart (`digestVersion`, BASELINE_DIGEST_VERSION): this version
5070
+ // also gates runtime, directory-home and provider-exclusion authority, so a bump would refuse them all.
4921
5071
  const RETIRE_BASELINE_VERSION = 2;
5072
+ /** The version of the stored digests a spawn baseline is written with (fingerprintTrees,
5073
+ * generatedWorkDigest); a baseline without `digestVersion` holds the legacy ones, 1. */
5074
+ const BASELINE_DIGEST_VERSION = 2;
5075
+ /** The version of a baseline's stored digests (`homeFingerprint`, `generatedWorkFingerprint`):
5076
+ * 1 when it has no `digestVersion` (or there is no baseline), 2 when it says 2, and undefined for
5077
+ * any other value, which no digest this kernel takes matches. It is never inferred. */
5078
+ function baselineDigestVersion(baseline) {
5079
+ if (!baseline || !Object.hasOwn(baseline, "digestVersion")) return 1;
5080
+ return baseline.digestVersion === BASELINE_DIGEST_VERSION ? BASELINE_DIGEST_VERSION : undefined;
5081
+ }
4922
5082
 
4923
5083
  function retirementStateRoot(home) {
4924
5084
  // Independent of the bytes it authenticates, but colocated with the agent's
@@ -4927,12 +5087,58 @@ function retirementStateRoot(home) {
4927
5087
  return join(dirname(home), ".oats-retirement");
4928
5088
  }
4929
5089
 
4930
- function retirementKey(home) {
4931
- return createHash("sha256").update(join(realPathOrNearest(dirname(home)), basename(home))).digest("hex");
5090
+ /** A home's identity as a receipt records it: its on-disk spelling, own name included. A home that
5091
+ * is a symlink is not followed: its parent's on-disk spelling and its name as given (a home
5092
+ * exchanged for a symlink is not the home it points at). */
5093
+ function receiptHomeIdentity(home) {
5094
+ let st;
5095
+ try { st = lstatSync(home); } catch { /* not there: spelled as the nearest existing ancestor */ }
5096
+ return st && !st.isSymbolicLink() ? canonicalHomePath(home) : join(canonicalHomePath(dirname(home)), basename(home));
5097
+ }
5098
+
5099
+ /** Whether a receipt's recorded home is this home, whatever spelling either was written in.
5100
+ * `current` is the home as the caller resolves it for the comparison. */
5101
+ function receiptRecordsHome(baseline, current) {
5102
+ return typeof baseline?.home === "string" && receiptHomeIdentity(baseline.home) === current;
5103
+ }
5104
+
5105
+ function retirementBaselineFile(identity) {
5106
+ return join(retirementStateRoot(identity), "baselines", `${createHash("sha256").update(identity).digest("hex")}.json`);
4932
5107
  }
4933
5108
 
5109
+ /** Where a spawn writes a home's receipt: keyed by its canonical identity. */
4934
5110
  function retirementBaselinePath(home) {
4935
- return join(retirementStateRoot(home), "baselines", `${retirementKey(home)}.json`);
5111
+ return retirementBaselineFile(receiptHomeIdentity(home));
5112
+ }
5113
+
5114
+ /** Where a kernel before 0.49.0 wrote it: keyed by the parent's realpath in the spawn's own
5115
+ * spelling, which on a case-insensitive filesystem need not be the on-disk one. */
5116
+ function legacyRetirementBaselinePath(home) {
5117
+ return retirementBaselineFile(join(realPathOrNearest(dirname(home)), basename(home)));
5118
+ }
5119
+
5120
+ /** The receipt every reader uses: the canonical one if it exists, else one an earlier kernel left
5121
+ * under this caller's spelling, else the canonical path (absent). Read-only: a receipt found at the
5122
+ * legacy key is used where it is, never moved, copied or rewritten elsewhere.
5123
+ *
5124
+ * Limits. A legacy receipt written under spelling S is found only from S, or from the canonical
5125
+ * spelling when that is S: a third spelling of such a home misses it (address the home as
5126
+ * `oats status` prints it, the spawn's spelling). Receipts outlive retire, so a reused name can
5127
+ * leave an earlier incarnation's receipt behind; the canonical one wins, which is right for every
5128
+ * home spawned from 0.49.0 on. It is wrong in one case: two incarnations of the same name, both
5129
+ * spawned by a kernel before 0.49.0 under different spellings, the earlier one under the canonical
5130
+ * spelling. The later home then reads the earlier one's receipt. Its stale endpoint disagrees with
5131
+ * instance.json (E_RUNTIME_AUTHORITY_MISMATCH) unless the later incarnation sits at the same
5132
+ * endpoint, where session control already targets the right session. Retire finds the home
5133
+ * fingerprint changed and preserves the home, less the stale receipt's disposable roots; a
5134
+ * directory-work disagreement is E_WORK_INSPECTION_FAILED; and a start's record rewrites the stale
5135
+ * file, as a kernel before 0.49.0 already does when a caller's spelling matches an earlier
5136
+ * incarnation's. */
5137
+ function findRetirementBaseline(home) {
5138
+ const canonical = retirementBaselinePath(home);
5139
+ if (existsSync(canonical)) return canonical;
5140
+ const legacy = legacyRetirementBaselinePath(home);
5141
+ return legacy !== canonical && existsSync(legacy) ? legacy : canonical;
4936
5142
  }
4937
5143
 
4938
5144
  /** git's output for a large tree (status with untracked and ignored files,
@@ -4944,6 +5150,53 @@ function retirementBaselinePath(home) {
4944
5150
  * loudly, and streaming is deliberately not attempted in this change. */
4945
5151
  const GIT_MAX_BUFFER = 512 * 1024 * 1024;
4946
5152
 
5153
+ /** How the retire runs Git on the instance's work, its repository, a
5154
+ * repository under the work and a recovery clone (awebai/oats#662, #679):
5155
+ * argv only, no shell; optional locks off (`--no-optional-locks` and
5156
+ * GIT_OPTIONAL_LOCKS=0), so a status never refreshes, and so never rewrites,
5157
+ * the index it inspects; no helper that a repository's own configuration
5158
+ * names can run (fsmonitor, hooks, an external diff), nor any command a
5159
+ * fetch would run (GIT_NO_LAZY_FETCH=1: an object a promisor repository
5160
+ * lacks is a failed read, never fetched through a remote, helper, ssh
5161
+ * command or credential helper its configuration names; Git before 2.44
5162
+ * ignores the variable); and nothing of the caller's environment redirects
5163
+ * what is read. Git's own list of
5164
+ * repository-local variables (`git rev-parse --local-env-vars`: GIT_DIR,
5165
+ * GIT_WORK_TREE, GIT_INDEX_FILE, GIT_COMMON_DIR, the object directories,
5166
+ * GIT_CONFIG and GIT_CONFIG_PARAMETERS, …) and the GIT_CONFIG_KEY_<n> and
5167
+ * GIT_CONFIG_VALUE_<n> pairs are left out. `env` adds variables after that:
5168
+ * a read that names its own GIT_INDEX_FILE keeps it.
5169
+ * The operator's global and system configuration stay read, unlike
5170
+ * lib/instance-git.mjs's READ_ONLY_GIT with gitEnv(): the spawn baseline was
5171
+ * taken under them, and without them a status reads differently (a global
5172
+ * core.excludesFile, core.autocrlf, a filter), which would add a copy
5173
+ * attempt to every existing instance's retire. These flags leave a status as
5174
+ * it was. They are the operator's own; what the retire guards against is
5175
+ * configuration the retired agent could write.
5176
+ * Known limit: a filter driver that the repository's configuration names and
5177
+ * its .gitattributes select can still run during `git status`; turning it
5178
+ * off would change what status reports. */
5179
+ const RETIRE_GIT_FLAGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "diff.external="];
5180
+ const RETIRE_GIT_DROPPED_ENV = new Set(["GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_PREFIX", "GIT_SHALLOW_FILE", "GIT_COMMON_DIR"]);
5181
+ function retireGitEnv(env) {
5182
+ const out = {};
5183
+ for (const [key, value] of Object.entries(process.env)) {
5184
+ if (!RETIRE_GIT_DROPPED_ENV.has(key) && !/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(key)) out[key] = value;
5185
+ }
5186
+ return { ...out, GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1", ...env };
5187
+ }
5188
+ /** One retire Git command in `repo` (`-C`; null for none, as for a clone) →
5189
+ * its stdout (a Buffer, or text with `encoding`); throws what execFileSync
5190
+ * throws. */
5191
+ function retireGit(repo, args, { env, input, encoding } = {}) {
5192
+ return execFileSync("git", [...RETIRE_GIT_FLAGS, ...(repo === null ? [] : ["-C", repo]), ...args],
5193
+ { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, encoding, maxBuffer: GIT_MAX_BUFFER, shell: false, env: retireGitEnv(env) });
5194
+ }
5195
+ /** retireGit that never throws → spawnSync's result, for a caller that reads the exit status. */
5196
+ function retireGitProbe(repo, args, { encoding } = {}) {
5197
+ return spawnSync("git", [...RETIRE_GIT_FLAGS, "-C", repo, ...args], { stdio: ["ignore", "pipe", "pipe"], encoding, maxBuffer: GIT_MAX_BUFFER, shell: false, env: retireGitEnv() });
5198
+ }
5199
+
4947
5200
  /** Kernel-owned receipts the kernel itself appends to a home after the spawn
4948
5201
  * baseline (events log, stop/restart receipts). They are evidence about the
4949
5202
  * instance, not the instance's work, so the stored digest a spawn baseline is
@@ -4962,12 +5215,19 @@ const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oat
4962
5215
  * settings.json at every launch. The stored digest passes over exactly that
4963
5216
  * path, home-relative; the exact digest holds it, as the home copy does. */
4964
5217
  const HARNESS_HOME_SETTINGS = new Set([join(".claude", "settings.json")]);
5218
+ /** Kernel state written under `.oats/` after the spawn baseline (#796): the extra
5219
+ * trees' records (`oats worktree add|remove`) and the `worktree` hooks' logs.
5220
+ * Receipts, not work: the stored digest passes over them as it does over the
5221
+ * kernel's top-level receipts; the exact digest and the home copy hold them.
5222
+ * They live under `.oats`, which a capability may not declare as its own. */
5223
+ const KERNEL_HOME_STATE_DIRS = new Set([join(".oats", "trees"), join(".oats", "logs")]);
4965
5224
  /** The refusal for an entry that is not a file, a directory or a symbolic link
4966
5225
  * (a socket, a FIFO, a device): it has no bytes to read or to copy. One
4967
5226
  * sentence for every caller of fingerprintTree, at spawn and at retire, so it
4968
5227
  * names neither. It does not say "remove": the entry may be a live endpoint. */
4969
5228
  const unsupportedEntry = (path) => oatsError("E_WORK_INSPECTION_FAILED", `${path} has an unsupported filesystem type: it is not a file, a directory or a symbolic link, so it cannot be read or copied. Safely stop the process or resource that owns it, or move the entry elsewhere, before retrying`);
4970
5229
  const PATH_SEPARATOR_BYTES = Buffer.from(sep);
5230
+ const GIT_NAME = Buffer.from(".git");
4971
5231
  /** The digests of a tree, from one walk that reads each file once → { stored,
4972
5232
  * exact }; each only when asked for (`stored` by default).
4973
5233
  *
@@ -4975,29 +5235,39 @@ const PATH_SEPARATOR_BYTES = Buffer.from(sep);
4975
5235
  * permission bits, its kind, and a file's bytes or a link's target. Entry
4976
5236
  * names and link targets are read and hashed as bytes, never as decoded
4977
5237
  * text: two trees that differ only in bytes that are not UTF-8 have two
4978
- * digests, and an entry with such a name is read, not missed. This is about
4979
- * what a digest tells apart. It does not make such a tree copyable:
4980
- * copyTreeSafe reads entry names as text and cannot carry a file name that
4981
- * is not UTF-8.
5238
+ * digests, and an entry with such a name is read, not missed. copyTreeSafe
5239
+ * reads, joins and writes names as bytes too, so such an entry is copied.
5240
+ * `root` is a path, as text or as bytes.
4982
5241
  *
4983
5242
  * A name's text (its bytes decoded as UTF-8, the way readdirSync decodes
4984
5243
  * them: replacement characters for bytes that are not UTF-8, a byte order
4985
- * mark kept) is used only to order the entries and to test membership: the
4986
- * names a digest passes over and `instance.json`, as they have always been
4987
- * tested. Both digests pass over what a copy does not carry: `excludeRoot`
4988
- * and, with `excludeGitMetadata`, `.git`. Only the stored digest also passes
4989
- * over the kernel's receipts and the harness settings of a home.
5244
+ * mark kept) is used only to test membership: the names a digest passes over
5245
+ * and `instance.json`, as they have always been tested, and to order the
5246
+ * entries for the legacy stored digest. Both digests pass over what a copy
5247
+ * does not carry: `excludeRoot`, names at the top level tested as text, and
5248
+ * `excludePaths`, exact paths under the root as bytes (a list of Buffers):
5249
+ * an entry is passed over only where its whole path is one of them, whatever
5250
+ * its kind, never by its name alone. Only the stored digest also passes over
5251
+ * the kernel's receipts and the harness settings of a home.
4990
5252
  *
4991
- * `stored` is the digest a spawn baseline holds, written by this kernel or
4992
- * by an older one, so it never changes: its framing (each field followed by
4993
- * NUL, no lengths), its order, and a home's `instance.json` without the
4994
- * fields the kernel writes after spawn (kernelNeutralInstanceJson). For a
4995
- * tree whose names and link targets are all valid UTF-8 it is what it was
4996
- * when they were read as text: hashing a text hashes its UTF-8, which is
4997
- * those bytes. It is what is compared with a baseline. Without lengths it
4998
- * reads alike a file whose bytes spell the entry that follows it and those
4999
- * two entries, and the neutral form reads alike two `instance.json` files
5000
- * that parse to the same value.
5253
+ * `stored` is the digest a spawn baseline holds and is compared with, in the
5254
+ * version `digestVersion` names (the baseline's own: baselineDigestVersion).
5255
+ * Both versions hold a home's `instance.json` without the fields the kernel
5256
+ * writes after spawn (kernelNeutralInstanceJson), so they read alike two
5257
+ * `instance.json` files that parse to the same value.
5258
+ * - 1, the legacy digest: what a baseline without `digestVersion` holds,
5259
+ * written by a kernel before 0.49.0. It never changes: its framing (each
5260
+ * field followed by NUL, no lengths) and its order (the names as text,
5261
+ * compared by localeCompare, so it depends on the locale). For a tree whose
5262
+ * names and link targets are all valid UTF-8 it is what it was when they
5263
+ * were read as text: hashing a text hashes its UTF-8, which is those bytes.
5264
+ * Without lengths it reads alike a file whose bytes spell the entry that
5265
+ * follows it and those two entries.
5266
+ * - 2 (BASELINE_DIGEST_VERSION), what a spawn writes now: the framing of the
5267
+ * exact digest below, and the entries ordered by the bytes of their names,
5268
+ * which no locale changes. Two trees it does not read alike are two
5269
+ * trees, but for the receipts, the harness settings and the neutral form
5270
+ * of `instance.json` it passes over.
5001
5271
  *
5002
5272
  * `exact` is for every comparison of a tree with itself later, or with its
5003
5273
  * copy: whether the retire hooks left it as it was. It is kept nowhere. It
@@ -5007,7 +5277,11 @@ const PATH_SEPARATOR_BYTES = Buffer.from(sep);
5007
5277
  * path, its mode, its kind and its content, where the path and the content
5008
5278
  * carry their length and the mode and the kind end in NUL, so the stream can
5009
5279
  * be read back into its entries in one way only, and a tree is the set of
5010
- * its entries. A home's `instance.json` goes in as the bytes it has.
5280
+ * its entries. A home's `instance.json` goes in as the bytes it has. It
5281
+ * follows the walk's order: the legacy digest's when the walk takes that
5282
+ * one too, the order of the bytes otherwise. An exact digest is compared
5283
+ * only with one taken with the same options (an inspection's, with the
5284
+ * same baseline), so the two are taken in one order.
5011
5285
  *
5012
5286
  * The root's own permission bits, which are no entry of the walk, are in
5013
5287
  * the exact digest: a path the recovery copier copies is compared with its
@@ -5016,69 +5290,90 @@ const PATH_SEPARATOR_BYTES = Buffer.from(sep);
5016
5290
  * its copy is made inside a directory the copier creates, so the root's bits
5017
5291
  * are no part of what it carries, and the root is compared through its
5018
5292
  * children alone. The stored digest never holds the root's bits. */
5019
- function fingerprintTrees(root, { excludeRoot = new Set(), excludeGitMetadata = false, instanceHome = false, stored = true, exact = false, children = false } = {}) {
5020
- const s = stored ? createHash("sha256") : null, x = exact ? createHash("sha256") : null;
5021
- const digests = () => ({ stored: s ? `sha256:${s.digest("hex")}` : undefined, exact: x ? `sha256:${x.digest("hex")}` : undefined });
5022
- /** A field of the exact digest whose length is not fixed: its length, NUL, its bytes. */
5023
- const sized = (bytes) => { x.update(String(bytes.length)); x.update("\0"); x.update(bytes); };
5293
+ function fingerprintTrees(root, { excludeRoot = new Set(), excludePaths = [], instanceHome = false, stored = true, digestVersion = 1, exact = false, children = false } = {}) {
5294
+ if (stored && digestVersion !== 1 && digestVersion !== BASELINE_DIGEST_VERSION) throw new Error(`no stored digest of version ${digestVersion}`);
5295
+ const legacy = stored && digestVersion === 1;
5296
+ const excluded = new Set(excludePaths.map((path) => path.toString("hex")));
5297
+ // The stored digest: `s` when it is the legacy one, `v` when it is version 2.
5298
+ const s = legacy ? createHash("sha256") : null, v = stored && !legacy ? createHash("sha256") : null, x = exact ? createHash("sha256") : null;
5299
+ const digests = () => ({ stored: s || v ? `sha256:${(s || v).digest("hex")}` : undefined, exact: x ? `sha256:${x.digest("hex")}` : undefined });
5300
+ /** A field whose length is not fixed, in the exact digest or in version 2: its length, NUL, its bytes. */
5301
+ const sizedIn = (hash, bytes) => { hash.update(String(bytes.length)); hash.update("\0"); hash.update(bytes); };
5302
+ const sized = (bytes) => sizedIn(x, bytes);
5024
5303
  const rootStat = lstatSync(root);
5025
5304
  if (!rootStat.isDirectory()) {
5026
5305
  const mode = String(rootStat.mode & 0o7777);
5027
5306
  s?.update(mode); s?.update("\0");
5307
+ v?.update("entry\0"); v?.update(mode); v?.update("\0");
5028
5308
  x?.update("entry\0"); x?.update(mode); x?.update("\0");
5029
- if (rootStat.isSymbolicLink()) { const target = readlinkSync(root, "buffer"); s?.update("link\0"); s?.update(target); if (x) { x.update("link\0"); sized(target); } }
5030
- else if (rootStat.isFile()) { const bytes = readFileSync(root); s?.update("file\0"); s?.update(bytes); if (x) { x.update("file\0"); sized(bytes); } }
5031
- else throw unsupportedEntry(root);
5309
+ 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); } }
5310
+ 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); } }
5311
+ else throw unsupportedEntry(String(root));
5032
5312
  return digests();
5033
5313
  }
5314
+ v?.update("tree\0");
5034
5315
  x?.update(children ? "tree\0" : `tree with its mode\0${rootStat.mode & 0o7777}\0`);
5035
5316
  // `dir` and `rel` are bytes: the directory, and its path under the root
5036
5317
  // (empty at the root). `relText` is `rel` as text, for the name tests.
5037
- // `outer` is the stored hash, or null inside an entry it passes over.
5038
- const walk = (dir, rel, relText, outer) => {
5039
- // The order is the one it has always been: the names as text, compared
5040
- // by localeCompare, on the listing as readdirSync returns it. The sort is
5041
- // stable and the listing is the same whether its names come as text or
5042
- // as bytes, so a tree whose names are all valid UTF-8 is walked in the
5043
- // order it always was. Names that decode alike (two that are not UTF-8,
5044
- // or one and a name that really holds the replacement character) keep
5045
- // the listing's order. Where that order is not fixed, two reads of one
5046
- // directory can differ, which adds a copy attempt; two different trees
5047
- // cannot read alike for it, because the bytes of every name are hashed.
5048
- const entries = readdirSync(dir, { encoding: "buffer" }).map((bytes) => ({ bytes, name: bytes.toString("utf8") }));
5049
- entries.sort((a, b) => a.name.localeCompare(b.name));
5318
+ // `storedOn` is false inside an entry the stored digest passes over.
5319
+ const walk = (dir, rel, relText, storedOn) => {
5320
+ // The legacy order is the one it has always been: the names as text,
5321
+ // compared by localeCompare, on the listing as readdirSync returns it.
5322
+ // The sort is stable and the listing is the same whether its names come
5323
+ // as text or as bytes, so a tree whose names are all valid UTF-8 is
5324
+ // walked in the order it always was. Names that decode alike (two that
5325
+ // are not UTF-8, or one and a name that really holds the replacement
5326
+ // character) keep the listing's order. Where that order is not fixed, two
5327
+ // reads of one directory can differ, which adds a copy attempt; two
5328
+ // different trees cannot read alike for it, because the bytes of every
5329
+ // name are hashed. Every other walk is in the order of the names' bytes
5330
+ // (entriesAsBytes), which is fixed.
5331
+ const entries = legacy
5332
+ ? readdirSync(dir, { encoding: "buffer" }).map((bytes) => ({ bytes, name: bytes.toString("utf8") })).sort((a, b) => a.name.localeCompare(b.name))
5333
+ : entriesAsBytes(dir).map((e) => ({ bytes: e.name, name: e.name.toString("utf8") }));
5050
5334
  for (const { bytes: nameBytes, name } of entries) {
5051
- if ((!relText && excludeRoot.has(name)) || (excludeGitMetadata && name === ".git")) continue;
5335
+ const childRel = rel.length ? Buffer.concat([rel, PATH_SEPARATOR_BYTES, nameBytes]) : nameBytes;
5336
+ if ((!relText && excludeRoot.has(name)) || (excluded.size && excluded.has(childRel.toString("hex")))) continue;
5052
5337
  const childRelText = relText ? join(relText, name) : name;
5053
- const storedPassesOver = instanceHome && ((!relText && (KERNEL_HOME_RECEIPTS.has(name) || KERNEL_HOME_RECEIPT_PATTERNS.some((p) => p.test(name)))) || HARNESS_HOME_SETTINGS.has(childRelText));
5338
+ const storedPassesOver = instanceHome && ((!relText && (KERNEL_HOME_RECEIPTS.has(name) || KERNEL_HOME_RECEIPT_PATTERNS.some((p) => p.test(name)))) || HARNESS_HOME_SETTINGS.has(childRelText) || KERNEL_HOME_STATE_DIRS.has(childRelText));
5054
5339
  if (storedPassesOver && !x) continue;
5055
- const s = storedPassesOver ? null : outer;
5056
- const childRel = rel.length ? Buffer.concat([rel, PATH_SEPARATOR_BYTES, nameBytes]) : nameBytes;
5340
+ const on = storedOn && !storedPassesOver;
5341
+ const s = on ? outerS : null, v = on ? outerV : null;
5057
5342
  const path = Buffer.concat([dir, PATH_SEPARATOR_BYTES, nameBytes]);
5058
5343
  const st = lstatSync(path);
5059
5344
  const mode = String(st.mode & 0o7777);
5060
5345
  s?.update(childRel); s?.update("\0"); s?.update(mode); s?.update("\0");
5346
+ if (v) { sizedIn(v, childRel); v.update(mode); v.update("\0"); }
5061
5347
  if (x) { sized(childRel); x.update(mode); x.update("\0"); }
5062
5348
  if (st.isSymbolicLink()) {
5063
5349
  const target = readlinkSync(path, "buffer");
5064
5350
  s?.update("link\0"); s?.update(target); s?.update("\0");
5351
+ if (v) { v.update("link\0"); sizedIn(v, target); }
5065
5352
  if (x) { x.update("link\0"); sized(target); }
5066
5353
  } else if (st.isFile()) {
5067
5354
  const bytes = readFileSync(path);
5068
5355
  // Kernel-field neutrality applies ONLY when the tree IS an instance home, and only to the
5069
5356
  // stored digest; a work tree's instance.json is the agent's bytes.
5070
- s?.update("file\0"); s?.update(instanceHome && !relText && name === "instance.json" ? kernelNeutralInstanceJson(bytes) : bytes); s?.update("\0");
5357
+ const storedBytes = s || v ? (instanceHome && !relText && name === "instance.json" ? kernelNeutralInstanceJson(bytes) : bytes) : undefined;
5358
+ s?.update("file\0"); s?.update(storedBytes); s?.update("\0");
5359
+ if (v) { v.update("file\0"); sizedIn(v, storedBytes); }
5071
5360
  if (x) { x.update("file\0"); sized(bytes); }
5072
- } else if (st.isDirectory()) { s?.update("dir\0"); x?.update("dir\0"); walk(path, childRel, childRelText, s); }
5073
- else throw unsupportedEntry(join(root, childRelText));
5361
+ } else if (st.isDirectory()) { s?.update("dir\0"); v?.update("dir\0"); x?.update("dir\0"); walk(path, childRel, childRelText, on); }
5362
+ else throw unsupportedEntry(join(String(root), childRelText));
5074
5363
  }
5075
5364
  };
5076
- walk(Buffer.from(root), Buffer.alloc(0), "", s);
5365
+ const outerS = s, outerV = v;
5366
+ walk(Buffer.from(root), Buffer.alloc(0), "", true);
5077
5367
  return digests();
5078
5368
  }
5079
- /** The stored digest of a tree (fingerprintTrees): what a spawn baseline holds and is compared with. */
5369
+ /** The legacy stored digest of a tree (fingerprintTrees, version 1): what a spawn baseline without
5370
+ * `digestVersion` holds and is compared with. */
5080
5371
  function fingerprintTree(root, options = {}) {
5081
- return fingerprintTrees(root, { ...options, stored: true, exact: false }).stored;
5372
+ return fingerprintTrees(root, { ...options, stored: true, digestVersion: 1, exact: false }).stored;
5373
+ }
5374
+ /** The stored digest of a tree in `digestVersion` (fingerprintTrees): 1, the legacy one, or 2. */
5375
+ function storedTreeDigest(root, digestVersion, options = {}) {
5376
+ return fingerprintTrees(root, { ...options, stored: true, digestVersion, exact: false }).stored;
5082
5377
  }
5083
5378
  /** The exact digest of a tree (fingerprintTrees): what a tree is compared with itself later, or with its copy. */
5084
5379
  function exactTreeDigest(root, options = {}) {
@@ -5090,7 +5385,10 @@ const directoryBytes = (work) => exactTreeDigest(work);
5090
5385
 
5091
5386
  /** A worktree directory whose git admin entry is gone: no `.git`, an unreadable one, or a gitfile naming an
5092
5387
  * admin directory that no longer exists. Read from the gitfile, not asked of git, which would walk up into
5093
- * whatever repository encloses the home. A `.git` directory is a repository of its own, not this case. */
5388
+ * whatever repository encloses the home. A `.git` directory is a repository of its own, not this case.
5389
+ * The gitfile is parsed as Git parses it (setup.c, read_gitfile_gently): the file starts with `gitdir: `,
5390
+ * and the path is the rest of it with its trailing run of line feeds and carriage returns removed, white
5391
+ * space kept (awebai/oats#647). A file Git would not read as a gitfile names no admin entry. */
5094
5392
  function worktreeAdminMissing(work) {
5095
5393
  const dotGit = join(work, ".git");
5096
5394
  let stat;
@@ -5099,9 +5397,10 @@ function worktreeAdminMissing(work) {
5099
5397
  if (!stat.isFile()) return true;
5100
5398
  let text;
5101
5399
  try { text = readFileSync(dotGit, "utf8"); } catch { return true; }
5102
- const m = /^gitdir:\s*(.+?)\s*$/m.exec(text);
5103
- if (!m) return true;
5104
- return !existsSync(join(resolve(work, m[1]), "HEAD"));
5400
+ if (!text.startsWith("gitdir: ")) return true;
5401
+ const path = text.slice("gitdir: ".length).replace(/[\r\n]+$/, "");
5402
+ if (!path) return true;
5403
+ return !existsSync(join(resolve(work, path), "HEAD"));
5105
5404
  }
5106
5405
  /** A repository's status as Git printed it, as bytes. A path that is not
5107
5406
  * UTF-8 is in there as it is: the work state compares these bytes
@@ -5109,7 +5408,7 @@ function worktreeAdminMissing(work) {
5109
5408
  * a `git status` that fails is. */
5110
5409
  function worktreeStatusBytes(repo) {
5111
5410
  try {
5112
- return execFileSync("git", ["-C", repo, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching", "--ignore-submodules=none"], { stdio: ["ignore", "pipe", "pipe"] , maxBuffer: GIT_MAX_BUFFER });
5411
+ return retireGit(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching", "--ignore-submodules=none"]);
5113
5412
  } catch (e) {
5114
5413
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not inspect instance worktree: ${String(e.stderr ?? e.message ?? "").trim() || "git status failed"}`);
5115
5414
  }
@@ -5152,6 +5451,48 @@ function assertStatusAgrees(source, recovered, what, repo) {
5152
5451
  throw Object.assign(new Error(`${what}${shown ? `: ${shown}${more}` : ""}`), { statusDisagreement: { repo, ...diff } });
5153
5452
  }
5154
5453
 
5454
+ /** The digest of a worktree's untracked (`??`) and ignored (`!!`) paths, outside the disposable
5455
+ * roots, that a spawn baseline stores as `generatedWorkFingerprint`, in the baseline's digest
5456
+ * version (baselineDigestVersion) → the digest, or undefined for a version this kernel does not
5457
+ * take. `statusBytes` is the worktree's status as bytes (worktreeStatusBytes). */
5458
+ function generatedWorkFingerprintIn(digestVersion, work, statusBytes, disposableRoots = []) {
5459
+ if (digestVersion === 1) return generatedWorkFingerprint(work, statusBytes.toString("utf8"), disposableRoots);
5460
+ if (digestVersion === BASELINE_DIGEST_VERSION) return generatedWorkDigest(work, statusBytes, disposableRoots);
5461
+ return undefined;
5462
+ }
5463
+ /** Version 2 of generatedWorkFingerprint. The paths are the status's bytes (untrackedOrIgnoredPaths),
5464
+ * so a name that is not UTF-8 is read by its own name, and they are in the order of those bytes. A
5465
+ * path is hashed as its length and its bytes, then, by lstat (a link is never followed): `missing`
5466
+ * for one that is not there, else its stored digest of version 2 (a link is its target's bytes,
5467
+ * whether or not the target exists). A trailing `/` (an ignored directory's row) is hashed with the
5468
+ * path but not used to read it, so a link in its place is read as the link. A disposable root owns
5469
+ * a path that is it or under it, compared as bytes, as the legacy digest compares it as text.
5470
+ * A path that cannot be tested (lstat fails otherwise than for an entry that is not there) or read
5471
+ * (an entry under it without permission, for example) is no path the digest can prove anything
5472
+ * of: it throws E_WORK_INSPECTION_FAILED, `could not inspect <path>: <reason>`, the path as text. */
5473
+ function generatedWorkDigest(work, statusBytes, disposableRoots = []) {
5474
+ const roots = disposableRoots.map((root) => [Buffer.from(root), Buffer.from(`${root}${sep}`)]);
5475
+ const owned = (path) => roots.some(([root, under]) => path.equals(root) || (path.length >= under.length && path.subarray(0, under.length).equals(under)));
5476
+ const paths = untrackedOrIgnoredPaths(statusBytes).filter((path) => !owned(path)).sort(Buffer.compare);
5477
+ const hash = createHash("sha256");
5478
+ for (const rel of paths) {
5479
+ hash.update(String(rel.length)); hash.update("\0"); hash.update(rel);
5480
+ const path = joinBytes(work, rel.length > 1 && rel[rel.length - 1] === 0x2f ? rel.subarray(0, -1) : rel);
5481
+ const uninspectable = (e) => (e?.code === "E_WORK_INSPECTION_FAILED" ? e : oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path.toString()}: ${e.message}`));
5482
+ try { lstatSync(path); }
5483
+ catch (e) {
5484
+ if (e?.code !== "ENOENT" && e?.code !== "ENOTDIR") throw uninspectable(e);
5485
+ hash.update("missing\0"); continue;
5486
+ }
5487
+ let digest;
5488
+ try { digest = storedTreeDigest(path, BASELINE_DIGEST_VERSION); }
5489
+ catch (e) { throw uninspectable(e); }
5490
+ hash.update(digest); hash.update("\0");
5491
+ }
5492
+ return `sha256:${hash.digest("hex")}`;
5493
+ }
5494
+ /** The legacy generatedWorkFingerprint (digest version 1), for a baseline without `digestVersion`.
5495
+ * It never changes: the decoded status's paths, tested with existsSync, which follows a link. */
5155
5496
  function generatedWorkFingerprint(work, status, disposableRoots = []) {
5156
5497
  const owned = (path) => disposableRoots.some((root) => path === root || path.startsWith(`${root}${sep}`));
5157
5498
  const paths = status.split("\0").filter(Boolean)
@@ -5173,12 +5514,15 @@ function retirementDisposableRoots(work, capabilities) {
5173
5514
  ];
5174
5515
  const roots = [];
5175
5516
  for (const receipt of receipts) {
5176
- if (typeof receipt.root !== "string" || !receipt.root || isAbsolute(receipt.root)) throw new Error(`retirement disposable root from ${receipt.owner} must be relative`);
5517
+ // The manifest check (capability-contract.mjs, disposableWorkRootProblem) refuses
5518
+ // the first two before a spawn gets here; they stay for a copy read without it.
5519
+ if (typeof receipt.root !== "string" || !receipt.root || isAbsolute(receipt.root)) throw oatsError("E_CAPABILITY_BROKEN", `retirement disposable root from ${receipt.owner} must be relative`);
5177
5520
  const normalized = receipt.root.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, "");
5178
- if (!normalized || normalized.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`unsafe retirement disposable root from ${receipt.owner}: ${receipt.root}`);
5521
+ if (!normalized || normalized.split("/").some((part) => !part || part === "." || part === "..")) throw oatsError("E_CAPABILITY_BROKEN", `unsafe retirement disposable root from ${receipt.owner}: ${receipt.root}`);
5179
5522
  const path = join(work, normalized);
5180
- if (existsSync(path) && lstatSync(path).isSymbolicLink()) throw new Error(`retirement disposable root from ${receipt.owner} is a symlink: ${normalized}`);
5181
- if (roots.some((r) => normalized === r.root || normalized.startsWith(`${r.root}/`) || r.root.startsWith(`${normalized}/`))) throw new Error(`overlapping retirement disposable roots: ${normalized}`);
5523
+ // lstat, never existsSync: a link whose target is missing is a link all the same.
5524
+ if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) throw oatsError("E_CAPABILITY_BROKEN", `retirement disposable root from ${receipt.owner} is a symlink: ${normalized}`);
5525
+ if (roots.some((r) => normalized === r.root || normalized.startsWith(`${r.root}/`) || r.root.startsWith(`${normalized}/`))) throw oatsError("E_CAPABILITY_BROKEN", `overlapping retirement disposable roots: ${normalized}`);
5182
5526
  roots.push({ owner: receipt.owner, root: normalized });
5183
5527
  }
5184
5528
  return roots;
@@ -5279,8 +5623,9 @@ function extraWorktreesOf(home) {
5279
5623
  const trees = [];
5280
5624
  let names;
5281
5625
  try { names = readdirSync(home); } catch { return trees; }
5282
- const realHome = realPathOrNearest(home);
5283
- const inHome = (p) => { const rel = relative(realHome, realPathOrNearest(p)); return rel === "" || !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)); };
5626
+ // Git reports paths in their on-disk spelling: the home and each tree are compared in it too.
5627
+ const realHome = canonicalHomePath(home);
5628
+ const inHome = (p) => { const rel = relative(realHome, canonicalHomePath(p)); return rel === "" || !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)); };
5284
5629
  for (const name of names.sort(byCodeUnit)) {
5285
5630
  if (!name.startsWith(".work-")) continue;
5286
5631
  const path = join(home, name);
@@ -5291,13 +5636,13 @@ function extraWorktreesOf(home) {
5291
5636
  if (!dirs.ok) continue;
5292
5637
  const [gitDir, commonDir, toplevel] = dirs.out.split("\n");
5293
5638
  if (!gitDir || !commonDir || !toplevel || realPathOrNearest(gitDir) === realPathOrNearest(commonDir)) continue;
5294
- const real = realPathOrNearest(path);
5639
+ const real = canonicalHomePath(path);
5295
5640
  // A repository inside the home goes with the home: its trees are home bytes.
5296
- if (realPathOrNearest(toplevel) !== real || inHome(commonDir)) continue;
5641
+ if (canonicalHomePath(toplevel) !== real || inHome(commonDir)) continue;
5297
5642
  const list = gitRead(path, ["worktree", "list", "--porcelain", "-z"]);
5298
5643
  if (!list.ok) continue;
5299
5644
  const records = parseWorktreeList(list.out);
5300
- const self = records.find((r) => realPathOrNearest(r.worktree) === real);
5645
+ const self = records.find((r) => canonicalHomePath(r.worktree) === real);
5301
5646
  if (!records.length || !self) continue;
5302
5647
  trees.push({ name, path, repo: records[0].worktree, gitDir, commonDir: realPathOrNearest(commonDir), locked: self.locked });
5303
5648
  }
@@ -5360,30 +5705,31 @@ function unionNotCopied(...lists) {
5360
5705
  return [...byPath.values()].sort((a, b) => byCodeUnit(a.path, b.path));
5361
5706
  }
5362
5707
  function retirementBaselineValid(baseline, home) {
5363
- return baseline?.version === RETIRE_BASELINE_VERSION && baseline.home === realPathOrNearest(home);
5708
+ return baseline?.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home));
5364
5709
  }
5365
5710
  /** What a retire plan may say about recovery without hashing anything: where a
5366
5711
  * recovery would be written, and the home entries the spawn baseline declares
5367
5712
  * as not copied (none without a valid baseline). */
5368
5713
  export function retirementRecoveryFacts(home) {
5369
- const baseline = readJsonOrUndefined(retirementBaselinePath(home));
5714
+ const baseline = readJsonOrUndefined(findRetirementBaseline(home));
5370
5715
  return { recoveryRoot: join(retirementStateRoot(home), "recovery"), disposableHome: retirementBaselineValid(baseline, home) ? baselineDisposableHome(baseline) : [] };
5371
5716
  }
5372
5717
  function writeRetirementBaseline(home, work, mode, capabilities, runtime, { exclusive = false, incarnationId, executionBinding } = {}) {
5373
5718
  if (mode === "directory") assertDirectoryRoots(home);
5374
5719
  const isWorktree = mode === "worktree";
5375
- const status = isWorktree && existsSync(work) ? worktreeStatus(work) : "";
5720
+ const statusBytes = isWorktree && existsSync(work) ? worktreeStatusBytes(work) : Buffer.alloc(0);
5376
5721
  const disposableReceipts = isWorktree ? retirementDisposableRoots(work, capabilities) : [];
5377
5722
  const disposableHome = retirementDisposableHome(capabilities);
5378
5723
  const baseline = {
5379
5724
  version: RETIRE_BASELINE_VERSION,
5725
+ digestVersion: BASELINE_DIGEST_VERSION,
5380
5726
  ...(incarnationId ? { incarnationId, executionBinding } : {}),
5381
5727
  ...(mode === "directory" ? { directoryWork: true, directoryRoots: { home: directoryIdentity(home), work: directoryIdentity(work) } } : {}),
5382
- home: realPathOrNearest(home),
5383
- homeFingerprint: fingerprintTree(home, { excludeRoot: resolveHomeExclusions(home, disposableHome).excludeRoot, instanceHome: true }),
5728
+ home: canonicalHomePath(home),
5729
+ homeFingerprint: storedTreeDigest(home, BASELINE_DIGEST_VERSION, { excludeRoot: resolveHomeExclusions(home, disposableHome).excludeRoot, instanceHome: true }),
5384
5730
  disposableReceipts,
5385
5731
  disposableHome,
5386
- generatedWorkFingerprint: isWorktree ? generatedWorkFingerprint(work, status, disposableReceipts.map((r) => r.root)) : undefined,
5732
+ generatedWorkFingerprint: isWorktree ? generatedWorkDigest(work, statusBytes, disposableReceipts.map((r) => r.root)) : undefined,
5387
5733
  runtime: {
5388
5734
  launched: runtime?.launched === true,
5389
5735
  ...(runtime?.tmux ? { tmux: { session: runtime.tmux.session, window: runtime.tmux.window, ...(runtime.tmux.socket ? { socket: resolve(runtime.tmux.socket) } : {}) } } : {}),
@@ -5394,17 +5740,24 @@ function writeRetirementBaseline(home, work, mode, capabilities, runtime, { excl
5394
5740
  writeFileSync(path, JSON.stringify(baseline, null, 2) + "\n", { mode: 0o600, ...(exclusive ? { flag: "wx" } : {}) });
5395
5741
  }
5396
5742
 
5743
+ /** The repositories a recovery rebuilds from a clone, under a worktree at
5744
+ * any depth → their paths, as bytes: each directory (never a link to one)
5745
+ * whose `.git` stat finds, a link to one followed. Names are read as bytes,
5746
+ * so a directory whose name is not UTF-8 is found, not missed. The walk does
5747
+ * not go into a repository it found: no path is under another, and a
5748
+ * repository inside one is no root of its own (it comes along as its
5749
+ * parent's plain files, its `.git` included: repositoriesUnder's `inner`). */
5397
5750
  function nestedGitRoots(root) {
5398
5751
  const out = [];
5399
5752
  const walk = (dir) => {
5400
- for (const e of readdirSync(dir, { withFileTypes: true })) {
5401
- if (!e.isDirectory() || e.isSymbolicLink?.()) continue;
5402
- const path = join(dir, e.name);
5403
- if (existsSync(join(path, ".git"))) { out.push(path); continue; }
5753
+ for (const e of entriesAsBytes(dir)) {
5754
+ if (!e.isDirectory() || e.isSymbolicLink()) continue;
5755
+ const path = joinBytes(dir, e.name);
5756
+ if (existsSync(joinBytes(path, GIT_NAME))) { out.push(path); continue; }
5404
5757
  walk(path);
5405
5758
  }
5406
5759
  };
5407
- walk(root);
5760
+ walk(pathBytes(root));
5408
5761
  return out;
5409
5762
  }
5410
5763
 
@@ -5416,7 +5769,7 @@ function nestedGitRoots(root) {
5416
5769
  * whether it could be shown gone. */
5417
5770
  function recordedBranchExists(repo, branch) {
5418
5771
  if (!repo || !branch) return true;
5419
- const r = spawnSync("git", ["-C", repo, "rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], { stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER });
5772
+ const r = retireGitProbe(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]);
5420
5773
  return !r.error && r.status === 0;
5421
5774
  }
5422
5775
 
@@ -5431,7 +5784,7 @@ function readJsonOrUndefined(path) { try { return JSON.parse(readFileSync(path,
5431
5784
  /** Refuse any session operation on a home opened in Herdr, from its files as they are (either may be
5432
5785
  * missing or unreadable): before any receipt validation, so the refusal is never an endpoint error. */
5433
5786
  function refuseHerdrHome(home) {
5434
- if (recordsHerdr(readJsonOrUndefined(join(home, "instance.json")), readJsonOrUndefined(retirementBaselinePath(home)))) throw herdrInstanceRemoved(basename(home));
5787
+ if (recordsHerdr(readJsonOrUndefined(join(home, "instance.json")), readJsonOrUndefined(findRetirementBaseline(home)))) throw herdrInstanceRemoved(basename(home));
5435
5788
  }
5436
5789
 
5437
5790
  function runtimeAuthorityOf(baseline) {
@@ -5456,10 +5809,13 @@ function launchStateAgrees(meta, authority) {
5456
5809
  ["blocked", "incomplete"].includes(meta.launchPrompts?.status) && tmuxEndpointAgrees(meta, authority));
5457
5810
  }
5458
5811
 
5459
- /** The refusal for a home whose session receipt file does not exist where its path says it is. The
5460
- * receipt is keyed by the home's path, so a different spelling of that path looks elsewhere. */
5461
- function missingSessionReceipt(home, receiptPath) {
5462
- return oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `no session receipt for ${home} at ${receiptPath}. First address the home exactly as \`oats status\` prints it (a different spelling — letter case, a moved deployment directory — looks for the receipt elsewhere). Otherwise the home was copied, the .oats-retirement beside it was removed, or its creation did not finish: stop its session yourself if one runs, then \`oats retire ${basename(home)} --plan\` and \`oats retire ${basename(home)}\` (work is preserved), and respawn.`);
5812
+ /** The refusal for a home whose session receipt is at neither key its path gives (findRetirementBaseline):
5813
+ * the canonical one, and the one an earlier kernel used for this spelling when that differs. The
5814
+ * receipt is keyed by the home's path, so a moved deployment looks elsewhere. */
5815
+ function missingSessionReceipt(home) {
5816
+ const canonical = retirementBaselinePath(home), legacy = legacyRetirementBaselinePath(home);
5817
+ const where = legacy === canonical ? canonical : `${canonical} (nor at ${legacy}, where a kernel before 0.49.0 kept it for this spelling)`;
5818
+ return oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `no session receipt for ${home} at ${where}. First address the home exactly as \`oats status\` prints it (a deployment directory moved since spawn looks for the receipt elsewhere, and so does a letter-case spelling other than the spawn's, for a home spawned before 0.49.0). Otherwise the home was copied, the .oats-retirement beside it was removed, or its creation did not finish: stop its session yourself if one runs, then \`oats retire ${basename(home)} --plan\` and \`oats retire ${basename(home)}\` (work is preserved), and respawn.`);
5463
5819
  }
5464
5820
 
5465
5821
  /** Session control uses the independent endpoint receipt. */
@@ -5467,16 +5823,16 @@ function instanceSessionTarget(home) {
5467
5823
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
5468
5824
  home = realPathOrNearest(home);
5469
5825
  refuseHerdrHome(home);
5470
- const receiptPath = retirementBaselinePath(home);
5826
+ const receiptPath = findRetirementBaseline(home);
5471
5827
  let baseline, meta;
5472
5828
  try {
5473
5829
  baseline = JSON.parse(readFileSync(receiptPath, "utf8"));
5474
5830
  meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
5475
5831
  } catch (e) {
5476
- if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home, receiptPath);
5832
+ if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
5477
5833
  throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${e.message}`);
5478
5834
  }
5479
- const authority = baseline.version === RETIRE_BASELINE_VERSION && baseline.home === home && runtimeAuthorityOf(baseline);
5835
+ const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
5480
5836
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
5481
5837
  if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
5482
5838
  return { home, target: authority.launched ? { backend: "tmux", ...authority.tmux } : undefined };
@@ -5529,7 +5885,8 @@ export function processesInHome(home, io) {
5529
5885
  }
5530
5886
  // A listing holds at least one process (lsof and its caller are always in it), whichever exit it came with.
5531
5887
  if (!/^p\d+$/m.test(String(out))) return { ok: false, error: "lsof listed no process" };
5532
- const realHome = realPathOrNearest(home);
5888
+ // lsof reports each cwd in its on-disk spelling: the home is compared in it too.
5889
+ const realHome = canonicalHomePath(home);
5533
5890
  const processes = [];
5534
5891
  let cur = {};
5535
5892
  for (const line of String(out).split("\n")) {
@@ -5538,7 +5895,7 @@ export function processesInHome(home, io) {
5538
5895
  else if (tag === "R") cur.ppid = Number(value);
5539
5896
  else if (tag === "c") cur.command = value;
5540
5897
  else if (tag === "n" && cur.pid && cur.pid !== process.pid && cur.ppid !== process.pid) {
5541
- const cwd = realPathOrNearest(value);
5898
+ const cwd = canonicalHomePath(value);
5542
5899
  if (cwd === realHome || cwd.startsWith(`${realHome}/`)) processes.push({ pid: cur.pid, command: cur.command ?? "?" });
5543
5900
  }
5544
5901
  }
@@ -5580,8 +5937,9 @@ function recordedSessionAbsence(home, meta, io) {
5580
5937
  return { absent: false, backend: "tmux", note: `tmux could not list ${tmux.socket}: ${String(e.stderr ?? e.message ?? "").trim() || "tmux failed"}` };
5581
5938
  }
5582
5939
  if (rows.some(([s, w]) => s === tmux.session && w === tmux.window)) return { absent: false, backend: "tmux", note: `the recorded window ${where} is still present` };
5583
- const realHome = realPathOrNearest(home);
5584
- const inHome = rows.find(([, , cwd]) => { const p = cwd ? realPathOrNearest(cwd) : ""; return p === realHome || p.startsWith(`${realHome}/`); });
5940
+ // tmux reports each pane's cwd in its on-disk spelling: the home is compared in it too.
5941
+ const realHome = canonicalHomePath(home);
5942
+ const inHome = rows.find(([, , cwd]) => { const p = cwd ? canonicalHomePath(cwd) : ""; return p === realHome || p.startsWith(`${realHome}/`); });
5585
5943
  if (inHome) return { absent: false, backend: "tmux", note: `a tmux pane (${inHome[0]}:${inHome[1]}) on ${tmux.socket} works in this home` };
5586
5944
  return { absent: true, backend: "tmux", note: `no session receipt (a home from before 0.25.9); the recorded window ${where} is gone` };
5587
5945
  }
@@ -6014,13 +6372,13 @@ export function startInstanceSession(home, o = {}) {
6014
6372
  // pending receipt exists for.
6015
6373
  const record = (meta, { id, target, model, command, startedAt, reused, launch, harness: newHarness, yolo: newYolo, stop, nativeRecordId, hookMeta, modelFrom, launchFrom, launchAt, launchDeclared, launchPrompts, launchPromptTarget }, clearPending = true) => {
6016
6374
  checkRoots();
6017
- const baselinePath = retirementBaselinePath(realHome);
6375
+ const baselinePath = findRetirementBaseline(realHome);
6018
6376
  let baseline;
6019
6377
  try { baseline = JSON.parse(readFileSync(baselinePath, "utf8")); } catch (e) {
6020
- if (e.code === "ENOENT") throw missingSessionReceipt(realHome, baselinePath);
6378
+ if (e.code === "ENOENT") throw missingSessionReceipt(realHome);
6021
6379
  throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or unreadable for ${realHome}: ${e.message}`);
6022
6380
  }
6023
- if (baseline.version !== RETIRE_BASELINE_VERSION || baseline.home !== realHome || !runtimeAuthorityOf(baseline)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is invalid for ${realHome}`);
6381
+ if (baseline.version !== RETIRE_BASELINE_VERSION || !receiptRecordsHome(baseline, canonicalHomePath(realHome)) || !runtimeAuthorityOf(baseline)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is invalid for ${realHome}`);
6024
6382
  baseline.runtime = { launched: true, tmux: { session: target.session, window: target.window, socket: resolve(target.socket) } };
6025
6383
  writeJsonAtomic(baselinePath, baseline, 0o600);
6026
6384
  if (o.io?.failBeforeMetadataWrite && reused !== "adopted") throw new Error("injected metadata write failure"); // the write after THIS start's allocation
@@ -6431,7 +6789,7 @@ export function startInstanceSession(home, o = {}) {
6431
6789
  * decision: not provable. */
6432
6790
  function inspectGit(repo, args, { absent = false, env } = {}) {
6433
6791
  try {
6434
- return execFileSync("git", ["-C", repo, ...args], { stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, ...(env ? { env: { ...process.env, ...env } } : {}) }).toString("latin1");
6792
+ return retireGit(repo, args, { env }).toString("latin1");
6435
6793
  } catch (e) {
6436
6794
  const detail = String(e.stderr ?? "").trim();
6437
6795
  if (absent && e.status === 1 && !detail) return null;
@@ -6453,23 +6811,20 @@ function inspectedEntryExists(path) {
6453
6811
  /** How the recovery copier resolves what it reads from a repository, read by
6454
6812
  * the copier and by the comparison alike (repositoryGitState), so that the
6455
6813
  * comparison holds the files the copy carries, found where the copy finds
6456
- * them. Git's answer decoded as UTF-8 and trimmed of white space at both
6457
- * ends: a path that ends in white space is read without it, which Git itself
6458
- * does not do. That is the copier's own reading, kept as it is; a copy of
6459
- * the file Git reads would be a change to the copier.
6814
+ * them. Git's answer decoded as UTF-8, exactly as Git printed it but for the
6815
+ * one line feed that ends it: a path that begins or ends in white space is
6816
+ * the path Git reads, so the copier reads the file Git reads
6817
+ * (awebai/oats#647).
6460
6818
  * A worktree whose `core.worktree` (per-worktree configuration) names a
6461
- * directory other than `<home>/work` is outside what the retire is
6462
- * specified for: Git's status then describes that other directory while
6463
- * the retire reads, copies and removes `<home>/work`. copierExcludesFile
6464
- * resolves the excludes base the copier's way for it all the same; no test
6465
- * pins it. */
6466
- const copierGitText = (repo, args) => execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER }).trim();
6819
+ * directory other than `<home>/work` never gets here: each inspection
6820
+ * refuses it first (assertWorktreeTopLevel, awebai/oats#648). */
6821
+ const copierGitText = (repo, args) => retireGit(repo, args, { encoding: "utf8" }).replace(/\n$/, "");
6467
6822
  /** The Git directory the copier copies the index and the operation entries from. */
6468
6823
  const copierGitDir = (repo) => copierGitText(repo, ["rev-parse", "--absolute-git-dir"]);
6469
6824
  /** The common directory the copier reads info/exclude, info/attributes and the stash's log from. */
6470
6825
  const copierCommonDir = (repo) => copierGitText(repo, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
6471
6826
  /** The file the copier reads for core.excludesFile; null when it reads none:
6472
- * the value is unset, cannot be read, or is only white space. */
6827
+ * the value is unset, empty or cannot be read. */
6473
6828
  function copierExcludesFile(repo) {
6474
6829
  let value = "";
6475
6830
  try { value = copierGitText(repo, ["config", "--path", "--get", "core.excludesFile"]); } catch { /* unset: Git's default applies to both repositories alike */ }
@@ -6585,9 +6940,8 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
6585
6940
  status: (status ?? worktreeStatusBytes(repo)).toString("latin1"),
6586
6941
  head: head.ref === null ? null : head.ref.toString("latin1"),
6587
6942
  commit: valueOf("rev-parse", "--verify", "--quiet", "HEAD"),
6588
- // The index the copier copies (copierGitDir), read as an index: Git's
6589
- // own, at a path that differs from it only in white space, is not what
6590
- // the copy carries. One that is not there lists nothing.
6943
+ // The index the copier copies (copierGitDir), named explicitly
6944
+ // (GIT_INDEX_FILE), read as an index. One that is not there lists nothing.
6591
6945
  index: inspectGit(repo, ["ls-files", "-s", "-v", "-z"], { env: { GIT_INDEX_FILE: join(copierGit, "index") } }),
6592
6946
  resolveUndo: inspectGit(repo, ["ls-files", "--resolve-undo", "-z"], { env: { GIT_INDEX_FILE: join(copierGit, "index") } }),
6593
6947
  indexMode: modeOf(join(copierGit, "index")),
@@ -6610,10 +6964,11 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
6610
6964
  * nestedGitRoots, and (`inner`) the repositories inside those. A recovery
6611
6965
  * rebuilds a nested repository from a clone; one inside it comes along as
6612
6966
  * plain files, its Git directory included, which the copy's verification
6613
- * leaves out and which no read-only Git command can describe whole.
6967
+ * holds as bytes (worktreeGitPaths) and which no read-only Git command can
6968
+ * describe whole.
6614
6969
  * A directory whose `.git` cannot be tested (inspectedEntryExists throws),
6615
6970
  * or is a dangling symbolic link (a link `stat` cannot follow, which the
6616
- * copy carries as a link and the digests pass over by its name), is listed
6971
+ * copy carries as a link and the copy's verification holds), is listed
6617
6972
  * as { path, unknown: true }: it is not taken for a directory without a
6618
6973
  * repository, and not for a repository either. So every directory with a
6619
6974
  * `.git` entry of any kind is listed: a directory, a file, a link to
@@ -6625,17 +6980,19 @@ function repositoriesUnder(work) {
6625
6980
  try { lstatSync(path); return true; }
6626
6981
  catch (e) {
6627
6982
  if (e.code === "ENOENT") return false;
6628
- throw oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path}: ${e.message}`);
6983
+ throw oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path.toString()}: ${e.message}`);
6629
6984
  }
6630
6985
  };
6986
+ // Names are read as bytes (`path` is a Buffer), so a directory whose name
6987
+ // is not UTF-8 is walked like any other.
6631
6988
  const walk = (dir, inner) => {
6632
- for (const e of readdirSync(dir, { withFileTypes: true })) {
6633
- if (!e.isDirectory() || e.isSymbolicLink?.() || e.name === ".git") continue;
6634
- const path = join(dir, e.name);
6989
+ for (const e of entriesAsBytes(dir)) {
6990
+ if (!e.isDirectory() || e.isSymbolicLink() || e.name.equals(GIT_NAME)) continue;
6991
+ const path = joinBytes(dir, e.name);
6635
6992
  let repository = false;
6636
6993
  try {
6637
- repository = inspectedEntryExists(join(path, ".git"));
6638
- if (!repository && entryIsThere(join(path, ".git"))) out.push({ path, unknown: true });
6994
+ repository = inspectedEntryExists(joinBytes(path, GIT_NAME));
6995
+ if (!repository && entryIsThere(joinBytes(path, GIT_NAME))) out.push({ path, unknown: true });
6639
6996
  } catch (e) {
6640
6997
  if (e?.code !== "E_WORK_INSPECTION_FAILED") throw e;
6641
6998
  out.push({ path, unknown: true });
@@ -6644,7 +7001,7 @@ function repositoriesUnder(work) {
6644
7001
  walk(path, inner || repository);
6645
7002
  }
6646
7003
  };
6647
- walk(work, false);
7004
+ walk(pathBytes(work), false);
6648
7005
  return out;
6649
7006
  }
6650
7007
  /** The work state of a worktree instance, without the bytes of its files: the
@@ -6655,12 +7012,28 @@ function repositoriesUnder(work) {
6655
7012
  function worktreeGitState(work, status, cloneSource) { // `status`: the worktree's status bytes
6656
7013
  return JSON.stringify({ worktree: repositoryGitState(work, { status, cloneSource }) });
6657
7014
  }
6658
- /** The bytes of a worktree, Git metadata left out, as their exact digest: what a work copy is verified
6659
- * with, and what proves that the hooks left the files as they were. One full read. Kept nowhere. */
6660
- const worktreeBytes = (work) => exactTreeDigest(work, { excludeRoot: new Set([".git"]), excludeGitMetadata: true, children: true });
7015
+ /** The `.git` entries a worktree's bytes leave out, as paths under it in
7016
+ * bytes: the worktree's own, and that of each repository the copier rebuilds
7017
+ * from a clone (nestedGitRoots, materializeNestedRepositories). Exact paths,
7018
+ * never a name: any other entry named `.git` is bytes like any other
7019
+ * (awebai/oats#663), such as a dangling `.git` link, or the `.git` of a
7020
+ * repository inside a nested one, which the copy carries as plain files.
7021
+ * Read from the source and used for the source and its copy alike: a
7022
+ * rebuilt `.git` is a directory in the copy where the source's can be a
7023
+ * file, and the path covers both. */
7024
+ function worktreeGitPaths(work) {
7025
+ const under = pathBytes(work).length + PATH_SEPARATOR_BYTES.length;
7026
+ return [GIT_NAME, ...nestedGitRoots(work).map((root) => joinBytes(root.subarray(under), GIT_NAME))];
7027
+ }
7028
+ /** The bytes of a worktree, its Git directories (`gitPaths`, worktreeGitPaths of
7029
+ * the source) left out, as their exact digest: what a work copy is verified
7030
+ * with, and what proves that the hooks left the files as they were. One full
7031
+ * read. Kept nowhere. */
7032
+ const worktreeBytes = (work, gitPaths = worktreeGitPaths(work)) => exactTreeDigest(work, { excludePaths: gitPaths, children: true });
6661
7033
  /** The byte part of an observed worktree's work state, read at most once per
6662
- * observation and kept on it; undefined where the observation saw no
6663
- * worktree. An inspection never reads it. The retire reads it before it
7034
+ * observation and kept on it with the Git directories it leaves out
7035
+ * (`workGitPaths`, for the copy's verification); undefined where the
7036
+ * observation saw no worktree. An inspection never reads it. The retire reads it before it
6664
7037
  * writes the pre-hook recovery, the copy's verification uses it (so a pass
6665
7038
  * that copies the work costs no extra read), and so does the proof that the
6666
7039
  * retire hooks left the work as it was (movedByHooks). */
@@ -6668,7 +7041,11 @@ function observedWorkBytes(observation) {
6668
7041
  if (observation.worktree && observation.workBytes === undefined) {
6669
7042
  // A read that fails is an inspection that failed, with its code: where the
6670
7043
  // retire reads before it writes, nothing else gives the failure one.
6671
- try { observation.workBytes = worktreeBytes(observation.work); }
7044
+ try {
7045
+ const gitPaths = worktreeGitPaths(observation.work);
7046
+ observation.workBytes = worktreeBytes(observation.work, gitPaths);
7047
+ observation.workGitPaths = gitPaths;
7048
+ }
6672
7049
  catch (e) {
6673
7050
  if (e?.code === "E_WORK_INSPECTION_FAILED") throw e;
6674
7051
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not read the worktree at ${observation.work}: ${e.message}`);
@@ -6680,8 +7057,8 @@ function observedWorkBytes(observation) {
6680
7057
  * one after → { home, work }. Nothing when the later observation has nothing
6681
7058
  * to preserve. The home moved when its exact digest did: that is its bytes,
6682
7059
  * `instance.json` as it is. (The stored digest, which a baseline is compared
6683
- * with, leaves the kernel's own fields of that file out and frames entries
6684
- * without lengths; it reads alike some homes that differ.)
7060
+ * with, leaves the kernel's own fields of that file out and passes over the
7061
+ * kernel's receipts, so it reads alike some homes that differ.)
6685
7062
  * The work moved unless it is proven unchanged: a directory by its bytes
6686
7063
  * (its exact digest); a worktree by its Git state and, only when that is
6687
7064
  * equal, by its bytes. A status text or a class list alone proves nothing: a
@@ -6698,11 +7075,30 @@ function movedByHooks(before, after) {
6698
7075
  return { home, work };
6699
7076
  }
6700
7077
 
6701
- function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, orphanedWork = false } = {}) {
7078
+ /** The check made before a worktree's status is trusted (awebai/oats#648):
7079
+ * Git's top level for the worktree at `work` is `work` itself, both in
7080
+ * their canonical spelling (canonicalHomePath, so a path reached through a
7081
+ * link, or spelled in another letter case on a case-insensitive
7082
+ * filesystem, is the same path). A per-worktree `core.worktree` can name
7083
+ * another directory: Git's status then describes that one, while the
7084
+ * retire reads, copies and removes `work`. That, and a top level that
7085
+ * cannot be read, throws E_WORK_INSPECTION_FAILED with `disclosure` (what
7086
+ * the retire has and has not done by then) as its last sentence. */
7087
+ function assertWorktreeTopLevel(work, disclosure) {
7088
+ const refuse = (why) => oatsError("E_WORK_INSPECTION_FAILED", `${why}, so its Git status describes another directory than the one the retire reads, copies and removes.${disclosure ? ` ${disclosure}.` : ""}`);
7089
+ let top;
7090
+ try { top = retireGit(work, ["rev-parse", "--show-toplevel"]).toString("utf8").replace(/\n$/, ""); }
7091
+ catch (e) { throw refuse(`could not read the top level of the worktree at ${work} (${String(e.stderr ?? e.message ?? "").trim() || "git rev-parse failed"})`); }
7092
+ if (!top || canonicalHomePath(top) !== canonicalHomePath(work)) {
7093
+ throw refuse(`Git reads the worktree at ${work} as the directory ${top || "(none)"} (its core.worktree names another directory)`);
7094
+ }
7095
+ }
7096
+
7097
+ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, orphanedWork = false, disclosure } = {}) {
6702
7098
  if (directory) assertDirectoryRoots(home);
6703
7099
  const classes = [];
6704
7100
  let baseline;
6705
- const path = retirementBaselinePath(home);
7101
+ const path = findRetirementBaseline(home);
6706
7102
  try {
6707
7103
  if (existsSync(path)) baseline = JSON.parse(readFileSync(path, "utf8"));
6708
7104
  } catch (e) {
@@ -6718,12 +7114,15 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
6718
7114
  // One walk of the home, two digests: the stored one for the comparison with
6719
7115
  // the baseline, which must not see the kernel's own fields of instance.json,
6720
7116
  // and the exact one for the comparison after the hooks, which must see
6721
- // every byte.
7117
+ // every byte. The stored one is in the baseline's digest version; a
7118
+ // version this kernel does not take matches nothing, and the walk is then
7119
+ // the one version 2 takes, for the exact digest alone.
7120
+ const digestVersion = baselineDigestVersion(baseline);
6722
7121
  let homeDigests;
6723
- const fingerprintHome = () => (homeDigests ??= fingerprintTrees(home, { excludeRoot: homeExclusions.excludeRoot, instanceHome: true, exact: true, children: true })).stored;
7122
+ const fingerprintHome = () => (homeDigests ??= fingerprintTrees(home, { excludeRoot: homeExclusions.excludeRoot, instanceHome: true, digestVersion: digestVersion ?? BASELINE_DIGEST_VERSION, exact: true, children: true })).stored;
6724
7123
  if (!baselineValid) {
6725
7124
  classes.push("unknown instance-home provenance");
6726
- } else if (baseline.homeFingerprint !== fingerprintHome()) {
7125
+ } else if (digestVersion === undefined || baseline.homeFingerprint !== fingerprintHome()) {
6727
7126
  classes.push("changed instance-home bytes");
6728
7127
  }
6729
7128
  // A mutable mode must not turn owned directory bytes into an excluded shared
@@ -6740,6 +7139,8 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
6740
7139
  // For a quarantine retry whose worktree is gone, whether the recorded branch
6741
7140
  // is still there to copy. Every other retire takes it to be there.
6742
7141
  const branchExists = !directory && recordedBranch && !existsSync(work) ? recordedBranchExists(recordedBranch.repo, recordedBranch.branch) : true;
7142
+ // Before anything of the worktree is read: its status describes it, not another directory.
7143
+ if (!directory && isWorktree && existsSync(work)) assertWorktreeTopLevel(work, disclosure);
6743
7144
  // A retire that will remove the worktree asks whether a ref that outlives it
6744
7145
  // reaches its commit. `head` is kept for the check before the removal.
6745
7146
  const unreached = worktreeRemoval?.removes && worktreeRemoval.repo && !directory && isWorktree && existsSync(work) ? worktreeCommitUnreached(worktreeRemoval.repo, work) : undefined;
@@ -6747,14 +7148,23 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
6747
7148
  const worktree = isWorktree && existsSync(work);
6748
7149
  let gitState = "", workProvable = true;
6749
7150
  if (worktree) {
6750
- // Read once, as bytes. The bytes go into the Git state; the rows, the
6751
- // classes and the comparison with the spawn baseline read them as text.
7151
+ // Read once, as bytes. The bytes go into the Git state and into the
7152
+ // comparison with the spawn baseline (its legacy digest reads them as
7153
+ // text); the rows and the classes read them as text.
6752
7154
  const statusBytes = worktreeStatusBytes(work);
6753
7155
  const status = statusBytes.toString("utf8");
6754
7156
  const rows = status.split("\0").filter(Boolean);
6755
7157
  if (rows.some((row) => !row.startsWith("?? ") && !row.startsWith("!! "))) classes.push("tracked or index worktree state");
6756
7158
  const disposableRoots = baseline?.disposableReceipts?.map((r) => r.root) || [];
6757
- if (!baseline || baseline.generatedWorkFingerprint !== generatedWorkFingerprint(work, status, disposableRoots)) classes.push("untracked or ignored worktree bytes");
7159
+ // A path the digest cannot inspect refuses, with what this retire has
7160
+ // and has not done by now, as the other refusals of an inspection do.
7161
+ let generated;
7162
+ try { generated = baseline && digestVersion !== undefined ? generatedWorkFingerprintIn(digestVersion, work, statusBytes, disposableRoots) : undefined; }
7163
+ catch (e) {
7164
+ if (e?.code !== "E_WORK_INSPECTION_FAILED") throw e;
7165
+ throw oatsError(e.code, `${e.message}.${disclosure ? ` ${disclosure}.` : ""}`);
7166
+ }
7167
+ if (generated === undefined || baseline.generatedWorkFingerprint !== generated) classes.push("untracked or ignored worktree bytes");
6758
7168
  const found = repositoriesUnder(work);
6759
7169
  if (found.some((r) => !r.unknown)) classes.push("nested repository state");
6760
7170
  // The one place where a read of the Git state that fails is decided. It
@@ -6805,13 +7215,27 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
6805
7215
  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 };
6806
7216
  }
6807
7217
 
7218
+ /** Copy the entries of `src` into `dest` (created), names as bytes, except
7219
+ * the top-level names in `excludeRoot`, tested as text the way the digests
7220
+ * test them (fingerprintTrees). */
6808
7221
  function copyRecoveryTree(src, dest, { excludeRoot = new Set() } = {}) {
6809
7222
  mkdirSync(dest, { recursive: true });
6810
- for (const e of readdirSync(src, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
6811
- if (excludeRoot.has(e.name)) continue;
6812
- copyTreeSafe(join(src, e.name), join(dest, e.name));
7223
+ for (const e of entriesAsBytes(src)) {
7224
+ if (excludeRoot.has(e.name.toString("utf8"))) continue;
7225
+ copyTreeSafe(joinBytes(src, e.name), joinBytes(dest, e.name));
6813
7226
  }
6814
7227
  }
7228
+ /** Make the top level of `dest`, a fresh clone, the top level of `source`,
7229
+ * names as bytes: every entry of `dest` but its `.git` is removed, then
7230
+ * every entry of `source` but its `.git` is copied (copyTreeSafe). A mirror,
7231
+ * not an overlay: a tracked top-level entry the source deleted or renamed is
7232
+ * not left in the copy as the clone checked it out (awebai/oats#656). The
7233
+ * `.git` of `dest` is never touched: the copy's Git state is restored
7234
+ * separately (restoreStandaloneGitState). */
7235
+ function mirrorTopLevel(source, dest) {
7236
+ for (const e of entriesAsBytes(dest)) if (!e.name.equals(GIT_NAME)) rmSync(joinBytes(dest, e.name), { recursive: true, force: true });
7237
+ for (const e of entriesAsBytes(source)) if (!e.name.equals(GIT_NAME)) copyTreeSafe(joinBytes(source, e.name), joinBytes(dest, e.name));
7238
+ }
6815
7239
 
6816
7240
  const RECOVERABLE_GIT_ADMIN = [
6817
7241
  "MERGE_HEAD", "MERGE_MSG", "AUTO_MERGE", "CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD",
@@ -6860,7 +7284,7 @@ function copiedGitPathDigest(entry, at) {
6860
7284
  * `cat-file --batch-check` process. */
6861
7285
  export function missingGitObjects(repo, oids) {
6862
7286
  if (!oids.length) return [];
6863
- const out = execFileSync("git", ["-C", repo, "cat-file", "--batch-check=%(objectname) %(objecttype)"], { input: oids.join("\n") + "\n", encoding: "utf8", maxBuffer: GIT_MAX_BUFFER });
7287
+ const out = retireGit(repo, ["cat-file", "--batch-check=%(objectname) %(objecttype)"], { input: oids.join("\n") + "\n", encoding: "utf8" });
6864
7288
  const missing = [];
6865
7289
  for (const line of out.split("\n")) {
6866
7290
  if (!line.endsWith(" missing")) continue;
@@ -6869,31 +7293,95 @@ export function missingGitObjects(repo, oids) {
6869
7293
  return missing;
6870
7294
  }
6871
7295
 
7296
+ /** A fetch into a recovery clone from the repository it copies. Protocol
7297
+ * version 2, whatever the user's configuration says: its upload-pack serves
7298
+ * an object id the source has although no ref advertises it, which is how
7299
+ * the copier fetches a detached HEAD and the commits only a log names. A
7300
+ * client setting; it runs nothing. */
7301
+ function copierFetch(recovered, source, refspecs, { input } = {}) {
7302
+ retireGit(recovered, ["-c", "protocol.version=2", "fetch", "--quiet", "--no-tags", source, ...refspecs], input === undefined ? {} : { input });
7303
+ }
7304
+
7305
+ /** The commits a reflog file names: the new object id of each entry, which is
7306
+ * what `git log -g` shows for it, the zero id left out. A file that is not
7307
+ * there names none. Read from the copy of the file, so that what is proven
7308
+ * is what the copy carries. */
7309
+ function reflogCommits(file) {
7310
+ if (!existsSync(file)) return [];
7311
+ const out = [];
7312
+ for (const line of readFileSync(file, "latin1").split("\n")) {
7313
+ const m = /^[0-9a-f]{40}(?:[0-9a-f]{24})? ([0-9a-f]{40}(?:[0-9a-f]{24})?) /.exec(line);
7314
+ if (m && !/^0+$/.test(m[1])) out.push(m[1]);
7315
+ }
7316
+ return out;
7317
+ }
7318
+
7319
+ /** The blobs an index listing names (`git ls-files --stage -z` or
7320
+ * `--resolve-undo -z`): rows `<mode> <oid> <stage>\t<path>`. Gitlink rows
7321
+ * (mode 160000) name commits of nested repositories, which
7322
+ * materializeNestedRepositories restores; they and the zero id are never
7323
+ * blobs here. */
7324
+ function indexBlobs(rows) {
7325
+ const out = [];
7326
+ for (const row of rows.toString("latin1").split("\0")) {
7327
+ const m = /^(\d+) ([0-9a-f]+) \d\t/.exec(row);
7328
+ if (m && m[1] !== "160000" && !/^0+$/.test(m[2])) out.push(m[2]);
7329
+ }
7330
+ return out;
7331
+ }
7332
+
7333
+ /** The one step that makes a recovery copy hold every object the Git
7334
+ * metadata it carries names (awebai/oats#654, #655, #657): measure, repair,
7335
+ * re-measure. One `cat-file --batch-check` asks which of the named objects
7336
+ * the copy lacks; the missing commits are fetched from `source` by id (one
7337
+ * fetch, with everything they reach), the missing blobs, which can be in no
7338
+ * commit (staged content, a resolved conflict's sides), are copied by
7339
+ * content (`cat-file blob` → `hash-object -w`); then the whole set is
7340
+ * checked again. A fetch or a read that fails is not the failure itself:
7341
+ * whatever is still missing after the repair is, named by its id, and the
7342
+ * copy is refused (E_WORK_PRESERVATION_FAILED). That covers an object the
7343
+ * source itself lacks, which GIT_NO_LAZY_FETCH keeps the copier from
7344
+ * fetching from a promisor remote. */
7345
+ function carryNamedObjects(source, recovered, { commits = [], blobs = [] }) {
7346
+ const named = [...new Set([...commits, ...blobs])];
7347
+ if (!named.length) return;
7348
+ const missing = new Set(missingGitObjects(recovered, named));
7349
+ const fetch = [...new Set(commits)].filter((oid) => missing.has(oid));
7350
+ if (fetch.length) {
7351
+ try { copierFetch(recovered, source, ["--stdin"], { input: fetch.join("\n") + "\n" }); }
7352
+ catch { /* the re-measure names what the fetch did not bring */ }
7353
+ }
7354
+ for (const oid of new Set(blobs)) {
7355
+ if (!missing.has(oid)) continue;
7356
+ let blob;
7357
+ try { blob = retireGit(source, ["cat-file", "blob", oid]); }
7358
+ catch { continue; /* the re-measure names it */ }
7359
+ const restored = retireGit(recovered, ["hash-object", "-w", "--stdin"], { input: blob, encoding: "utf8" }).trim();
7360
+ if (restored !== oid) throw new Error(`recovered Git object ${restored} did not match source ${oid}`);
7361
+ }
7362
+ const stillMissing = missingGitObjects(recovered, named);
7363
+ if (stillMissing.length) {
7364
+ const more = stillMissing.length > 3 ? ` and ${stillMissing.length - 3} more` : "";
7365
+ throw new Error(`the recovery lacks ${stillMissing.length} Git object(s) that its copied Git metadata names, and ${source} could not supply them: ${stillMissing.slice(0, 3).join(", ")}${more}`);
7366
+ }
7367
+ }
7368
+
6872
7369
  function restoreStandaloneGitState(sourceWork, recoveredRepo) {
6873
7370
  const sourceGit = copierGitDir(sourceWork);
6874
7371
  const recoveredGit = join(recoveredRepo, ".git");
6875
- const indexRows = execFileSync("git", ["-C", sourceWork, "ls-files", "--stage", "-z"], { maxBuffer: GIT_MAX_BUFFER });
6876
- // The staged blobs the recovered index will point at. The clone already
6877
- // holds every blob reachable from a commit; only content that is staged but
6878
- // never committed is missing, so ask once which objects the recovered
6879
- // repository lacks (one process for the whole index) and copy only those.
6880
- // Copying every row cost two Git processes per index entry: a clean 9,500
6881
- // file tree took ~19,000 launches and looked like a hang. Gitlink rows
6882
- // (mode 160000) name commits of nested repositories, which
6883
- // materializeNestedRepositories restores; they are never blobs here.
6884
- const staged = new Set();
6885
- for (const row of indexRows.toString("utf8").split("\0").filter(Boolean)) {
6886
- const match = row.match(/^(\d+) ([0-9a-f]+) \d+\t/);
6887
- if (!match || match[1] === "160000") continue;
6888
- staged.add(match[2]);
6889
- }
6890
- for (const oid of missingGitObjects(recoveredRepo, [...staged])) {
6891
- const blob = execFileSync("git", ["-C", sourceWork, "cat-file", "blob", oid], { maxBuffer: GIT_MAX_BUFFER });
6892
- const restored = execFileSync("git", ["-C", recoveredRepo, "hash-object", "-w", "--stdin"], { input: blob, encoding: "utf8" , maxBuffer: GIT_MAX_BUFFER }).trim();
6893
- if (restored !== oid) throw new Error(`recovered Git object ${restored} did not match source ${oid}`);
6894
- }
6895
- const stillMissing = missingGitObjects(recoveredRepo, [...staged]);
6896
- if (stillMissing.length) throw new Error(`recovered repository lacks ${stillMissing.length} staged object(s) after restore: ${stillMissing.slice(0, 3).join(", ")}`);
7372
+ // The blobs the copied index names, read from the index file the copier
7373
+ // copies (awebai/oats#647), not from Git's own idea of the index: its
7374
+ // staged entries and its resolve-undo records (awebai/oats#655). The clone
7375
+ // already holds every blob reachable from a commit; carryNamedObjects asks
7376
+ // once which the copy lacks and copies only those. Copying every row cost
7377
+ // two Git processes per index entry: a clean 9,500 file tree took ~19,000
7378
+ // launches and looked like a hang.
7379
+ const index = { env: { GIT_INDEX_FILE: join(sourceGit, "index") } };
7380
+ const blobs = [
7381
+ ...indexBlobs(retireGit(sourceWork, ["ls-files", "--stage", "-z"], index)),
7382
+ ...indexBlobs(retireGit(sourceWork, ["ls-files", "--resolve-undo", "-z"], index)),
7383
+ ];
7384
+ carryNamedObjects(sourceWork, recoveredRepo, { blobs });
6897
7385
  // The index is the selection's one exception (COPIED_GIT_PATHS): copied
6898
7386
  // whole, compared by its entries, resolve-undo records and mode.
6899
7387
  copyFileSync(join(sourceGit, "index"), join(recoveredGit, "index"));
@@ -6940,14 +7428,14 @@ const STATUS_CONFIG = ["core.fileMode", "core.ignoreCase", "core.precomposeUnico
6940
7428
  * carried: [{ kind: "config", key, value } | { kind: "info/attributes", path }]. */
6941
7429
  function carryStatusConfig(sourceWork, recoveredRepo) {
6942
7430
  const get = (repo, key) => {
6943
- try { return execFileSync("git", ["-C", repo, "config", "--get", key], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER }).replace(/\n$/, ""); }
7431
+ try { return retireGit(repo, ["config", "--get", key], { encoding: "utf8" }).replace(/\n$/, ""); }
6944
7432
  catch (e) { if (e.status === 1) return null; throw e; }
6945
7433
  };
6946
7434
  const carried = [];
6947
7435
  for (const key of STATUS_CONFIG) {
6948
7436
  const value = get(sourceWork, key);
6949
7437
  if (value === get(recoveredRepo, key)) continue;
6950
- execFileSync("git", ["-C", recoveredRepo, "config", "--local", ...(value === null ? ["--unset-all", key] : [key, value])], { stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER });
7438
+ retireGit(recoveredRepo, ["config", "--local", ...(value === null ? ["--unset-all", key] : [key, value])]);
6951
7439
  carried.push({ kind: "config", key, value });
6952
7440
  }
6953
7441
  const common = copierCommonDir(sourceWork);
@@ -6961,71 +7449,161 @@ function carryStatusConfig(sourceWork, recoveredRepo) {
6961
7449
  return carried;
6962
7450
  }
6963
7451
 
6964
- function detachRecoveryClone(source, recovered) {
7452
+ /** Make a recovery clone stand on its own: give it the source's stash (the
7453
+ * ref, its log, and every commit the copied log names: awebai/oats#654),
7454
+ * prove it holds those and `commits` (what the caller's carried metadata
7455
+ * names) with carryNamedObjects, then remove the remote it was cloned from. */
7456
+ function detachRecoveryClone(source, recovered, commits = []) {
7457
+ const named = [...commits];
6965
7458
  let stash;
6966
- try { stash = execFileSync("git", ["-C", source, "rev-parse", "--verify", "--quiet", "refs/stash"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] , maxBuffer: GIT_MAX_BUFFER }).trim(); }
7459
+ try { stash = retireGit(source, ["rev-parse", "--verify", "--quiet", "refs/stash"], { encoding: "utf8" }).trim(); }
6967
7460
  catch { stash = undefined; }
6968
7461
  if (stash) {
6969
- execFileSync("git", ["-C", recovered, "fetch", "--quiet", source, "refs/stash:refs/stash"], { maxBuffer: GIT_MAX_BUFFER });
7462
+ copierFetch(recovered, source, ["refs/stash:refs/stash"]);
7463
+ named.push(stash);
6970
7464
  const sourceCommon = copierCommonDir(source);
6971
7465
  const stashLog = copiedGitPath(GIT_STASH_LOG, null, sourceCommon);
6972
7466
  if (existsSync(stashLog)) {
6973
7467
  const recoveredLog = copiedGitPath(GIT_STASH_LOG, null, join(recovered, ".git"));
6974
7468
  mkdirSync(dirname(recoveredLog), { recursive: true });
6975
7469
  copyFileSync(stashLog, recoveredLog);
7470
+ named.push(...reflogCommits(recoveredLog));
6976
7471
  }
6977
7472
  }
6978
- try { execFileSync("git", ["-C", recovered, "remote", "remove", "origin"], { stdio: "ignore" , maxBuffer: GIT_MAX_BUFFER }); } catch { /* no remote is already independent */ }
6979
- }
6980
-
7473
+ carryNamedObjects(source, recovered, { commits: named });
7474
+ try { retireGit(recovered, ["remote", "remove", "origin"]); } catch { /* no remote is already independent */ }
7475
+ }
7476
+
7477
+ /** A path under a Git directory for a ref name read as bytes: a branch name
7478
+ * need not be UTF-8, and the file Git keeps for it is named by its bytes. */
7479
+ const gitPathOf = (dir, ...parts) => Buffer.concat([Buffer.from(`${dir}${sep}`), ...parts]);
7480
+ const parentOf = (path) => path.subarray(0, path.lastIndexOf(sep.charCodeAt(0)));
7481
+
7482
+ /** Give the clone of a nested repository the source's refs where they matter
7483
+ * for recovering work (awebai/oats#657): every local branch under its name at
7484
+ * its commit, HEAD on the source's branch when the source is on one (`name`:
7485
+ * headName) and detached at `head` otherwise, and the source's reflogs of
7486
+ * HEAD and of each branch, copied over the clone's own. The branches are the
7487
+ * source's own `refs/heads`, not the clone's `refs/remotes/origin/*`: those
7488
+ * are only what the source advertises, and its configuration can hide a
7489
+ * branch from a clone (`uploadpack.hideRefs`). A tip the clone lacks is
7490
+ * fetched by id (carryNamedObjects), and the copy's branches are then
7491
+ * checked to be the source's, name and commit, byte for byte. Its local
7492
+ * configuration is not carried beyond the status settings
7493
+ * (carryStatusConfig): a recovery must be inert to inspect, and
7494
+ * configuration can name programs Git runs. → the commits the copied
7495
+ * reflogs name, for carryNamedObjects: a commit only a reflog reaches is not
7496
+ * in the clone until it is fetched. */
7497
+ function carryNestedRefs(source, dest, name, head) {
7498
+ const BRANCHES = ["for-each-ref", "--format=%(objectname)%00%(refname)", "refs/heads/"];
7499
+ const listing = retireGit(source, BRANCHES);
7500
+ const branches = [];
7501
+ for (let at = 0; at < listing.length;) {
7502
+ let end = listing.indexOf(0x0a, at);
7503
+ if (end < 0) end = listing.length;
7504
+ const row = listing.subarray(at, end);
7505
+ at = end + 1;
7506
+ if (!row.length) continue;
7507
+ const nul = row.indexOf(0);
7508
+ branches.push({ oid: row.subarray(0, nul).toString("latin1"), ref: row.subarray(nul + 1) });
7509
+ }
7510
+ carryNamedObjects(source, dest, { commits: branches.map((b) => b.oid) });
7511
+ if (branches.length) {
7512
+ retireGit(dest, ["update-ref", "--stdin"], { input: Buffer.concat(branches.flatMap(({ oid, ref }) => [Buffer.from("update "), ref, Buffer.from(` ${oid}\n`)])) });
7513
+ }
7514
+ if (!retireGit(dest, BRANCHES).equals(listing)) throw new Error(`nested recovery ${dest} does not have the local branches of its source`);
7515
+ if (name.branch !== null) retireGit(dest, ["symbolic-ref", "HEAD", `refs/heads/${name.branch}`]);
7516
+ else retireGit(dest, ["checkout", "--quiet", "--detach", head]);
7517
+ const recovered = retireGit(dest, ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
7518
+ if (recovered !== head) throw new Error(`nested recovery ${dest} is at ${recovered}, not at the commit ${head} its source has checked out`);
7519
+ // The reflogs last, so that nothing above writes to them after the copy.
7520
+ const named = [];
7521
+ const carryLog = (from, to) => {
7522
+ if (existsSync(from)) {
7523
+ mkdirSync(parentOf(to), { recursive: true });
7524
+ copyFileSync(from, to);
7525
+ named.push(...reflogCommits(to));
7526
+ } else rmSync(to, { force: true });
7527
+ };
7528
+ const destGit = join(dest, ".git");
7529
+ carryLog(gitPathOf(copierGitDir(source), Buffer.from("logs/HEAD")), gitPathOf(destGit, Buffer.from("logs/HEAD")));
7530
+ const sourceCommon = copierCommonDir(source);
7531
+ for (const { ref } of branches) carryLog(gitPathOf(sourceCommon, Buffer.from("logs/"), ref), gitPathOf(destGit, Buffer.from("logs/"), ref));
7532
+ return named;
7533
+ }
7534
+
7535
+ /** Rebuild each nested repository (nestedGitRoots) in the copy of a worktree
7536
+ * at `recoveredRepo`, from a clone, and mirror its files into it
7537
+ * (mirrorTopLevel). It runs after the worktree's own mirror, which put every
7538
+ * nested repository's plain files in place; each rebuild replaces one of
7539
+ * them. No root is under another (nestedGitRoots does not go into a
7540
+ * repository), so no mirror here removes a repository rebuilt before it.
7541
+ * Git is run on each repository by its path, which Node passes as UTF-8
7542
+ * text: a repository whose path is not valid UTF-8 cannot be named to Git,
7543
+ * and refuses the copy. */
6981
7544
  function materializeNestedRepositories(sourceWork, recoveredRepo) {
6982
7545
  const excludes = [], statusConfig = [];
6983
- for (const source of nestedGitRoots(sourceWork)) {
7546
+ for (const root of nestedGitRoots(sourceWork)) {
7547
+ const source = root.toString("utf8");
7548
+ if (!Buffer.from(source).equals(root)) throw new Error(`nested repository ${source} has a path that is not valid UTF-8, and Git cannot be run on such a path; rename the directory, then retire again`);
6984
7549
  const rel = relative(sourceWork, source);
6985
7550
  const dest = join(recoveredRepo, rel);
6986
- const head = execFileSync("git", ["-C", source, "rev-parse", "HEAD"], { encoding: "utf8" , maxBuffer: GIT_MAX_BUFFER }).trim();
7551
+ const name = headName(source);
7552
+ const head = retireGit(source, ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
6987
7553
  rmSync(dest, { recursive: true, force: true });
6988
- execFileSync("git", ["clone", "--no-local", "--quiet", source, dest], { stdio: ["ignore", "pipe", "pipe"] , maxBuffer: GIT_MAX_BUFFER });
6989
- execFileSync("git", ["-C", dest, "checkout", "--quiet", head], { maxBuffer: GIT_MAX_BUFFER });
6990
- detachRecoveryClone(source, dest);
7554
+ retireGit(null, ["clone", "--no-local", "--quiet", source, dest]);
7555
+ detachRecoveryClone(source, dest, carryNestedRefs(source, dest, name, head));
6991
7556
  restoreStandaloneGitState(source, dest);
6992
7557
  for (const c of carryExcludes(source, dest)) excludes.push({ repo: rel, ...c });
6993
7558
  for (const c of carryStatusConfig(source, dest)) statusConfig.push({ repo: rel, ...c });
6994
- for (const e of readdirSync(source, { withFileTypes: true })) {
6995
- if (e.name === ".git") continue;
6996
- const target = join(dest, e.name);
6997
- rmSync(target, { recursive: true, force: true });
6998
- copyTreeSafe(join(source, e.name), target);
6999
- }
7559
+ mirrorTopLevel(source, dest);
7000
7560
  if (existsSync(join(dest, ".git", "objects", "info", "alternates"))) throw new Error(`nested recovery ${rel} depends on object alternates`);
7001
7561
  assertStatusAgrees(source, dest, `nested recovery ${rel} Git state disagreed with source`, rel);
7002
7562
  }
7003
7563
  return { excludes, statusConfig };
7004
7564
  }
7005
7565
 
7006
- /** Bytes a path holds, never following a symlink (a link counts as its own entry). */
7566
+ /** Bytes a path holds, never following a symlink (a link counts as its own
7567
+ * entry). `path` is a string or a Buffer; names under it are read as bytes. */
7007
7568
  function treeBytes(path) {
7008
7569
  let st; try { st = lstatSync(path); } catch { return 0; }
7009
7570
  if (!st.isDirectory()) return st.size;
7010
7571
  let n = 0;
7011
- for (const e of readdirSync(path)) n += treeBytes(join(path, e));
7572
+ for (const name of readdirSync(path, { encoding: "buffer" })) n += treeBytes(joinBytes(path, name));
7012
7573
  return n;
7013
7574
  }
7575
+ /** The paths of the untracked (`??`) and ignored (`!!`) rows of
7576
+ * `git status --porcelain=v1 -z` output, as bytes. */
7577
+ function untrackedOrIgnoredPaths(z) {
7578
+ const out = [];
7579
+ for (let at = 0; at < z.length;) {
7580
+ let end = z.indexOf(0, at);
7581
+ if (end < 0) end = z.length;
7582
+ const row = z.subarray(at, end);
7583
+ at = end + 1;
7584
+ const xy = row.subarray(0, 3).toString("latin1");
7585
+ if (xy === "?? " || xy === "!! ") out.push(row.subarray(3));
7586
+ }
7587
+ return out;
7588
+ }
7014
7589
  /** The outputs a recovery copies beyond committed and tracked state — a worktree's
7015
7590
  * untracked and ignored paths (its status), or a directory's work entries —
7016
7591
  * grouped by top-level entry with their bytes, largest first. There is no
7017
7592
  * disposable declaration on the workspace model, so node_modules/ or build/
7018
7593
  * outputs are copied too: the retire summary names them and what they cost. */
7019
7594
  function preservedOutputs(work, directory) {
7020
- const rows = directory
7021
- ? readdirSync(work)
7022
- : worktreeStatus(work).split("\0").filter((row) => row.startsWith("?? ") || row.startsWith("!! ")).map((row) => row.slice(3));
7595
+ // Paths as bytes, so every one is read by its own name; each group is
7596
+ // named as text, a name that is not UTF-8 with replacement characters.
7597
+ const rows = directory ? readdirSync(work, { encoding: "buffer" }) : untrackedOrIgnoredPaths(worktreeStatusBytes(work));
7598
+ const SLASH = 0x2f;
7023
7599
  const groups = new Map();
7024
7600
  for (const rel of rows) {
7025
- const parts = rel.replace(/\/$/, "").split("/");
7026
- const isDir = parts.length > 1 || rel.endsWith("/") || (directory && lstatSync(join(work, rel)).isDirectory());
7027
- const key = isDir ? `${parts[0]}/` : parts[0];
7028
- groups.set(key, (groups.get(key) || 0) + treeBytes(join(work, rel)));
7601
+ const trailing = rel.length > 0 && rel[rel.length - 1] === SLASH;
7602
+ const slash = rel.indexOf(SLASH);
7603
+ const first = slash < 0 ? rel : rel.subarray(0, slash);
7604
+ const isDir = (slash >= 0 && slash < rel.length - 1) || trailing || (directory && lstatSync(joinBytes(work, rel)).isDirectory());
7605
+ const key = isDir ? `${first.toString("utf8")}/` : first.toString("utf8");
7606
+ groups.set(key, (groups.get(key) || 0) + treeBytes(joinBytes(work, rel)));
7029
7607
  }
7030
7608
  const paths = [...groups].map(([path, bytes]) => ({ path, bytes })).sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
7031
7609
  return { paths, bytes: paths.reduce((n, p) => n + p.bytes, 0) };
@@ -7034,17 +7612,18 @@ function preservedOutputs(work, directory) {
7034
7612
  /** The home part of a recovery at `dest`: everything but work/ and this pass's
7035
7613
  * excluded provider-owned entries (observation.homeExclude), verified against
7036
7614
  * the source with that same set. The copy is hashed whole, so an excluded
7037
- * entry that reached it fails the verification. The stored digest is what
7038
- * is compared: it leaves the kernel's own fields of instance.json out, so a
7039
- * kernel write there between the copy and this check is not a disagreement.
7040
- * That is an inherited limit, and this is not an exact verification of the
7041
- * whole home: the stored digest also passes over the kernel's receipts and
7042
- * the harness settings, reads instance.json through a parse, and frames its
7043
- * entries without lengths. */
7615
+ * entry that reached it fails the verification. Source and copy are compared
7616
+ * in this run, so whatever version the baseline holds, the stored digest of
7617
+ * version 2 is what is compared (fingerprintTrees): its order is the bytes'
7618
+ * and its fields carry their lengths. It leaves the kernel's own fields of
7619
+ * instance.json out, so a kernel write there between the copy and this check
7620
+ * is not a disagreement. That is why this is not an exact verification of
7621
+ * the whole home: the stored digest also passes over the kernel's receipts
7622
+ * and the harness settings, and reads instance.json through a parse. */
7044
7623
  function copyRecoveryHome(observation, dest) {
7045
7624
  const excludeRoot = observation.homeExclude || new Set(["work"]);
7046
7625
  copyRecoveryTree(observation.home, dest, { excludeRoot });
7047
- if (fingerprintTree(observation.home, { excludeRoot, instanceHome: true }) !== fingerprintTree(dest, { instanceHome: true })) {
7626
+ if (storedTreeDigest(observation.home, BASELINE_DIGEST_VERSION, { excludeRoot, instanceHome: true }) !== storedTreeDigest(dest, BASELINE_DIGEST_VERSION, { instanceHome: true })) {
7048
7627
  throw new Error("home recovery verification disagreed with the source");
7049
7628
  }
7050
7629
  }
@@ -7072,11 +7651,11 @@ function copyRecoveryWork(observation, meta, parent) {
7072
7651
  try { ref = existsSync(observation.work) ? worktreeHead(observation.work) : { branch: meta.branch, commit: null }; }
7073
7652
  catch (e) { unreadableHeads.add(e); throw e; }
7074
7653
  if (ref.branch !== meta.branch) branchDrift = { recordedBranch: meta.branch, worktreeBranch: ref.branch, detachedAt: ref.branch === null ? ref.commit : null };
7075
- if (ref.branch !== null) execFileSync("git", ["clone", "--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo], { stdio: ["ignore", "pipe", "pipe"] , maxBuffer: GIT_MAX_BUFFER });
7654
+ if (ref.branch !== null) retireGit(null, ["clone", "--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo]);
7076
7655
  else {
7077
- execFileSync("git", ["clone", "--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo], { stdio: ["ignore", "pipe", "pipe"] , maxBuffer: GIT_MAX_BUFFER });
7078
- execFileSync("git", ["-C", recoveredRepo, "fetch", "--quiet", observation.work, ref.commit], { stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER });
7079
- execFileSync("git", ["-C", recoveredRepo, "checkout", "--quiet", "--detach", ref.commit], { stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER });
7656
+ retireGit(null, ["clone", "--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo]);
7657
+ copierFetch(recoveredRepo, observation.work, [ref.commit]);
7658
+ retireGit(recoveredRepo, ["checkout", "--quiet", "--detach", ref.commit]);
7080
7659
  }
7081
7660
  const sourceGitContext = existsSync(observation.work) ? observation.work : meta.repo;
7082
7661
  detachRecoveryClone(sourceGitContext, recoveredRepo);
@@ -7084,12 +7663,10 @@ function copyRecoveryWork(observation, meta, parent) {
7084
7663
  restoreStandaloneGitState(observation.work, recoveredRepo);
7085
7664
  excludes = carryExcludes(observation.work, recoveredRepo).map((c) => ({ repo: ".", ...c }));
7086
7665
  statusConfig = carryStatusConfig(observation.work, recoveredRepo).map((c) => ({ repo: ".", ...c }));
7087
- for (const e of readdirSync(observation.work, { withFileTypes: true })) {
7088
- if (e.name === ".git") continue;
7089
- const dest = join(recoveredRepo, e.name);
7090
- rmSync(dest, { recursive: true, force: true });
7091
- copyTreeSafe(join(observation.work, e.name), dest);
7092
- }
7666
+ // The worktree's top level first, then each nested repository rebuilt
7667
+ // inside it (materializeNestedRepositories): that order is what keeps
7668
+ // a rebuilt repository from being removed by a mirror.
7669
+ mirrorTopLevel(observation.work, recoveredRepo);
7093
7670
  const nested = materializeNestedRepositories(observation.work, recoveredRepo);
7094
7671
  excludes.push(...nested.excludes); statusConfig.push(...nested.statusConfig);
7095
7672
  }
@@ -7099,7 +7676,12 @@ function copyRecoveryWork(observation, meta, parent) {
7099
7676
  // pre-hook recovery was written, or by the proof that the hooks moved
7100
7677
  // nothing, or else here. Either way they are kept as the observation's
7101
7678
  // byte state.
7102
- if ((observation.worktree ? observedWorkBytes(observation) : worktreeBytes(observation.work)) !== worktreeBytes(recoveredRepo)) throw new Error("worktree recovery verification disagreed with the source");
7679
+ // The Git directories the comparison leaves out are the source's
7680
+ // (worktreeGitPaths), read with its bytes, for both sides.
7681
+ let sourceBytes, gitPaths;
7682
+ if (observation.worktree) { sourceBytes = observedWorkBytes(observation); gitPaths = observation.workGitPaths ?? worktreeGitPaths(observation.work); }
7683
+ else { gitPaths = worktreeGitPaths(observation.work); sourceBytes = worktreeBytes(observation.work, gitPaths); }
7684
+ if (sourceBytes !== worktreeBytes(recoveredRepo, gitPaths)) throw new Error("worktree recovery verification disagreed with the source");
7103
7685
  assertStatusAgrees(observation.work, recoveredRepo, "recovered Git index/status disagreed with the source", ".");
7104
7686
  }
7105
7687
  // The proof of the copy: its HEAD is the commit the worktree has checked
@@ -7107,9 +7689,9 @@ function copyRecoveryWork(observation, meta, parent) {
7107
7689
  // same files, so the branch's tip there proves nothing about the copy.
7108
7690
  // With the worktree gone there is no such commit to read, and the copy
7109
7691
  // is the recorded branch as the repository has it.
7110
- const recoveredHead = execFileSync("git", ["-C", recoveredRepo, "rev-parse", "HEAD"], { encoding: "utf8" , maxBuffer: GIT_MAX_BUFFER }).trim();
7692
+ const recoveredHead = retireGit(recoveredRepo, ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
7111
7693
  const sourceHead = ref.commit
7112
- ?? execFileSync("git", ["-C", meta.repo, "rev-parse", `refs/heads/${ref.branch}`], { encoding: "utf8" , maxBuffer: GIT_MAX_BUFFER }).trim();
7694
+ ?? retireGit(meta.repo, ["rev-parse", `refs/heads/${ref.branch}`], { encoding: "utf8" }).trim();
7113
7695
  if (recoveredHead !== sourceHead) throw new Error(ref.commit ? "recovery clone is not at the commit the worktree has checked out" : "recovery clone does not retain the instance branch tip");
7114
7696
  copied = true;
7115
7697
  }
@@ -7128,8 +7710,8 @@ function copyRecoveryWork(observation, meta, parent) {
7128
7710
  * largest first; a directory ends in `/`. What the retire summary names as
7129
7711
  * copied from the home. */
7130
7712
  function preservedHome(recoveredHome) {
7131
- const paths = readdirSync(recoveredHome, { withFileTypes: true })
7132
- .map((e) => ({ path: e.isDirectory() ? `${e.name}/` : e.name, bytes: treeBytes(join(recoveredHome, e.name)) }))
7713
+ const paths = entriesAsBytes(recoveredHome)
7714
+ .map((e) => ({ path: e.isDirectory() ? `${e.name.toString("utf8")}/` : e.name.toString("utf8"), bytes: treeBytes(joinBytes(recoveredHome, e.name)) }))
7133
7715
  .sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
7134
7716
  return { paths, bytes: paths.reduce((n, p) => n + p.bytes, 0) };
7135
7717
  }
@@ -7151,6 +7733,30 @@ function homeOnlyRecovery(observation, meta) {
7151
7733
  return !RECOVERABLE_GIT_ADMIN.some((name) => existsSync(join(gitDir, name)));
7152
7734
  }
7153
7735
 
7736
+ /** Remove a recovery's staging directory, after a copy that failed or that had
7737
+ * nothing to keep. The copy gives each directory its source's mode
7738
+ * (tree-copy.mjs), and a read-only one (a Go module cache, 0555) keeps
7739
+ * rmSync from unlinking what is in it: each directory is made u+rwx first,
7740
+ * before it is read (an unreadable one could not be listed), symbolic links
7741
+ * are never followed, and then the tree is removed. Never throws: a cleanup
7742
+ * must not replace the error that made it (#659). → null when the staging is
7743
+ * gone, else the clause a refusal adds to name what is left. */
7744
+ function removeStaging(staging) {
7745
+ const open = (dir) => {
7746
+ let names;
7747
+ try {
7748
+ const st = lstatSync(dir);
7749
+ if (!st.isDirectory()) return;
7750
+ if ((st.mode & 0o700) !== 0o700) chmodSync(dir, (st.mode & 0o7777) | 0o700);
7751
+ names = readdirSync(dir);
7752
+ } catch { return; }
7753
+ for (const name of names) open(join(dir, name));
7754
+ };
7755
+ try { open(staging); rmSync(staging, { recursive: true, force: true }); } catch { /* named below */ }
7756
+ try { lstatSync(staging); } catch (e) { if (e?.code === "ENOENT") return null; }
7757
+ return `; its partial copy ${staging} could not be removed: remove it by hand`;
7758
+ }
7759
+
7154
7760
  /** Write one verified recovery of an observed home and work: staged beside its
7155
7761
  * final name and renamed into place. `phase` goes into recovery.json:
7156
7762
  * "before-hooks" for the snapshot a retirement takes before its retire hooks
@@ -7183,10 +7789,10 @@ function writeRetirementRecovery(observation, meta, instance, phase) {
7183
7789
  renameSync(staging, recovery);
7184
7790
  return { receipt: { path: recovery, classes: observation.classes, bytes, home, ...(outputs ? { outputs } : {}), ...(repoCopy ? { repoCopy } : {}), ...(notCopied ? { notCopied } : {}) }, manifest };
7185
7791
  } catch (e) {
7186
- rmSync(staging, { recursive: true, force: true });
7187
- if (unreadableHeads.has(e)) throw e;
7792
+ const left = removeStaging(staging);
7793
+ if (unreadableHeads.has(e)) { if (left) e.message += left; throw e; }
7188
7794
  const details = e.statusDisagreement ? { home: observation.home, statusDisagreement: e.statusDisagreement } : undefined;
7189
- throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `retirement work remains at ${observation.home}; recovery could not be verified: ${e.message}`, details), details ? { details } : {});
7795
+ throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `retirement work remains at ${observation.home}; recovery could not be verified: ${e.message}${left ?? ""}`, details), details ? { details } : {});
7190
7796
  }
7191
7797
  }
7192
7798
 
@@ -7253,7 +7859,11 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
7253
7859
  if (occupied()) throw new Error(`${final} already exists`);
7254
7860
  renameSync(staging, final);
7255
7861
  afterHooks = { home: wantHome, work: workCopied };
7256
- } else rmSync(staging, { recursive: true, force: true });
7862
+ } else {
7863
+ const left = removeStaging(staging);
7864
+ staging = undefined;
7865
+ if (left) throw new Error(`nothing was copied after the hooks${left}`);
7866
+ }
7257
7867
  staging = undefined;
7258
7868
  }
7259
7869
  const classes = [...new Set([...receipt.classes, ...after.classes])];
@@ -7266,12 +7876,37 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
7266
7876
  const { notCopied: _was, ...kept } = receipt;
7267
7877
  return { ...kept, classes, bytes: treeBytes(recovery), ...(notCopied.length ? { notCopied } : {}), ...(afterHooks ? { afterHooks } : {}) };
7268
7878
  } catch (e) {
7269
- if (staging) rmSync(staging, { recursive: true, force: true });
7270
- if (manifestStarted) rmSync(manifestTmp, { force: true });
7271
- if (unreadableHeads.has(e)) throw e;
7879
+ const left = staging ? removeStaging(staging) : null;
7880
+ if (manifestStarted) { try { rmSync(manifestTmp, { force: true }); } catch { /* the original error is the refusal */ } }
7881
+ if (unreadableHeads.has(e)) { if (left) e.message += left; throw e; }
7272
7882
  const details = e.statusDisagreement ? { home: after.home, statusDisagreement: e.statusDisagreement } : undefined;
7273
- throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `retirement work remains at ${after.home}; recovery could not be verified: ${e.message}`, details), details ? { details } : {});
7274
- }
7883
+ throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `retirement work remains at ${after.home}; recovery could not be verified: ${e.message}${left ?? ""}`, details), details ? { details } : {});
7884
+ }
7885
+ }
7886
+
7887
+ /** The `work` link of the instance at `kidHome` when it is attached to
7888
+ * `home`'s work (#718), else null: instance.json says `work: "attached"`, and
7889
+ * its `work` is a symbolic link that leads to `<home>/work`, as written (in
7890
+ * any spelling of the home) or through other links (`--work-dir` given as an
7891
+ * alias of the tree). The latter is seen only while `<home>/work` exists, so a
7892
+ * retire asks before it re-homes the worktree. → the link's target as written:
7893
+ * the evidence a later relink checks is still there. */
7894
+ export function attachedWorkLink(kidHome, home) {
7895
+ if (readJsonOrUndefined(join(kidHome, "instance.json"))?.work !== "attached") return null;
7896
+ const link = join(kidHome, "work");
7897
+ let written;
7898
+ try { written = readlinkSync(link); } catch { return null; }
7899
+ const target = resolve(kidHome, written);
7900
+ if (target === join(resolve(home), "work")) return written;
7901
+ try { if (basename(target) === "work" && realpathSync(dirname(target)) === realpathSync(home)) return written; } catch { /* below */ }
7902
+ try { return realpathSync(link) === realpathSync(join(home, "work")) ? written : null; } catch { return null; }
7903
+ }
7904
+ /** Point an attached instance's `work` link at `to`, atomically: a new link
7905
+ * beside it is renamed over the old one, so the link is never missing. */
7906
+ function relinkAttachedWork(kidHome, to) {
7907
+ const tmp = join(kidHome, `.work.relink-${process.pid}`);
7908
+ try { rmSync(tmp, { force: true }); symlinkSync(to, tmp); renameSync(tmp, join(kidHome, "work")); }
7909
+ catch (e) { try { rmSync(tmp, { force: true }); } catch { /* the first error is the one reported */ } throw e; }
7275
7910
  }
7276
7911
 
7277
7912
  /** Marker a self-retiring instance leaves BESIDE its home: the retirement is
@@ -7427,6 +8062,10 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
7427
8062
  return true;
7428
8063
  }
7429
8064
 
8065
+ /** The key of the home a retire selected (a string) on retireInstance's result
8066
+ * (awebai/oats#693): the CLI cleans that home's wake schedules. A symbol, so
8067
+ * the printed and JSON receipt, and a recorded one, do not carry it. */
8068
+ export const RETIRE_SELECTED_HOME = Symbol("oats.retireSelectedHome");
7430
8069
  export function retireInstance(root, name, o = {}) {
7431
8070
  if (o.deleteBranch) throw oatsError("E_BAD_ARGS", RETIRE_DELETE_BRANCH_REFUSED);
7432
8071
  const session = o.tmuxSession || DEFAULT_TMUX_SESSION;
@@ -7460,6 +8099,7 @@ export function retireInstance(root, name, o = {}) {
7460
8099
  const quarantinePath = existsSync(directoryFallbackPath) ? directoryFallbackPath : join(found.home, ".oats-rollback-incomplete.json");
7461
8100
  let quarantine;
7462
8101
  let markerUnusable = false;
8102
+ let rawMarker;
7463
8103
  // A marker means the home is quarantined, WHETHER OR NOT instance.json exists:
7464
8104
  // the post-launch rollback retains a home that already has one, and gating on
7465
8105
  // its absence meant that quarantine was silently ignored — retire took the
@@ -7474,10 +8114,46 @@ export function retireInstance(root, name, o = {}) {
7474
8114
  // against what the retry below consumes (reviewer-45ff039r2).
7475
8115
  try {
7476
8116
  const parsed = JSON.parse(readFileSync(quarantinePath, "utf8"));
8117
+ rawMarker = parsed;
7477
8118
  if (isPlainObject(parsed) && usableCleanupDescriptor(parsed)) quarantine = parsed;
7478
8119
  else markerUnusable = true;
7479
8120
  } catch { markerUnusable = true; }
7480
8121
  }
8122
+ // #796: a marker a spawn wrote before its worktree hooks (`inProgress`). While that spawn's
8123
+ // process is verifiably alive it is a spawn in progress, never a quarantine to retry, --force
8124
+ // included. Once it is gone, the hook group it left is ended when its leader is alive at the
8125
+ // recorded start time; a group whose leader is gone is never signalled, only reported (its id may
8126
+ // be another group's by now). The retry below completes the rollback from the marker like any other.
8127
+ // Whether that process still runs may also be unreadable (no procfs and `ps` failing): that is never
8128
+ // taken for gone. Retire refuses it, naming the recorded pid and start for a check by hand, and the
8129
+ // existing forced path (`--force`) is the way out; a forced retry then keeps the spawn's branch.
8130
+ // The same holds for a hook group with members whose leader's start cannot be read.
8131
+ const spawnGroupWarnings = [];
8132
+ let inProgressUnverified = false;
8133
+ if (isPlainObject(rawMarker?.inProgress)) {
8134
+ const p = rawMarker.inProgress;
8135
+ const live = processLiveness(p);
8136
+ if (live.state === "alive") throw oatsError("E_LIFECYCLE_BUSY", `${name} is still being spawned (pid ${p.pid}, running its worktree hooks since ${p.startedAt ?? "?"}); nothing was retired — wait for the spawn to end, or stop that process, then retire`);
8137
+ if (live.state === "unknown") {
8138
+ if (!o.force) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `${name}: whether its spawn (pid ${p.pid}, recorded start ${p.processStart ?? "none"}, running its worktree hooks since ${p.startedAt ?? "?"}) still runs cannot be read (${live.reason}); nothing was retired — check that pid by hand, and if it is not that spawn, run \`oats retire ${name} --force\``), { details: { pid: p.pid, processStart: p.processStart ?? null, unknown: live.reason, remedy: `oats retire ${name} --force` } });
8139
+ inProgressUnverified = true;
8140
+ spawnGroupWarnings.push(`retired with --force although whether its spawn (pid ${p.pid}) still runs could not be read (${live.reason}); its branch is kept`);
8141
+ }
8142
+ }
8143
+ if (quarantine?.inProgress) {
8144
+ const p = quarantine.inProgress;
8145
+ const ended = terminateRecordedGroup(p);
8146
+ if (ended === "survived") throw oatsError("E_LIFECYCLE_BUSY", `${name}: the worktree hook process group ${p.hookPgid} that an interrupted spawn left could not be ended (it survived SIGKILL); nothing was retired`);
8147
+ if (ended === "unverified") spawnGroupWarnings.push(unverifiedGroupWarning(p.hookPgid));
8148
+ // A group whose leader's start cannot be read may still be that spawn's hook: never signalled,
8149
+ // and refused like an unreadable spawn above, with the same way out.
8150
+ if (ended === "unknown") {
8151
+ const note = unknownGroupNote(p);
8152
+ if (!o.force) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `${name}: the worktree hook ${note}; nothing was retired — check process group ${p.hookPgid} by hand: if it is that hook, end it (kill -TERM -- -${p.hookPgid}) and retire again; if it is not, run \`oats retire ${name} --force\``), { details: { hookPgid: p.hookPgid, hookStart: p.hookStart ?? null, remedy: `oats retire ${name} --force` } });
8153
+ inProgressUnverified = true;
8154
+ spawnGroupWarnings.push(`retired with --force although the worktree ${note}; its branch is kept`);
8155
+ }
8156
+ }
7481
8157
  const liveMeta = existsSync(metaPath) ? JSON.parse(readFileSync(metaPath, "utf8")) : undefined;
7482
8158
  // A quarantined home may carry an instance.json that is NOT the spawn record:
7483
8159
  // module materialization writes a pre-hook stub ({ modules, providers,
@@ -7524,7 +8200,7 @@ export function retireInstance(root, name, o = {}) {
7524
8200
  // (aweb-abep). `--keep-dir` keeps the old in-process path: nothing to inspect.
7525
8201
  // A home opened in Herdr (removed in 0.31.0) has no endpoint OATS can quiesce in-process. A
7526
8202
  // quarantined home's cleanup descriptor overrides the live record's endpoint: either may name it.
7527
- const herdrHome = recordsHerdr(meta, readJsonOrUndefined(retirementBaselinePath(found.home))) || recordsHerdr(liveMeta);
8203
+ const herdrHome = recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(found.home))) || recordsHerdr(liveMeta);
7528
8204
  if (self && (!o.keepDir || herdrHome)) {
7529
8205
  return scheduleDeferredSelfRetirement(root, found, name, o, session);
7530
8206
  }
@@ -7543,7 +8219,7 @@ export function retireInstance(root, name, o = {}) {
7543
8219
  const recordedBranch = quarantine ? { repo: meta.repo, branch: meta.branch } : undefined;
7544
8220
  // Whether this retire removes the worktree, when it gets to that step.
7545
8221
  const worktreeRemoval = { removes: !!(o.discardWorktree || owesWorktree), repo: meta.repo };
7546
- const initialObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork });
8222
+ const initialObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: "Nothing was stopped, run or removed" });
7547
8223
  // A locked extra tree is known from the home as it is now: Git will neither move nor remove it, so a retire that
7548
8224
  // would remove the home refuses here, before the session is stopped and before any retire hook runs (the hooks
7549
8225
  // revoke identities a kept home would still need). The extra-tree step keeps its own check, for a lock that appears
@@ -7624,7 +8300,11 @@ export function retireInstance(root, name, o = {}) {
7624
8300
  }
7625
8301
  sessionStopped = true;
7626
8302
  }
7627
- const stableObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork });
8303
+ // What a refusal before the hooks tells the operator about the retire so far.
8304
+ const soFar = (kept) => `${name} is not retired and ${kept}; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}`;
8305
+ // What a refusal after the hooks tells the operator about the retire so far.
8306
+ const afterHooks = () => `The retire hooks have run; the home, its work and the pre-hook recovery (if any) are kept; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}`;
8307
+ const stableObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: `No retire hook has run and nothing was deleted: ${soFar("its home and work are kept")}` });
7628
8308
  // The bytes of the worktree as they are before the hooks: after the hooks,
7629
8309
  // "the work did not move" is then proven, never taken from a status text.
7630
8310
  // Read before the recovery is written, so that a worktree that cannot be
@@ -7636,8 +8316,6 @@ export function retireInstance(root, name, o = {}) {
7636
8316
  // unchanged is copied again in any case, and with nothing to preserve
7637
8317
  // before the hooks there is nothing to prove: any class after them is
7638
8318
  // preserved.
7639
- // What a refusal before the hooks tells the operator about the retire so far.
7640
- const soFar = (kept) => `${name} is not retired and ${kept}; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}`;
7641
8319
  if (stableObservation.classes.length && stableObservation.workProvable) {
7642
8320
  try { observedWorkBytes(stableObservation); }
7643
8321
  catch (e) {
@@ -7740,10 +8418,17 @@ export function retireInstance(root, name, o = {}) {
7740
8418
  // baseline): it does not have to be a move of the observed state. Either
7741
8419
  // way this finishes, or refuses and keeps the home, before the worktree
7742
8420
  // step and before the home is removed.
7743
- const finalObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork });
7744
- if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, meta);
7745
- else if (finalObservation.classes.length) {
7746
- workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, meta, name);
8421
+ // A refusal here says what has and has not happened, as one before the hooks
8422
+ // does: the hooks have run, and what is kept (#659).
8423
+ const finalObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: afterHooks() });
8424
+ try {
8425
+ if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, meta);
8426
+ else if (finalObservation.classes.length) {
8427
+ workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, meta, name);
8428
+ }
8429
+ } catch (e) {
8430
+ if (!e?.code) throw e;
8431
+ throw Object.assign(oatsError(e.code, `${e.message}. ${afterHooks()}.`, e.provenance), e.details ? { details: e.details } : {});
7747
8432
  }
7748
8433
 
7749
8434
  // Lineage repair: any instance pointing at the retiree (parentInstance from a
@@ -7842,8 +8527,8 @@ export function retireInstance(root, name, o = {}) {
7842
8527
  try {
7843
8528
  git(row, ["worktree", "remove", row.path]);
7844
8529
  git(row, ["worktree", "prune"]);
7845
- const real = realPathOrNearest(row.path);
7846
- if (existsSync(row.path) || parseWorktreeList(git(row, ["worktree", "list", "--porcelain", "-z"])).some((r) => realPathOrNearest(r.worktree) === real)) throw new Error("it is still there after `git worktree remove`");
8530
+ const real = canonicalHomePath(row.path);
8531
+ if (existsSync(row.path) || parseWorktreeList(git(row, ["worktree", "list", "--porcelain", "-z"])).some((r) => canonicalHomePath(r.worktree) === real)) throw new Error("it is still there after `git worktree remove`");
7847
8532
  } catch (e) { throw failed(row, "could not be removed, or its removal could not be verified", e); }
7848
8533
  extraWorktrees.push({ ...row, outcome: "removed" });
7849
8534
  appendEvent(found.home, { kind: "worktree-removed", data: { branch: row.branch, extra: true, path: row.path } }, { workspaceOnly: true });
@@ -7858,10 +8543,31 @@ export function retireInstance(root, name, o = {}) {
7858
8543
  }
7859
8544
  if (!extraWorktrees.length) extraWorktrees = undefined;
7860
8545
  }
8546
+ // The attached children this retire stopped whose work is this home's work/
8547
+ // (#718), found while work/ is still here (a link through an alias of the
8548
+ // tree resolves only then), each with its link as written.
8549
+ const attachedKids = (childrenStopped || []).filter((k) => k.ok).map((k) => ({ ...k, link: attachedWorkLink(k.home, found.home) })).filter((k) => k.link !== null);
7861
8550
  const worktreeStep = isWorktree && !!meta.repo && !orphanedWork;
7862
8551
  const worktreeDeferred = worktreeStep && existsSync(workPath) && outstandingBeforeWorktree.length > 0 && !o.force;
7863
8552
  const keptForRetry = worktreeDeferred ? `git worktree ${workPath}: kept for the retry; outstanding: ${outstandingBeforeWorktree.join("; ")}` : null;
7864
8553
  let retention = null;
8554
+ // The repository of work/, by its common Git directory (awebai/oats#679), read once from meta.repo: the
8555
+ // step's commands and the quarantine's verification below run helper-free against it (gitRepoRun,
8556
+ // gitRepoRead), as the extra-tree step's do. A bare repository is named as its Git directory.
8557
+ // → { dir } or { error }.
8558
+ let workRepo;
8559
+ const workRepoGitDir = () => {
8560
+ if (workRepo) return workRepo;
8561
+ const args = ["rev-parse", "--path-format=absolute", "--git-common-dir"];
8562
+ let r = gitRead(meta.repo, args);
8563
+ if (!r.ok) { const asGitDir = gitRepoRead(meta.repo, args); if (asGitDir.ok) r = asGitDir; }
8564
+ const dir = r.ok ? r.out.replace(/\n$/, "") : "";
8565
+ return (workRepo = dir && !dir.includes("\n") ? { dir: realPathOrNearest(dir) } : { error: r.ok ? `git rev-parse printed no single Git directory for ${meta.repo}` : r.err });
8566
+ };
8567
+ // Whether an entry is at the path: lstat, so a dangling link is an entry; one that cannot be tested counts.
8568
+ const entryAt = (path) => { try { lstatSync(path); return true; } catch (e) { return e?.code !== "ENOENT"; } };
8569
+ // A removal that work/ was not there for, from a repository that could not be read: nothing was verified.
8570
+ let removalUnverified;
7865
8571
  if (worktreeStep && !worktreeDeferred) {
7866
8572
  // A HEAD that cannot be read here is recorded as no branch and no commit, and the worktree is retained.
7867
8573
  const ref = existsSync(workPath) ? (() => { try { return worktreeHead(workPath); } catch { return { branch: null, commit: null }; } })() : { branch: meta.branch ?? null, commit: null };
@@ -7877,14 +8583,36 @@ export function retireInstance(root, name, o = {}) {
7877
8583
  catch (e) { throw oatsError("E_WORK_INSPECTION_FAILED", `${e.message}. The worktree was not removed. The home and the worktree are kept, and so is any recovery the retire wrote; retry the retire.`); }
7878
8584
  assertSameWorktreeHead(finalObservation.head, now);
7879
8585
  }
7880
- shTry(`git -C ${shq(meta.repo)} worktree remove --force ${shq(workPath)}`);
7881
- shTry(`git -C ${shq(meta.repo)} worktree prune`);
7882
- retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
8586
+ // The removal is verified as the extra-tree step's is: nothing is at work/ and the repository's
8587
+ // worktree list does not name it. A removal that did not happen, or cannot be shown to have
8588
+ // happened, refuses and keeps the home, --force included. One exception: nothing at work/ and a
8589
+ // repository that cannot be read is recorded as absent, never removed; a quarantine keeps that
8590
+ // as an item its retry could not verify (below).
8591
+ const present = entryAt(workPath);
8592
+ const gitDir = workRepoGitDir();
8593
+ if (gitDir.error && !present) {
8594
+ removalUnverified = gitDir.error;
8595
+ retention = { worktree: "absent", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
8596
+ } else {
8597
+ const real = canonicalHomePath(workPath);
8598
+ try {
8599
+ if (gitDir.error) throw new Error(gitDir.error);
8600
+ if (present) gitRepoRun(gitDir.dir, ["worktree", "remove", "--force", workPath]);
8601
+ gitRepoRun(gitDir.dir, ["worktree", "prune"]);
8602
+ if (entryAt(workPath) || parseWorktreeList(gitRepoRun(gitDir.dir, ["worktree", "list", "--porcelain", "-z"])).some((r) => canonicalHomePath(r.worktree) === real)) throw new Error("it is still there after `git worktree remove`");
8603
+ } catch (e) {
8604
+ const done = extraWorktrees?.length ? ` Already done in this retire: ${extraWorktrees.map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`).join(", ")}.` : "";
8605
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be removed, or its removal could not be verified (${String(e?.stderr || e?.message || e || "").trim() || "unknown error"}).${done} The retire hooks have run; the home is kept, and so is any recovery the retire wrote; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}. Check what is left at ${workPath}, then retry the retire.`);
8606
+ }
8607
+ retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
8608
+ }
7883
8609
  } else if (existsSync(workPath)) {
7884
8610
  const dest = retainedWorktreeDest(workspaceOf(root), meta.repo, verifiedBranch, ref.commit);
7885
8611
  mkdirSync(dirname(dest), { recursive: true });
7886
8612
  try {
7887
- execFileSync("git", ["-C", meta.repo, "worktree", "move", workPath, dest], { stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER });
8613
+ const gitDir = workRepoGitDir();
8614
+ if (gitDir.error) throw new Error(gitDir.error);
8615
+ gitRepoRun(gitDir.dir, ["worktree", "move", workPath, dest]);
7888
8616
  } catch (e) {
7889
8617
  throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be re-homed to ${dest} (${String(e.stderr ?? e.message ?? "").trim()}); the home is kept so nothing is lost — resolve and retry, or pass --discard-worktree to remove the worktree instead`);
7890
8618
  }
@@ -7927,29 +8655,31 @@ export function retireInstance(root, name, o = {}) {
7927
8655
  });
7928
8656
  stillIncomplete = ordinaryIncomplete;
7929
8657
  }
8658
+ let branchDeletedByRetry = false, branchKeptReason;
7930
8659
  if (quarantine) {
7931
8660
  const failures = [...retryFailures];
7932
8661
  if (keptForRetry) failures.push(keptForRetry);
7933
8662
  // The quarantine may exist BECAUSE Git cleanup failed, so a retry has to
7934
8663
  // redo those steps and verify them — not just rerun hooks. No retire deletes a branch.
7935
8664
  if (meta.work === "worktree" && meta.repo) {
7936
- const gitProbe = (argv) => {
7937
- try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
7938
- catch (e2) { return { ok: false, status: e2.status, err: String(e2.stderr ?? e2.message ?? "").trim() }; }
7939
- };
7940
8665
  // A worktree this retry removed (the step above ran) must be verified gone; one it retained or kept for
7941
8666
  // the next retry stays registered by design. The removal is not attempted a second time here: only the
7942
8667
  // worktree step removes, after its check of HEAD, so a worktree it failed to remove is still registered
7943
8668
  // and the next retry goes through that step again.
8669
+ // Its commands run helper-free against the repository's common Git directory (workRepoGitDir).
8670
+ const gitDir = workRepoGitDir();
7944
8671
  if (retention?.worktree === "removed") {
7945
- const wtCanonical = realPathOrNearest(workPath);
7946
- gitProbe(["git", "-C", meta.repo, "worktree", "prune"]);
7947
- const wtProbe = gitProbe(["git", "-C", meta.repo, "worktree", "list", "--porcelain", "-z"]);
7948
- if (!wtProbe.ok) failures.push(`git worktree ${wtCanonical}: could not verify removal (${wtProbe.err || "worktree list failed"})`);
8672
+ const wtCanonical = canonicalHomePath(workPath);
8673
+ let wtProbe;
8674
+ if (gitDir.error) wtProbe = { ok: false, err: gitDir.error };
7949
8675
  else {
7950
- const registered = wtProbe.out.split("\0").filter((f) => f.startsWith("worktree ")).map((f) => f.slice("worktree ".length));
7951
- if (registered.includes(wtCanonical)) failures.push(`git worktree ${wtCanonical}: still registered`);
8676
+ try { gitRepoRun(gitDir.dir, ["worktree", "prune"]); } catch { /* the list below decides */ }
8677
+ wtProbe = gitRepoRead(gitDir.dir, ["worktree", "list", "--porcelain", "-z"]);
7952
8678
  }
8679
+ if (!wtProbe.ok) failures.push(`git worktree ${wtCanonical}: could not verify removal (${wtProbe.err || "worktree list failed"})`);
8680
+ else if (parseWorktreeList(wtProbe.out).some((r) => canonicalHomePath(r.worktree) === wtCanonical)) failures.push(`git worktree ${wtCanonical}: still registered`);
8681
+ } else if (retention?.worktree === "absent" && removalUnverified !== undefined) {
8682
+ failures.push(`git worktree ${realPathOrNearest(workPath)}: could not verify removal (${removalUnverified})`);
7953
8683
  }
7954
8684
  // The branch is a debt only when the failed spawn's rollback still owes its deletion. A retry never
7955
8685
  // deletes it: the debt is cleared only when the branch is shown to be gone. Git's quiet exit 1 is
@@ -7957,8 +8687,38 @@ export function retireInstance(root, name, o = {}) {
7957
8687
  // "could not verify", and the debt stays. The text is never matched: this read can only err
7958
8688
  // toward keeping the debt.
7959
8689
  const owesBranch = (quarantine.cleanup.outstanding?.git || []).includes("branch");
8690
+ // The one exception (#796): a spawn killed while its worktree hooks ran never reached its own
8691
+ // compensation. Its marker carries `inProgress` (its process verified dead above) with the branch
8692
+ // and the commit the spawn created it at. Once the retire hooks ran and the worktree's removal is
8693
+ // verified, the retry finishes that compensation: an atomic compare-and-delete at that commit,
8694
+ // refused when the tip moved, the branch is checked out anywhere, or the ref cannot be read. A
8695
+ // branch still at its creation commit holds no work. Every other quarantine keeps the rule above.
8696
+ const ip = quarantine.inProgress;
8697
+ if (owesBranch && meta.branch && ip && ip.branch === meta.branch && inProgressUnverified) branchKeptReason = "the spawn's process or its hook group could not be verified gone (retired with --force)";
8698
+ else if (owesBranch && meta.branch && ip && ip.branch === meta.branch && /^[0-9a-f]{40,64}$/.test(String(ip.baseOid ?? "")) && retention?.worktree === "removed" && !failures.length) {
8699
+ const ref = `refs/heads/${meta.branch}`;
8700
+ // Retire's Git, bounded and helper-free (retireGit, #809): two reads, then the one write.
8701
+ const tip = retireGitProbe(meta.repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", ref], { encoding: "utf8" });
8702
+ const list = retireGitProbe(meta.repo, ["worktree", "list", "--porcelain", "-z"], { encoding: "utf8" });
8703
+ const listOk = !list.error && list.status === 0;
8704
+ const checkedOut = listOk && list.stdout.split("\0").includes(`branch ${ref}`);
8705
+ if (tip.error || tip.status !== 0 || tip.stderr.length) branchKeptReason = "the branch could not be read";
8706
+ else if (tip.stdout.trim() !== ip.baseOid) branchKeptReason = `its tip moved from ${ip.baseOid.slice(0, 12)}, where the spawn created it`;
8707
+ else if (!listOk) branchKeptReason = "whether it is checked out could not be read";
8708
+ else if (checkedOut) branchKeptReason = "it is checked out in a worktree";
8709
+ else {
8710
+ const del = retireGitProbe(meta.repo, ["update-ref", "-d", ref, ip.baseOid], { encoding: "utf8" });
8711
+ if (del.error || del.status !== 0) branchKeptReason = `git refused to delete it (${String(del.stderr || del.error?.message || "").trim().split("\n")[0] || "update-ref failed"})`;
8712
+ else branchDeletedByRetry = true;
8713
+ }
8714
+ }
7960
8715
  if (owesBranch && meta.branch) {
7961
- const br = spawnSync("git", ["-C", meta.repo, "rev-parse", "--verify", "--quiet", `refs/heads/${meta.branch}`], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
8716
+ let br;
8717
+ if (gitDir.error) br = { error: new Error(gitDir.error) };
8718
+ else {
8719
+ try { gitRepoRun(gitDir.dir, ["rev-parse", "--verify", "--quiet", `refs/heads/${meta.branch}`]); br = { status: 0, stderr: "" }; }
8720
+ catch (e2) { br = { error: e2.status === undefined || e2.status === null ? e2 : undefined, status: e2.status, stderr: String(e2.stderr ?? "") }; }
8721
+ }
7962
8722
  if (!br.error && br.status === 0) failures.push(FAILED_SPAWN_BRANCH_LEFT);
7963
8723
  else if (br.error || br.status !== 1 || br.stderr.length) failures.push(`git branch ${meta.branch}: could not verify whether it still exists (${String(br.stderr ?? "").trim() || br.error?.message || `rev-parse exit ${br.status}`})`);
7964
8724
  }
@@ -7975,6 +8735,33 @@ export function retireInstance(root, name, o = {}) {
7975
8735
  } catch { /* the quarantine stands regardless */ }
7976
8736
  }
7977
8737
  }
8738
+ // An attached child whose `work` links to this home's work/ would dangle once
8739
+ // the worktree is re-homed (#718): each one this retire stopped is repointed
8740
+ // to the retained worktree, whether or not the home is then removed (the work
8741
+ // has left it either way). It is a write to another instance, so it comes
8742
+ // last, once the move is done and seen done: the worktree is at its new path
8743
+ // and nothing is left at work/. One that fails is a warning; the retire is
8744
+ // not undone. The child's AGENTS.md still names the old path.
8745
+ const relinkWarnings = [];
8746
+ if (retention?.worktree === "retained") {
8747
+ const present = (p) => { try { lstatSync(p); return true; } catch { return false; } };
8748
+ const moved = attachedKids.length > 0 && (() => { try { return lstatSync(retention.movedTo).isDirectory(); } catch { return false; } })() && !present(workPath);
8749
+ for (const kid of attachedKids) {
8750
+ // The attachment as it was found, still: attached, and the same link. One that changed is
8751
+ // someone else's now, and is left as it is.
8752
+ const still = (() => { try { return readJsonOrUndefined(join(kid.home, "instance.json"))?.work === "attached" && readlinkSync(join(kid.home, "work")) === kid.link; } catch { return false; } })();
8753
+ if (!still) {
8754
+ relinkWarnings.push(`${kid.instance}: its attachment changed during the retire, so its work was left as it is now and not repointed to the retained worktree ${retention.movedTo}; inspect ${join(kid.home, "work")}`);
8755
+ continue;
8756
+ }
8757
+ try {
8758
+ if (!moved) throw new Error(`the worktree was not seen at ${retention.movedTo} with nothing left at ${workPath}`);
8759
+ relinkAttachedWork(kid.home, retention.movedTo);
8760
+ } catch (e) {
8761
+ relinkWarnings.push(`${kid.instance}: its work link could not be repointed to the retained worktree ${retention.movedTo} (${e.message}) and still points at ${kid.link}; repoint it by hand: ln -sfn ${shq(retention.movedTo)} ${shq(join(kid.home, "work"))}`);
8762
+ }
8763
+ }
8764
+ }
7978
8765
  // Forcing is the operator overriding the fail-closed default with their eyes
7979
8766
  // open: the home goes, and what remains outstanding is reported rather than
7980
8767
  // swallowed. Without this, a quarantine whose cleanup can never succeed (a
@@ -7993,8 +8780,8 @@ export function retireInstance(root, name, o = {}) {
7993
8780
  rmSync(deferredRetireResultPath(found.home).replace(/\.json$/, ".log"), { force: true });
7994
8781
  }
7995
8782
 
7996
- const result = { retired: name, agent: found.agent.name, workRecovery, retention, extraWorktrees, worktreeRemoved: isWorktree && !!retention && retention.worktree !== "retained", branchDeleted: false, removedDir: !o.keepDir && (!stillIncomplete || forced), rollbackIncomplete: forced ? undefined : stillIncomplete, forcedIncomplete: forced ? stillIncomplete : undefined, retainedHome: stillIncomplete && !forced ? found.home : undefined, relinked: relinked.length ? relinked : undefined, childrenStopped, capabilityMeta: hookResults?.meta, warnings: (() => {
7997
- const w = [...(hookResults?.warnings || [])];
8783
+ const result = { retired: name, agent: found.agent.name, workRecovery, retention, extraWorktrees, worktreeRemoved: isWorktree && !!retention && retention.worktree !== "retained", branchDeleted: false, ...(branchDeletedByRetry || branchKeptReason ? { spawnCompensation: { branch: meta.branch, branchDeleted: branchDeletedByRetry, ...(branchKeptReason ? { reason: branchKeptReason } : {}) } } : {}), removedDir: !o.keepDir && (!stillIncomplete || forced), rollbackIncomplete: forced ? undefined : stillIncomplete, forcedIncomplete: forced ? stillIncomplete : undefined, retainedHome: stillIncomplete && !forced ? found.home : undefined, relinked: relinked.length ? relinked : undefined, childrenStopped, capabilityMeta: hookResults?.meta, warnings: (() => {
8784
+ const w = [...spawnGroupWarnings, ...(hookResults?.warnings || []), ...relinkWarnings];
7998
8785
  if (o[OBSOLETE_DELETE_BRANCH]) w.push(OBSOLETE_DELETE_BRANCH_SENTENCE);
7999
8786
  if (isCapturedHome(meta) && !quarantine) {
8000
8787
  // A captured home retires through the workspace path; its captured retire hooks do not
@@ -8005,6 +8792,7 @@ export function retireInstance(root, name, o = {}) {
8005
8792
  } else if (!Array.isArray(meta?.capabilityRuntime) && !quarantine) w.push("this home records no capability hooks (an earlier kernel spawned it): no retire hook ran; any external state its capabilities created is the operator's to clean up");
8006
8793
  return w.length ? w : undefined;
8007
8794
  })() };
8795
+ result[RETIRE_SELECTED_HOME] = found.home;
8008
8796
  if (self) {
8009
8797
  // The caller is the instance: its process lives in the window we are about to
8010
8798
  // kill. Detach the kill so this function can return and the caller can report