@feigi/fleet-ctl 3.138.0 → 3.139.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.138.0",
3
+ "version": "3.139.0",
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": {
@@ -276,12 +276,26 @@ in_progress=$(node "$script_dir/label-map.mjs" show in-progress) \
276
276
 
277
277
  if [ "$apply" = false ]; then
278
278
  echo "$NAME: DRY RUN — nothing created. Pass --apply to act." >&2
279
+ printf ' would: git config --remove-section branch.%s — if one is left under that name\n' "$branch" >&2
279
280
  echo " would: gh issue edit $issue --add-label $in_progress" >&2
280
281
  printf ' would: git worktree add --no-track %s -b %s origin/main\n' "$wt" "$branch" >&2
281
282
  printf ' would: (cd %s && %s)\n' "$wt" "$install" >&2
282
283
  printf ' would: write %s and add it to .git/info/exclude — skipped if %s is\n' "$runner" "$runner" >&2
283
284
  printf ' already present, a repo-local runner checked out with the worktree\n' >&2
284
285
  else
286
+ # The branch does not exist yet (refused above), so any `[branch "$branch"]`
287
+ # config under its name is a leftover from an earlier branch of that name:
288
+ # `git update-ref -d` removes a ref and nothing else, and `git worktree add
289
+ # --no-track -b` does not clear what is there. Left in place, the new branch
290
+ # inherits the old upstream — a remote ref that no longer exists — and reads
291
+ # `[gone]` from its first moment, which is what reap.sh selects on. Before
292
+ # the label, for the reason the stamp is derived before it: a refusal here
293
+ # has nothing to clean up. A section that cannot be removed is a refusal,
294
+ # since claiming past it is the defect.
295
+ printf '$ git config --remove-section branch.%s\n' "$branch" >&2
296
+ wt_clear_branch_config "$branch" ||
297
+ die "could not remove the leftover config of branch.$branch — $wt_err"
298
+
285
299
  echo "\$ gh issue edit $issue --add-label $in_progress" >&2
286
300
  gh issue edit "$issue" --add-label "$in_progress" >/dev/null || die "could not label issue $issue"
287
301
 
@@ -16,7 +16,10 @@
16
16
  // deletes the pending file. A crash between the write and the delete leaves
17
17
  // rows the next drain finds already there, so a second run changes nothing.
18
18
  // A corpus written before a column the pending file carries — one the row
19
- // grammar names — gains that column, blank on every row it already holds.
19
+ // grammar names, `objective`, `parent`, `named_paths`, `named_lines`, `dirs`,
20
+ // `title` or `plugin_version` — gains that column, blank on every row it
21
+ // already holds. A pending file begun before one of them drains its rows
22
+ // blank in it.
20
23
  // A pending file that is empty, or blank lines only, is removed with its own
21
24
  // line: an append created it and never wrote.
22
25
  // The drain takes no lock by design: it assumes only the run's controller
