@osdlc/repo-cleaner 0.0.0-stage → 0.5.2

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/dist/apply.js ADDED
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Apply an approved cleanup plan.
3
+ *
4
+ * Re-sweeps each repository and drops selected rows that are gone, no longer
5
+ * deletable, changed, or lack a grant. Deletes the rest in a fixed order and
6
+ * stops at the first failure:
7
+ *
8
+ * 1. worktrees, each unlocked first when its lock's owner is dead, and each
9
+ * checked again for live processes just before it is unlocked or removed;
10
+ * 2. local branches;
11
+ * 3. remote branches;
12
+ * 4. one prune per repository.
13
+ *
14
+ * Branch deletes are compare-and-swap on the planned sha. Every step is
15
+ * verified, and the receipt is rewritten after each.
16
+ */
17
+ import { existsSync } from 'node:fs';
18
+ import { resolve } from 'node:path';
19
+ import { CommandFailed, Git } from '@osdlc/typed-git';
20
+ import { localDeleteCommand, remoteDeleteCommand } from "./branches.js";
21
+ import { busyHolders, defaultProcessProbe, parseLockOwner } from "./processes.js";
22
+ import { PLAN_CATEGORIES, fingerprint, isPlanCategory, sameFingerprint, } from "./plan.js";
23
+ import { sweepRepo } from "./sweep.js";
24
+ import { AUTHORIZATIONS } from "./types.js";
25
+ import { worktreePruneCommand, worktreeRemoveCommand, worktreeUnlockCommand } from "./worktrees.js";
26
+ import { writeJsonAtomic } from "./write-json.js";
27
+ /** A selection or grant the plan cannot satisfy. Nothing has been touched. */
28
+ export class ApplyArgumentError extends Error {
29
+ }
30
+ /** `<category>:<id>`, split at the first colon. */
31
+ export function parseRowRef(text) {
32
+ const colon = text.indexOf(':');
33
+ const category = colon < 0 ? '' : text.slice(0, colon);
34
+ const id = colon < 0 ? '' : text.slice(colon + 1);
35
+ if (!isPlanCategory(category) || id === '') {
36
+ throw new ApplyArgumentError(`bad row ${JSON.stringify(text)}: expected <category>:<id> with category one of ${PLAN_CATEGORIES.join(', ')}`);
37
+ }
38
+ return { category, id };
39
+ }
40
+ /** `<name>` for every row, or `<name>=<category>:<id>` for one. */
41
+ export function parseGrant(text) {
42
+ const eq = text.indexOf('=');
43
+ const name = eq < 0 ? text : text.slice(0, eq);
44
+ if (!AUTHORIZATIONS.includes(name)) {
45
+ throw new ApplyArgumentError(`unknown authorization ${JSON.stringify(name)}: expected one of ${AUTHORIZATIONS.join(', ')}`);
46
+ }
47
+ return { name: name, row: eq < 0 ? null : parseRowRef(text.slice(eq + 1)) };
48
+ }
49
+ const sameRow = (a, b) => a.category === b.category && a.id === b.id;
50
+ const label = (row) => `${row.category}:${row.id}`;
51
+ function errorText(err) {
52
+ if (err instanceof CommandFailed)
53
+ return err.detail.trim() || err.message;
54
+ return err instanceof Error ? err.message : String(err);
55
+ }
56
+ /** Each selected row's plan repository. Unknown and ambiguous rows are errors. */
57
+ function locate(plan, rows, repoRoot) {
58
+ const repos = repoRoot === undefined
59
+ ? plan.repos
60
+ : plan.repos.filter((r) => resolve(r.root) === resolve(repoRoot));
61
+ if (repos.length === 0)
62
+ throw new ApplyArgumentError(`no plan repository at ${repoRoot}`);
63
+ return rows.map((ref) => {
64
+ const hits = repos.filter((r) => r.rows.some((row) => sameRow(row, ref)));
65
+ if (hits.length === 0)
66
+ throw new ApplyArgumentError(`row ${label(ref)} is not in the plan`);
67
+ if (hits.length > 1) {
68
+ throw new ApplyArgumentError(`row ${label(ref)} is in ${hits.length} plan repositories; pass --repo-root`);
69
+ }
70
+ return { repo: hits[0], ref };
71
+ });
72
+ }
73
+ function granted(grants, ref, name) {
74
+ return grants.some((g) => g.name === name && (g.row === null || sameRow(g.row, ref)));
75
+ }
76
+ /** The plan repository's rows as they stand now, with the host's overlay applied. */
77
+ function resweep(repo, opts) {
78
+ const sweep = sweepRepo(repo.root, {
79
+ remote: repo.remote,
80
+ noGh: repo.no_gh,
81
+ branch: repo.branch ?? undefined,
82
+ cwd: opts.callerCwd,
83
+ git: opts.git,
84
+ gh: opts.gh,
85
+ probe: opts.probe,
86
+ });
87
+ if (sweep.repo === null || sweep.error !== null) {
88
+ throw new Error(sweep.error ?? `could not read repository: ${repo.root}`);
89
+ }
90
+ return opts.annotate === undefined ? sweep.items : opts.annotate(sweep.repo, sweep.items);
91
+ }
92
+ /** Re-sweep, then split the selection into rows to run and rows dropped. */
93
+ function recheck(selected, grants, opts) {
94
+ const swept = new Map();
95
+ for (const { repo } of selected) {
96
+ if (!swept.has(repo))
97
+ swept.set(repo, resweep(repo, opts));
98
+ }
99
+ const accepted = [];
100
+ const dropped = [];
101
+ for (const { repo, ref } of selected) {
102
+ const drop = (reason, detail) => {
103
+ dropped.push({ repo: repo.root, ...ref, reason, detail });
104
+ };
105
+ const planned = repo.rows.find((row) => sameRow(row, ref));
106
+ const item = swept.get(repo).find((it) => sameRow(it, ref));
107
+ if (item === undefined) {
108
+ drop('gone', 'no longer in the sweep');
109
+ continue;
110
+ }
111
+ if (!item.deletable) {
112
+ drop('not-deletable', item.reason);
113
+ continue;
114
+ }
115
+ const now = fingerprint(item);
116
+ if (!sameFingerprint(planned.fingerprint, now)) {
117
+ drop('facts-changed', `planned ${JSON.stringify(planned.fingerprint)}, now ${JSON.stringify(now)}`);
118
+ continue;
119
+ }
120
+ const missing = item.requires.filter((name) => !granted(grants, ref, name));
121
+ if (missing.length > 0) {
122
+ drop('not-authorized', `needs ${missing.join(', ')}`);
123
+ continue;
124
+ }
125
+ accepted.push({ repo: repo.root, item, force: granted(grants, ref, 'discard-changes') });
126
+ }
127
+ return { accepted, dropped };
128
+ }
129
+ function pending(repo, row, action, command, expectedSha = null) {
130
+ return {
131
+ repo,
132
+ row,
133
+ action,
134
+ command,
135
+ expected_sha: expectedSha,
136
+ result: 'pending',
137
+ error: null,
138
+ verification: null,
139
+ };
140
+ }
141
+ const pruneStep = (repo, row) => pending(repo, row, 'prune-worktrees', worktreePruneCommand(repo));
142
+ function stepsFor({ repo, item, force }) {
143
+ const ref = { category: item.category, id: item.id };
144
+ const sha = typeof item.facts['sha'] === 'string' ? item.facts['sha'] : null;
145
+ switch (item.category) {
146
+ case 'worktree': {
147
+ // Remove and prune both skip a locked worktree, so a stale lock goes first.
148
+ const unlock = item.facts['stale_lock'] === true
149
+ ? [pending(repo, ref, 'unlock-worktree', worktreeUnlockCommand(repo, item.id))]
150
+ : [];
151
+ if (item.facts['on_disk'] === false)
152
+ return [...unlock, pruneStep(repo, ref)];
153
+ return [
154
+ ...unlock,
155
+ pending(repo, ref, 'remove-worktree', worktreeRemoveCommand(repo, item.id, { force })),
156
+ ];
157
+ }
158
+ case 'local_branch':
159
+ return [pending(repo, ref, 'delete-local', localDeleteCommand(item.id, sha ?? ''), sha)];
160
+ case 'remote_branch':
161
+ return [
162
+ pending(repo, ref, 'delete-remote', remoteDeleteCommand(String(item.facts['remote']), String(item.facts['branch']), sha ?? ''), sha),
163
+ ];
164
+ }
165
+ }
166
+ /**
167
+ * Refuse while a process other than an idle shell works inside `path`. Reads
168
+ * the process table afresh; a table that cannot be read refuses too.
169
+ */
170
+ function assertNoLiveProcess(path, probe) {
171
+ let busy;
172
+ try {
173
+ busy = busyHolders(probe.holders(path, { fresh: true }));
174
+ }
175
+ catch (err) {
176
+ throw new Error(`refused: cannot tell whether a process runs in ${path}: ${errorText(err)}`);
177
+ }
178
+ if (busy.length > 0) {
179
+ throw new Error(`refused: running in ${path}: ${busy.map((h) => `${h.command} (pid ${h.pid})`).join(', ')}`);
180
+ }
181
+ }
182
+ /** Run one step, then confirm it took. Throws with the reason on failure. */
183
+ function execute(step, row, git, probe) {
184
+ const at = git.at(step.repo);
185
+ const registered = (path) => at.worktrees().some((w) => resolve(w.path) === resolve(path));
186
+ switch (step.action) {
187
+ case 'unlock-worktree': {
188
+ const path = row.item.id;
189
+ // The sweep that accepted this row is behind us; ask again just before
190
+ // acting, so an owner that came back keeps its lock.
191
+ const lockReason = row.item.facts['lock_reason'];
192
+ const owner = parseLockOwner(typeof lockReason === 'string' ? lockReason : null);
193
+ if (owner === null)
194
+ throw new Error(`refused: lock on ${path} names no owner`);
195
+ if (probe.alive(owner.pid, owner.startedAt)) {
196
+ throw new Error(`refused: lock owner pid ${owner.pid} is alive`);
197
+ }
198
+ if (row.item.facts['on_disk'] !== false)
199
+ assertNoLiveProcess(path, probe);
200
+ at.worktreeUnlock(path);
201
+ const entry = at.worktrees().find((w) => resolve(w.path) === resolve(path));
202
+ if (entry?.locked === true)
203
+ throw new Error(`still locked: ${path}`);
204
+ return 'lock owner dead, unlocked';
205
+ }
206
+ case 'prune-worktrees': {
207
+ at.worktreePrune();
208
+ if (row !== null && registered(row.item.id))
209
+ throw new Error('still registered after prune');
210
+ return row === null ? 'pruned' : 'unregistered';
211
+ }
212
+ case 'remove-worktree': {
213
+ const path = row.item.id;
214
+ assertNoLiveProcess(path, probe);
215
+ at.worktreeRemove(path, { force: row.force });
216
+ if (existsSync(path))
217
+ throw new Error(`directory still exists: ${path}`);
218
+ if (registered(path))
219
+ throw new Error(`still registered: ${path}`);
220
+ return 'directory gone and unregistered';
221
+ }
222
+ case 'delete-local': {
223
+ const name = row.item.id;
224
+ const holder = at.worktrees().find((w) => w.branch === name);
225
+ if (holder !== undefined)
226
+ throw new Error(`refused: checked out in ${holder.path}`);
227
+ at.deleteRef(`refs/heads/${name}`, { expected: step.expected_sha });
228
+ // `update-ref -d` does not remove the `branch.<name>` config section.
229
+ at.configRemoveSection(`branch.${name}`);
230
+ if (at.resolveRef(`refs/heads/${name}`) !== null)
231
+ throw new Error('ref still resolves');
232
+ return 'ref does not resolve';
233
+ }
234
+ case 'delete-remote': {
235
+ const remote = String(row.item.facts['remote']);
236
+ const ref = `refs/heads/${String(row.item.facts['branch'])}`;
237
+ at.push(remote, `:${ref}`, { forceWithLease: { ref, expect: step.expected_sha } });
238
+ if (at.lsRemote(remote, ref).some((r) => r.ref === ref)) {
239
+ throw new Error(`ls-remote still lists ${ref}`);
240
+ }
241
+ return 'ls-remote lists nothing';
242
+ }
243
+ }
244
+ }
245
+ /**
246
+ * Apply the `requested` rows of `plan` under `grants`. A row named twice runs once.
247
+ *
248
+ * @throws ApplyArgumentError before touching anything, when a row or grant does
249
+ * not fit the plan.
250
+ */
251
+ export function applyPlan(plan, requested, grants, opts) {
252
+ const now = opts.now ?? (() => new Date());
253
+ const rows = requested.filter((row, i) => requested.findIndex((other) => sameRow(other, row)) === i);
254
+ if (rows.length === 0)
255
+ throw new ApplyArgumentError('no rows selected');
256
+ const selected = locate(plan, rows, opts.repoRoot);
257
+ for (const grant of grants) {
258
+ if (grant.row !== null && !rows.some((r) => sameRow(r, grant.row))) {
259
+ throw new ApplyArgumentError(`--authorize names unselected row ${label(grant.row)}`);
260
+ }
261
+ }
262
+ const receipt = {
263
+ version: 1,
264
+ plan: opts.planPath,
265
+ status: opts.dryRun ? 'dry-run' : 'applying',
266
+ started_at: now().toISOString(),
267
+ finished_at: null,
268
+ dropped: [],
269
+ steps: [],
270
+ };
271
+ const { accepted, dropped } = recheck(selected, grants, opts);
272
+ receipt.dropped = dropped;
273
+ const ordered = PLAN_CATEGORIES.flatMap((category) => accepted.filter((row) => row.item.category === category));
274
+ const plannedSteps = ordered.flatMap((row) => stepsFor(row).map((step) => [step, row]));
275
+ for (const repo of new Set(ordered.map((row) => row.repo))) {
276
+ plannedSteps.push([pruneStep(repo, null), null]);
277
+ }
278
+ receipt.steps = plannedSteps.map(([step]) => step);
279
+ if (opts.dryRun) {
280
+ for (const step of receipt.steps)
281
+ step.result = 'would-run';
282
+ receipt.finished_at = now().toISOString();
283
+ return receipt;
284
+ }
285
+ const save = () => writeJsonAtomic(opts.receiptPath, receipt);
286
+ save();
287
+ const git = new Git(opts.callerCwd, { runner: opts.git });
288
+ const probe = opts.probe ?? defaultProcessProbe();
289
+ // Worktrees whose lock this run cleared. typed-git has no `worktree lock`
290
+ // verb, so a failed remove cannot put the lock back; the receipt says so.
291
+ const unlocked = new Set();
292
+ for (const [step, row] of plannedSteps) {
293
+ try {
294
+ step.verification = execute(step, row, git, probe);
295
+ step.result = 'ok';
296
+ if (step.action === 'unlock-worktree')
297
+ unlocked.add(row.item.id);
298
+ }
299
+ catch (err) {
300
+ step.result = 'failed';
301
+ step.error = errorText(err);
302
+ if (row !== null && step.action !== 'unlock-worktree' && unlocked.has(row.item.id)) {
303
+ step.error += `; the lock on ${row.item.id} was cleared earlier in this run and is not restored`;
304
+ }
305
+ receipt.status = 'failed';
306
+ receipt.finished_at = now().toISOString();
307
+ save();
308
+ return receipt;
309
+ }
310
+ save();
311
+ }
312
+ receipt.status = 'complete';
313
+ receipt.finished_at = now().toISOString();
314
+ save();
315
+ return receipt;
316
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Local and remote branches: gather them, then decide what each one is.
3
+ *
4
+ * Two signals settle most branches. A merged pull request whose head commit is
5
+ * the branch tip says the work landed. Ancestry says the same thing without
6
+ * GitHub's help — if the branch tip is reachable from the default branch,
7
+ * every commit on it is already there. Either one is enough to call a branch
8
+ * spent; neither leaves the branch for a person to look at.
9
+ */
10
+ import { type Git } from '@osdlc/typed-git';
11
+ import { type PRInfo, type RepoInfo, type SweepItem } from './types.ts';
12
+ /** Why a merged PR does not prove that `tip` landed. */
13
+ export type PrEvidenceGap = 'other-base' | 'head-moved';
14
+ /**
15
+ * True when merged `pr` proves `tip` landed: it targeted the default branch
16
+ * and its head commit is `tip`. Fork PRs never reach here; `fetchPrs` drops
17
+ * them. A PR with no reported head counts as `head-moved`.
18
+ */
19
+ export declare function prCapturesTip(pr: PRInfo, tip: string, repo: RepoInfo): true | PrEvidenceGap;
20
+ /**
21
+ * `facts.pr`, plus `evidence` for a merged PR: `exact-head` when it proves
22
+ * `tip` landed, otherwise the gap. Returns whether it counts as landing proof.
23
+ */
24
+ export declare function recordPr(facts: Record<string, unknown>, pr: PRInfo | undefined, tip: string, repo: RepoInfo): {
25
+ landed: boolean;
26
+ gap: PrEvidenceGap | null;
27
+ };
28
+ /** One sentence on why a merged PR did not count, for `investigationParts`. */
29
+ export declare function gapSentence(pr: PRInfo, gap: PrEvidenceGap, repo: RepoInfo): string;
30
+ /** `HEAD` as the branch checked out at `git`'s directory; any other name as given. */
31
+ export declare function resolveBranch(value: string, git: Git): string;
32
+ /**
33
+ * Delete local branch `name` only while it still points at `sha` (the full
34
+ * sha). Same caveats as `deleteRef` in `@osdlc/typed-git`. Only a `branch`
35
+ * sweep proposes a branch checked out in a worktree, and only alongside that
36
+ * worktree's removal, which must run first.
37
+ */
38
+ export declare function localDeleteCommand(name: string, sha: string): string;
39
+ /** Delete `remote`'s branch `name` only while it still points at `sha`. */
40
+ export declare function remoteDeleteCommand(remote: string, name: string, sha: string): string;
41
+ export declare function gatherLocalBranches(repo: RepoInfo, prs: Map<string, PRInfo>, worktreeBranches: ReadonlySet<string>, git: Git, only?: string): SweepItem[];
42
+ export declare function classifyLocalBranch(opts: {
43
+ name: string;
44
+ upstream: string;
45
+ track: string;
46
+ lastCommit: string;
47
+ sha: string;
48
+ repo: RepoInfo;
49
+ prs: Map<string, PRInfo>;
50
+ worktreeBranches: ReadonlySet<string>;
51
+ git: Git;
52
+ }): SweepItem;
53
+ export declare function gatherRemoteBranches(repo: RepoInfo, prs: Map<string, PRInfo>, localBranchNames: ReadonlySet<string>, git: Git, only?: string): SweepItem[];
54
+ export declare function classifyRemoteBranch(opts: {
55
+ name: string;
56
+ sha: string;
57
+ repo: RepoInfo;
58
+ prs: Map<string, PRInfo>;
59
+ localBranchNames: ReadonlySet<string>;
60
+ git: Git;
61
+ }): SweepItem;
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Local and remote branches: gather them, then decide what each one is.
3
+ *
4
+ * Two signals settle most branches. A merged pull request whose head commit is
5
+ * the branch tip says the work landed. Ancestry says the same thing without
6
+ * GitHub's help — if the branch tip is reachable from the default branch,
7
+ * every commit on it is already there. Either one is enough to call a branch
8
+ * spent; neither leaves the branch for a person to look at.
9
+ */
10
+ import { shellJoin } from '@osdlc/command-seam';
11
+ import { forceWithLeaseArg } from '@osdlc/typed-git';
12
+ import { authorizationsFor, landedRef, makeItem, } from "./types.js";
13
+ /**
14
+ * Five fields in one pass, so a repository costs one `for-each-ref`. The full
15
+ * sha, so it compares with a PR's `headRefOid`.
16
+ */
17
+ const LOCAL_FORMAT = '%(refname:short)%09%(upstream:short)%09%(upstream:track)%09%(committerdate:iso8601-strict)%09%(objectname)';
18
+ /**
19
+ * True when merged `pr` proves `tip` landed: it targeted the default branch
20
+ * and its head commit is `tip`. Fork PRs never reach here; `fetchPrs` drops
21
+ * them. A PR with no reported head counts as `head-moved`.
22
+ */
23
+ export function prCapturesTip(pr, tip, repo) {
24
+ if (pr.baseRef !== repo.mainBranch)
25
+ return 'other-base';
26
+ if (pr.headOid === null || pr.headOid !== tip)
27
+ return 'head-moved';
28
+ return true;
29
+ }
30
+ /**
31
+ * `facts.pr`, plus `evidence` for a merged PR: `exact-head` when it proves
32
+ * `tip` landed, otherwise the gap. Returns whether it counts as landing proof.
33
+ */
34
+ export function recordPr(facts, pr, tip, repo) {
35
+ if (pr === undefined)
36
+ return { landed: false, gap: null };
37
+ const out = {
38
+ number: pr.number,
39
+ state: pr.state,
40
+ merged_at: pr.mergedAt,
41
+ url: pr.url,
42
+ title: pr.title,
43
+ head_oid: pr.headOid,
44
+ base_ref: pr.baseRef,
45
+ };
46
+ facts['pr'] = out;
47
+ if (pr.state !== 'MERGED')
48
+ return { landed: false, gap: null };
49
+ const verdict = prCapturesTip(pr, tip, repo);
50
+ out['evidence'] = verdict === true ? 'exact-head' : verdict;
51
+ return verdict === true ? { landed: true, gap: null } : { landed: false, gap: verdict };
52
+ }
53
+ /** One sentence on why a merged PR did not count, for `investigationParts`. */
54
+ export function gapSentence(pr, gap, repo) {
55
+ return gap === 'other-base'
56
+ ? `PR #${pr.number} merged into \`${pr.baseRef}\`, not \`${repo.mainBranch}\`, so it is not landing proof (other-base).`
57
+ : `PR #${pr.number} merged at head ${pr.headOid ?? '(unknown)'}, which is not this tip, so it is not landing proof (head-moved).`;
58
+ }
59
+ /** What deleting a branch needs: its unlanded commits, and its open PR. */
60
+ function branchRequires(unmerged, pr) {
61
+ return authorizationsFor({
62
+ 'abandon-unmerged': unmerged,
63
+ 'confirm-open-pr': pr?.state === 'OPEN',
64
+ });
65
+ }
66
+ /** `HEAD` as the branch checked out at `git`'s directory; any other name as given. */
67
+ export function resolveBranch(value, git) {
68
+ if (value !== 'HEAD')
69
+ return value;
70
+ const current = git.currentBranch();
71
+ if (current === null)
72
+ throw new Error(`--branch HEAD: no branch is checked out at ${git.cwd}`);
73
+ return current;
74
+ }
75
+ /**
76
+ * Delete local branch `name` only while it still points at `sha` (the full
77
+ * sha). Same caveats as `deleteRef` in `@osdlc/typed-git`. Only a `branch`
78
+ * sweep proposes a branch checked out in a worktree, and only alongside that
79
+ * worktree's removal, which must run first.
80
+ */
81
+ export function localDeleteCommand(name, sha) {
82
+ return shellJoin(['git', 'update-ref', '-d', `refs/heads/${name}`, sha]);
83
+ }
84
+ /** Delete `remote`'s branch `name` only while it still points at `sha`. */
85
+ export function remoteDeleteCommand(remote, name, sha) {
86
+ return shellJoin([
87
+ 'git',
88
+ 'push',
89
+ forceWithLeaseArg({ ref: `refs/heads/${name}`, expect: sha }),
90
+ remote,
91
+ `:refs/heads/${name}`,
92
+ ]);
93
+ }
94
+ // ── local branches ─────────────────────────────────────────────────────────
95
+ export function gatherLocalBranches(repo, prs, worktreeBranches, git, only) {
96
+ const rows = git.at(repo.root).forEachRef('refs/heads/', { format: LOCAL_FORMAT });
97
+ const items = [];
98
+ for (const line of rows) {
99
+ const parts = line.split('\t');
100
+ if (parts.length !== 5)
101
+ continue;
102
+ const [name, upstream, track, lastCommit, sha] = parts;
103
+ if (only !== undefined && name !== only)
104
+ continue;
105
+ items.push(classifyLocalBranch({
106
+ name,
107
+ upstream,
108
+ track,
109
+ lastCommit,
110
+ sha,
111
+ repo,
112
+ prs,
113
+ worktreeBranches,
114
+ git,
115
+ }));
116
+ }
117
+ return items;
118
+ }
119
+ export function classifyLocalBranch(opts) {
120
+ const { name, upstream, track, lastCommit, sha, repo, prs, worktreeBranches, git } = opts;
121
+ const facts = {
122
+ branch: name,
123
+ upstream: upstream || null,
124
+ track: track || null,
125
+ last_commit: lastCommit,
126
+ sha,
127
+ };
128
+ const keep = (reason, extra = {}) => makeItem({
129
+ category: 'local_branch',
130
+ id: name,
131
+ classification: 'safe-to-keep',
132
+ action: 'keep',
133
+ reason,
134
+ facts,
135
+ ...extra,
136
+ });
137
+ const pinned = (reason) => keep(reason, { deletable: false });
138
+ if (name === repo.mainBranch)
139
+ return pinned('default branch');
140
+ if (name === repo.currentBranch)
141
+ return pinned('current HEAD');
142
+ if (worktreeBranches.has(name))
143
+ return pinned('checked out in a worktree (handle via that worktree)');
144
+ // Work merged only into an unpushed local default has not landed. A missing
145
+ // remote-tracking ref exits 128: ancestry unknown (null).
146
+ const compareRef = landedRef(repo);
147
+ facts['compare_against'] = compareRef;
148
+ const ancestry = git.at(repo.root).try.isAncestor(name, compareRef);
149
+ const ancestor = ancestry.ok ? ancestry.value : null;
150
+ facts['ancestor_of_remote_main'] = ancestor;
151
+ const isAncestor = ancestor === true;
152
+ const pr = prs.get(name);
153
+ const { landed, gap } = recordPr(facts, pr, sha, repo);
154
+ const unmerged = !landed && !isAncestor;
155
+ if (unmerged)
156
+ facts['unique_commits'] = git.at(repo.root).aheadBehind(repo.mainBranch, sha).ahead;
157
+ const requires = branchRequires(unmerged, pr);
158
+ const deleteCmd = [localDeleteCommand(name, sha)];
159
+ if (pr && landed) {
160
+ return makeItem({
161
+ category: 'local_branch',
162
+ id: name,
163
+ classification: 'safe-to-delete',
164
+ action: 'delete',
165
+ reason: `PR #${pr.number} merged`,
166
+ facts,
167
+ commands: deleteCmd,
168
+ requires,
169
+ });
170
+ }
171
+ if (isAncestor) {
172
+ return makeItem({
173
+ category: 'local_branch',
174
+ id: name,
175
+ classification: 'safe-to-delete',
176
+ action: 'delete',
177
+ reason: `fully merged into ${compareRef}`,
178
+ facts,
179
+ commands: deleteCmd,
180
+ requires,
181
+ });
182
+ }
183
+ if (pr && pr.state === 'OPEN')
184
+ return keep(`open PR #${pr.number}`, { requires });
185
+ const lead = ancestor === null
186
+ ? `Remote default branch \`${compareRef}\` was not found, so ancestry is unknown.`
187
+ : `Branch \`${name}\` is not an ancestor of \`${compareRef}\`.`;
188
+ const parts = [lead];
189
+ parts.push(upstream ? `Tracks \`${upstream}\` (${track || 'in sync'}).` : 'Has no upstream.');
190
+ parts.push(pr
191
+ ? `Associated PR #${pr.number} is ${pr.state} (${pr.url}).`
192
+ : 'No PR found via `gh pr list`.');
193
+ if (pr && gap)
194
+ parts.push(gapSentence(pr, gap, repo));
195
+ parts.push(`Last commit: ${lastCommit} (${sha}).`);
196
+ return makeItem({
197
+ category: 'local_branch',
198
+ id: name,
199
+ classification: 'needs-investigation',
200
+ action: 'review',
201
+ reason: 'mixed or absent signals',
202
+ facts,
203
+ investigationParts: parts,
204
+ requires,
205
+ });
206
+ }
207
+ // ── remote branches ────────────────────────────────────────────────────────
208
+ export function gatherRemoteBranches(repo, prs, localBranchNames, git, only) {
209
+ if (repo.remote === null)
210
+ return [];
211
+ // Default door: an unreachable remote throws rather than rendering as "the
212
+ // remote has no branches". `[]` here means the remote really has none.
213
+ const pattern = only === undefined ? undefined : `refs/heads/${only}`;
214
+ const rows = git.at(repo.root).lsRemote(repo.remote, pattern, { heads: true });
215
+ const items = [];
216
+ for (const { sha, ref } of rows) {
217
+ if (!ref.startsWith('refs/heads/'))
218
+ continue;
219
+ const name = ref.slice('refs/heads/'.length);
220
+ if (only !== undefined && name !== only)
221
+ continue;
222
+ items.push(classifyRemoteBranch({ name, sha, repo, prs, localBranchNames, git }));
223
+ }
224
+ return items;
225
+ }
226
+ export function classifyRemoteBranch(opts) {
227
+ const { name, sha, repo, prs, localBranchNames, git } = opts;
228
+ const id = `${repo.remote}/${name}`;
229
+ const facts = {
230
+ branch: name,
231
+ remote: repo.remote,
232
+ sha,
233
+ has_local: localBranchNames.has(name),
234
+ };
235
+ const keep = (reason, extra = {}) => makeItem({
236
+ category: 'remote_branch',
237
+ id,
238
+ classification: 'safe-to-keep',
239
+ action: 'keep',
240
+ reason,
241
+ facts,
242
+ ...extra,
243
+ });
244
+ if (name === repo.mainBranch)
245
+ return keep('default branch', { deletable: false });
246
+ const remoteMain = landedRef(repo);
247
+ // `soft`: `sha` comes from `ls-remote`, so the clone may never have fetched
248
+ // it, and `remoteMain` may not exist either. Both exit 128; this row renders
249
+ // "cannot tell" as false.
250
+ const isAncestor = git.at(repo.root).soft.isAncestor(sha, remoteMain);
251
+ facts['ancestor_of_remote_main'] = isAncestor;
252
+ const pr = prs.get(name);
253
+ const { landed, gap } = recordPr(facts, pr, sha, repo);
254
+ const unmerged = !landed && !isAncestor;
255
+ if (unmerged) {
256
+ // Unknown (null) when the clone lacks `sha` or `remoteMain`, as above.
257
+ const counted = git.at(repo.root).try.aheadBehind(remoteMain, sha);
258
+ facts['unique_commits'] = counted.ok ? counted.value.ahead : null;
259
+ }
260
+ const requires = branchRequires(unmerged, pr);
261
+ const deleteCmd = repo.remote === null ? [] : [remoteDeleteCommand(repo.remote, name, sha)];
262
+ if (pr && landed) {
263
+ return makeItem({
264
+ category: 'remote_branch',
265
+ id,
266
+ classification: 'safe-to-delete',
267
+ action: 'delete',
268
+ reason: `PR #${pr.number} merged (auto-delete didn't fire)`,
269
+ facts,
270
+ commands: deleteCmd,
271
+ requires,
272
+ });
273
+ }
274
+ if (isAncestor) {
275
+ return makeItem({
276
+ category: 'remote_branch',
277
+ id,
278
+ classification: 'safe-to-delete',
279
+ action: 'delete',
280
+ reason: `fully merged into ${remoteMain}`,
281
+ facts,
282
+ commands: deleteCmd,
283
+ requires,
284
+ });
285
+ }
286
+ if (pr && pr.state === 'OPEN')
287
+ return keep(`open PR #${pr.number}`, { requires });
288
+ const parts = [`Remote branch \`${id}\` is not an ancestor of \`${remoteMain}\`.`];
289
+ parts.push(pr ? `Associated PR #${pr.number} is ${pr.state}.` : 'No PR found.');
290
+ if (pr && gap)
291
+ parts.push(gapSentence(pr, gap, repo));
292
+ parts.push('Decide whether to push more work, delete, or leave it as long-lived.');
293
+ return makeItem({
294
+ category: 'remote_branch',
295
+ id,
296
+ classification: 'needs-investigation',
297
+ action: 'review',
298
+ reason: 'mixed or absent signals',
299
+ facts,
300
+ investigationParts: parts,
301
+ requires,
302
+ });
303
+ }