@feigi/fleet-ctl 3.46.1 → 3.46.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.46.1",
3
+ "version": "3.46.3",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -22,11 +22,19 @@
22
22
  // an unsignaled row (no mention, no PR-bound member, no review=/reviewed=)
23
23
  // still gets pr: null here while fleet-tick.mjs's own row-key fallback keys
24
24
  // it to its ticket number regardless; see the same paragraph below.
25
+ // A card's review, finisher and fix-applier state is its PR's, read off
26
+ // fleet-tick.mjs's own per-PR fold (foldLedger, in its lenient mode: a token
27
+ // it cannot read is skipped and flags the row `ledger-error`, never thrown),
28
+ // not off the card's own row — a ticket retried under a new PR has that PR's
29
+ // tokens on another row. A fallback `#M` row for a PR a ticket row's latest
30
+ // attempt claims is that card's other half and renders no card of its own:
31
+ // its row-level signals (`ledger-error`, held-behind, the cause words, a live
32
+ // member) are the claiming card's.
25
33
  // fleet-tick.mjs's I/O and main() never run here, main() being guarded on
26
34
  // argv[1].
27
35
  import { assessBeat, isStalled, isReported, stallReport, NO_OWNER } from "./fleet-state.mjs";
28
- import { parseToken, rowPr, premisesOf, HALT_CAUSES, REVIEW, REVIEWED } from "./ledger-grammar.mjs";
29
- import { latestFinisherAttempts } from "./fleet-tick.mjs";
36
+ import { parseToken, rowPr, premisesOf, HALT_CAUSES, REVIEW } from "./ledger-grammar.mjs";
37
+ import { latestFinisherAttempts, foldLedger, pastPinDue } from "./fleet-tick.mjs";
30
38
 
31
39
  // A ledger row is freeform, controller-authored text. Two example shapes:
32
40
  // #<n> impl-<n>=PR#<m> → PR#<m> → MERGED 73b356de
@@ -85,14 +93,14 @@ import { latestFinisherAttempts } from "./fleet-tick.mjs";
85
93
  // live until the token is settled `=failed` or a later `reviewed=` records
86
94
  // its result.
87
95
  //
88
- // A `review=` token puts the PR under review only while
89
- // it is live. A settled `review=…=failed` is a dead review and the PR is owed
90
- // one again, as run-team SKILL.md defines review-due and as fleet-tick.mjs's
91
- // `reviewedAny` reads the token: the PR is owed none while the row carries
92
- // ANY live `review=` — wherever it sits, not only as the last one — or any
93
- // `reviewed=`. A `review=` token outside the grammar is still read as live
94
- // here; fleet-tick.mjs refuses that ledger outright, so there is no reading of
95
- // it to agree with.
96
+ // A `review=` token puts the PR under review only while it is live. A settled
97
+ // `review=…=failed` is a dead review and the PR is owed one again, as run-team
98
+ // SKILL.md defines review-due and as fleet-tick.mjs's `reviewedAny` reads the
99
+ // token: the PR is owed none while any row naming it carries ANY live
100
+ // `review=` — wherever it sits, not only as the last one — or any `reviewed=`.
101
+ // A `review=` token outside the grammar is read as live by foldLedger's
102
+ // lenient mode, which the board reads the PR's state through; the strict tick
103
+ // refuses that ledger outright instead, and the board flags the row.
96
104
  //
97
105
  // `#N excluded · behind-pr:#M` / `behind-issue:#M` is an Exclusion — pool
98
106
  // supply, not a claim — read through ledger-grammar.mjs's premisesOf(), the
@@ -149,16 +157,12 @@ export function parseRow(row) {
149
157
  // exists for.
150
158
  const live = [];
151
159
  const implOutcomes = new Map();
152
- const finisherOutcomes = new Map();
153
160
  const settled = new Set();
154
161
  let lastImpl = null; // the latest well-formed impl token (laterAttempt)
155
- const finishers = []; // well-formed finisher tokens, for the row's PR below
156
162
  let anyImpl = false;
157
163
  let prMember = false;
158
164
  let review = false; // any review= token: a PR-bound signal on a row with no impl token
159
- let reviewLive = false; // one not settled `=failed`: a live review
160
165
  let reviewed = false;
161
- let reviewedHead = null;
162
166
  let runners = [];
163
167
  let malformed = false;
164
168
  for (const tok of row.split(/\s+/).filter(Boolean)) {
@@ -174,32 +178,18 @@ export function parseRow(row) {
174
178
  if (!lastImpl || laterAttempt(t, lastImpl, ticket)) lastImpl = t;
175
179
  }
176
180
  }
177
- if (t.family === "finisher-pr" && !t.error) {
178
- if (t.outcome !== null) finisherOutcomes.set(t.name, t.outcome);
179
- finishers.push(t);
180
- }
181
181
  if (t.bound === "pr") prMember = true;
182
182
  continue;
183
183
  }
