@webpieces/rules-config 0.4.494 → 0.4.495
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": "@webpieces/rules-config",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.495",
|
|
4
4
|
"description": "Shared webpieces.config.json loader. Single source of truth for validation rule configuration consumed by @webpieces/ai-hook-rules, @webpieces/code-rules, and @webpieces/nx-webpieces-rules.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
package/src/merged-branches.d.ts
CHANGED
|
@@ -4,11 +4,31 @@ export declare class MergedBranch {
|
|
|
4
4
|
pr: number;
|
|
5
5
|
constructor(branch: string, pr: number);
|
|
6
6
|
}
|
|
7
|
+
/**
|
|
8
|
+
* A local branch and the verdict on it. `pr` is 0 when no merged PR backs the verdict (a `keep`).
|
|
9
|
+
*
|
|
10
|
+
* `sha`, `commits` and `prState` exist for the SPARED branches specifically. When nothing is
|
|
11
|
+
* auto-reapable the branch cap has nothing safe to offer, and its only remaining advice was "raise
|
|
12
|
+
* maxLocalBranches" / "set turnOffRuleUntilEpoch" — both of which loosen the rule. An agent with no
|
|
13
|
+
* human present took the config edit, which is the exact failure the cap exists to prevent. To ask a
|
|
14
|
+
* human "may I delete these?" instead, the guard has to be able to SHOW what it would delete: tip SHA
|
|
15
|
+
* (so the delete is recoverable), PR state (closed? never opened?) and how much unique work is on it.
|
|
16
|
+
*
|
|
17
|
+
* All three are computed in the DETACHED refresher and read straight off merged-branches.json — the
|
|
18
|
+
* blocking hook path never recomputes them. Defaulted so a cache written by an older release (and
|
|
19
|
+
* every existing call site) revives without them.
|
|
20
|
+
*/
|
|
7
21
|
export declare class DeletableBranch {
|
|
8
22
|
branch: string;
|
|
9
23
|
reason: string;
|
|
10
24
|
pr: number;
|
|
11
|
-
|
|
25
|
+
/** Short tip SHA — what makes the delete undoable (`git branch <name> <sha>`). '' when unknown. */
|
|
26
|
+
sha: string;
|
|
27
|
+
/** Commits on this branch that are not on origin/main. -1 when it could not be established. */
|
|
28
|
+
commits: number;
|
|
29
|
+
/** GitHub's state for the PR whose head is this branch: MERGED / CLOSED / OPEN, or '' for none. */
|
|
30
|
+
prState: string;
|
|
31
|
+
constructor(branch: string, reason: string, pr: number, sha?: string, commits?: number, prState?: string);
|
|
12
32
|
}
|
|
13
33
|
/**
|
|
14
34
|
* A worktree and the verdict on it. Carries `path` (what `git worktree remove` takes) AND `branch`
|
|
@@ -66,7 +86,16 @@ export declare class MergedBranchesService {
|
|
|
66
86
|
* its branch still holds unmerged work.
|
|
67
87
|
*/
|
|
68
88
|
private classifyWorktrees;
|
|
89
|
+
/**
|
|
90
|
+
* Verdict for one branch: its own merged PR, else the base it was backed up from, else empty.
|
|
91
|
+
*
|
|
92
|
+
* The verdict itself is unchanged. What is new is that EVERY entry now carries its tip SHA, its
|
|
93
|
+
* unique-commit count and its PR state, so a `keep` can be shown to a human as a delete candidate
|
|
94
|
+
* rather than just counted. This runs only in the detached refresher, so the two extra local git
|
|
95
|
+
* calls per branch cost the blocking hook path nothing.
|
|
96
|
+
*/
|
|
69
97
|
private classify;
|
|
98
|
+
private tipSha;
|
|
70
99
|
/**
|
|
71
100
|
* Commits on `branch` that are not on origin/main. Returns -1 ("assume it has work") whenever the
|
|
72
101
|
* count cannot be established — an unresolvable origin/main must never read as "empty branch".
|
|
@@ -78,6 +107,14 @@ export declare class MergedBranchesService {
|
|
|
78
107
|
* every branch a `keep`. The guard then deletes nothing rather than guessing.
|
|
79
108
|
*/
|
|
80
109
|
private fetchMergedPrs;
|
|
110
|
+
/**
|
|
111
|
+
* The DISPLAY-only second lookup: every PR (any state) keyed by head branch, so a spared branch can
|
|
112
|
+
* be shown to a human as "PR #12 CLOSED (not merged)" or "no PR" instead of an opaque name. Kept
|
|
113
|
+
* SEPARATE from fetchMergedPrs on purpose — folding both into one `--state all` call would let a
|
|
114
|
+
* flood of open/closed PRs push older MERGED ones out of the limit and silently stop reaping real
|
|
115
|
+
* dead branches. Fails soft to an empty map: the verdicts do not depend on it.
|
|
116
|
+
*/
|
|
117
|
+
private fetchPrStates;
|
|
81
118
|
private reviveList;
|
|
82
119
|
private reviveWorktrees;
|
|
83
120
|
private capture;
|
package/src/merged-branches.js
CHANGED
|
@@ -41,15 +41,37 @@ class MergedBranch {
|
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
43
|
exports.MergedBranch = MergedBranch;
|
|
44
|
-
|
|
44
|
+
/**
|
|
45
|
+
* A local branch and the verdict on it. `pr` is 0 when no merged PR backs the verdict (a `keep`).
|
|
46
|
+
*
|
|
47
|
+
* `sha`, `commits` and `prState` exist for the SPARED branches specifically. When nothing is
|
|
48
|
+
* auto-reapable the branch cap has nothing safe to offer, and its only remaining advice was "raise
|
|
49
|
+
* maxLocalBranches" / "set turnOffRuleUntilEpoch" — both of which loosen the rule. An agent with no
|
|
50
|
+
* human present took the config edit, which is the exact failure the cap exists to prevent. To ask a
|
|
51
|
+
* human "may I delete these?" instead, the guard has to be able to SHOW what it would delete: tip SHA
|
|
52
|
+
* (so the delete is recoverable), PR state (closed? never opened?) and how much unique work is on it.
|
|
53
|
+
*
|
|
54
|
+
* All three are computed in the DETACHED refresher and read straight off merged-branches.json — the
|
|
55
|
+
* blocking hook path never recomputes them. Defaulted so a cache written by an older release (and
|
|
56
|
+
* every existing call site) revives without them.
|
|
57
|
+
*/
|
|
45
58
|
class DeletableBranch {
|
|
46
59
|
branch;
|
|
47
60
|
reason;
|
|
48
61
|
pr;
|
|
49
|
-
|
|
62
|
+
/** Short tip SHA — what makes the delete undoable (`git branch <name> <sha>`). '' when unknown. */
|
|
63
|
+
sha;
|
|
64
|
+
/** Commits on this branch that are not on origin/main. -1 when it could not be established. */
|
|
65
|
+
commits;
|
|
66
|
+
/** GitHub's state for the PR whose head is this branch: MERGED / CLOSED / OPEN, or '' for none. */
|
|
67
|
+
prState;
|
|
68
|
+
constructor(branch, reason, pr, sha = '', commits = -1, prState = '') {
|
|
50
69
|
this.branch = branch;
|
|
51
70
|
this.reason = reason;
|
|
52
71
|
this.pr = pr;
|
|
72
|
+
this.sha = sha;
|
|
73
|
+
this.commits = commits;
|
|
74
|
+
this.prState = prState;
|
|
53
75
|
}
|
|
54
76
|
}
|
|
55
77
|
exports.DeletableBranch = DeletableBranch;
|
|
@@ -94,6 +116,30 @@ class MergedBranchesCache {
|
|
|
94
116
|
}
|
|
95
117
|
}
|
|
96
118
|
exports.MergedBranchesCache = MergedBranchesCache;
|
|
119
|
+
/**
|
|
120
|
+
* Internal: the bulk PR lookup, indexed.
|
|
121
|
+
*
|
|
122
|
+
* `merged` drives the DELETE verdicts and comes from the `--state merged` call, unchanged — the
|
|
123
|
+
* reaping logic must not get looser or tighter here. `state` is display-only, from a second
|
|
124
|
+
* `--state all` call, and answers the question a human needs in order to say "yes, delete it":
|
|
125
|
+
* was there a PR at all, and did it close without merging? It fails soft to an empty map.
|
|
126
|
+
*/
|
|
127
|
+
class PrRef {
|
|
128
|
+
number;
|
|
129
|
+
state;
|
|
130
|
+
constructor(prNumber, state) {
|
|
131
|
+
this.number = prNumber;
|
|
132
|
+
this.state = state;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
class PrLookup {
|
|
136
|
+
merged;
|
|
137
|
+
state;
|
|
138
|
+
constructor(merged, state) {
|
|
139
|
+
this.merged = merged;
|
|
140
|
+
this.state = state;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
97
143
|
// Internal: a classification result. `deletable` is the decision; `entry` carries the branch + reason
|
|
98
144
|
// either way (a spared branch still needs its reason recorded, and it has no PR to key off).
|
|
99
145
|
class Verdict {
|
|
@@ -158,6 +204,7 @@ let MergedBranchesService = class MergedBranchesService {
|
|
|
158
204
|
const byBranch = new Map();
|
|
159
205
|
for (const entry of merged)
|
|
160
206
|
byBranch.set(entry.branch, entry.pr);
|
|
207
|
+
const prs = new PrLookup(byBranch, this.fetchPrStates(repoRoot));
|
|
161
208
|
const trees = this.worktrees.listWorktrees(repoRoot);
|
|
162
209
|
const holder = new Map();
|
|
163
210
|
for (const tree of trees) {
|
|
@@ -167,7 +214,7 @@ let MergedBranchesService = class MergedBranchesService {
|
|
|
167
214
|
const deletable = [];
|
|
168
215
|
const keep = [];
|
|
169
216
|
for (const branch of this.localBranches(repoRoot)) {
|
|
170
|
-
const verdict = this.classify(repoRoot, branch,
|
|
217
|
+
const verdict = this.classify(repoRoot, branch, prs);
|
|
171
218
|
// A branch checked out in ANY worktree (including the branch we are standing on right here)
|
|
172
219
|
// cannot be deleted — git refuses, and since the reap is ONE `git branch -D a b c`, a single
|
|
173
220
|
// such branch would fail the entire command and strand the branches that would have deleted
|
|
@@ -175,7 +222,7 @@ let MergedBranchesService = class MergedBranchesService {
|
|
|
175
222
|
// worktree list below is what actually reaps it, and a human should see the connection.
|
|
176
223
|
const heldAt = holder.get(branch);
|
|
177
224
|
if (heldAt !== undefined) {
|
|
178
|
-
keep.push(new DeletableBranch(branch, `checked out in worktree '${heldAt}' — remove that worktree before deleting the branch`, verdict.entry.pr));
|
|
225
|
+
keep.push(new DeletableBranch(branch, `checked out in worktree '${heldAt}' — remove that worktree before deleting the branch`, verdict.entry.pr, verdict.entry.sha, verdict.entry.commits, verdict.entry.prState));
|
|
179
226
|
continue;
|
|
180
227
|
}
|
|
181
228
|
if (verdict.deletable)
|
|
@@ -183,7 +230,7 @@ let MergedBranchesService = class MergedBranchesService {
|
|
|
183
230
|
else
|
|
184
231
|
keep.push(verdict.entry);
|
|
185
232
|
}
|
|
186
|
-
const worktrees = this.classifyWorktrees(repoRoot, trees,
|
|
233
|
+
const worktrees = this.classifyWorktrees(repoRoot, trees, prs);
|
|
187
234
|
return new MergedBranchesCache(new Date().toISOString(), deletable, keep, worktrees);
|
|
188
235
|
}
|
|
189
236
|
/**
|
|
@@ -196,7 +243,7 @@ let MergedBranchesService = class MergedBranchesService {
|
|
|
196
243
|
* are standing in right now (removing your own cwd is not a thing to suggest to an agent), or when
|
|
197
244
|
* its branch still holds unmerged work.
|
|
198
245
|
*/
|
|
199
|
-
classifyWorktrees(repoRoot, trees,
|
|
246
|
+
classifyWorktrees(repoRoot, trees, prs) {
|
|
200
247
|
const out = [];
|
|
201
248
|
for (const tree of trees) {
|
|
202
249
|
if (tree.isMain)
|
|
@@ -217,32 +264,51 @@ let MergedBranchesService = class MergedBranchesService {
|
|
|
217
264
|
out.push(new DeletableWorktree(tree.path, '', 'detached HEAD — no branch to check, so a human must decide', 0, false));
|
|
218
265
|
continue;
|
|
219
266
|
}
|
|
220
|
-
const verdict = this.classify(repoRoot, tree.branch,
|
|
267
|
+
const verdict = this.classify(repoRoot, tree.branch, prs);
|
|
221
268
|
out.push(new DeletableWorktree(tree.path, tree.branch, verdict.entry.reason, verdict.entry.pr, verdict.deletable));
|
|
222
269
|
}
|
|
223
270
|
return out;
|
|
224
271
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
272
|
+
/**
|
|
273
|
+
* Verdict for one branch: its own merged PR, else the base it was backed up from, else empty.
|
|
274
|
+
*
|
|
275
|
+
* The verdict itself is unchanged. What is new is that EVERY entry now carries its tip SHA, its
|
|
276
|
+
* unique-commit count and its PR state, so a `keep` can be shown to a human as a delete candidate
|
|
277
|
+
* rather than just counted. This runs only in the detached refresher, so the two extra local git
|
|
278
|
+
* calls per branch cost the blocking hook path nothing.
|
|
279
|
+
*/
|
|
280
|
+
classify(repoRoot, branch, prs) {
|
|
281
|
+
const sha = this.tipSha(repoRoot, branch);
|
|
282
|
+
const commits = this.commitsAheadOfMain(repoRoot, branch);
|
|
283
|
+
const known = prs.state.get(branch);
|
|
284
|
+
const prState = known ? known.state : '';
|
|
285
|
+
const own = prs.merged.get(branch);
|
|
228
286
|
if (own !== undefined) {
|
|
229
|
-
return new Verdict(true, new DeletableBranch(branch, `PR #${String(own)} merged`, own));
|
|
287
|
+
return new Verdict(true, new DeletableBranch(branch, `PR #${String(own)} merged`, own, sha, commits, prState || 'MERGED'));
|
|
230
288
|
}
|
|
231
289
|
const base = branch.replace(BACKUP_SUFFIX, '');
|
|
232
290
|
if (base !== branch && base.length > 0) {
|
|
233
|
-
const basePr =
|
|
291
|
+
const basePr = prs.merged.get(base);
|
|
234
292
|
if (basePr !== undefined) {
|
|
235
|
-
return new Verdict(true, new DeletableBranch(branch, `squash-merge backup of '${base}' (PR #${String(basePr)} merged) — its job is done`, basePr));
|
|
293
|
+
return new Verdict(true, new DeletableBranch(branch, `squash-merge backup of '${base}' (PR #${String(basePr)} merged) — its job is done`, basePr, sha, commits, prState));
|
|
236
294
|
}
|
|
237
295
|
}
|
|
238
296
|
// The one git-local signal that squash-merge CANNOT corrupt: a branch with zero commits of its
|
|
239
297
|
// own holds no work, so deleting it can lose nothing. (Squash breaks patch-id and ancestry, so
|
|
240
298
|
// "are these commits in main?" is unanswerable from git — but "are there any commits at all?"
|
|
241
299
|
// is exact.) These are the husks left behind by branching and then never committing.
|
|
242
|
-
if (
|
|
243
|
-
return new Verdict(true, new DeletableBranch(branch, 'no commits of its own — identical to origin/main', 0));
|
|
300
|
+
if (commits === 0) {
|
|
301
|
+
return new Verdict(true, new DeletableBranch(branch, 'no commits of its own — identical to origin/main', 0, sha, 0, prState));
|
|
244
302
|
}
|
|
245
|
-
|
|
303
|
+
const why = known
|
|
304
|
+
? `PR #${String(known.number)} is ${known.state} (not merged) — a human must decide`
|
|
305
|
+
: 'no merged PR found — a human must decide';
|
|
306
|
+
return new Verdict(false, new DeletableBranch(branch, why, 0, sha, commits, prState));
|
|
307
|
+
}
|
|
308
|
+
// Short tip SHA — the value that makes any delete of this branch reversible.
|
|
309
|
+
tipSha(repoRoot, branch) {
|
|
310
|
+
const result = this.capture(repoRoot, 'git', ['rev-parse', '--short', branch]);
|
|
311
|
+
return result.ok ? result.out : '';
|
|
246
312
|
}
|
|
247
313
|
/**
|
|
248
314
|
* Commits on `branch` that are not on origin/main. Returns -1 ("assume it has work") whenever the
|
|
@@ -287,10 +353,46 @@ let MergedBranchesService = class MergedBranchesService {
|
|
|
287
353
|
return [];
|
|
288
354
|
}
|
|
289
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* The DISPLAY-only second lookup: every PR (any state) keyed by head branch, so a spared branch can
|
|
358
|
+
* be shown to a human as "PR #12 CLOSED (not merged)" or "no PR" instead of an opaque name. Kept
|
|
359
|
+
* SEPARATE from fetchMergedPrs on purpose — folding both into one `--state all` call would let a
|
|
360
|
+
* flood of open/closed PRs push older MERGED ones out of the limit and silently stop reaping real
|
|
361
|
+
* dead branches. Fails soft to an empty map: the verdicts do not depend on it.
|
|
362
|
+
*/
|
|
363
|
+
fetchPrStates(repoRoot) {
|
|
364
|
+
const out = new Map();
|
|
365
|
+
const result = this.capture(repoRoot, 'gh', [
|
|
366
|
+
'pr', 'list',
|
|
367
|
+
'--state', 'all',
|
|
368
|
+
'--limit', String(MERGED_PR_LOOKUP_LIMIT),
|
|
369
|
+
'--json', 'number,headRefName,state',
|
|
370
|
+
]);
|
|
371
|
+
if (!result.ok || result.out === '')
|
|
372
|
+
return out;
|
|
373
|
+
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
374
|
+
try {
|
|
375
|
+
const raw = JSON.parse(result.out);
|
|
376
|
+
for (const entry of raw) {
|
|
377
|
+
const branch = entry.headRefName ?? '';
|
|
378
|
+
const pr = entry.number ?? 0;
|
|
379
|
+
// `gh` lists newest-first, so the FIRST entry for a branch is its latest PR — keep it.
|
|
380
|
+
if (branch !== '' && pr > 0 && !out.has(branch)) {
|
|
381
|
+
out.set(branch, new PrRef(pr, entry.state ?? ''));
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return out;
|
|
385
|
+
}
|
|
386
|
+
catch (err) {
|
|
387
|
+
const error = (0, to_error_1.toError)(err);
|
|
388
|
+
void error;
|
|
389
|
+
return out;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
290
392
|
reviveList(raw) {
|
|
291
393
|
if (!raw)
|
|
292
394
|
return [];
|
|
293
|
-
return raw.map((entry) => new DeletableBranch(entry.branch ?? '', entry.reason ?? '', entry.pr ?? 0));
|
|
395
|
+
return raw.map((entry) => new DeletableBranch(entry.branch ?? '', entry.reason ?? '', entry.pr ?? 0, entry.sha ?? '', entry.commits ?? -1, entry.prState ?? ''));
|
|
294
396
|
}
|
|
295
397
|
reviveWorktrees(raw) {
|
|
296
398
|
if (!raw)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merged-branches.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/merged-branches.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,2CAAgD;AAChD,yCAAqC;AACrC,2CAAwD;AAExD;;;;;;;;;;;;GAYG;AAEH,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAEpD,6FAA6F;AAC7F,kGAAkG;AAClG,qCAAqC;AACrC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAEnC,8FAA8F;AAC9F,sGAAsG;AACtG,kGAAkG;AAClG,MAAM,aAAa,GAAG,+BAA+B,CAAC;AAEtD,+CAA+C;AAC/C,MAAa,YAAY;IACrB,MAAM,CAAS;IACf,EAAE,CAAS;IAEX,YAAY,MAAc,EAAE,EAAU;QAClC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACjB,CAAC;CACJ;AARD,oCAQC;AAED,kGAAkG;AAClG,MAAa,eAAe;IACxB,MAAM,CAAS;IACf,MAAM,CAAS;IACf,EAAE,CAAS;IAEX,YAAY,MAAc,EAAE,MAAc,EAAE,EAAU;QAClD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACjB,CAAC;CAC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AkB,CAAC,SAAS,CAAC;6CAIG,2BAAe;GAH9C,qBAAqB,CA6OjC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { toError } from './to-error';\nimport { Worktree, WorktreeService } from './worktrees';\n\n/**\n * The \"which local branches are dead?\" cache.\n *\n * WHY a cache, and why a STALE one is correct: cleanup is eventual, never urgent. A branch that\n * merged 30 seconds ago simply survives until the next refresh — nobody cares. So the (slow, network)\n * merged-PR lookup runs in the DETACHED background refresher, and the branch-creation-guard only READS\n * this file on its blocking path. Staleness is the whole point: it is what keeps the guard fast.\n *\n * WHY the GitHub PR API and not git: the repo squash-merges, which destroys BOTH commit ancestry and\n * patch-id. `git branch --merged` and `git cherry` therefore report merged branches as unmerged\n * (observed: deanhiller/config-overhaul, PR #188, merged — yet its patch is absent from main). A MERGED\n * PR is the only trustworthy signal, and ONE bulk `gh pr list --state merged` answers for every branch.\n */\n\nconst MERGED_BRANCHES_FILE = 'merged-branches.json';\n\n// How many merged PRs to pull in the single bulk lookup. Branches older than this window are\n// vanishingly unlikely to still be checked out locally; if one is, it lands in `keep` and a human\n// decides — the fail-safe direction.\nconst MERGED_PR_LOOKUP_LIMIT = 100;\n\n// Suffixes the squash-merge tooling appends to a feature branch when it snapshots it mid-sync\n// (base → baseSquash / basewp2 / basePreMerge3). GitHub has never seen these SHAs, so no PR will ever\n// name them — they can only be reaped by stripping back to the base branch they were cloned from.\nconst BACKUP_SUFFIX = /(?:Squash|PreMerge\\d*|wp\\d+)$/;\n\n// Data-only (per CLAUDE.md, classes for data).\nexport class MergedBranch {\n branch: string;\n pr: number;\n\n constructor(branch: string, pr: number) {\n this.branch = branch;\n this.pr = pr;\n }\n}\n\n// A local branch and the verdict on it. `pr` is 0 when no merged PR backs the verdict (a `keep`).\nexport class DeletableBranch {\n branch: string;\n reason: string;\n pr: number;\n\n constructor(branch: string, reason: string, pr: number) {\n this.branch = branch;\n this.reason = reason;\n this.pr = pr;\n }\n}\n\n/**\n * A worktree and the verdict on it. Carries `path` (what `git worktree remove` takes) AND `branch`\n * (what `git branch -D` takes afterwards) because reaping a worktree is always those two steps, in\n * that order — git refuses to delete a branch that is still checked out somewhere.\n */\nexport class DeletableWorktree {\n path: string;\n branch: string;\n reason: string;\n pr: number;\n deletable: boolean;\n\n constructor(path: string, branch: string, reason: string, pr: number, deletable: boolean) {\n this.path = path;\n this.branch = branch;\n this.reason = reason;\n this.pr = pr;\n this.deletable = deletable;\n }\n}\n\n/**\n * `deletable` is PRECOMPUTED so the consumer just deletes the list — no re-deriving, no judgement\n * call at block time. `keep` carries the branches we refuse to touch (no merged PR found), each with\n * its reason, so a human can see what was spared and why.\n *\n * `worktrees` is the parallel verdict list for the SECOND budget (see worktrees.ts): every linked\n * worktree, each flagged deletable or not. Both budgets are reaped from this one cache file.\n */\nexport class MergedBranchesCache {\n timestamp: string;\n deletable: DeletableBranch[];\n keep: DeletableBranch[];\n worktrees: DeletableWorktree[];\n\n constructor(\n timestamp: string,\n deletable: DeletableBranch[],\n keep: DeletableBranch[],\n worktrees: DeletableWorktree[] = [],\n ) {\n this.timestamp = timestamp;\n this.deletable = deletable;\n this.keep = keep;\n this.worktrees = worktrees;\n }\n}\n\n// Internal: a classification result. `deletable` is the decision; `entry` carries the branch + reason\n// either way (a spared branch still needs its reason recorded, and it has no PR to key off).\nclass Verdict {\n deletable: boolean;\n entry: DeletableBranch;\n\n constructor(deletable: boolean, entry: DeletableBranch) {\n this.deletable = deletable;\n this.entry = entry;\n }\n}\n\n// Raw JSON shapes for the cast at the parse boundary.\ninterface RawDeletable {\n branch?: string;\n reason?: string;\n pr?: number;\n}\n\ninterface RawWorktree {\n path?: string;\n branch?: string;\n reason?: string;\n pr?: number;\n deletable?: boolean;\n}\n\ninterface RawCache {\n timestamp?: string;\n deletable?: RawDeletable[];\n keep?: RawDeletable[];\n // Absent in caches written by releases before the worktree cap existed — revives to [], which\n // makes the worktree cap fail OPEN on a stale file rather than hard-failing the guard.\n worktrees?: RawWorktree[];\n}\n\ninterface RawMergedPr {\n number?: number;\n headRefName?: string;\n}\n\n// Result of a captured git/gh invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MergedBranchesService {\n // Defaulted so the non-DI call sites (`new MergedBranchesService()` in the guard and the detached\n // refresher) keep working, while inversify still injects the singleton when resolved from a container.\n constructor(private readonly worktrees: WorktreeService = new WorktreeService()) {}\n\n mergedBranchesPath(repoRoot: string): string {\n return path.join(repoRoot, WEBPIECES_TMP_DIR, MERGED_BRANCHES_FILE);\n }\n\n // Pure read — any error (missing file, malformed JSON) returns null so the guard fails OPEN.\n readMergedBranches(repoRoot: string): MergedBranchesCache | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const cachePath = this.mergedBranchesPath(repoRoot);\n if (!fs.existsSync(cachePath)) return null;\n const raw = JSON.parse(fs.readFileSync(cachePath, 'utf8')) as RawCache;\n return new MergedBranchesCache(\n raw.timestamp ?? '',\n this.reviveList(raw.deletable),\n this.reviveList(raw.keep),\n this.reviveWorktrees(raw.worktrees),\n );\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n writeMergedBranches(repoRoot: string, cache: MergedBranchesCache): void {\n const cachePath = this.mergedBranchesPath(repoRoot);\n fs.mkdirSync(path.dirname(cachePath), { recursive: true });\n fs.writeFileSync(cachePath, JSON.stringify(cache, null, 2) + '\\n');\n }\n\n /**\n * Every local branch except `main`. Uses `git for-each-ref`, NOT `git branch` — the latter is a\n * porcelain command whose output the branch-creation-guard's own regex mistakes for a branch\n * CREATION, so the guard would block the cleanup it just demanded.\n */\n localBranches(repoRoot: string): string[] {\n const result = this.capture(repoRoot, 'git', ['for-each-ref', '--format=%(refname:short)', 'refs/heads/']);\n if (!result.ok || result.out === '') return [];\n return result.out\n .split('\\n')\n .map((line: string): string => line.trim())\n .filter((line: string): boolean => line.length > 0 && line !== 'main');\n }\n\n /**\n * The SLOW path, run only inside the detached refresher. ONE bulk `gh` call, then a purely local\n * classification. Never run on the hook's blocking path.\n */\n computeMergedBranches(repoRoot: string): MergedBranchesCache {\n const merged = this.fetchMergedPrs(repoRoot);\n const byBranch = new Map<string, number>();\n for (const entry of merged) byBranch.set(entry.branch, entry.pr);\n\n const trees = this.worktrees.listWorktrees(repoRoot);\n const holder = new Map<string, string>();\n for (const tree of trees) {\n if (tree.branch !== '') holder.set(tree.branch, tree.path);\n }\n\n const deletable: DeletableBranch[] = [];\n const keep: DeletableBranch[] = [];\n\n for (const branch of this.localBranches(repoRoot)) {\n const verdict = this.classify(repoRoot, branch, byBranch);\n\n // A branch checked out in ANY worktree (including the branch we are standing on right here)\n // cannot be deleted — git refuses, and since the reap is ONE `git branch -D a b c`, a single\n // such branch would fail the entire command and strand the branches that would have deleted\n // fine. Spare it LOUDLY (into `keep`, with the reason) rather than dropping it silently: the\n // worktree list below is what actually reaps it, and a human should see the connection.\n const heldAt = holder.get(branch);\n if (heldAt !== undefined) {\n keep.push(new DeletableBranch(\n branch,\n `checked out in worktree '${heldAt}' — remove that worktree before deleting the branch`,\n verdict.entry.pr,\n ));\n continue;\n }\n\n if (verdict.deletable) deletable.push(verdict.entry);\n else keep.push(verdict.entry);\n }\n\n const worktrees = this.classifyWorktrees(repoRoot, trees, byBranch);\n return new MergedBranchesCache(new Date().toISOString(), deletable, keep, worktrees);\n }\n\n /**\n * Verdicts for the worktree budget. The main worktree is excluded outright — it is the primary\n * clone and is not a thing you can remove.\n *\n * A worktree is deletable when its directory is already gone (`prunable`), or when its branch is\n * dead by the very same proofs the branch cap uses (merged PR, backup-of-merged, or zero commits of\n * its own). It is spared when it is LOCKED (a human said \"do not touch\"), when it is the worktree we\n * are standing in right now (removing your own cwd is not a thing to suggest to an agent), or when\n * its branch still holds unmerged work.\n */\n private classifyWorktrees(\n repoRoot: string,\n trees: Worktree[],\n byBranch: Map<string, number>,\n ): DeletableWorktree[] {\n const out: DeletableWorktree[] = [];\n\n for (const tree of trees) {\n if (tree.isMain) continue;\n\n if (tree.prunable) {\n out.push(new DeletableWorktree(\n tree.path, tree.branch, 'its directory is gone — `git worktree prune` clears it', 0, true));\n continue;\n }\n if (tree.locked) {\n out.push(new DeletableWorktree(\n tree.path, tree.branch, 'locked by a human — do not touch', 0, false));\n continue;\n }\n if (tree.path === repoRoot) {\n out.push(new DeletableWorktree(\n tree.path, tree.branch, 'you are standing in it', 0, false));\n continue;\n }\n if (tree.branch === '') {\n out.push(new DeletableWorktree(\n tree.path, '', 'detached HEAD — no branch to check, so a human must decide', 0, false));\n continue;\n }\n\n const verdict = this.classify(repoRoot, tree.branch, byBranch);\n out.push(new DeletableWorktree(\n tree.path, tree.branch, verdict.entry.reason, verdict.entry.pr, verdict.deletable));\n }\n\n return out;\n }\n\n // Verdict for one branch: its own merged PR, else the base it was backed up from, else empty.\n private classify(repoRoot: string, branch: string, byBranch: Map<string, number>): Verdict {\n const own = byBranch.get(branch);\n if (own !== undefined) {\n return new Verdict(true, new DeletableBranch(branch, `PR #${String(own)} merged`, own));\n }\n\n const base = branch.replace(BACKUP_SUFFIX, '');\n if (base !== branch && base.length > 0) {\n const basePr = byBranch.get(base);\n if (basePr !== undefined) {\n return new Verdict(true, new DeletableBranch(\n branch,\n `squash-merge backup of '${base}' (PR #${String(basePr)} merged) — its job is done`,\n basePr,\n ));\n }\n }\n\n // The one git-local signal that squash-merge CANNOT corrupt: a branch with zero commits of its\n // own holds no work, so deleting it can lose nothing. (Squash breaks patch-id and ancestry, so\n // \"are these commits in main?\" is unanswerable from git — but \"are there any commits at all?\"\n // is exact.) These are the husks left behind by branching and then never committing.\n if (this.commitsAheadOfMain(repoRoot, branch) === 0) {\n return new Verdict(true, new DeletableBranch(branch, 'no commits of its own — identical to origin/main', 0));\n }\n\n return new Verdict(false, new DeletableBranch(branch, 'no merged PR found — a human must decide', 0));\n }\n\n /**\n * Commits on `branch` that are not on origin/main. Returns -1 (\"assume it has work\") whenever the\n * count cannot be established — an unresolvable origin/main must never read as \"empty branch\".\n */\n private commitsAheadOfMain(repoRoot: string, branch: string): number {\n const result = this.capture(repoRoot, 'git', ['rev-list', '--count', `origin/main..${branch}`]);\n if (!result.ok) return -1;\n const count = Number(result.out);\n return Number.isInteger(count) ? count : -1;\n }\n\n /**\n * The ONE bulk network call. Every merged PR's head branch in a single round trip — no per-branch\n * lookups. Fails SOFT: if `gh` is missing, unauthenticated, or offline we return [], which makes\n * every branch a `keep`. The guard then deletes nothing rather than guessing.\n */\n private fetchMergedPrs(repoRoot: string): MergedBranch[] {\n const result = this.capture(repoRoot, 'gh', [\n 'pr', 'list',\n '--state', 'merged',\n '--limit', String(MERGED_PR_LOOKUP_LIMIT),\n '--json', 'number,headRefName',\n ]);\n if (!result.ok || result.out === '') return [];\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = JSON.parse(result.out) as RawMergedPr[];\n const out: MergedBranch[] = [];\n for (const entry of raw) {\n const branch = entry.headRefName ?? '';\n const pr = entry.number ?? 0;\n if (branch !== '' && pr > 0) out.push(new MergedBranch(branch, pr));\n }\n return out;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n private reviveList(raw: RawDeletable[] | undefined): DeletableBranch[] {\n if (!raw) return [];\n return raw.map((entry: RawDeletable): DeletableBranch =>\n new DeletableBranch(entry.branch ?? '', entry.reason ?? '', entry.pr ?? 0));\n }\n\n private reviveWorktrees(raw: RawWorktree[] | undefined): DeletableWorktree[] {\n if (!raw) return [];\n return raw.map((entry: RawWorktree): DeletableWorktree => new DeletableWorktree(\n entry.path ?? '',\n entry.branch ?? '',\n entry.reason ?? '',\n entry.pr ?? 0,\n entry.deletable ?? false,\n ));\n }\n\n // Run a command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, cmd: string, args: string[]): CmdCapture {\n const result = spawnSync(cmd, args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return { ok: false, out: '' };\n return { ok: true, out: result.stdout.trim() };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"merged-branches.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/merged-branches.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,2CAAgD;AAChD,yCAAqC;AACrC,2CAAwD;AAExD;;;;;;;;;;;;GAYG;AAEH,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAEpD,6FAA6F;AAC7F,kGAAkG;AAClG,qCAAqC;AACrC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAEnC,8FAA8F;AAC9F,sGAAsG;AACtG,kGAAkG;AAClG,MAAM,aAAa,GAAG,+BAA+B,CAAC;AAEtD,+CAA+C;AAC/C,MAAa,YAAY;IACrB,MAAM,CAAS;IACf,EAAE,CAAS;IAEX,YAAY,MAAc,EAAE,EAAU;QAClC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACjB,CAAC;CACJ;AARD,oCAQC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAa,eAAe;IACxB,MAAM,CAAS;IACf,MAAM,CAAS;IACf,EAAE,CAAS;IACX,mGAAmG;IACnG,GAAG,CAAS;IACZ,+FAA+F;IAC/F,OAAO,CAAS;IAChB,mGAAmG;IACnG,OAAO,CAAS;IAEhB,YACI,MAAc,EACd,MAAc,EACd,EAAU,EACV,MAAc,EAAE,EAChB,UAAkB,CAAC,CAAC,EACpB,UAAkB,EAAE;QAEpB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,G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S,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QACzE,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;YAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC;QAC5F,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;IACnD,CAAC;CACJ,CAAA;AAlTY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIG,2BAAe;GAH9C,qBAAqB,CAkTjC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { toError } from './to-error';\nimport { Worktree, WorktreeService } from './worktrees';\n\n/**\n * The \"which local branches are dead?\" cache.\n *\n * WHY a cache, and why a STALE one is correct: cleanup is eventual, never urgent. A branch that\n * merged 30 seconds ago simply survives until the next refresh — nobody cares. So the (slow, network)\n * merged-PR lookup runs in the DETACHED background refresher, and the branch-creation-guard only READS\n * this file on its blocking path. Staleness is the whole point: it is what keeps the guard fast.\n *\n * WHY the GitHub PR API and not git: the repo squash-merges, which destroys BOTH commit ancestry and\n * patch-id. `git branch --merged` and `git cherry` therefore report merged branches as unmerged\n * (observed: deanhiller/config-overhaul, PR #188, merged — yet its patch is absent from main). A MERGED\n * PR is the only trustworthy signal, and ONE bulk `gh pr list --state merged` answers for every branch.\n */\n\nconst MERGED_BRANCHES_FILE = 'merged-branches.json';\n\n// How many merged PRs to pull in the single bulk lookup. Branches older than this window are\n// vanishingly unlikely to still be checked out locally; if one is, it lands in `keep` and a human\n// decides — the fail-safe direction.\nconst MERGED_PR_LOOKUP_LIMIT = 100;\n\n// Suffixes the squash-merge tooling appends to a feature branch when it snapshots it mid-sync\n// (base → baseSquash / basewp2 / basePreMerge3). GitHub has never seen these SHAs, so no PR will ever\n// name them — they can only be reaped by stripping back to the base branch they were cloned from.\nconst BACKUP_SUFFIX = /(?:Squash|PreMerge\\d*|wp\\d+)$/;\n\n// Data-only (per CLAUDE.md, classes for data).\nexport class MergedBranch {\n branch: string;\n pr: number;\n\n constructor(branch: string, pr: number) {\n this.branch = branch;\n this.pr = pr;\n }\n}\n\n/**\n * A local branch and the verdict on it. `pr` is 0 when no merged PR backs the verdict (a `keep`).\n *\n * `sha`, `commits` and `prState` exist for the SPARED branches specifically. When nothing is\n * auto-reapable the branch cap has nothing safe to offer, and its only remaining advice was \"raise\n * maxLocalBranches\" / \"set turnOffRuleUntilEpoch\" — both of which loosen the rule. An agent with no\n * human present took the config edit, which is the exact failure the cap exists to prevent. To ask a\n * human \"may I delete these?\" instead, the guard has to be able to SHOW what it would delete: tip SHA\n * (so the delete is recoverable), PR state (closed? never opened?) and how much unique work is on it.\n *\n * All three are computed in the DETACHED refresher and read straight off merged-branches.json — the\n * blocking hook path never recomputes them. Defaulted so a cache written by an older release (and\n * every existing call site) revives without them.\n */\nexport class DeletableBranch {\n branch: string;\n reason: string;\n pr: number;\n /** Short tip SHA — what makes the delete undoable (`git branch <name> <sha>`). '' when unknown. */\n sha: string;\n /** Commits on this branch that are not on origin/main. -1 when it could not be established. */\n commits: number;\n /** GitHub's state for the PR whose head is this branch: MERGED / CLOSED / OPEN, or '' for none. */\n prState: string;\n\n constructor(\n branch: string,\n reason: string,\n pr: number,\n sha: string = '',\n commits: number = -1,\n prState: string = '',\n ) {\n this.branch = branch;\n this.reason = reason;\n this.pr = pr;\n this.sha = sha;\n this.commits = commits;\n this.prState = prState;\n }\n}\n\n/**\n * A worktree and the verdict on it. Carries `path` (what `git worktree remove` takes) AND `branch`\n * (what `git branch -D` takes afterwards) because reaping a worktree is always those two steps, in\n * that order — git refuses to delete a branch that is still checked out somewhere.\n */\nexport class DeletableWorktree {\n path: string;\n branch: string;\n reason: string;\n pr: number;\n deletable: boolean;\n\n constructor(path: string, branch: string, reason: string, pr: number, deletable: boolean) {\n this.path = path;\n this.branch = branch;\n this.reason = reason;\n this.pr = pr;\n this.deletable = deletable;\n }\n}\n\n/**\n * `deletable` is PRECOMPUTED so the consumer just deletes the list — no re-deriving, no judgement\n * call at block time. `keep` carries the branches we refuse to touch (no merged PR found), each with\n * its reason, so a human can see what was spared and why.\n *\n * `worktrees` is the parallel verdict list for the SECOND budget (see worktrees.ts): every linked\n * worktree, each flagged deletable or not. Both budgets are reaped from this one cache file.\n */\nexport class MergedBranchesCache {\n timestamp: string;\n deletable: DeletableBranch[];\n keep: DeletableBranch[];\n worktrees: DeletableWorktree[];\n\n constructor(\n timestamp: string,\n deletable: DeletableBranch[],\n keep: DeletableBranch[],\n worktrees: DeletableWorktree[] = [],\n ) {\n this.timestamp = timestamp;\n this.deletable = deletable;\n this.keep = keep;\n this.worktrees = worktrees;\n }\n}\n\n/**\n * Internal: the bulk PR lookup, indexed.\n *\n * `merged` drives the DELETE verdicts and comes from the `--state merged` call, unchanged — the\n * reaping logic must not get looser or tighter here. `state` is display-only, from a second\n * `--state all` call, and answers the question a human needs in order to say \"yes, delete it\":\n * was there a PR at all, and did it close without merging? It fails soft to an empty map.\n */\nclass PrRef {\n number: number;\n state: string;\n\n constructor(prNumber: number, state: string) {\n this.number = prNumber;\n this.state = state;\n }\n}\n\nclass PrLookup {\n merged: Map<string, number>;\n state: Map<string, PrRef>;\n\n constructor(merged: Map<string, number>, state: Map<string, PrRef>) {\n this.merged = merged;\n this.state = state;\n }\n}\n\n// Internal: a classification result. `deletable` is the decision; `entry` carries the branch + reason\n// either way (a spared branch still needs its reason recorded, and it has no PR to key off).\nclass Verdict {\n deletable: boolean;\n entry: DeletableBranch;\n\n constructor(deletable: boolean, entry: DeletableBranch) {\n this.deletable = deletable;\n this.entry = entry;\n }\n}\n\n// Raw JSON shapes for the cast at the parse boundary.\ninterface RawDeletable {\n branch?: string;\n reason?: string;\n pr?: number;\n // Absent in caches written before the \"ask the human which of these to delete\" remedy existed.\n sha?: string;\n commits?: number;\n prState?: string;\n}\n\ninterface RawWorktree {\n path?: string;\n branch?: string;\n reason?: string;\n pr?: number;\n deletable?: boolean;\n}\n\ninterface RawCache {\n timestamp?: string;\n deletable?: RawDeletable[];\n keep?: RawDeletable[];\n // Absent in caches written by releases before the worktree cap existed — revives to [], which\n // makes the worktree cap fail OPEN on a stale file rather than hard-failing the guard.\n worktrees?: RawWorktree[];\n}\n\ninterface RawMergedPr {\n number?: number;\n headRefName?: string;\n // Only requested by the display-only fetchPrStates call.\n state?: string;\n}\n\n// Result of a captured git/gh invocation: ok=false on spawn failure or non-zero exit.\ninterface CmdCapture {\n ok: boolean;\n out: string;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MergedBranchesService {\n // Defaulted so the non-DI call sites (`new MergedBranchesService()` in the guard and the detached\n // refresher) keep working, while inversify still injects the singleton when resolved from a container.\n constructor(private readonly worktrees: WorktreeService = new WorktreeService()) {}\n\n mergedBranchesPath(repoRoot: string): string {\n return path.join(repoRoot, WEBPIECES_TMP_DIR, MERGED_BRANCHES_FILE);\n }\n\n // Pure read — any error (missing file, malformed JSON) returns null so the guard fails OPEN.\n readMergedBranches(repoRoot: string): MergedBranchesCache | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const cachePath = this.mergedBranchesPath(repoRoot);\n if (!fs.existsSync(cachePath)) return null;\n const raw = JSON.parse(fs.readFileSync(cachePath, 'utf8')) as RawCache;\n return new MergedBranchesCache(\n raw.timestamp ?? '',\n this.reviveList(raw.deletable),\n this.reviveList(raw.keep),\n this.reviveWorktrees(raw.worktrees),\n );\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n writeMergedBranches(repoRoot: string, cache: MergedBranchesCache): void {\n const cachePath = this.mergedBranchesPath(repoRoot);\n fs.mkdirSync(path.dirname(cachePath), { recursive: true });\n fs.writeFileSync(cachePath, JSON.stringify(cache, null, 2) + '\\n');\n }\n\n /**\n * Every local branch except `main`. Uses `git for-each-ref`, NOT `git branch` — the latter is a\n * porcelain command whose output the branch-creation-guard's own regex mistakes for a branch\n * CREATION, so the guard would block the cleanup it just demanded.\n */\n localBranches(repoRoot: string): string[] {\n const result = this.capture(repoRoot, 'git', ['for-each-ref', '--format=%(refname:short)', 'refs/heads/']);\n if (!result.ok || result.out === '') return [];\n return result.out\n .split('\\n')\n .map((line: string): string => line.trim())\n .filter((line: string): boolean => line.length > 0 && line !== 'main');\n }\n\n /**\n * The SLOW path, run only inside the detached refresher. ONE bulk `gh` call, then a purely local\n * classification. Never run on the hook's blocking path.\n */\n computeMergedBranches(repoRoot: string): MergedBranchesCache {\n const merged = this.fetchMergedPrs(repoRoot);\n const byBranch = new Map<string, number>();\n for (const entry of merged) byBranch.set(entry.branch, entry.pr);\n const prs = new PrLookup(byBranch, this.fetchPrStates(repoRoot));\n\n const trees = this.worktrees.listWorktrees(repoRoot);\n const holder = new Map<string, string>();\n for (const tree of trees) {\n if (tree.branch !== '') holder.set(tree.branch, tree.path);\n }\n\n const deletable: DeletableBranch[] = [];\n const keep: DeletableBranch[] = [];\n\n for (const branch of this.localBranches(repoRoot)) {\n const verdict = this.classify(repoRoot, branch, prs);\n\n // A branch checked out in ANY worktree (including the branch we are standing on right here)\n // cannot be deleted — git refuses, and since the reap is ONE `git branch -D a b c`, a single\n // such branch would fail the entire command and strand the branches that would have deleted\n // fine. Spare it LOUDLY (into `keep`, with the reason) rather than dropping it silently: the\n // worktree list below is what actually reaps it, and a human should see the connection.\n const heldAt = holder.get(branch);\n if (heldAt !== undefined) {\n keep.push(new DeletableBranch(\n branch,\n `checked out in worktree '${heldAt}' — remove that worktree before deleting the branch`,\n verdict.entry.pr,\n verdict.entry.sha,\n verdict.entry.commits,\n verdict.entry.prState,\n ));\n continue;\n }\n\n if (verdict.deletable) deletable.push(verdict.entry);\n else keep.push(verdict.entry);\n }\n\n const worktrees = this.classifyWorktrees(repoRoot, trees, prs);\n return new MergedBranchesCache(new Date().toISOString(), deletable, keep, worktrees);\n }\n\n /**\n * Verdicts for the worktree budget. The main worktree is excluded outright — it is the primary\n * clone and is not a thing you can remove.\n *\n * A worktree is deletable when its directory is already gone (`prunable`), or when its branch is\n * dead by the very same proofs the branch cap uses (merged PR, backup-of-merged, or zero commits of\n * its own). It is spared when it is LOCKED (a human said \"do not touch\"), when it is the worktree we\n * are standing in right now (removing your own cwd is not a thing to suggest to an agent), or when\n * its branch still holds unmerged work.\n */\n private classifyWorktrees(\n repoRoot: string,\n trees: Worktree[],\n prs: PrLookup,\n ): DeletableWorktree[] {\n const out: DeletableWorktree[] = [];\n\n for (const tree of trees) {\n if (tree.isMain) continue;\n\n if (tree.prunable) {\n out.push(new DeletableWorktree(\n tree.path, tree.branch, 'its directory is gone — `git worktree prune` clears it', 0, true));\n continue;\n }\n if (tree.locked) {\n out.push(new DeletableWorktree(\n tree.path, tree.branch, 'locked by a human — do not touch', 0, false));\n continue;\n }\n if (tree.path === repoRoot) {\n out.push(new DeletableWorktree(\n tree.path, tree.branch, 'you are standing in it', 0, false));\n continue;\n }\n if (tree.branch === '') {\n out.push(new DeletableWorktree(\n tree.path, '', 'detached HEAD — no branch to check, so a human must decide', 0, false));\n continue;\n }\n\n const verdict = this.classify(repoRoot, tree.branch, prs);\n out.push(new DeletableWorktree(\n tree.path, tree.branch, verdict.entry.reason, verdict.entry.pr, verdict.deletable));\n }\n\n return out;\n }\n\n /**\n * Verdict for one branch: its own merged PR, else the base it was backed up from, else empty.\n *\n * The verdict itself is unchanged. What is new is that EVERY entry now carries its tip SHA, its\n * unique-commit count and its PR state, so a `keep` can be shown to a human as a delete candidate\n * rather than just counted. This runs only in the detached refresher, so the two extra local git\n * calls per branch cost the blocking hook path nothing.\n */\n private classify(repoRoot: string, branch: string, prs: PrLookup): Verdict {\n const sha = this.tipSha(repoRoot, branch);\n const commits = this.commitsAheadOfMain(repoRoot, branch);\n const known = prs.state.get(branch);\n const prState = known ? known.state : '';\n\n const own = prs.merged.get(branch);\n if (own !== undefined) {\n return new Verdict(true, new DeletableBranch(\n branch, `PR #${String(own)} merged`, own, sha, commits, prState || 'MERGED'));\n }\n\n const base = branch.replace(BACKUP_SUFFIX, '');\n if (base !== branch && base.length > 0) {\n const basePr = prs.merged.get(base);\n if (basePr !== undefined) {\n return new Verdict(true, new DeletableBranch(\n branch,\n `squash-merge backup of '${base}' (PR #${String(basePr)} merged) — its job is done`,\n basePr, sha, commits, prState,\n ));\n }\n }\n\n // The one git-local signal that squash-merge CANNOT corrupt: a branch with zero commits of its\n // own holds no work, so deleting it can lose nothing. (Squash breaks patch-id and ancestry, so\n // \"are these commits in main?\" is unanswerable from git — but \"are there any commits at all?\"\n // is exact.) These are the husks left behind by branching and then never committing.\n if (commits === 0) {\n return new Verdict(true, new DeletableBranch(\n branch, 'no commits of its own — identical to origin/main', 0, sha, 0, prState));\n }\n\n const why = known\n ? `PR #${String(known.number)} is ${known.state} (not merged) — a human must decide`\n : 'no merged PR found — a human must decide';\n return new Verdict(false, new DeletableBranch(branch, why, 0, sha, commits, prState));\n }\n\n // Short tip SHA — the value that makes any delete of this branch reversible.\n private tipSha(repoRoot: string, branch: string): string {\n const result = this.capture(repoRoot, 'git', ['rev-parse', '--short', branch]);\n return result.ok ? result.out : '';\n }\n\n /**\n * Commits on `branch` that are not on origin/main. Returns -1 (\"assume it has work\") whenever the\n * count cannot be established — an unresolvable origin/main must never read as \"empty branch\".\n */\n private commitsAheadOfMain(repoRoot: string, branch: string): number {\n const result = this.capture(repoRoot, 'git', ['rev-list', '--count', `origin/main..${branch}`]);\n if (!result.ok) return -1;\n const count = Number(result.out);\n return Number.isInteger(count) ? count : -1;\n }\n\n /**\n * The ONE bulk network call. Every merged PR's head branch in a single round trip — no per-branch\n * lookups. Fails SOFT: if `gh` is missing, unauthenticated, or offline we return [], which makes\n * every branch a `keep`. The guard then deletes nothing rather than guessing.\n */\n private fetchMergedPrs(repoRoot: string): MergedBranch[] {\n const result = this.capture(repoRoot, 'gh', [\n 'pr', 'list',\n '--state', 'merged',\n '--limit', String(MERGED_PR_LOOKUP_LIMIT),\n '--json', 'number,headRefName',\n ]);\n if (!result.ok || result.out === '') return [];\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = JSON.parse(result.out) as RawMergedPr[];\n const out: MergedBranch[] = [];\n for (const entry of raw) {\n const branch = entry.headRefName ?? '';\n const pr = entry.number ?? 0;\n if (branch !== '' && pr > 0) out.push(new MergedBranch(branch, pr));\n }\n return out;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n\n /**\n * The DISPLAY-only second lookup: every PR (any state) keyed by head branch, so a spared branch can\n * be shown to a human as \"PR #12 CLOSED (not merged)\" or \"no PR\" instead of an opaque name. Kept\n * SEPARATE from fetchMergedPrs on purpose — folding both into one `--state all` call would let a\n * flood of open/closed PRs push older MERGED ones out of the limit and silently stop reaping real\n * dead branches. Fails soft to an empty map: the verdicts do not depend on it.\n */\n private fetchPrStates(repoRoot: string): Map<string, PrRef> {\n const out = new Map<string, PrRef>();\n const result = this.capture(repoRoot, 'gh', [\n 'pr', 'list',\n '--state', 'all',\n '--limit', String(MERGED_PR_LOOKUP_LIMIT),\n '--json', 'number,headRefName,state',\n ]);\n if (!result.ok || result.out === '') return out;\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = JSON.parse(result.out) as RawMergedPr[];\n for (const entry of raw) {\n const branch = entry.headRefName ?? '';\n const pr = entry.number ?? 0;\n // `gh` lists newest-first, so the FIRST entry for a branch is its latest PR — keep it.\n if (branch !== '' && pr > 0 && !out.has(branch)) {\n out.set(branch, new PrRef(pr, entry.state ?? ''));\n }\n }\n return out;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return out;\n }\n }\n\n private reviveList(raw: RawDeletable[] | undefined): DeletableBranch[] {\n if (!raw) return [];\n return raw.map((entry: RawDeletable): DeletableBranch => new DeletableBranch(\n entry.branch ?? '',\n entry.reason ?? '',\n entry.pr ?? 0,\n entry.sha ?? '',\n entry.commits ?? -1,\n entry.prState ?? '',\n ));\n }\n\n private reviveWorktrees(raw: RawWorktree[] | undefined): DeletableWorktree[] {\n if (!raw) return [];\n return raw.map((entry: RawWorktree): DeletableWorktree => new DeletableWorktree(\n entry.path ?? '',\n entry.branch ?? '',\n entry.reason ?? '',\n entry.pr ?? 0,\n entry.deletable ?? false,\n ));\n }\n\n // Run a command capturing trimmed stdout; ok=false on spawn failure or non-zero exit.\n private capture(repoRoot: string, cmd: string, args: string[]): CmdCapture {\n const result = spawnSync(cmd, args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status !== 0 || typeof result.stdout !== 'string') return { ok: false, out: '' };\n return { ok: true, out: result.stdout.trim() };\n }\n}\n"]}
|
|
@@ -16,7 +16,8 @@ That question is already answered: **yes, always.** Run the flow:
|
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
18
|
pnpm wp-start-upsert-pr # updates from main, pushes, runs the build gate, tells you to write review.json
|
|
19
|
-
# → write
|
|
19
|
+
# → write the review.json at the exact path wp-start-upsert-pr prints
|
|
20
|
+
# (.webpieces/pr-review/<feature>/review.json — its `title` becomes the PR title)
|
|
20
21
|
pnpm wp-finish-upsert-pr # authoritative build gate, then creates/updates the PR
|
|
21
22
|
```
|
|
22
23
|
|