@awebai/oats 0.56.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/core.mjs CHANGED
@@ -1876,21 +1876,76 @@ export function resolveRepo(root, repo) {
1876
1876
  return abs;
1877
1877
  }
1878
1878
 
1879
- /** The repository an attached work tree's OWNER recorded: `<owner home>/work` is the
1880
- * tree (the owner's own worktree or checkout). Undefined when the tree is not an
1881
- * instance's work/ (an integration worktree names its repository explicitly). */
1882
- function attachedOwnerRepo(workDir) {
1883
- if (typeof workDir !== "string" || !workDir) return undefined;
1884
- let tree;
1885
- try { tree = realpathSync(workDir); } catch { return undefined; }
1886
- for (const home of new Set([dirname(resolve(workDir)), dirname(tree)])) {
1879
+ /** Whose tree an attached spawn's work directory is, and of which repository: the one read both
1880
+ * questions are answered from (awebai/oats#958). An attached instance's repository is the
1881
+ * repository of the tree it is attached to, and the tree's owner is the instance in whose home it
1882
+ * is: the home's `work`, whose repository is the one that instance recorded, or one of the home's
1883
+ * extra trees, whose repository is the one extraWorktreesOf reads from Git (the test of an extra
1884
+ * tree is that function's, never the shape of the path).
1885
+ * → { owner: { name, home } | undefined, repo: string | undefined }. `owner` is the first home
1886
+ * under `root` that holds the tree: every agent dir is scanned, souls and capability-defined
1887
+ * agents alike, and the match is by path, never by name (instance names are only unique per
1888
+ * agent dir). Whether that name resolves back to that home is the caller's check. A tree in no
1889
+ * such home has no owner here; a `work` whose home is not one of them still gives the repository
1890
+ * that home recorded, as it always did. Read-only. */
1891
+ function attachedTreeOf(root, workDir) {
1892
+ const found = { owner: undefined, repo: undefined };
1893
+ if (typeof workDir !== "string" || !workDir) return found;
1894
+ const wd = resolve(workDir);
1895
+ let wdReal;
1896
+ try { wdReal = realpathSync(wd); } catch { return found; }
1897
+ // A home's work/: the repository its instance recorded. The home is the directory the path is in,
1898
+ // as given or as resolved.
1899
+ for (const home of new Set([dirname(wd), dirname(wdReal)])) {
1887
1900
  try {
1888
- if (realpathSync(join(home, "work")) !== tree) continue;
1901
+ if (realpathSync(join(home, "work")) !== wdReal) continue;
1889
1902
  const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
1890
- if (typeof meta?.repo === "string" && meta.repo) return meta.repo;
1903
+ if (typeof meta?.repo === "string" && meta.repo) { found.repo = meta.repo; break; }
1891
1904
  } catch { /* not an instance home */ }
1892
1905
  }
1893
- return undefined;
1906
+ // Lexical form of workDir with the HOME part canonicalized — checkout-mode
1907
+ // instances have work as a symlink to the shared repo, so realpath alone
1908
+ // would collide across every checkout instance; symlinked work trees only
1909
+ // match when workDir IS that home's work path.
1910
+ let wdLexical; try { wdLexical = join(realpathSync(dirname(wd)), basename(wd)); } catch { wdLexical = wd; }
1911
+ // An extra tree is compared as extraWorktreesOf compares paths, and looked for only in the home
1912
+ // the path is directly in: that function runs Git per `.work-*` entry of a home.
1913
+ const wdCanonical = canonicalHomePath(wd), treeHome = dirname(wdCanonical);
1914
+ let agentsRoot; try { agentsRoot = realpathSync(root); } catch { agentsRoot = root; }
1915
+ const hits = [];
1916
+ const candidate = (instHome, instName) => {
1917
+ let homeReal; try { homeReal = realpathSync(instHome); } catch { return; }
1918
+ try {
1919
+ if (join(homeReal, "work") === wdLexical) { hits.push({ home: instHome, name: instName }); return; }
1920
+ const wp = join(instHome, "work");
1921
+ if (!lstatSync(wp).isSymbolicLink() && realpathSync(wp) === wdReal) { hits.push({ home: instHome, name: instName }); return; }
1922
+ } catch { /* no work tree */ }
1923
+ if (hits.length || canonicalHomePath(instHome) !== treeHome) return;
1924
+ const tree = extraWorktreesOf(instHome).find((t) => canonicalHomePath(t.path) === wdCanonical);
1925
+ if (tree) hits.push({ home: instHome, name: instName, extraTreeRepo: tree.repo });
1926
+ };
1927
+ if (existsSync(agentsRoot)) {
1928
+ for (const ag of readdirSync(agentsRoot, { withFileTypes: true })) {
1929
+ if (!ag.isDirectory() || ag.name.startsWith(".")) continue;
1930
+ const dir = join(agentsRoot, ag.name, "instances");
1931
+ if (!existsSync(dir)) continue;
1932
+ for (const e of readdirSync(dir, { withFileTypes: true })) if (e.isDirectory()) candidate(join(dir, e.name), e.name);
1933
+ }
1934
+ }
1935
+ if (hits.length) {
1936
+ found.owner = { name: hits[0].name, home: hits[0].home };
1937
+ if (hits[0].extraTreeRepo !== undefined) found.repo = hits[0].extraTreeRepo;
1938
+ }
1939
+ return found;
1940
+ }
1941
+ /** The refusal of an attached spawn on a tree of no known instance: neither a home's `work` nor one
1942
+ * of its extra trees, so nothing is derived. One sentence names every flag still missing
1943
+ * (`parent`, `repo`), so one retry is enough. */
1944
+ function attachedTreeOfNoInstance(wd, { parent, repo }) {
1945
+ const what = `attached workDir ${wd} is not a known instance's <home>/work or an extra tree of a known instance's home (<home>/.work-<purpose>)`;
1946
+ if (parent && repo) return `${what}, so neither its owner nor its repository is derived — pass both: --parent <instance> (the owning instance) and --repo <repository>`;
1947
+ return parent ? `${what}, so its owner is not derived — name the owning instance explicitly (--parent <instance>)`
1948
+ : `${what}, so its repository is not derived — pass --repo <repository>`;
1894
1949
  }
1895
1950
  /** Only explicit directory execution relaxes the Git requirement. `repo` is
1896
1951
  * still the config/deployment context, never a directory we take ownership of. */
@@ -3677,11 +3732,20 @@ function* spawnBody(root, agent, o = {}) {
3677
3732
  const preparedDeployment = work === "workspace" && typeof o.prepared.deployment === "string" && o.prepared.deployment ? resolve(o.prepared.deployment) : undefined;
3678
3733
  if (preparedDeployment !== undefined && !(existsSync(preparedDeployment) && statSync(preparedDeployment).isDirectory())) throw oatsError("E_BAD_ARGS", `workspace mode: the deployment directory ${preparedDeployment} (where oats-local.yaml lives) is not a directory`);
3679
3734
  // A soul declares no repository (lead decision c3 Q6): the caller passes one, and an
3680
- // attached instance works in its owner's repository — the one the work tree's
3681
- // owning instance recorded.
3682
- const repoTarget = o.repo !== undefined ? o.repo : work === "attached" ? attachedOwnerRepo(o.workDir) : undefined;
3735
+ // attached instance's repository is the repository of the tree it is attached to
3736
+ // (attachedTreeOf, read once here: its owner is taken from the same read, below).
3737
+ const attachedTree = work === "attached" ? attachedTreeOf(root, o.workDir) : undefined;
3738
+ const repoTarget = o.repo !== undefined ? o.repo : attachedTree?.repo;
3683
3739
  const repoAbs = preparedDeployment ?? resolveExecutionContext(root, repoTarget, work);
3684
- if (!repoAbs) throw oatsError("E_BAD_ARGS", `${agent.name}: no repository for a ${work} instance — pass --repo${work === "attached" ? " (the work tree's owner records none)" : ""}`);
3740
+ if (!repoAbs) {
3741
+ // A tree of no known instance: the owner is not derived either, so a caller that named none
3742
+ // is told both at once (awebai/oats#958).
3743
+ if (work === "attached" && !attachedTree.owner) {
3744
+ const childOf = (typeof o.parent === "string" && o.parent.trim()) || (typeof o.relation === "string" && o.relation.trim() === "child" && typeof o.relativeTo === "string" && o.relativeTo.trim());
3745
+ throw oatsError("E_BAD_ARGS", attachedTreeOfNoInstance(typeof o.workDir === "string" ? resolve(o.workDir) : o.workDir, { parent: !childOf, repo: true }));
3746
+ }
3747
+ throw oatsError("E_BAD_ARGS", `${agent.name}: no repository for a ${work} instance — pass --repo${work === "attached" ? " (the work tree's owner records none)" : ""}`);
3748
+ }
3685
3749
  // Launch selection: a named configuration (explicit, or the soul's
3686
3750
  // launch-config default), or none; the harness and model follow from it.
3687
3751
  // K6b: a preview's native probes (model catalogue, harness packages) share
@@ -3799,56 +3863,28 @@ function* spawnBody(root, agent, o = {}) {
3799
3863
  if (relation === "unrelated") { relation = undefined; relativeTo = undefined; }
3800
3864
 
3801
3865
  // Attached = child of the work-tree owner, always (design decision). The
3802
- // owner is CANONICALLY resolved BY PATH: every instance home in the
3803
- // deployment (local root + team scope) is enumerated and matched on
3804
- // realpath(<home>/work) === realpath(workDir) — never by name, since
3866
+ // owner is CANONICALLY resolved BY PATH (attachedTreeOf, read above with the
3867
+ // repository): the instance in whose home the tree is, as that home's work
3868
+ // or as one of its extra trees — never by name, since
3805
3869
  // instance names are only unique per agent dir and a same-named local
3806
- // instance must not shadow the tree's true owner. For trees that are no
3807
- // instance's home/work (e.g. a coordinator's integration worktree), the
3870
+ // instance must not shadow the tree's true owner. For trees that are in no
3871
+ // instance's home (e.g. a coordinator's integration worktree), the
3808
3872
  // spawner must name the owner explicitly with a child relation — nothing
3809
3873
  // else can attach there.
3810
3874
  let attachedOwner;
3811
3875
  if (work === "attached" && o.workDir) {
3812
3876
  const wd = resolve(o.workDir);
3813
- let wdReal; try { wdReal = realpathSync(wd); } catch { wdReal = undefined; }
3814
3877
  let ownerName;
3815
- if (wdReal) {
3816
- // Every agent dir under the root: souls and capability-defined agents alike.
3817
- const scanInstances = (agentsRoot, cb) => {
3818
- if (!existsSync(agentsRoot)) return;
3819
- for (const ag of readdirSync(agentsRoot, { withFileTypes: true })) {
3820
- if (!ag.isDirectory() || ag.name.startsWith(".")) continue;
3821
- const dir = join(agentsRoot, ag.name, "instances");
3822
- if (!existsSync(dir)) continue;
3823
- for (const e of readdirSync(dir, { withFileTypes: true })) if (e.isDirectory()) cb(join(dir, e.name), e.name);
3824
- }
3825
- };
3826
- const ownerRoots = new Set();
3827
- try { ownerRoots.add(realpathSync(root)); } catch { ownerRoots.add(root); }
3828
- const hits = [];
3829
- // Lexical form of workDir with the HOME part canonicalized — checkout-mode
3830
- // instances have work as a symlink to the shared repo, so realpath alone
3831
- // would collide across every checkout instance; symlinked work trees only
3832
- // match when workDir IS that home's work path.
3833
- let wdLexical; try { wdLexical = join(realpathSync(dirname(wd)), basename(wd)); } catch { wdLexical = wd; }
3834
- for (const r2 of ownerRoots) scanInstances(r2, (instHome, instName) => {
3835
- const wp = join(instHome, "work");
3836
- try {
3837
- let homeReal; try { homeReal = realpathSync(instHome); } catch { return; }
3838
- if (join(homeReal, "work") === wdLexical) { hits.push({ home: instHome, name: instName }); return; }
3839
- if (!lstatSync(wp).isSymbolicLink() && realpathSync(wp) === wdReal) hits.push({ home: instHome, name: instName });
3840
- } catch { /* no work tree */ }
3841
- });
3842
- if (hits.length) {
3843
- ownerName = hits[0].name;
3844
- // The owner must be representable unambiguously from the CHILD's root:
3845
- // the recorded name, resolved like every other lineage edge, must land
3846
- // back on the matched home.
3847
- const check = findInstanceHome(root, ownerName);
3848
- let resolvesBack = false;
3849
- try { resolvesBack = !!check && realpathSync(check.home) === realpathSync(hits[0].home); } catch { /* not resolvable */ }
3850
- if (!resolvesBack) throw new Error(`attached workDir ${wd} belongs to instance "${ownerName}" (${hits[0].home}), but that name resolves to a different instance from this deployment root — the parent link would be ambiguous; retire/rename the shadowing instance or attach to a tree owned here`);
3851
- }
3878
+ const owner = attachedTree.owner;
3879
+ if (owner) {
3880
+ ownerName = owner.name;
3881
+ // The owner must be representable unambiguously from the CHILD's root:
3882
+ // the recorded name, resolved like every other lineage edge, must land
3883
+ // back on the matched home.
3884
+ const check = findInstanceHome(root, ownerName);
3885
+ let resolvesBack = false;
3886
+ try { resolvesBack = !!check && realpathSync(check.home) === realpathSync(owner.home); } catch { /* not resolvable */ }
3887
+ if (!resolvesBack) throw new Error(`attached workDir ${wd} belongs to instance "${ownerName}" (${owner.home}), but that name resolves to a different instance from this deployment root — the parent link would be ambiguous; retire/rename the shadowing instance or attach to a tree owned here`);
3852
3888
  }
3853
3889
  if (ownerName) {
3854
3890
  attachedOwner = ownerName;
@@ -3856,9 +3892,9 @@ function* spawnBody(root, agent, o = {}) {
3856
3892
  throw new Error(`attached agents are always children of the work-tree owner (${attachedOwner}) — drop the relation flags or use --work worktree for a different relation`);
3857
3893
  }
3858
3894
  } else {
3859
- // Path matches NO known instance's work tree: require an explicit,
3895
+ // The tree is in NO known instance's home: require an explicit,
3860
3896
  // validated child link so the "attached = child" invariant still holds.
3861
- if (!relation) throw new Error(`attached workDir ${wd} is not a known instance's <home>/work — name the owning instance explicitly (--parent <instance>)`);
3897
+ if (!relation) throw oatsError("E_BAD_ARGS", attachedTreeOfNoInstance(wd, { parent: true, repo: false }));
3862
3898
  if (relation !== "child") throw new Error(`attached agents are always children — only --parent <instance> (child) is valid for a non-instance work tree`);
3863
3899
  attachedOwner = relativeTo;
3864
3900
  }
@@ -5753,7 +5789,7 @@ const GIT_MAX_BUFFER = 512 * 1024 * 1024;
5753
5789
  * its .gitattributes select can still run during `git status`; turning it
5754
5790
  * off would change what status reports. */
5755
5791
  const RETIRE_GIT_FLAGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "diff.external="];
5756
- 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"]);
5792
+ const RETIRE_GIT_DROPPED_ENV = new Set(["GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_DEFAULT_REF_FORMAT", "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"]);
5757
5793
  function retireGitEnv(env) {
5758
5794
  const out = {};
5759
5795
  for (const [key, value] of Object.entries(process.env)) {
@@ -7700,6 +7736,18 @@ function inspectedEntryExists(path) {
7700
7736
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path}: ${e.message}`);
7701
7737
  }
7702
7738
  }
7739
+ /** inspectedEntryExists with a link not followed: a link is there as itself,
7740
+ * also one that leads nowhere. What the copier asks of an entry it copies
7741
+ * with copyTreeSafe, which copies a link as a link, and what the comparison
7742
+ * asks of the same entry (copiedGitPathDigest), so both read one thing
7743
+ * (awebai/oats#1038). Absence is ENOENT alone, as there. */
7744
+ function inspectedEntryPresent(path) {
7745
+ try { lstatSync(path); return true; }
7746
+ catch (e) {
7747
+ if (e.code === "ENOENT") return false;
7748
+ throw oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path}: ${e.message}`);
7749
+ }
7750
+ }
7703
7751
  /** How the recovery copier resolves what it reads from a repository, read by
7704
7752
  * the copier and by the comparison alike (repositoryGitState), so that the
7705
7753
  * comparison holds the files the copy carries, found where the copy finds
@@ -7827,6 +7875,8 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
7827
7875
  const copierGit = asCopier(copierGitDir), copierCommon = asCopier(copierCommonDir);
7828
7876
  const excludesFile = valueOf("config", "--path", "--get", "core.excludesFile");
7829
7877
  const excludesRead = asCopier(copierExcludesFile);
7878
+ const copied = COPIED_GIT_PATHS.map((entry) => copiedGitPathDigest(entry, copiedGitPath(entry, copierGit, copierCommon)));
7879
+ const stash = valueOf("rev-parse", "--verify", "--quiet", "refs/stash");
7830
7880
  return {
7831
7881
  paths: printed,
7832
7882
  status: (status ?? worktreeStatusBytes(repo)).toString("latin1"),
@@ -7837,9 +7887,14 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
7837
7887
  index: inspectGit(repo, ["ls-files", "-s", "-v", "-z"], { env: { GIT_INDEX_FILE: join(copierGit, "index") } }),
7838
7888
  resolveUndo: inspectGit(repo, ["ls-files", "--resolve-undo", "-z"], { env: { GIT_INDEX_FILE: join(copierGit, "index") } }),
7839
7889
  indexMode: modeOf(join(copierGit, "index")),
7840
- copied: COPIED_GIT_PATHS.map((entry) => copiedGitPathDigest(entry, copiedGitPath(entry, copierGit, copierCommon))),
7890
+ copied,
7891
+ // What the copy carries through Git rather than as files (awebai/oats#1038), read as the
7892
+ // copier reads it: the operation's refs it writes, and the stash's entries where its log
7893
+ // is not a file (stashEntries).
7894
+ operationRefs: asCopier(() => operationRefsWritten(repo, copierGit)),
7895
+ stashEntries: stash !== null && copied[COPIED_GIT_PATHS.indexOf(GIT_STASH_LOG)] === null ? asCopier(() => stashEntries(repo).map((e) => e.line)) : null,
7841
7896
  tags: inspectGit(repo, ["for-each-ref", "--format=%(objectname) %(refname)", "refs/tags"]),
7842
- stash: valueOf("rev-parse", "--verify", "--quiet", "refs/stash"),
7897
+ stash,
7843
7898
  excludesFile: excludesFile === null && excludesRead === null ? null : [excludesFile, excludesRead, excludesRead && bytesOf(excludesRead)],
7844
7899
  exclude: bytesOf(join(copierCommon, "info", "exclude")),
7845
7900
  statusConfig: STATUS_CONFIG.map((key) => valueOf("config", "--get", key)),
@@ -8235,10 +8290,12 @@ const copiedGitPath = ({ dir, path }, gitDir, commonDir) => join(dir === "git" ?
8235
8290
  * path is not there. copyTreeSafe gives a copy the entry's kind, bytes or
8236
8291
  * target, and the bits of the entry and of everything under it: its exact
8237
8292
  * digest. copyRegularFile follows a link and gives the copy the bytes and the
8238
- * mode of what it reaches: those. Any failure but "not there" throws, as a
8293
+ * mode of what it reaches: those. So a "tree" path is looked at as the copier
8294
+ * looks at it, a link not followed (inspectedEntryPresent): a link that leads
8295
+ * nowhere is there, as a link. Any failure but "not there" throws, as a
8239
8296
  * read of the Git state does, and so does a file path that is not a file. */
8240
8297
  function copiedGitPathDigest(entry, at) {
8241
- if (!inspectedEntryExists(at)) return null;
8298
+ if (!(entry.copy === "tree" ? inspectedEntryPresent(at) : inspectedEntryExists(at))) return null;
8242
8299
  try {
8243
8300
  if (entry.copy === "tree") return exactTreeDigest(at);
8244
8301
  const st = statSync(at);
@@ -8306,14 +8363,17 @@ function indexBlobs(rows) {
8306
8363
  * the copy lacks; the missing commits are fetched from `source` by id (one
8307
8364
  * fetch, with everything they reach), the missing blobs, which can be in no
8308
8365
  * commit (staged content, a resolved conflict's sides), are copied by
8309
- * content (`cat-file blob` → `hash-object -w`); then the whole set is
8366
+ * content (`cat-file blob` → `hash-object -w`), and so are the missing trees
8367
+ * (`cat-file tree` → `hash-object -t tree -w`: the tree AUTO_MERGE names
8368
+ * and the trees under it that hold a conflict's files, which no commit
8369
+ * reaches, awebai/oats#1038); then the whole set is
8310
8370
  * checked again. A fetch or a read that fails is not the failure itself:
8311
8371
  * whatever is still missing after the repair is, named by its id, and the
8312
8372
  * copy is refused (E_WORK_PRESERVATION_FAILED). That covers an object the
8313
8373
  * source itself lacks, which GIT_NO_LAZY_FETCH keeps the copier from
8314
8374
  * fetching from a promisor remote. */
8315
- function carryNamedObjects(source, recovered, { commits = [], blobs = [] }) {
8316
- const named = [...new Set([...commits, ...blobs])];
8375
+ function carryNamedObjects(source, recovered, { commits = [], blobs = [], trees = [] }) {
8376
+ const named = [...new Set([...commits, ...blobs, ...trees])];
8317
8377
  if (!named.length) return;
8318
8378
  const missing = new Set(missingGitObjects(recovered, named));
8319
8379
  const fetch = [...new Set(commits)].filter((oid) => missing.has(oid));
@@ -8321,13 +8381,15 @@ function carryNamedObjects(source, recovered, { commits = [], blobs = [] }) {
8321
8381
  try { copierFetch(recovered, source, ["--stdin"], { input: fetch.join("\n") + "\n" }); }
8322
8382
  catch { /* the re-measure names what the fetch did not bring */ }
8323
8383
  }
8324
- for (const oid of new Set(blobs)) {
8325
- if (!missing.has(oid)) continue;
8326
- let blob;
8327
- try { blob = retireGit(source, ["cat-file", "blob", oid]); }
8328
- catch { continue; /* the re-measure names it */ }
8329
- const restored = retireGit(recovered, ["hash-object", "-w", "--stdin"], { input: blob, encoding: "utf8" }).trim();
8330
- if (restored !== oid) throw new Error(`recovered Git object ${restored} did not match source ${oid}`);
8384
+ for (const [type, oids] of [["blob", blobs], ["tree", trees]]) {
8385
+ for (const oid of new Set(oids)) {
8386
+ if (!missing.has(oid)) continue;
8387
+ let content;
8388
+ try { content = retireGit(source, ["cat-file", type, oid]); }
8389
+ catch { continue; /* the re-measure names it */ }
8390
+ const restored = retireGit(recovered, ["hash-object", "-t", type, "-w", "--stdin"], { input: content, encoding: "utf8" }).trim();
8391
+ if (restored !== oid) throw new Error(`recovered Git object ${restored} did not match source ${oid}`);
8392
+ }
8331
8393
  }
8332
8394
  const stillMissing = missingGitObjects(recovered, named);
8333
8395
  if (stillMissing.length) {
@@ -8405,13 +8467,169 @@ function restoreStandaloneGitState(sourceWork, recoveredRepo) {
8405
8467
  // that the copy reads to Git as the source does, every committed file a
8406
8468
  // staged deletion (awebai/oats#1048).
8407
8469
  if (!copyRegularFile(join(sourceGit, "index"), join(recoveredGit, "index"))) rmSync(join(recoveredGit, "index"), { force: true });
8470
+ // A link at one of these names is copied as a link, also one that leads
8471
+ // nowhere: the look does not follow it (inspectedEntryPresent), and
8472
+ // copyTreeSafe copies a link as a link (awebai/oats#1038).
8408
8473
  for (const entry of COPIED_GIT_PATHS.filter((e) => e.dir === "git")) {
8409
8474
  const source = copiedGitPath(entry, sourceGit);
8410
- if (!existsSync(source)) continue;
8475
+ if (!inspectedEntryPresent(source)) continue;
8411
8476
  const dest = copiedGitPath(entry, recoveredGit);
8412
8477
  rmSync(dest, { recursive: true, force: true });
8413
8478
  copyTreeSafe(source, dest);
8414
8479
  }
8480
+ carryOperationRefs(sourceWork, recoveredRepo, sourceGit);
8481
+ }
8482
+
8483
+ /** The refs an operation leaves in a worktree's own Git directory that the
8484
+ * copy above takes as files where they are files. In the reftable format they
8485
+ * are refs, not files (awebai/oats#1038). A fixed list: no name is ever read
8486
+ * from the source. */
8487
+ const CARRIED_OPERATION_REFS = Object.freeze(["CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD", "AUTO_MERGE"]);
8488
+ /** A full object id of `repo`'s object format, as a pattern. */
8489
+ function objectIdPattern(repo) {
8490
+ const format = retireGit(repo, ["rev-parse", "--show-object-format"], { encoding: "utf8" }).trim();
8491
+ if (format === "sha1") return /^[0-9a-f]{40}$/;
8492
+ if (format === "sha256") return /^[0-9a-f]{64}$/;
8493
+ throw new Error(`${repo} uses the object format ${JSON.stringify(format)}, which the recovery does not know`);
8494
+ }
8495
+ /** The object id the ref named exactly `name` holds in `repo`, or null when
8496
+ * there is no such ref. `show-ref --exists` takes the name as it is (a branch
8497
+ * or a tag of the same name, which `rev-parse` would find in its place, is not
8498
+ * that ref) and does not ask for the object; once the ref is there, `rev-parse`
8499
+ * reads it, the ref at the Git directory's top level coming first in its
8500
+ * order. Only Git's answer that the ref does not exist (exit 2) is "none";
8501
+ * any other failure throws. Asked only of a repository whose refs may be in
8502
+ * the reftable format, which needs a Git that has `--exists` (2.43). */
8503
+ function exactRefValue(repo, name) {
8504
+ try { retireGit(repo, ["show-ref", "--exists", name]); }
8505
+ catch (e) { if (e.status === 2) return null; throw e; }
8506
+ return retireGit(repo, ["rev-parse", "--verify", "--quiet", name], { encoding: "utf8" }).trim();
8507
+ }
8508
+ /** The trees and blobs under the tree `tree`, itself included, that
8509
+ * `recovered` lacks, read from `source`: one level at a time, and only below
8510
+ * a tree the copy lacks. A tree the clone holds came with what it reaches, so
8511
+ * AUTO_MERGE's tree, which is the whole worktree's, costs the trees on the
8512
+ * conflict's paths, not the whole tree's. Gitlinks name commits of other
8513
+ * repositories and are not followed. */
8514
+ function missingTreeObjects(source, recovered, tree) {
8515
+ const trees = [], blobs = [];
8516
+ for (let level = missingGitObjects(recovered, [tree]); level.length;) {
8517
+ trees.push(...level);
8518
+ const children = [];
8519
+ for (const t of level) {
8520
+ for (const row of retireGit(source, ["ls-tree", "-z", t]).toString("latin1").split("\0")) {
8521
+ const m = /^\d+ (blob|tree) ([0-9a-f]+)\t/.exec(row);
8522
+ if (m) children.push({ type: m[1], oid: m[2] });
8523
+ }
8524
+ }
8525
+ const missing = new Set(missingGitObjects(recovered, [...new Set(children.map((c) => c.oid))]));
8526
+ blobs.push(...new Set(children.filter((c) => c.type === "blob" && missing.has(c.oid)).map((c) => c.oid)));
8527
+ level = [...new Set(children.filter((c) => c.type === "tree" && missing.has(c.oid)).map((c) => c.oid))];
8528
+ }
8529
+ return { trees, blobs };
8530
+ }
8531
+ /** Clone into a recovery, `args` being what follows `git clone`, its last the
8532
+ * destination. A recovery's refs are files, whatever the operator's Git
8533
+ * configuration or environment makes a new repository: the copy takes an
8534
+ * operation's refs as files of the Git directory, which a repository whose
8535
+ * refs are in the reftable format does not read (awebai/oats#1038). So the
8536
+ * clone is told the files format (`init.defaultRefFormat`, which a Git older
8537
+ * than the reftable format ignores; GIT_DEFAULT_REF_FORMAT, which would come
8538
+ * first, is not passed to the retire's Git: retireGitEnv), and a clone whose
8539
+ * Git directory still holds `reftable` refuses the copy. */
8540
+ function cloneRecovery(args) {
8541
+ retireGit(null, ["-c", "init.defaultRefFormat=files", "clone", ...args]);
8542
+ if (gitEntryAt(join(args.at(-1), ".git", "reftable")) !== false) throw new Error(`the recovery clone ${args.at(-1)} does not store its refs as files`);
8543
+ }
8544
+ /** The refs of an operation whose objects the recovery carries, whichever way
8545
+ * the ref came: written by carryOperationRefs, or copied as a file of the Git
8546
+ * directory. MERGE_HEAD is a file in every format, and is never written. */
8547
+ const OPERATION_OBJECT_REFS = Object.freeze([...CARRIED_OPERATION_REFS, "MERGE_HEAD"]);
8548
+ /** The object ids the operation ref `name` names in the recovery, read after
8549
+ * the copy from the file at its name: Git writes each of these refs, in the
8550
+ * files format, as one id per line (a merge of several commits names one per
8551
+ * line in MERGE_HEAD, of which a Git read gives the first only), and Git
8552
+ * would refuse to read a ref whose object is not yet there. A link at the
8553
+ * name is carried as itself (restoreStandaloneGitState), and what it leads
8554
+ * to is not read: it names nothing here. */
8555
+ function recoveredOperationObjects(recoveredRepo, name) {
8556
+ const at = join(recoveredRepo, ".git", name);
8557
+ let st;
8558
+ try { st = lstatSync(at); }
8559
+ catch (e) { if (e.code === "ENOENT") return []; throw e; }
8560
+ if (!st.isFile()) return [];
8561
+ return readFileSync(at, "latin1").split("\n").filter((line) => line !== "");
8562
+ }
8563
+ /** The type of each of `oids` in `repo` (`cat-file --batch-check`), "missing"
8564
+ * for one it does not hold. */
8565
+ function gitObjectTypes(repo, oids) {
8566
+ const types = new Map();
8567
+ if (!oids.length) return types;
8568
+ const out = retireGit(repo, ["cat-file", "--batch-check=%(objectname) %(objecttype)"], { input: oids.join("\n") + "\n", encoding: "utf8" });
8569
+ for (const line of out.split("\n")) {
8570
+ const space = line.indexOf(" ");
8571
+ if (space > 0) types.set(line.slice(0, space), line.slice(space + 1));
8572
+ }
8573
+ return types;
8574
+ }
8575
+ /** The operation's refs that the copy writes through Git, as { name, oid }:
8576
+ * each of CARRIED_OPERATION_REFS that the source's Git holds by its exact
8577
+ * name and that has nothing at its name in the worktree's own Git directory
8578
+ * `gitDir`, which the copy of the Git directory's files therefore does not
8579
+ * take. Asked only where the refs may be in the reftable format
8580
+ * (refsMayBeReftable); in the files format each is a file. The one read for
8581
+ * the copier (carryOperationRefs) and for the comparison (repositoryGitState),
8582
+ * so that what the copy writes is what is compared. */
8583
+ function operationRefsWritten(work, gitDir) {
8584
+ if (!refsMayBeReftable(gitDir)) return [];
8585
+ const refs = [];
8586
+ for (const name of CARRIED_OPERATION_REFS) {
8587
+ if (inspectedEntryPresent(join(gitDir, name))) continue;
8588
+ const oid = exactRefValue(work, name);
8589
+ if (oid !== null) refs.push({ name, oid });
8590
+ }
8591
+ return refs;
8592
+ }
8593
+ /** Give the recovery the operation's refs and the objects they name
8594
+ * (awebai/oats#1038):
8595
+ * - each of CARRIED_OPERATION_REFS that the source's Git holds and that has
8596
+ * nothing at its name in the source's own Git directory, which the copy of
8597
+ * the Git directory's files therefore did not take, is written with `git
8598
+ * update-ref` at the same object id. Git is asked only where the refs may
8599
+ * be in the reftable format (refsMayBeReftable): in the files format each
8600
+ * of these refs is a file, and the copy took it;
8601
+ * - every object an operation ref of the recovery names (OPERATION_OBJECT_REFS,
8602
+ * written or copied) is carried before any ref is written, with
8603
+ * carryNamedObjects: a commit by id, a tree with what under it the copy
8604
+ * lacks (AUTO_MERGE's), a blob by content. Such an object is often in no
8605
+ * branch (a commit reset away, a conflict's tree), and a clone does not
8606
+ * bring it. One the source itself lacks is not carried: the recovery's ref
8607
+ * names nothing there either. Git refuses to write a ref whose object is
8608
+ * not there, so a reftable ref the source holds without its object refuses
8609
+ * the copy.
8610
+ * Every id is checked as a full object id of the repository's object format
8611
+ * before use: a written ref's that is not one refuses the copy; a line of a
8612
+ * copied file that is not one names nothing, as for Git, carries no object
8613
+ * and is not used. A Git step that fails throws, as a failed copy does. */
8614
+ function carryOperationRefs(sourceWork, recoveredRepo, sourceGit) {
8615
+ const written = operationRefsWritten(sourceWork, sourceGit);
8616
+ const copied = [];
8617
+ for (const name of OPERATION_OBJECT_REFS) if (!written.some((r) => r.name === name)) copied.push(...recoveredOperationObjects(recoveredRepo, name));
8618
+ if (!written.length && !copied.length) return;
8619
+ const full = objectIdPattern(sourceWork);
8620
+ for (const { name, oid } of written) if (!full.test(oid)) throw new Error(`${name} of ${sourceWork} holds ${JSON.stringify(oid)}, which is not a full object id of the repository's object format`);
8621
+ // A line of a copied file that is no full object id names no object: the copy holds the same
8622
+ // file, which Git reads as naming nothing there either, and the line reaches no Git command.
8623
+ const named = [...written.map((r) => r.oid), ...copied.filter((oid) => full.test(oid))];
8624
+ if (!named.length) return;
8625
+ const commits = [], trees = [], blobs = [];
8626
+ for (const [oid, type] of gitObjectTypes(sourceWork, [...new Set(named)])) {
8627
+ if (type === "tree") { const under = missingTreeObjects(sourceWork, recoveredRepo, oid); trees.push(...under.trees); blobs.push(...under.blobs); }
8628
+ else if (type === "blob") blobs.push(oid);
8629
+ else if (type !== "missing") commits.push(oid);
8630
+ }
8631
+ carryNamedObjects(sourceWork, recoveredRepo, { commits, trees, blobs });
8632
+ for (const { name, oid } of written) retireGit(recoveredRepo, ["update-ref", name, oid]);
8415
8633
  }
8416
8634
 
8417
8635
  /** Give a recovery clone the source's effective exclude rules, so the status comparison sees the same
@@ -8467,10 +8685,14 @@ function carryStatusConfig(sourceWork, recoveredRepo) {
8467
8685
  /** Make a recovery clone stand on its own: give it the source's stash (the
8468
8686
  * ref, its log, and every commit the copied log names: awebai/oats#654),
8469
8687
  * prove it holds those and `commits` (what the caller's carried metadata
8470
- * names) with carryNamedObjects, then remove the remote it was cloned from. */
8688
+ * names) with carryNamedObjects, then remove the remote it was cloned from.
8689
+ * The log is copied as a file where it is one. In the reftable format it is
8690
+ * not (awebai/oats#1038): its entries are read through Git (stashEntries) and
8691
+ * written back with `git stash store`, so that `git stash list` reads the
8692
+ * same in the copy. */
8471
8693
  function detachRecoveryClone(source, recovered, commits = []) {
8472
8694
  const named = [...commits];
8473
- let stash;
8695
+ let stash, entries = [];
8474
8696
  try { stash = retireGit(source, ["rev-parse", "--verify", "--quiet", "refs/stash"], { encoding: "utf8" }).trim(); }
8475
8697
  catch { stash = undefined; }
8476
8698
  if (stash) {
@@ -8480,10 +8702,56 @@ function detachRecoveryClone(source, recovered, commits = []) {
8480
8702
  const stashLog = copiedGitPath(GIT_STASH_LOG, null, sourceCommon);
8481
8703
  const recoveredLog = copiedGitPath(GIT_STASH_LOG, null, join(recovered, ".git"));
8482
8704
  if (copyRegularFile(stashLog, recoveredLog)) named.push(...reflogCommits(recoveredLog));
8705
+ else {
8706
+ entries = stashEntries(source);
8707
+ named.push(...entries.map((e) => e.oid));
8708
+ }
8483
8709
  }
8484
8710
  carryNamedObjects(source, recovered, { commits: named });
8711
+ if (entries.length) storeStashEntries(source, recovered, entries);
8485
8712
  try { retireGit(recovered, ["remote", "remove", "origin"]); } catch { /* no remote is already independent */ }
8486
8713
  }
8714
+ /** The stash's entries as Git reads them from its reflog, oldest first:
8715
+ * { oid, subject, line }, `subject` the entry's message (`%gs`), `line` its row
8716
+ * as read. Read only where the log is not a file (the reftable format). A
8717
+ * message that is not UTF-8 cannot be given back to Git as an argument: that
8718
+ * refuses the copy, as an object id that is not a full one does. */
8719
+ function stashEntries(source) {
8720
+ const full = objectIdPattern(source);
8721
+ const rows = retireGit(source, ["reflog", "show", "--format=%H %gs", "refs/stash", "--"]);
8722
+ const out = [];
8723
+ for (const bytes of splitLines(rows)) {
8724
+ const line = bytes.toString("utf8");
8725
+ if (!Buffer.from(line).equals(bytes)) throw new Error(`a stash entry of ${source} has a message that is not UTF-8, and Git cannot be given it back`);
8726
+ const space = line.indexOf(" ");
8727
+ const oid = space < 0 ? line : line.slice(0, space);
8728
+ if (!full.test(oid)) throw new Error(`a stash entry of ${source} names ${JSON.stringify(oid)}, which is not a full object id of the repository's object format`);
8729
+ out.push({ oid, subject: space < 0 ? "" : line.slice(space + 1), line });
8730
+ }
8731
+ return out.reverse();
8732
+ }
8733
+ /** Write `entries` (stashEntries) into the copy's stash, oldest first, over the
8734
+ * fetched ref and its empty log, then check that the copy's stash reads as the
8735
+ * source's, entry for entry. */
8736
+ function storeStashEntries(source, recovered, entries) {
8737
+ retireGit(recovered, ["update-ref", "-d", "refs/stash"]);
8738
+ for (const { oid, subject } of entries) retireGit(recovered, ["stash", "store", "-m", subject, oid]);
8739
+ const copied = splitLines(retireGit(recovered, ["reflog", "show", "--format=%H %gs", "refs/stash", "--"])).map((b) => b.toString("utf8")).reverse();
8740
+ if (copied.length !== entries.length || copied.some((line, i) => line !== entries[i].line)) {
8741
+ throw new Error(`the recovery's stash does not read as the stash of ${source}: ${entries.length} entries there, ${copied.length} written`);
8742
+ }
8743
+ }
8744
+ /** The lines of Git's output, each as bytes, without the line feed that ends it. */
8745
+ function splitLines(out) {
8746
+ const lines = [];
8747
+ for (let at = 0; at < out.length;) {
8748
+ let end = out.indexOf(10, at);
8749
+ if (end < 0) end = out.length;
8750
+ if (end > at) lines.push(out.subarray(at, end));
8751
+ at = end + 1;
8752
+ }
8753
+ return lines;
8754
+ }
8487
8755
 
8488
8756
  /** The commit at a repository's HEAD as the copier reads it, or null when
8489
8757
  * its HEAD has none: a branch nobody has committed on (`git init` and no
@@ -8578,7 +8846,7 @@ function materializeNestedRepositories(sourceWork, recoveredRepo) {
8578
8846
  // HEAD holds is not said: it is a file's content, and need not be text.
8579
8847
  if (head === null && name.branch === null) throw new Error(`nested repository ${source} has no commit at its HEAD, and its HEAD names no local branch`);
8580
8848
  rmSync(dest, { recursive: true, force: true });
8581
- retireGit(null, ["clone", "--no-local", "--quiet", source, dest]);
8849
+ cloneRecovery(["--no-local", "--quiet", source, dest]);
8582
8850
  detachRecoveryClone(source, dest, carryNestedRefs(source, dest, name, head));
8583
8851
  restoreStandaloneGitState(source, dest);
8584
8852
  for (const c of carryExcludes(source, dest)) excludes.push({ repo: rel, ...c });
@@ -8681,9 +8949,9 @@ function copyRecoveryWork(observation, meta, parent) {
8681
8949
  try { ref = existsSync(observation.work) ? worktreeHead(observation.work) : { branch: meta.branch, commit: null }; }
8682
8950
  catch (e) { unreadableHeads.add(e); throw e; }
8683
8951
  if (meta.branch && ref.branch !== meta.branch) branchDrift = { recordedBranch: meta.branch, worktreeBranch: ref.branch, detachedAt: ref.branch === null ? ref.commit : null };
8684
- if (ref.branch !== null) retireGit(null, ["clone", "--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo]);
8952
+ if (ref.branch !== null) cloneRecovery(["--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo]);
8685
8953
  else {
8686
- retireGit(null, ["clone", "--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo]);
8954
+ cloneRecovery(["--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo]);
8687
8955
  copierFetch(recoveredRepo, observation.work, [ref.commit]);
8688
8956
  retireGit(recoveredRepo, ["checkout", "--quiet", "--detach", ref.commit]);
8689
8957
  }
@@ -8913,22 +9181,28 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
8913
9181
  }
8914
9182
  }
8915
9183
 
8916
- /** The `work` link of the instance at `kidHome` when it is attached to
8917
- * `home`'s work (#718), else null: instance.json says `work: "attached"`, and
8918
- * its `work` is a symbolic link that leads to `<home>/work`, as written (in
8919
- * any spelling of the home) or through other links (`--work-dir` given as an
8920
- * alias of the tree). The latter is seen only while `<home>/work` exists, so a
8921
- * retire asks before it re-homes the worktree. → the link's target as written:
8922
- * the evidence a later relink checks is still there. */
8923
- export function attachedWorkLink(kidHome, home) {
9184
+ /** The `work` link of the instance at `kidHome` when it is attached to the
9185
+ * tree at `tree` (#718, #964), else null. `tree` is a tree of a home: its
9186
+ * `<home>/work`, or an extra tree of it (`<home>/.work-<purpose>`). Attached:
9187
+ * instance.json says `work: "attached"`, and its `work` is a symbolic link
9188
+ * that leads to the tree, as written (in any spelling of the home) or
9189
+ * through other links (`--work-dir` given as an alias of the tree). The
9190
+ * latter is seen only while the tree exists, so whoever moves or removes the
9191
+ * tree asks first. The one test of who is attached to a tree: the retire,
9192
+ * its plan and `oats worktree remove` read it. → the link's target as
9193
+ * written: the evidence a later relink checks is still there. */
9194
+ export function attachedWorkLink(kidHome, tree) {
8924
9195
  if (readJsonOrUndefined(join(kidHome, "instance.json"))?.work !== "attached") return null;
8925
9196
  const link = join(kidHome, "work");
8926
9197
  let written;
8927
9198
  try { written = readlinkSync(link); } catch { return null; }
8928
- const target = resolve(kidHome, written);
8929
- if (target === join(resolve(home), "work")) return written;
8930
- try { if (basename(target) === "work" && realpathSync(dirname(target)) === realpathSync(home)) return written; } catch { /* below */ }
8931
- try { return realpathSync(link) === realpathSync(join(home, "work")) ? written : null; } catch { return null; }
9199
+ const target = resolve(kidHome, written), at = resolve(tree);
9200
+ if (target === at) return written;
9201
+ // Existing paths are compared in their one spelling on disk (realpathSync.native, as
9202
+ // canonicalHomePath): on a case-insensitive filesystem JS realpathSync keeps the caller's letter
9203
+ // case, so a tree named as `.WORK-X` and as `.work-x` would read as two trees.
9204
+ try { if (basename(target) === basename(at) && realpathSync.native(dirname(target)) === realpathSync.native(dirname(at))) return written; } catch { /* below */ }
9205
+ try { return realpathSync.native(link) === realpathSync.native(at) ? written : null; } catch { return null; }
8932
9206
  }
8933
9207
  /** Point an attached instance's `work` link at `to`, atomically: a new link
8934
9208
  * beside it is renamed over the old one, so the link is never missing. */
@@ -9528,7 +9802,7 @@ function retireUnderClaim(root, name, o) {
9528
9802
  // its plan and checks the revision): after the two answers above, before the retire reads
9529
9803
  // anything of the home. What it returns of the plan binds the retire.
9530
9804
  const confirmed = o[RETIRE_UNDER_CLAIM]?.();
9531
- const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}) } : o;
9805
+ const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}), ...(confirmed.ambiguous ? { ambiguous: confirmed.ambiguous } : {}) } : o;
9532
9806
  return retireClaimed(root, name, bound, now);
9533
9807
  } finally {
9534
9808
  releaseHomeClaim(held);
@@ -10121,14 +10395,65 @@ function retireSteps(root, name, o, found, at) {
10121
10395
  // as planned refuse as stale before any of them is touched.
10122
10396
  let extraWorktrees;
10123
10397
  let retention = null;
10398
+ // An attached child's `work` is a link to a tree of this home: to its work/ (#718) or to one of
10399
+ // its extra trees (#964). A tree the retire moves or removes would leave that link pointing at a
10400
+ // path that is gone. The children looked at are the recorded ones this retire stopped; each tree's
10401
+ // are found while the tree is still there (a link through an alias of the tree resolves only
10402
+ // then), each with its link as written. What the retire could not do for one, or leaves it with,
10403
+ // is a warning in the receipt: the retire is not undone.
10404
+ const relinkWarnings = [];
10405
+ const stoppedKids = (childrenStopped || []).filter((k) => k.ok);
10406
+ // The instances the plan lists under `ambiguous` (`o.ambiguous`, handed in with the children: this
10407
+ // function reads no lineage) are attached by their link as well. The retire does not act on them:
10408
+ // they are not stopped, and a write to an instance that may be running is not made. A tree that is
10409
+ // moved or removed leaves their link pointing at a path that is gone, and the receipt says so.
10410
+ const attachedTo = (tree) => [...stoppedKids, ...(Array.isArray(o.ambiguous) ? o.ambiguous.map((k) => ({ instance: k.instance, home: k.home, ambiguous: true })) : [])]
10411
+ .map((k) => ({ ...k, link: attachedWorkLink(k.home, tree) })).filter((k) => k.link !== null);
10412
+ const NOT_STOPPED = "it records this instance as its parent under a name that is not unique, so the retire did not stop it";
10413
+ // The attachment as it was found, still: attached, and the same link. One that changed is
10414
+ // someone else's now, and is left as it is.
10415
+ const stillAttached = (kid) => { try { return readJsonOrUndefined(join(kid.home, "instance.json"))?.work === "attached" && readlinkSync(join(kid.home, "work")) === kid.link; } catch { return false; } };
10416
+ /** Repoint each of `kids` to `to`, where the tree that was at `from` is retained. It is a write to
10417
+ * another instance, so it is made only once the move is done and seen done: the tree is at its
10418
+ * new path and nothing is left at the old one. The child's AGENTS.md still names the old path. */
10419
+ const repointAttached = (kids, from, to) => {
10420
+ const present = (p) => { try { lstatSync(p); return true; } catch { return false; } };
10421
+ const moved = kids.length > 0 && (() => { try { return lstatSync(to).isDirectory(); } catch { return false; } })() && !present(from);
10422
+ for (const kid of kids) {
10423
+ if (kid.ambiguous) {
10424
+ if (stillAttached(kid)) relinkWarnings.push(`${kid.instance}: its work was ${from}, which this retire re-homed to ${to}; its work link ${join(kid.home, "work")} was not repointed and now points at a path that is gone (${NOT_STOPPED}); to repoint it by hand: ln -sfn ${shq(to)} ${shq(join(kid.home, "work"))}`);
10425
+ continue;
10426
+ }
10427
+ if (!stillAttached(kid)) {
10428
+ 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 ${to}; inspect ${join(kid.home, "work")}`);
10429
+ continue;
10430
+ }
10431
+ try {
10432
+ if (!moved) throw new Error(`the worktree was not seen at ${to} with nothing left at ${from}`);
10433
+ relinkAttachedWork(kid.home, to);
10434
+ } catch (e) {
10435
+ relinkWarnings.push(`${kid.instance}: its work link could not be repointed to the retained worktree ${to} (${e.message}) and still points at ${kid.link}; repoint it by hand: ln -sfn ${shq(to)} ${shq(join(kid.home, "work"))}`);
10436
+ }
10437
+ }
10438
+ };
10439
+ /** Say of each of `kids` that the tree at `tree`, which this retire removed, was its work: its
10440
+ * link, when it is still the one that was found, now points at a path that is gone. */
10441
+ const leftWithoutWork = (kids, tree, why) => {
10442
+ for (const kid of kids) if (stillAttached(kid)) relinkWarnings.push(`${kid.instance}: its work was ${tree}, which this retire removed (${why}); its work link ${join(kid.home, "work")} now points at a path that is gone${kid.ambiguous ? ` (${NOT_STOPPED})` : ""}`);
10443
+ };
10124
10444
  // From here on the retire removes and re-homes trees: a failure no longer says that the work is
10125
- // kept, only what is still true, and which trees it has dealt with.
10445
+ // kept, only what is still true, which trees it has dealt with, and what that left an attached
10446
+ // child with.
10447
+ const attachedSaid = () => relinkWarnings.length ? `. Attached children: ${relinkWarnings.join("; ")}` : "";
10126
10448
  const treesDone = () => {
10127
10449
  const done = [...(extraWorktrees || []).map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`),
10128
10450
  ...(retention?.worktree === "removed" ? [`${workPath} removed`] : retention?.worktree === "retained" ? [`${workPath} re-homed to ${retention.movedTo}`] : [])];
10129
- return done.length ? `. Already done in this retire: ${done.join(", ")}` : "";
10451
+ return done.length ? `. Already done in this retire: ${done.join(", ")}${attachedSaid()}` : "";
10130
10452
  };
10131
10453
  at.said = () => `${hooksSaid()}; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}${treesDone()}`;
10454
+ // The same for a refusal that has its own sentence, once the extra-tree step has dealt with a
10455
+ // tree: the refusals of that step, and every one of the work/ step, which comes after it.
10456
+ const alreadyDone = () => extraWorktrees?.length ? ` Already done in this retire: ${extraWorktrees.map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`).join(", ")}${attachedSaid()}.` : "";
10132
10457
  if (!o.keepDir && !(outstandingBeforeWorktree.length > 0 && !o.force)) {
10133
10458
  const rows = extraWorktreeRows(finalObservation.extraTrees, root);
10134
10459
  if (o.plannedExtraWorktrees && JSON.stringify(rows) !== JSON.stringify(o.plannedExtraWorktrees)) {
@@ -10140,11 +10465,12 @@ function retireSteps(root, name, o, found, at) {
10140
10465
  throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: ${refused.map((r) => `the extra worktree ${r.path}: ${r.reason}`).join("; ")}. No extra worktree was moved or removed and work/ is untouched; the retire hooks have run and the home is kept so nothing is lost.`);
10141
10466
  }
10142
10467
  extraWorktrees = [];
10143
- 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(", ")}.` : "";
10468
+ // Who is attached to each tree, asked before any of them is moved or removed.
10469
+ const attachedOf = new Map(rows.map((row) => [row.path, attachedTo(row.path)]));
10144
10470
  // Each row's repository, by its Git directory: the commands run helper-free (gitRepoRun).
10145
10471
  const gitDirOf = new Map(finalObservation.extraTrees.map((tree) => [tree.path, tree.commonDir]));
10146
10472
  const git = (row, argv) => gitRepoRun(gitDirOf.get(row.path), argv);
10147
- const failed = (row, what, e) => oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the extra worktree ${row.path} ${what} (${String(e?.stderr ?? e?.message ?? e ?? "").trim()}).${done()} work/ is untouched; the retire hooks have run and the home is kept so nothing is lost — resolve and retry.`);
10473
+ const failed = (row, what, e) => oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the extra worktree ${row.path} ${what} (${String(e?.stderr ?? e?.message ?? e ?? "").trim()}).${alreadyDone()} work/ is untouched; the retire hooks have run and the home is kept so nothing is lost — resolve and retry.`);
10148
10474
  for (const row of rows) {
10149
10475
  if (row.disposition === "remove") {
10150
10476
  try {
@@ -10155,6 +10481,7 @@ function retireSteps(root, name, o, found, at) {
10155
10481
  } catch (e) { throw failed(row, "could not be removed, or its removal could not be verified", e); }
10156
10482
  extraWorktrees.push({ ...row, outcome: "removed" });
10157
10483
  appendEvent(found.home, { kind: "worktree-removed", data: { branch: row.branch, extra: true, path: row.path } }, { workspaceOnly: true });
10484
+ leftWithoutWork(attachedOf.get(row.path), row.path, "an extra worktree of the retired instance, clean: its branch and commits stay in its repository");
10158
10485
  } else {
10159
10486
  try {
10160
10487
  mkdirSync(dirname(row.movedTo), { recursive: true });
@@ -10162,14 +10489,16 @@ function retireSteps(root, name, o, found, at) {
10162
10489
  } catch (e) { throw failed(row, `could not be re-homed to ${row.movedTo}`, e); }
10163
10490
  extraWorktrees.push({ ...row, outcome: "retained" });
10164
10491
  appendEvent(found.home, { kind: "worktree-retained", data: { movedTo: row.movedTo, branch: row.branch, recordedBranch: null, extra: true, path: row.path } }, { workspaceOnly: true });
10492
+ // Right after this tree's move, not at the end as for work/: the work/ step below can still
10493
+ // refuse and keep the home, and the tree has left it either way.
10494
+ repointAttached(attachedOf.get(row.path), row.path, row.movedTo);
10165
10495
  }
10166
10496
  }
10167
10497
  if (!extraWorktrees.length) extraWorktrees = undefined;
10168
10498
  }
10169
10499
  // The attached children this retire stopped whose work is this home's work/
10170
- // (#718), found while work/ is still here (a link through an alias of the
10171
- // tree resolves only then), each with its link as written.
10172
- const attachedKids = (childrenStopped || []).filter((k) => k.ok).map((k) => ({ ...k, link: attachedWorkLink(k.home, found.home) })).filter((k) => k.link !== null);
10500
+ // (#718), found while work/ is still here.
10501
+ const attachedKids = attachedTo(workPath);
10173
10502
  const worktreeStep = isWorktree && !!workMeta.repo && !orphanedWork;
10174
10503
  const worktreeDeferred = worktreeStep && existsSync(workPath) && outstandingBeforeWorktree.length > 0 && !o.force;
10175
10504
  const keptForRetry = worktreeDeferred ? `git worktree ${workPath}: kept for the retry; outstanding: ${outstandingBeforeWorktree.join("; ")}` : null;
@@ -10202,8 +10531,9 @@ function retireSteps(root, name, o, found, at) {
10202
10531
  if (existsSync(workPath)) {
10203
10532
  let now;
10204
10533
  try { now = worktreeHead(workPath); }
10205
- 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.`); }
10206
- assertSameWorktreeHead(finalObservation.head, now);
10534
+ catch (e) { throw oatsError("E_WORK_INSPECTION_FAILED", `${e.message}. The worktree was not removed.${alreadyDone()} The home and the worktree are kept, and so is any recovery the retire wrote; retry the retire.`); }
10535
+ try { assertSameWorktreeHead(finalObservation.head, now); }
10536
+ catch (e) { throw oatsError(e.code, `${e.message}${alreadyDone()}`); }
10207
10537
  }
10208
10538
  // The removal is verified as the extra-tree step's is: nothing is at work/ and the repository's
10209
10539
  // worktree list does not name it. A removal that did not happen, or cannot be shown to have
@@ -10223,8 +10553,7 @@ function retireSteps(root, name, o, found, at) {
10223
10553
  gitRepoRun(gitDir.dir, ["worktree", "prune"]);
10224
10554
  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`");
10225
10555
  } catch (e) {
10226
- 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(", ")}.` : "";
10227
- 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; ${sessionSaid()}. Check what is left at ${workPath}, then retry the retire.`);
10556
+ 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"}).${alreadyDone()} The retire hooks have run; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}. Check what is left at ${workPath}, then retry the retire.`);
10228
10557
  }
10229
10558
  retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
10230
10559
  }