184
184
  if (tok.startsWith("review=")) {
185
185
  review = true;
186
186
  const { kind, name, failed } = REVIEW.exec(tok)?.groups ?? {};
187
- if (!failed) reviewLive = true;
188
187
  if (kind === "member") {
189
188
  if (failed) settled.add(name);
190
189
  else { live.push({ kind: "runner", name }); runners.push(name); }
191
190
  }
192
191
  } else if (tok.startsWith("reviewed=")) {
193
192
  reviewed = true;
194
- // The head that review actually read — the cockpit's own copy
195
- // of fleet-tick.mjs's `reviewedHead`, needed below to tell a past-pin
196
- // halt already answered by this review apart from one still owed a
197
- // fresh one. A token fleet-tick.mjs refuses — one that names no review
198
- // run — earns the row the same `ledger-error` flag any malformed token
199
- // does, rather than a row reviewed at no head.
200
- const m = REVIEWED.exec(tok);
201
- if (m) reviewedHead = m[1].toLowerCase();
202
- else malformed = true;
203
193
  for (const r of runners) settled.add(r);
204
194
  runners = [];
205
195
  }
@@ -222,16 +212,11 @@ export function parseRow(row) {
222
212
  if (own !== null) pr = own;
223
213
  else if ((prMember || review || reviewed) && row.split(/\s/)[0] === issueM[0]) pr = Number(issueM[1]);
224
214
  }
225
- let lastFinisher = null;
226
- for (const t of finishers) {
227
- if (t.number === pr && (!lastFinisher || laterAttempt(t, lastFinisher, pr))) lastFinisher = t;
228
- }
229
215
  return {
230
216
  issue: Number(issueM[1]),
231
217
  excluded,
232
218
  impl: lastImpl?.name ?? null,
233
219
  implOutcome,
234
- finisherOutcome: lastFinisher ? (finisherOutcomes.get(lastFinisher.name) ?? null) : null,
235
220
  agent: alive.length ? alive[alive.length - 1].name : null,
236
221
  pr,
237
222
  merged: !!mergedM,
@@ -239,9 +224,6 @@ export function parseRow(row) {
239
224
  heldBehind: heldM ? Number(heldM[1]) : null,
240
225
  causes,
241
226
  malformed,
242
- reviewed,
243
- reviewedHead,
244
- underReview: reviewLive || alive.some((e) => e.kind === "member" && (e.token.family === "fix-pr" || e.token.family === "finisher-pr")),
245
227
  };
246
228
  }
247
229
 
@@ -470,13 +452,45 @@ export function computeBoard(inputs) {
470
452
  if (s.issue != null) ruledByPr.set(s.issue, s.subject);
471
453
  }
472
454
 
473
- const parsed = (ledger.rows || []).map(parseRow).filter(Boolean);
455
+ const rows = ledger.rows || [];
456
+ const fold = foldLedger({ rows, dispatched: ledger.dispatched || [] }, new Set(prs.map((p) => p.number)), { lenient: true });
457
+ const parsed = [];
458
+ for (const [i, row] of rows.entries()) {
459
+ const p = parseRow(row);
460
+ if (p) parsed.push({ ...p, malformed: p.malformed || fold.malformed.has(i) });
461
+ }
462
+ // The ticket row each PR's latest attempt settled to, first row wins.
463
+ const claimedBy = new Map();
464
+ for (const p of parsed) if (p.impl !== null && p.pr != null && !claimedBy.has(p.pr)) claimedBy.set(p.pr, p);
465
+ // A fallback `#M` row — no impl token of its own, keyed to its own ticket
466
+ // number — for a PR a ticket row's latest attempt claims is that card's other
467
+ // half, not a second card: what the row says about the PR goes onto the
468
+ // claiming card, and a live member on it is the card's agent.
469
+ const cards = [];
470
+ for (const p of parsed) {
471
+ const claimer = p.impl === null && p.pr === p.issue ? claimedBy.get(p.pr) : undefined;
472
+ if (claimer === undefined) { cards.push(p); continue; }
473
+ claimer.malformed ||= p.malformed;
474
+ claimer.heldBehind ??= p.heldBehind;
475
+ for (const c of p.causes) if (!claimer.causes.includes(c)) claimer.causes.push(c);
476
+ claimer.agent = p.agent ?? claimer.agent;
477
+ claimer.merged ||= p.merged;
478
+ }
474
479
  const unqueued = new Set(prs.filter((p) => p.state === "OPEN" && !(p.labels || []).includes("ready-to-merge")).map((p) => p.number));