@@ -91,7 +94,7 @@ import { COLUMNS as MEMBER_COLUMNS, ENDINGS, isImplementer, parseTsv as parseMem
91
94
  import { blobId } from "./pr-cost.mjs";
92
95
  import { FEATURE_COLUMNS, parseFeatures } from "./pull-attribution.mjs";
93
96
  import { REPORT_STATUSES } from "./report-files.mjs";
94
- import { DEFAULT_TABLE, fitTable, readGuard, validateTable } from "./ticket-router.mjs";
97
+ import { DEFAULT_TABLE, INSTALL_PACKAGE, fitTable, installVersion, readGuard, validateTable } from "./ticket-router.mjs";
95
98
  import { parseTierOutcomes } from "./tier-outcomes.mjs";
96
99
 
97
100
  const NAME = "metrics-refresh";
@@ -103,8 +106,6 @@ const TIERS = join("docs", "metrics", "tier-outcomes.tsv");
103
106
  const CORPUS = [MEMBERS, TIERS, FEATURES];
104
107
  const GUARD = join(".fleet", "cost-guard.json");
105
108
  const PREVIEW = join(".fleet", "router-preview.json");
106
- // The install's own package.json, whose `version` names the prior.
107
- const PACKAGE = fileURLToPath(new URL("../package.json", import.meta.url));
108
109
  // pr-cost.mjs --guard: 0 no cell tripped, 3 a cell tripped, 4 no verdict yet —
109
110
  // all three are verdicts its readers consume; anything else is a failure.
110
111
  const GUARD_VERDICT_EXITS = new Set([0, 3, 4]);
@@ -275,23 +276,12 @@ function costGuard(repo) {
275
276
  return g;
276
277
  }
277
278
 
278
- // The install's `package.json` `version`, or null when it names none or cannot be read:
279
- // the prior is named by it, and the fit does not need it.
280
- function installVersion(path) {
281
- try {
282
- const v = JSON.parse(readFileSync(path, "utf8"))?.version;
283
- return typeof v === "string" ? v : null;
284
- } catch {
285
- return null;
286
- }
287
- }
288
-
289
279
  // The Preview fit over `repo`'s working-tree TSVs and `written`, the guard file the
290
280
  // guard duty just wrote (parsed), with the router table at `tablePath` as its
291
281
  // prior, written to `.fleet/router-preview.json` through a temp file and a
292
282
  // rename. Throws on anything it cannot read, fit or write, before the rename, so
293
283
  // the old file stays as it was.
294
- export function writePreview(repo, written, { tablePath = DEFAULT_TABLE, packagePath = PACKAGE, now = new Date() } = {}) {
284
+ export function writePreview(repo, written, { tablePath = DEFAULT_TABLE, packagePath = INSTALL_PACKAGE, now = new Date() } = {}) {
295
285
  const guard = readGuard(written);
296
286
  if (guard === null) throw new Error(`${GUARD} is not a guard the router reads`);
297
287
  let prior;
@@ -88,16 +88,23 @@ import { parseMemberName } from "./member-record.mjs";
88
88
  import { isImplementer } from "./member-outcomes.mjs";
89
89
  import { DATE, isDerivedNote, rulingFor, rulingsByTicket } from "./tier-outcomes.mjs";
90
90
 
91
- // The ticket-features row, one per Pull, in this order. `objective` and
92
- // `parent` came last and are optional on read: a file whose header lacks
93
- // either reads it blank. `parent` is a Slice's parent issue number, blank for
94
- // a ticket that is no Slice (ticket-router.mjs's sliceParent).
91
+ // The ticket-features row, one per Pull, in this order. `objective`, `parent`
92
+ // and every column after them came last and are optional on read: a file whose
93
+ // header lacks one reads it blank. `parent` is a Slice's parent issue number,
94
+ // blank for a ticket that is no Slice (ticket-router.mjs's sliceParent).
95
+ // `named_paths` is the paths the brief names (ticket-text.mjs's briefPaths),
96
+ // space-separated as named; `named_lines` one entry per path, aligned: the
97
+ // file's line count, `dir` for a directory, `-` for a path that does not exist
98
+ // or lies outside the checkout; `dirs` the number of distinct directories they
99
+ // span. Those three are blank when the brief names no path. `title` is the
100
+ // issue's title, and `plugin_version` the install's `package.json` `version`.
95
101
  export const FEATURE_COLUMNS = Object.freeze([
96
102
  "run_date", "session", "agent", "ticket", "policy_cell", "chosen_cell", "exploration_draw",
97
103
  "sizing_src", "sizing_pre", "router_usd", "brief_chars", "criteria", "comments", "age_days",
98
104
  "paths", "test_paths", "xrefs", "kind", "objective", "parent",
105
+ "named_paths", "named_lines", "dirs", "title", "plugin_version",
99
106
  ]);
100
- export const OPTIONAL_COLUMNS = new Set(["objective", "parent"]);
107
+ export const OPTIONAL_COLUMNS = new Set(FEATURE_COLUMNS.slice(FEATURE_COLUMNS.indexOf("objective")));
101
108
 
102
109
  // The quality floor's margin, in points of fail rate.
103
110
  export const TRIP_POINTS = 15;
package/scripts/pull.mjs CHANGED
@@ -141,7 +141,7 @@ import { isCLI } from "./is-cli.mjs";
141
141
  import { LabelMapUnreadable, readLabelMap } from "./label-map.mjs";
142
142
  import { EXCLUDED_REASON, POLICY_CELL, memberTokens, parseRouting, premisesOf, pullEnded, tierValues } from "./ledger-grammar.mjs";
143
143
  import { sessionFromReceipt } from "./phase0-receipt.mjs";
144
- import { briefPaths, briefText, defang, outOfScope, strandedRuling, ticketText } from "./ticket-text.mjs";
144
+ import { LINE_REF, briefPaths, briefText, defang, outOfScope, strandedRuling, ticketText } from "./ticket-text.mjs";
145
145
 
146
146
  const NAME = "pull";
147
147
  const SCRIPTS = dirname(fileURLToPath(import.meta.url));
@@ -251,8 +251,6 @@ export function issueRefs(section) {
251
251
 
252
252
  // ── the collision scan ───────────────────────────────────────────────────────
253
253
 
254
- // A brief path's trailing line reference, `:N` or `:N-M`.
255
- const LINE_REF = /:(\d+)(?:-(\d+))?$/;
256
254
  const MARKDOWN = /\.(md|markdown|mdx)$/i;
257
255
  // The byte each one-letter escape of a C-quoted diff path stands for.
258
256
  const ESC = { n: 10, t: 9, '"': 34, "\\": 92, a: 7, b: 8, f: 12, r: 13, v: 11 };
@@ -1335,6 +1335,7 @@ if [ "$apply" = false ]; then
1335
1335
  [ "$has_label" = true ] && echo " would: gh issue edit $issue --remove-label $in_progress" >&2
1336
1336
  [ -n "$wt" ] && printf ' would: git worktree remove %s\n' "$wt" >&2
1337
1337
  [ "$has_branch" = true ] && echo " would: git update-ref -d refs/heads/$branch <its current tip>" >&2
1338
+ [ "$has_branch" = true ] && echo " would: git config --remove-section branch.$branch — if one is left behind" >&2
1338
1339
  if [ "$closed_pr" = true ]; then
1339
1340
  echo " PR states on $branch:$pr_seen" >&2
1340
1341
  echo " would: git push origin --delete refs/heads/$branch (origin read at $remote_sha)" >&2
@@ -1476,6 +1477,21 @@ else
1476
1477
  ;;
1477
1478
  *) halt "$branch $wt_restore_why — branch restored, not deleted" ;;
1478
1479
  esac
1480
+
1481
+ # The `[branch "$branch"]` config section, which `git update-ref -d` leaves
1482
+ # behind and `git branch -D` would have removed with the ref. Left, a later
1483
+ # claim of the same name inherits the upstream and reads `[gone]` at once,
1484
+ # and reap.sh then removes the live claim (claim-ticket.sh clears it too;
1485
+ # this is the deleter cleaning up after itself, as reap.sh's delete does).
1486
+ # The ref is already gone and the release otherwise complete, so a section
1487
+ # that stays is a note on stderr and never a halt — the housekeeping
1488
+ # `git worktree prune` below is the same shape. Unlike reap.sh, which also
1489
+ # puts that note in its stdout `warnings`, the receipt has no field for it:
1490
+ # the next claim of the name removes the section itself, and refuses when
1491
+ # it cannot. A claim that never pushed has no section, and that is not a
1492
+ # fault: `wt_clear_branch_config` tells the two apart.
1493
+ wt_clear_branch_config "$branch" ||
1494
+ echo "$NAME: $branch deleted, but its branch config section was left: $wt_err" >&2
1479
1495
  done_branch=true
1480
1496
  fi
1481
1497
 
@@ -14,9 +14,11 @@
14
14
  // REASON=<reason>`,
15
15
  // routing by the objective's row set, and appends the Pull's
16
16
  // ticket-features row to the pending TSV (by default
17
- // `ticket-features.pending.tsv` beside `--guard`, in the run's `.fleet/`). Exit 0 on
18
- // every data degradation — a missing or unreadable issue, sizing or guard
19
- // file degrades the line, never the exit. Exit 2 only on a usage error or
17
+ // `ticket-features.pending.tsv` beside `--guard`, in the run's `.fleet/`).
18
+ // The paths its brief names are looked up under the working directory,
19
+ // the checkout, for `named_lines`. Exit 0 on every data degradation — a
20
+ // missing or unreadable issue, sizing or guard file degrades the line,
21
+ // never the exit. Exit 2 only on a usage error or
20
22
  // an unreadable/invalid table: the caller does not dispatch then. With no
21
23
  // `--session`, the session is the one the phase-0 receipt
22
24
  // `.fleet/phase0.json` records, and with no `--objective` the objective
@@ -43,9 +45,9 @@
43
45
  // the guard are files the caller wrote, and a fitted commit is fetched by the
44
46
  // caller.
45
47
 
46
- import { readFileSync, writeFileSync, renameSync, appendFileSync, mkdirSync, statSync } from "node:fs";
48
+ import { readFileSync, writeFileSync, renameSync, appendFileSync, mkdirSync, statSync, realpathSync } from "node:fs";
47
49
  import { spawnSync } from "node:child_process";
48
- import { basename, dirname, join, resolve } from "node:path";
50
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
49
51
  import { fileURLToPath } from "node:url";
50
52
  import { isDeepStrictEqual } from "node:util";
51
53
  import { isCLI } from "./is-cli.mjs";
@@ -58,11 +60,13 @@ import {
58
60
  AttributionError, FEATURE_COLUMNS, OPTIONAL_COLUMNS, TRIP_POINTS, attribute, bootUnit, bootstrapDiffCI, generations, parseFeatures, tally, underFloor,
59
61
  } from "./pull-attribution.mjs";
60
62
  import { RulingError, parseTierOutcomes } from "./tier-outcomes.mjs";
61
- import { briefPaths, briefText } from "./ticket-text.mjs";
63
+ import { LINE_REF, briefPaths, briefText } from "./ticket-text.mjs";
62
64
 
63
65
  const NAME = "ticket-router";
64
66
  const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
65
67
  export const DEFAULT_TABLE = join(SCRIPT_DIR, "router-table.json");
68
+ // The install's own package.json, whose `version` names the plugin a Pull was routed by.
69
+ export const INSTALL_PACKAGE = join(SCRIPT_DIR, "..", "package.json");
66
70
 
67
71
  // The free classifier's thresholds: heavy past the median brief length of
68
72
  // the tickets whose sizing verdict is known, or past five criteria.
@@ -109,6 +113,25 @@ export function sliceParent(body) {
109
113
  return ref === null ? "" : ref[1] ?? ref[2];
110
114
  }
111
115
 
116
+ /** The install's `package.json` `version`, or null when it names none or cannot be read. */
117
+ export function installVersion(path = INSTALL_PACKAGE) {
118
+ try {
119
+ const v = JSON.parse(readFileSync(path, "utf8"))?.version;
120
+ return typeof v === "string" ? v : null;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+
126
+ // The directory a brief path names: its parent once a line reference and any
127
+ // trailing `/` are dropped, or the path itself when it ended in `/`; `.` for a
128
+ // bare filename.
129
+ function pathDir(token) {
130
+ const t = token.replace(LINE_REF, "");
131
+ const q = t.replace(/\/+$/, "");
132
+ return posix.normalize(q === t ? posix.dirname(q) : q || "/");
133
+ }
134
+
112
135
  /** The metric columns for a parsed `gh issue view --json title,body,comments,labels,createdAt`, or null when it is not one. */
113
136
  export function issueMetrics(issue, now = Date.now()) {
114
137
  if (issue === null || typeof issue !== "object" || Array.isArray(issue) || typeof issue.body !== "string") return null;
@@ -127,9 +150,64 @@ export function issueMetrics(issue, now = Date.now()) {
127
150
  xrefs: String(new Set([...brief.matchAll(/#(\d+)/g)].map((m) => m[1])).size),
128
151
  kind,
129
152
  parent: sliceParent(issue.body),
153
+ // briefPaths' tokens hold no whitespace, so one space separates them unambiguously.
154
+ named_paths: paths.join(" "),
155
+ dirs: paths.length === 0 ? "" : String(new Set(paths.map(pathDir)).size),
156
+ title: typeof issue.title === "string" ? issue.title : "",
130
157
  };
131
158
  }
132
159
 
160
+ // Whether `abs` is `root` or lies below it. Posix `relative` resolves both
161
+ // first and never answers with an absolute path.
162
+ function within(root, abs) {
163
+ const r = relative(root, abs);
164
+ return r !== ".." && !r.startsWith(`..${sep}`);
165
+ }
166
+
167
+ // One `named_lines` entry: a line reference dropped, the path resolved against
168
+ // `root`, absolute, whose realpath is `realRoot`. One that is absolute, starts
169
+ // with `~` or lies outside `root` — as spelled, or once its symlinks are
170
+ // followed — is `-` and never read; so is one that does not exist, a file
171
+ // named with a trailing `/`, or one that is neither a file nor a directory.
172
+ function lineEntry(token, root, realRoot) {
173
+ const t = token.replace(LINE_REF, "");
174
+ if (isAbsolute(t) || t.startsWith("~")) return "-";
175
+ const at = join(root, t);
176
+ if (!within(root, at)) return "-";
177
+ try {
178
+ const real = realpathSync(at);
179
+ if (!within(realRoot, real)) return "-";
180
+ // `at`, not `real`: realpath drops a trailing `/`, which stat keeps, so a
181
+ // file named as a directory is ENOTDIR here.
182
+ const st = statSync(at);
183
+ if (st.isDirectory()) return "dir";
184
+ if (!st.isFile()) return "-";
185
+ const bytes = readFileSync(real);
186
+ let n = 0;
187
+ for (const b of bytes) if (b === 0x0a) n += 1;
188
+ return String(bytes.length > 0 && bytes[bytes.length - 1] !== 0x0a ? n + 1 : n);
189
+ } catch {
190
+ return "-";
191
+ }
192
+ }
193
+
194
+ /**
195
+ * The `named_lines` value for `named`, a `named_paths` value, resolved against
196
+ * the checkout `root`: per path, aligned and space-separated, the file's line
197
+ * count (its `\n`s, plus one when its last line has none), `dir` for a
198
+ * directory, `-` for anything else (lineEntry). Blank when `named` is.
199
+ */
200
+ export function namedLines(named, root) {
201
+ if (named === "") return "";
202
+ const paths = named.split(" ");
203
+ let realRoot;
204
+ // A root that cannot be resolved — null when the CLI's working directory is
205
+ // gone — reads every path `-`.
206
+ try { realRoot = realpathSync(root); } catch { return paths.map(() => "-").join(" "); }
207
+ const abs = resolve(root);
208
+ return paths.map((p) => lineEntry(p, abs, realRoot)).join(" ");
209
+ }
210
+
133
211
  /**
134
212
  * The `rule` classifier, over a row's metric columns: blank metrics are
135
213
  * `unknown`, a Slice (a row with a `parent`) is `heavy`, and any other row is
@@ -280,21 +358,28 @@ export function sessionDate(session) {
280
358
  }
281
359
 
282
360
  /**
283
- * One Pull's routing, by `objective`'s row set. Pure: every input is already
284
- * read. The exploration draw ignores the objective: it leaves out the cell
361
+ * One Pull's routing, by `objective`'s row set. Every input is already read
362
+ * but the paths the brief names, which `named_lines` reads under `root`, the
363
+ * checkout. `version` is the install's, `plugin_version` on the row. The
364
+ * exploration draw ignores the objective: it leaves out the cell
285
365
  * the `cost` set routes the Pull to — by the sizing when arm B is live for
286
366
  * the `cost` set, whichever set routes the Pull — so a Pull draws the same
287
367
  * cell under both.
288
368
  * @returns {{ line: string, row: Record<string,string> }}
289
369
  */
290
- export function route({ session, ticket, arm, implRow, chainHead = false, issue, sizing = null, guard, table, objective, now = Date.now() }) {
370
+ export function route({
371
+ session, ticket, arm, implRow, chainHead = false, issue, sizing = null, guard, table, objective, now = Date.now(),
372
+ root = process.cwd(), version = installVersion(),
373
+ }) {
291
374
  let reason = null;
292
375
  const degrade = (r) => { reason ??= r; };
293
376
 
294
377
  const metrics = issueMetrics(issue, now);
295
378
  if (metrics === null) degrade("no-issue-json");
296
- const blank = Object.fromEntries(["brief_chars", "criteria", "comments", "age_days", "paths", "test_paths", "xrefs", "kind", "parent"].map((c) => [c, ""]));
297
- const m = metrics ?? blank;
379
+ const blank = Object.fromEntries(FEATURE_COLUMNS
380
+ .slice(FEATURE_COLUMNS.indexOf("brief_chars"), FEATURE_COLUMNS.indexOf("plugin_version"))
381
+ .filter((c) => c !== "objective").map((c) => [c, ""]));
382
+ const m = metrics === null ? blank : { ...metrics, named_lines: namedLines(metrics.named_paths, root) };
298
383
  const ruleS = ruleStratum(m);
299
384
 
300
385
  let stratum = ruleS;
@@ -345,7 +430,7 @@ export function route({ session, ticket, arm, implRow, chainHead = false, issue,
345
430
  const row = {
346
431
  run_date: sessionDate(session), session, agent: `impl-${ticket}`, ticket: String(ticket),
347
432
  policy_cell: policy, chosen_cell: cell, exploration_draw: draw === null ? "" : `${draw.k}/${draw.K}`,
348
- sizing_src: sizingSrc, sizing_pre: sizingPre, router_usd: routerUsd, ...m, objective,
433
+ sizing_src: sizingSrc, sizing_pre: sizingPre, router_usd: routerUsd, ...m, objective, plugin_version: version ?? "",
349
434
  };
350
435
  const line = formatRouting({
351
436
  policy, cell, draw, by, stratum,
@@ -754,9 +839,17 @@ function main() {
754
839
  } else if (!OBJECTIVES.includes(objective)) {
755
840
  die(`--objective ${objective} is not ${OBJECTIVES.join(" or ")}`);
756
841
  }
842
+ // A working directory removed under the run, or an install `package.json`
843
+ // with no readable version, degrades the row and warns, never the exit.
844
+ let root = null;
845
+ try { root = process.cwd(); } catch (e) {
846
+ process.stderr.write(`${NAME}: WARNING cannot resolve the working directory: ${e.message} — every named path reads \`-\`\n`);
847
+ }
848
+ const version = installVersion();
849
+ if (version === null) process.stderr.write(`${NAME}: WARNING ${INSTALL_PACKAGE} names no readable version — plugin_version is blank\n`);
757
850
  const { line, row } = route({
758
851
  session, ticket: Number(ticket), arm, implRow: Number(implRowArg), chainHead: F.has("chain-head"),
759
- issue: readJson(issuePath), sizing: readJson(F.arg("sizing")), guard: readGuard(readJson(guardPath)), table, objective,
852
+ issue: readJson(issuePath), sizing: readJson(F.arg("sizing")), guard: readGuard(readJson(guardPath)), table, objective, root, version,
760
853
  });
761
854
  const pending = F.arg("pending") ?? join(dirname(guardPath), "ticket-features.pending.tsv");
762
855
  // The header decision and the append are not atomic and take no lock. That is
@@ -75,6 +75,9 @@ export function defang(text, names) {
75
75
  return names.reduce((t, n) => t.split(`<${n}>`).join(`‹${n}›`), text);
76
76
  }
77
77
 
78
+ /** A brief path's trailing line reference, `:N` or `:N-M`. */
79
+ export const LINE_REF = /:(\d+)(?:-(\d+))?$/;
80
+
78
81
  /**
79
82
  * The file paths a brief names: every backticked token without whitespace that
80
83
  * holds a `/` or ends in an extension, in first-seen order, each once. The
@@ -1345,3 +1345,49 @@ wt_outcome() {
1345
1345
  fi
1346
1346
  return 0
1347
1347
  }
1348
+
1349
+ # Removes the `[branch "<name>"]` config section of a branch whose ref is gone
1350
+ # or has never existed. `git branch -D` takes the section with the ref;
1351
+ # `git update-ref -d` leaves it, and `git worktree add --no-track -b <name>` of
1352
+ # a later claim under the same name inherits the leftover upstream, which
1353
+ # names a remote ref that no longer exists and so reads `[gone]` at once
1354
+ # (measured, git 2.50.1). Calling it with the ref still present would unset the
1355
+ # live branch's upstream, so while `refs/heads/<name>` exists it removes
1356
+ # nothing and returns 1.
1357
+ #
1358
+ # Returns 0 when no key of that section is left, whether this call removed it
1359
+ # or there was none to remove, and 1 when one remains or the config could not
1360
+ # be read, with `$wt_err` naming the cause. `--remove-section` fails the same
1361
+ # way for a missing section as for a lock it could not take, so its status
1362
+ # cannot tell them apart: the keys are listed afterwards, the way reap.sh's
1363
+ # `branch_keys_left` does, and only a key of this branch's section left behind
1364
+ # is a failure. `${key%.*}` drops the variable name off `branch.<name>.<var>`;
1365
+ # the subsection may itself hold dots and slashes, so a regex built from the
1366
+ # name would misread them. Only the repository's own config file is cleared and
1367
+ # listed (`--local`): a section in an included file or in config.worktree is
1368
+ # neither removed nor reported, and its upstream still applies. Writes
1369
+ # `$wt_err`, and clobbers `$wt_cfg_out`, `$wt_cfg_keys` and `$wt_cfg_k`; call as
1370
+ # a bare `if`/`||` condition, never inside `$( )`.
1371
+ wt_clear_branch_config() {
1372
+ wt_err=
1373
+ if git show-ref --verify --quiet "refs/heads/$1"; then
1374
+ wt_err="branch $1 still exists"
1375
+ return 1
1376
+ fi
1377
+ if wt_cfg_out=$(git config --remove-section "branch.$1" 2>&1); then return 0; fi
1378
+ if wt_cfg_keys=$(git config --local --name-only --get-regexp '^branch\.' 2>&1); then :
1379
+ elif [ "$?" -eq 1 ]; then return 0
1380
+ else
1381
+ wt_err="could not list the branch config keys: $(printf '%s' "$wt_cfg_keys" | tr '\n' ' ')"
1382
+ return 1
1383
+ fi
1384
+ while IFS= read -r wt_cfg_k; do
1385
+ if [ "${wt_cfg_k%.*}" = "branch.$1" ]; then
1386
+ wt_err=$(printf '%s' "$wt_cfg_out" | tr '\n' ' ')
1387
+ return 1
1388
+ fi
1389
+ done <<EOK
1390
+ $wt_cfg_keys
1391
+ EOK
1392
+ return 0
1393
+ }
@@ -72,6 +72,8 @@ So nothing in the run cleans it up. Next run, the in-flight probe's local-worktr
72
72
 
73
73
  **A checkout that lands between that fresh check and the delete halts the release after it.** `git worktree add` of an existing branch does not move the ref, so the compare-and-swap succeeds under it. The same `wt_recheck_delete` reap uses then finds the worktree, recreates the branch at the tip, and the release halts with exit 2, `released:false` and a blocker naming that worktree — the shape of a holder caught before the delete. A restore that fails halts the same way, with the tip and the repair command in the blocker.
74
74
 
75
+ **The branch's config section goes after the delete, as reap's does.** `git update-ref -d` removes the ref and not `[branch "<name>"]`; a later claim of the same name would inherit the dead upstream and read `[gone]` at once. worktree.sh's `wt_clear_branch_config` removes it; a claim that never pushed has none, which is not a fault, and a section that cannot be removed is a note on stderr, never a halt — the ref is already deleted. claim-ticket.sh `--apply` clears the same section before `git worktree add`, since whatever deleted the branch, config under a name no branch holds is leftover; there, a section that cannot be removed refuses the claim.
76
+
75
77
  **`worktree remove` without `--force`** refuses on modified and untracked files and deletes ignored files silently (verified, git 2.50.1). Ignored-silently is what is wanted: `claim-ticket.sh` writes an `agent-test` into each fresh worktree it claims of a repository that tracks none, and ignores it through the repository's exclude file, so treating ignored files as dirt would strand every such release. The same asymmetry is why a claim never writes over a tracked `agent-test`: that write would leave a modified tracked path, which this refusal does not forgive. Its refusal is the dirty check recomputed by git at the moment of the delete — for the live-directory case ONLY. `worktree remove` gates that clean check on the same `stat` the guard does, so it is not an independent second opinion: where the path cannot be stat'ed git reaches the same "gone" by the same means, accepts the entry at rc 0 and deregisters a worktree whose files are still on disk (measured, git 2.50.1: an untracked file in a worktree under a `chmod 000` parent). There the `gone` guard is sole arbiter — which is why it establishes absence instead of inferring it from a failed `-e`, and why the fail-open fixed in `1e54bac` survived being reasoned about: guard and backstop fail on the same inputs.
76
78
 
77
79
  **A worktree that wandered off the branch blocks too.** The worktree is located by the branch it has checked out, and it does not stay there — an interrupted rebase leaves it detached, a member can switch it. The lookup then finds nothing, which reads as "no worktree of ours": the dirty check is skipped entirely and the release reports success while the worktree stands with the member's work in it, so the next run's probe still reads the ticket as taken. So a linked worktree at `claim-ticket.sh`'s `.worktrees/<issue>-<slug>` that is *not* on the branch is its own blocker — which remedy it names is the next paragraph, and is not always a hand-release. The path is read as the whole rest of the `worktree list --porcelain` line, never the first whitespace field, or every checkout under a directory with a space in its name reads as a different path.