@@ -10236,7 +10565,7 @@ function retireSteps(root, name, o, found, at) {
10236
10565
  if (gitDir.error) throw new Error(gitDir.error);
10237
10566
  gitRepoRun(gitDir.dir, ["worktree", "move", workPath, dest]);
10238
10567
  } catch (e) {
10239
- 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`);
10568
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be re-homed to ${dest} (${String(e.stderr ?? e.message ?? "").trim()})${alreadyDone() ? `.${alreadyDone()} The` : "; the"} home is kept so nothing is lost — resolve and retry, or pass --discard-worktree to remove the worktree instead`);
10240
10569
  }
10241
10570
  retention = { worktree: "retained", movedTo: dest, branch: verifiedBranch, detachedAt: verifiedBranch === null ? ref.commit : null, recordedBranch: meta.branch ?? null };
10242
10571
  } else retention = { worktree: "absent", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
@@ -10364,26 +10693,10 @@ function retireSteps(root, name, o, found, at) {
10364
10693
  // last, once the move is done and seen done: the worktree is at its new path
10365
10694
  // and nothing is left at work/. One that fails is a warning; the retire is
10366
10695
  // not undone. The child's AGENTS.md still names the old path.
10367
- const relinkWarnings = [];
10368
- if (retention?.worktree === "retained") {
10369
- const present = (p) => { try { lstatSync(p); return true; } catch { return false; } };
10370
- const moved = attachedKids.length > 0 && (() => { try { return lstatSync(retention.movedTo).isDirectory(); } catch { return false; } })() && !present(workPath);
10371
- for (const kid of attachedKids) {
10372
- // The attachment as it was found, still: attached, and the same link. One that changed is
10373
- // someone else's now, and is left as it is.
10374
- const still = (() => { try { return readJsonOrUndefined(join(kid.home, "instance.json"))?.work === "attached" && readlinkSync(join(kid.home, "work")) === kid.link; } catch { return false; } })();
10375
- if (!still) {
10376
- 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")}`);
10377
- continue;
10378
- }
10379
- try {
10380
- if (!moved) throw new Error(`the worktree was not seen at ${retention.movedTo} with nothing left at ${workPath}`);
10381
- relinkAttachedWork(kid.home, retention.movedTo);
10382
- } catch (e) {
10383
- 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"))}`);
10384
- }
10385
- }
10386
- }
10696
+ if (retention?.worktree === "retained") repointAttached(attachedKids, workPath, retention.movedTo);
10697
+ // A work/ this retire removed (--discard-worktree, or a failed spawn's quarantine that owed it)
10698
+ // leaves each of them with a link to a path that is gone (#964): said, by name.
10699
+ else if (retention?.worktree === "removed") leftWithoutWork(attachedKids, workPath, o.discardWorktree ? "--discard-worktree" : "the worktree of a spawn that failed");
10387
10700
  // Forcing is the operator overriding the fail-closed default with their eyes
10388
10701
  // open: the home goes, and what remains outstanding is reported rather than
10389
10702
  // swallowed. Without this, a quarantine whose cleanup can never succeed (a