475
- const latestFinishers = new Map(latestFinisherAttempts({ rows: ledger.rows || [], dispatched: ledger.dispatched || [] }, unqueued).map((u) => [u.pr, u.outcome]));
480
+ const latestFinishers = new Map(latestFinisherAttempts({ rows, dispatched: ledger.dispatched || [] }, unqueued).map((u) => [u.pr, u.outcome]));
481
+ // Review state is the PR's, read off the tick's own fold — a card's
482
+ // PR is its row's latest attempt, whichever row carries that PR's tokens.
483
+ const liveMember = (names) => [...names].some((n) => fold.members.get(n).outcome === null);
484
+ const reviewOwed = (prNum) => {
485
+ const st = fold.byPr.get(prNum);
486
+ if (st === undefined) return true;
487
+ if (st.inFlight || liveMember(st.fixMembers) || liveMember(st.finishers)) return false;
488
+ return !st.reviewedAny || pastPinDue(st, prByNum.get(prNum)?.headRefOid);
489
+ };
476
490
  const rowIssues = new Set();
477
491
  const tickets = [];
478
492
 
479
- for (const p of parsed) {
493
+ for (const p of cards) {
480
494
  const pr = p.pr != null ? prByNum.get(p.pr) : undefined;
481
495
  const prevTicket = prevByIssue.get(p.issue);
482
496
  const prState = p.pr == null ? null
@@ -525,19 +539,14 @@ export function computeBoard(inputs) {
525
539
 
526
540
  // Backlog is a PR nobody has reviewed and nobody is reviewing: no live
527
541
  // `review=` (a settled `=failed` one is no review), no
528
- // `reviewed=`, and no live fix-applier or finisher on the row — or
542
+ // `reviewed=`, and no live fix-applier or finisher on the PR — or
529
543
  // a returned review whose finisher halted `past-pin` against a head it
530
544
  // never read: owed again until the head catches up to what `reviewed=`
531
545
  // recorded, the same rule fleet-tick.mjs's reviewDue reads off headRefOid
532
546
  // (pastPinDue). A PR absent from the open list (closed, not yet MERGED)
533
547
  // reads as an unmatched head, never as answered — silence is not review.
534
- const parsedByIssue = new Map(parsed.map((p) => [p.issue, p]));
535
- const pastPinBacklog = (p) => p.finisherOutcome === "halted:past-pin" && p.reviewedHead !== null
536
- && !String(prByNum.get(p.pr)?.headRefOid ?? "").toLowerCase().startsWith(p.reviewedHead);
537
- const reviewBacklog = tickets.filter((t) => {
538
- const p = parsedByIssue.get(t.issue);
539
- return t.column === "REVIEW" && !p.underReview && (!p.reviewed || pastPinBacklog(p));
540
- }).length;
548
+ // Counted once per PR, off the per-PR fold, however many cards name it.
549
+ const reviewBacklog = new Set(tickets.filter((t) => t.column === "REVIEW" && reviewOwed(t.pr)).map((t) => t.pr)).size;
541
550
  const cardsInPool = tickets.filter((t) => t.column === "POOL").length;
542
551
  // A capped pool read makes this count a floor, and it says so the way
543
552
  // fleet-tick.mjs's claimed count does — `"100+"`, never a bare 100 that
@@ -525,7 +525,20 @@ export function unlabelledFinishers(ledger, unqueued) {
525
525
  .map((u) => ({ pr: u.pr, labelled: u.attempts.filter((a) => a.outcome === "labelled").map((a) => a.name) }));
526
526
  }
527
527
 
528
- export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(), finished = new Set()) {
528
+ // The per-PR fold: every row and `## Dispatched` entry read once into one
529
+ // state per PR, shared by every row that resolves to it. deriveRun reads its
530
+ // counts off this, and compute-board.mjs reads each card's PR state off the
531
+ // same one — a second row→PR join in the cockpit is a second answer to which
532
+ // PR a token speaks for. Returns `{members, byPr, verdicts, claimed, excluded,
533
+ // malformed}`: `members` the merged record per member name, `byPr` the state
534
+ // per PR, `malformed` the indexes of the `rows` a token was skipped on.
535
+ //
536
+ // Strict by default: a token it cannot read throws LedgerError. `lenient` is
537
+ // the cockpit's mode — its contract is that unknown text is flagged, never
538
+ // fatal — and skips that token instead, recording its row in `malformed`. A
539
+ // skipped `review=` still reads as a live review and a skipped `reviewed=` as
540
+ // a returned one at no head, the readings the cockpit has always given them.
541
+ export function foldLedger({ rows, dispatched }, open, { lenient = false } = {}) {
529
542
  // One entry per member name across `## Dispatched` and every row. A member
530
543
  // settled ANYWHERE is settled: `settle` is the only writer of an outcome, and
531
544
  // a bare copy beside it is what a whole-line `row` rewrite leaves behind.
@@ -538,19 +551,26 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
538
551
  // row naming no PR, which settles no PR-bound member); a stray's token
539
552
  // still creates the member, live, as before.
540
553
  const members = new Map();
554
+ const malformed = new Set();
541
555
  const note = (t, where, rowPr) => {
542
- if (t.error) throw new LedgerError(`${where}: ${t.name}: ${t.error}`);
556
+ if (t.error) {
557
+ if (lenient) return false;
558
+ throw new LedgerError(`${where}: ${t.name}: ${t.error}`);
559
+ }
543
560
  const m = members.get(t.name) ?? { name: t.name, family: t.family, number: t.number, outcome: null };
544
561
  if (t.outcome !== null && (t.bound !== "pr" || rowPr === undefined || t.number === rowPr)) m.outcome = t.outcome;
545
562
  members.set(t.name, m);
563
+ return true;
546
564
  };
547
565
  for (const e of dispatched) {
548
566
  const t = parseToken(e);
549
- if (!t) throw new LedgerError(`## Dispatched entry '${e}' is not a member token — fix the ledger by hand before the tick can count from it`);
567
+ if (!t) {
568
+ if (lenient) continue;
569
+ throw new LedgerError(`## Dispatched entry '${e}' is not a member token — fix the ledger by hand before the tick can count from it`);
570
+ }
550
571
  note(t, `## Dispatched entry '${e}'`);
551
572
  }
552
573
 
553
- const open = new Set(prs.map((p) => p.number));
554
574
  const claimed = new Set();
555
575
  const excluded = [];
556
576
  const byPr = new Map();
@@ -581,7 +601,7 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
581
601
  if (t && !t.error && t.family === "fix-pr" && t.number === pr && t.outcome !== null) settledInRow.add(t.name);
582
602
  }
583
603
  }
584
- for (const text of rows) {
604
+ for (const [i, text] of rows.entries()) {
585
605
  const { keyNum, pr } = rowNums(text);
586
606
  const where = `row '${text}'`;
587
607
  // One state per PR, shared by every row that resolves to it: a
@@ -618,10 +638,10 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
618
638
  inFlight: false, reviewedAny: false, survived: 0, unverified: 0, reviewFixed: false,
619
639
  fixMembers: new Set(), fixLanded: new Set(), conflictLanded: new Set(), held: [],
620
640
  conflictOpen: false, reviewedHead: null, reviewedRun: null, pastPinHalt: false, dispositions: [], workers: new Set(),
641
+ finishers: new Set(),
621
642
  };
622
643
  // The finisher-pr token currently deciding `pastPinHalt`, picked by
623
- // retry suffix ("" < "b" < "c" …) the same way compute-board.mjs's
624
- // laterAttempt does — never by row-text position. A
644
+ // retry suffix ("" < "b" < "c" …) — never by row-text position. A
625
645
  // `-b` retry can sit before an older `halted:past-pin` token after a row
626
646
  // rewrite, and text order must not read the stale one as the live
627
647
  // finisher's replacement. Reset at each `reviewed=`, since `pastPinHalt`
@@ -630,7 +650,10 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
630
650
  for (const tok of text.split(/\s+/).filter(Boolean)) {
631
651
  const t = parseToken(tok);
632
652
  if (t) {
633
- note(t, where, pr);
653
+ if (!note(t, where, pr)) {
654
+ malformed.add(i);
655
+ continue;
656
+ }
634
657
  if ((t.bound === "pr" && t.number === pr) || t.family === "impl") st.workers.add(t.name);
635
658
  // A settled `failed`/`killed` fix-applier leaves review findings or a
636
659
  // conflict unfixed and no successor dispatched — the PR stays fix-due
@@ -675,6 +698,7 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
675
698
  } else st.reviewFixed = true;
676
699
  }
677
700
  }
701
+ if (t.family === "finisher-pr" && t.number === pr) st.finishers.add(t.name);
678
702
  if (t.family === "finisher-pr" && t.number === pr
679
703
  && (!latestFinisher || (t.retry ?? "") > (latestFinisher.retry ?? ""))) {
680
704
  latestFinisher = t;
@@ -684,11 +708,23 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
684
708
  }
685
709
  if (tok.startsWith("review=")) {
686
710
  const m = REVIEW.exec(tok);
711
+ if (!m && lenient) {
712
+ malformed.add(i);
713
+ st.inFlight = true;
714
+ st.reviewedAny = true;
715
+ continue;
716
+ }
687
717
  if (!m) throw new LedgerError(`${where}: '${tok}' is not review=wf:<runId> | member:review-pr-<n>, optionally =failed`);
688
718
  st.inFlight = !m.groups.failed;
689
719
  if (!m.groups.failed) st.reviewedAny = true;
690
720
  } else if (tok.startsWith("reviewed=")) {
691
721
  const m = REVIEWED.exec(tok);
722
+ if (!m && lenient) {
723
+ malformed.add(i);
724
+ latestFinisher = null;
725
+ Object.assign(st, { inFlight: false, reviewedAny: true, reviewFixed: false, pastPinHalt: false });
726
+ continue;
727
+ }
692
728
  if (!m && REVIEWED_RUNLESS.test(tok)) {
693
729
  throw new LedgerError(`${where}: '${tok}' names no review run — reviewed= is now <head>:<survived>/<refuted>/<unverified>:<run>, `
694
730
  + "<run> the run-XXXXXXXX directory holding that review's review.json; drop the token with `ledger.mjs row` and record it again with `ledger.mjs review <pr>`");
@@ -700,7 +736,8 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
700
736
  reviewedHead: m[1].toLowerCase(), reviewedRun: m[5], pastPinHalt: false,
701
737
  });
702
738
  } else if (labelOffMember(tok) === null) {
703
- throw new LedgerError(`${where}: '${tok}' is not label-off=<finisher-pr member> — fix the row with \`ledger.mjs row\``);
739
+ if (!lenient) throw new LedgerError(`${where}: '${tok}' is not label-off=<finisher-pr member> — fix the row with \`ledger.mjs row\``);
740
+ malformed.add(i);
704
741
  } else {
705
742
  const h = HELD.exec(tok);
706
743
  if (h) st.held.push(Number(h[1]));
@@ -710,14 +747,18 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
710
747
  // misrecorded one, and read on a guess it would either hold the
711
748
  // wrong PR or leave this one silently stalled.
712
749
  if (Number(c[1]) !== pr) {
713
- throw new LedgerError(`${where}: '${tok}' names PR #${c[1]}, but this row is ${pr === null ? "no PR's" : `PR #${pr}'s`} — a conflict hold goes on the held PR's own row`);
750
+ if (!lenient) {
751
+ throw new LedgerError(`${where}: '${tok}' names PR #${c[1]}, but this row is ${pr === null ? "no PR's" : `PR #${pr}'s`} — a conflict hold goes on the held PR's own row`);
752
+ }
753
+ malformed.add(i);
754
+ } else {
755
+ // A fresh hold is unresolved whatever settled before it, the way a
756
+ // fresh `reviewed=` resets `reviewFixed` above. A redundant re-hold
757
+ // (merge-bot retrying a PR it has already held) changes
758
+ // nothing a live fix-applier holds off: liveness is not read off
759
+ // token order.
760
+ st.conflictOpen = true;
714
761
  }
715
- // A fresh hold is unresolved whatever settled before it, the way a
716
- // fresh `reviewed=` resets `reviewFixed` above. A redundant re-hold
717
- // (merge-bot retrying a PR it has already held) changes
718
- // nothing a live fix-applier holds off: liveness is not read off
719
- // token order.
720
- st.conflictOpen = true;
721
762
  }
722
763
  const v = TIER_VERDICT.exec(tok);
723
764
  if (v) verdicts[v[1]].add(v[2]);
@@ -741,6 +782,20 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
741
782
  }
742
783
  if (pr !== null) byPr.set(pr, st);
743
784
  }
785
+ return { members, byPr, verdicts, claimed, excluded, malformed };
786
+ }
787
+
788
+ // A PR whose latest finisher halted `past-pin` against a returned review owes
789
+ // a fresh one while its head is still past what that review read: a
790
+ // `reviewed=` head (7-40 hex) prefix-matching gh's full headRefOid is the head
791
+ // that review read, and there is nothing more to review. `st` is a `byPr`
792
+ // state, `undefined` for a PR no row names.
793
+ export const pastPinDue = (st, head) => st !== undefined && st.pastPinHalt && !st.inFlight && st.reviewedHead !== null
794
+ && !String(head).toLowerCase().startsWith(st.reviewedHead);
795
+
796
+ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(), finished = new Set()) {
797
+ const open = new Set(prs.map((p) => p.number));
798
+ const { members, byPr, verdicts, claimed, excluded } = foldLedger({ rows, dispatched }, open);
744
799
 
745
800
  const all = [...members.values()];
746
801
  const live = (family) => all.filter((m) => m.family === family && m.outcome === null).length;
@@ -797,11 +852,6 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
797
852
  const retry = parseMember(cur.member).retry ?? "";
798
853
  return ![...st.fixLanded].some((n) => !st.conflictLanded.has(n) && (parseMember(n).retry ?? "") > retry);
799
854
  };
800
- // The halt holds only while the head is still past what was reviewed: a
801
- // `reviewed=` head (7-40 hex) prefix-matching gh's full headRefOid is the
802
- // head that review read, and there is nothing more to review.
803
- const pastPinDue = (st, head) => st !== undefined && st.pastPinHalt && !st.inFlight && st.reviewedHead !== null
804
- && !String(head).toLowerCase().startsWith(st.reviewedHead);
805
855
  // A `review=` token with no `reviewed=` after it reads as in flight, and the
806
856
  // ledger alone never says otherwise: a review whose own `reviewed=` write
807
857
  // never landed stays in flight after its PR merges, holding a reviewer slot
@@ -748,11 +748,33 @@ wt_count_pair() {
748
748
  wt_count_linked || return 1
749
749
  }
750
750
 
751
+ # Read the `gitdir` back-link of the admin dir $1 into `$wt_bl_back`: the
752
+ # worktree directory it names, made absolute against $1 when it is relative.
753
+ # 0 read; 1 the file could not be read. `$wt_bl_rel` holds the path as
754
+ # written, so a caller can tell an empty file from a path.
755
+ wt_read_backlink() {
756
+ if ! wt_bl_back=$(cat "$1/gitdir" 2>/dev/null && echo x); then
757
+ return 1
758
+ fi
759
+ # `cat` adds no newline of its own, so the sentinel alone comes off, then
760
+ # the one newline git writes after the path, if it is there.
761
+ wt_bl_back=${wt_bl_back%x}
762
+ wt_bl_back=${wt_bl_back%"
763
+ "}
764
+ wt_bl_back=${wt_bl_back%/.git}
765
+ wt_bl_rel=$wt_bl_back
766
+ case $wt_bl_back in
767
+ /*) ;;
768
+ *) wt_bl_back=$1/$wt_bl_back ;;
769
+ esac
770
+ }
771
+
751
772
  # Is any fleet worktree standing with its registration removed under it? 0
752
773
  # when none is; 1 with `$wt_why` naming the first `.worktrees/*` pointer git
753
- # does not list that names an admin dir the registry does not hold, or that
754
- # could not be read. Reads `$wt_list` for the main checkout and the listed
755
- # paths, and `$wt_root` for the registry, both as `wt_count_pair` left them.
774
+ # does not list that names an admin dir the registry does not hold, that
775
+ # names one whose registration is now another worktree's, or that could not
776
+ # be read. Reads `$wt_list` for the main checkout and the listed paths, and
777
+ # `$wt_root` for the registry, both as `wt_count_pair` left them.
756
778
  #
757
779
  # The counts cannot see this: git lists a linked worktree only from its admin
758
780
  # dir, so a registry `rm -rf`'d whole, or one entry removed, drops the entry
@@ -780,10 +802,30 @@ wt_count_pair() {
780
802
  # directory, pointer or named admin dir that cannot be read is a refusal: what
781
803
  # it names is unknown, and unknown is never "registered".
782
804
  #
805
+ # An unlisted directory whose pointer names a held admin dir of its own name is
806
+ # asked one more question, because that registration may have been reissued: the
807
+ # worktree was orphaned, and a later `git worktree add` of another worktree of
808
+ # the same basename took the id. Its branch then reads as held by nothing, and
809
+ # the admin dir answers for a live worktree elsewhere. The admin dir's `gitdir`
810
+ # back-link says whose it is now: a target that exists and is not this
811
+ # directory is a refusal; one that does not exist is a repo moved without `git
812
+ # worktree repair`, which git still holds through the registration's HEAD, but
813
+ # only where its nearest existing ancestor can be searched, since a target
814
+ # that cannot be stat'ed is unknown, not absent, and is a refusal too; and
815
+ # one that is this directory spelled another way (`-ef`) is the registration
816
+ # itself. A directory whose name is not its admin dir's id is a copy, skipped
817
+ # unanswered: a copy and a reissued id read the same through the back-link
818
+ # (another worktree's, that git lists), so the names are the only signal, git
819
+ # taking an id from the basename it was given.
820
+ #
783
821
  # Ceilings, left open on purpose. A `.worktrees` directory that cannot be
784
822
  # listed is skipped, not refused: every worktree in it that git still lists is
785
823
  # answered by the caller's own guards, each with its own remedy, and an
786
824
  # unlisted one behind it needs that fault and a removed registry entry at once.
825
+ # An orphan whose original id carried a number, `1-held1` for a worktree named
826
+ # `1-held`, is not caught: reissuing that id needs a new worktree with the
827
+ # literal basename `1-held1`, so the directory's own name and the registration's
828
+ # differ, and it reads as a copy.
787
829
  # And only `.worktrees/*` itself is read, the depth claim-ticket.sh creates
788
830
  # worktrees at: one nested deeper (`.worktrees/feature/x`) is not, since
789
831
  # reaching it means walking every directory under `.worktrees/` that holds no
@@ -866,6 +908,44 @@ worktree $wt_cp_wt
866
908
  wt_why="worktree pointer $wt_cp_ptr names admin dir $wt_cp_admin, an empty directory git does not list — git lists no worktree there, so no absence it reports can be trusted; inspect the directory and, once its work is saved, remove it by hand"
867
909
  return 1
868
910
  fi
911
+ # Past here the pointer names a registration that is held. A COPY of a
912
+ # worktree directory carries a pointer naming an admin dir git still
913
+ # lists for the ORIGINAL, and so does a directory whose registration was
914
+ # reissued: the admin dir's back-link is another worktree's in both. Only
915
+ # the names tell them apart. Git takes an id from the basename passed to
916
+ # `git worktree add`, so an id can be reissued only to a worktree of that
917
+ # same basename; a directory whose own name is not its admin dir's id is a
918
+ # copy and is skipped.
919
+ [ "${wt_cp_admin##*/}" = "${wt_cp_wt##*/}" ] || continue
920
+ # Git drops an admin dir with no readable back-link from its listing, and
921
+ # the counts refuse on that; this refusal covers only a fault landing
922
+ # between the listing and this read.
923
+ if ! wt_read_backlink "$wt_cp_admin" || [ -z "$wt_bl_rel" ]; then
924
+ wt_why="worktree pointer $wt_cp_ptr names admin dir $wt_cp_admin, whose gitdir back-link could not be read, so which worktree it is registered for is unknown; inspect the directory and, once its work is saved, remove it by hand"
925
+ return 1
926
+ fi
927
+ # A back-link to nothing is a repo moved without `git worktree repair`:
928
+ # git still holds the branch through that registration's HEAD. A target
929
+ # that cannot be stat'ed is not a target that is absent: if the nearest
930
+ # ancestor that exists is a directory that cannot be searched, what
931
+ # the back-link names is unknown, and unknown is never "moved".
932
+ if ! [ -e "$wt_bl_back" ]; then
933
+ wt_cp_up=${wt_bl_back%/*}
934
+ while [ -n "$wt_cp_up" ] && ! [ -e "$wt_cp_up" ]; do
935
+ wt_cp_up=${wt_cp_up%/*}
936
+ done
937
+ if ! [ -d "${wt_cp_up:-/}" ] || [ -x "${wt_cp_up:-/}" ]; then continue; fi
938
+ wt_why="could not look up the worktree $wt_bl_back that admin dir $wt_cp_admin is registered for (${wt_cp_up:-/} cannot be searched), so whether its registration is reissued is unknown"
939
+ return 1
940
+ fi
941
+ # shellcheck disable=SC3013,SC2319 # -ef as above; the else's $? is the `[ -ef ]` test's own rc
942
+ if [ "$wt_bl_back" -ef "$wt_cp_wt" ]; then continue; else wt_cp_rc=$?; fi
943
+ if [ "$wt_cp_rc" -ge 2 ]; then
944
+ wt_why="could not compare the worktree $wt_bl_back that admin dir $wt_cp_admin is registered for with $wt_cp_wt (test -ef exited $wt_cp_rc), so whether its registration is reissued is unknown"
945
+ return 1
946
+ fi
947
+ wt_why="worktree pointer $wt_cp_ptr names admin dir $wt_cp_admin, whose registration is now another worktree's ($wt_bl_back) — git lists no worktree at $wt_cp_wt, so its branch is held by nothing; inspect the directory and, once its work is saved, remove it by hand"
948
+ return 1
869
949
  done
870
950
  return 0
871
951
  }
@@ -884,7 +964,8 @@ worktree $wt_cp_wt
884
964
  # 1: refused — `$wt_why` names the cause: the common directory or the
885
965
  # registry could not be read, the listing could not be counted, the
886
966
  # counts still disagree, or a `.worktrees/*` pointer names an admin dir the
887
- # registry does not hold (`wt_count_pointers`). A standing disagreement is
967
+ # registry does not hold or whose registration is now another worktree's
968
+ # (`wt_count_pointers`). A standing disagreement is
888
969
  # named by the DIRECTION observed. FEWER listed than registered is git
889
970
  # dropping an entry it could not read — the fault this check exists to
890
971
  # catch. MORE listed than registered is the reverse, the registry read
@@ -1072,20 +1153,11 @@ EOF
1072
1153
  wt_why="$1 is a symbolic link through which git could not report its admin dir, so which worktree it stands for is unknown${wt_lk_err:+: $wt_lk_err}"
1073
1154
  return 1
1074
1155
  fi
1075
- if ! wt_lk_back=$(cat "${wt_lk_admin%?x}/gitdir" 2>/dev/null && echo x); then
1156
+ if ! wt_read_backlink "${wt_lk_admin%?x}"; then
1076
1157
  wt_why="$1 is a symbolic link whose admin dir's gitdir back-pointer could not be read, so which worktree it stands for is unknown"
1077
1158
  return 1
1078
1159
  fi
1079
- # `cat` adds no newline of its own, so the sentinel alone comes off, then
1080
- # the one newline git writes after the path, if it is there.
1081
- wt_lk_back=${wt_lk_back%x}
1082
- wt_lk_back=${wt_lk_back%"
1083
- "}
1084
- wt_lk_back=${wt_lk_back%/.git}
1085
- case $wt_lk_back in
1086
- /*) ;;
1087
- *) wt_lk_back=${wt_lk_admin%?x}/$wt_lk_back ;;
1088
- esac
1160
+ wt_lk_back=$wt_bl_back
1089
1161
  case $1 in
1090
1162
  */*) wt_lk_up=${1%/*} ;;
1091
1163
  *) wt_lk_up=. ;;