@webpieces/ai-hook-rules 0.3.377 → 0.3.379
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/ai-hook-rules",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.379",
|
|
4
4
|
"description": "Pluggable write-time validation framework for AI coding agents (@webpieces/ai-hook-rules). Claude Code PreToolUse + openclaw before_tool_call adapters share one rule engine.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"directory": "packages/tooling/ai-hook-rules"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@webpieces/rules-config": "0.3.
|
|
34
|
+
"@webpieces/rules-config": "0.3.379"
|
|
35
35
|
},
|
|
36
36
|
"publishConfig": {
|
|
37
37
|
"access": "public"
|
|
@@ -9,12 +9,18 @@ export declare class BranchCreationGuardRule extends BashRuleBase<BranchCreation
|
|
|
9
9
|
subBranchNaming: string;
|
|
10
10
|
branchFormat: string;
|
|
11
11
|
maxLocalBranches: number;
|
|
12
|
+
maxWorktrees: number;
|
|
12
13
|
};
|
|
14
|
+
private readonly worktrees;
|
|
13
15
|
private readonly mergedBranches;
|
|
14
16
|
private capCache;
|
|
17
|
+
private worktreeCapCache;
|
|
18
|
+
private worktreeAdd;
|
|
15
19
|
private get branchFormat();
|
|
16
20
|
private get subBranchNaming();
|
|
17
21
|
private get maxLocalBranches();
|
|
22
|
+
private get maxWorktrees();
|
|
23
|
+
private freshMainCommand;
|
|
18
24
|
get fixHint(): FixHint;
|
|
19
25
|
/**
|
|
20
26
|
* Strip the parts of a shell command that are DATA rather than executable commands, so the guard
|
|
@@ -33,6 +39,16 @@ export declare class BranchCreationGuardRule extends BashRuleBase<BranchCreation
|
|
|
33
39
|
*/
|
|
34
40
|
private stripNonCommandText;
|
|
35
41
|
check(ctx: BashContext): readonly Violation[];
|
|
42
|
+
/**
|
|
43
|
+
* Both budgets, in the order that produces the most useful complaint.
|
|
44
|
+
*
|
|
45
|
+
* Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,
|
|
46
|
+
* always-permitted path, so a cap checked after it would never once fire.
|
|
47
|
+
*
|
|
48
|
+
* Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the
|
|
49
|
+
* worktree is the thing the command was actually trying to make, so it is the thing to talk about.
|
|
50
|
+
*/
|
|
51
|
+
private checkCaps;
|
|
36
52
|
/**
|
|
37
53
|
* The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing
|
|
38
54
|
* keeping the local branch list bounded.
|
|
@@ -42,6 +58,14 @@ export declare class BranchCreationGuardRule extends BashRuleBase<BranchCreation
|
|
|
42
58
|
* so the cap starts enforcing on its own.
|
|
43
59
|
*/
|
|
44
60
|
private checkBranchCap;
|
|
61
|
+
/**
|
|
62
|
+
* The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a
|
|
63
|
+
* worktree list we cannot classify (no cache on disk) blocks nothing.
|
|
64
|
+
*
|
|
65
|
+
* Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the
|
|
66
|
+
* budget for it would just silently cost you one worktree.
|
|
67
|
+
*/
|
|
68
|
+
private checkWorktreeCap;
|
|
45
69
|
/**
|
|
46
70
|
* The reap instructions. `deletable` is PRECOMPUTED in the cache, and every entry earned its place
|
|
47
71
|
* by one of exactly two proofs: a MERGED PR (the work is in main), or zero commits of its own
|
|
@@ -51,4 +75,16 @@ export declare class BranchCreationGuardRule extends BashRuleBase<BranchCreation
|
|
|
51
75
|
* message that tells an agent to run `git branch -D` has to be exactly true about why that's safe.
|
|
52
76
|
*/
|
|
53
77
|
private capFixHint;
|
|
78
|
+
/**
|
|
79
|
+
* The worktree reap instructions.
|
|
80
|
+
*
|
|
81
|
+
* The command ORDER is load-bearing and is the whole reason this is generated rather than described:
|
|
82
|
+
* 1. `git worktree prune` — clears the admin data of worktrees whose directory is already gone.
|
|
83
|
+
* `git worktree remove` FAILS on those, so it cannot be the first step.
|
|
84
|
+
* 2. `git worktree remove <path>` — one path per invocation; git takes no path list here.
|
|
85
|
+
* 3. `git branch -D <names>` — only now. git flatly refuses to delete a branch that is still
|
|
86
|
+
* checked out in a worktree, so a branch delete placed before the removal fails, and because
|
|
87
|
+
* it is one multi-name command it takes every other branch in the list down with it.
|
|
88
|
+
*/
|
|
89
|
+
private worktreeCapFixHint;
|
|
54
90
|
}
|
|
@@ -13,7 +13,13 @@ const DEFAULT_BRANCH_FORMAT = 'Name it {whoami}/<short-feature-description> —
|
|
|
13
13
|
const DEFAULT_SUB_BRANCH_NAMING = 'feature/<ticket>/<short-description>';
|
|
14
14
|
// Hard cap on local feature branches. Enforced at CREATION because that is the one moment cleanup is
|
|
15
15
|
// both cheap and obviously worth it — reaping happens over time, never "ASAP".
|
|
16
|
+
//
|
|
17
|
+
// The branch cap counts PARKED branches only — branches not checked out in any worktree. Worktree-held
|
|
18
|
+
// branches are counted by the worktree cap instead. Two budgets, because they are not substitutes: if
|
|
19
|
+
// held branches also spent the branch budget, five worktrees would leave room for zero branches and no
|
|
20
|
+
// branch could ever be created again.
|
|
16
21
|
const DEFAULT_MAX_LOCAL_BRANCHES = 5;
|
|
22
|
+
const DEFAULT_MAX_WORKTREES = 5;
|
|
17
23
|
// A plausible git ref name. Deliberately NOT `[^\s-]` — that class matches shell metacharacters, so
|
|
18
24
|
// `git branch | wc -l` (a read-only LISTING, piped) was parsed as "create a branch named `|`" and
|
|
19
25
|
// blocked. Cleanup work necessarily reads and deletes branches, so a listing must never trip this.
|
|
@@ -22,7 +28,16 @@ const BRANCH_PATTERNS = [
|
|
|
22
28
|
new RegExp(String.raw `git\s+checkout\s+-[bB]\s+(${REF_NAME})`),
|
|
23
29
|
new RegExp(String.raw `git\s+switch\s+-[cC]\s+(${REF_NAME})`),
|
|
24
30
|
new RegExp(String.raw `git\s+branch\s+(?!-)(${REF_NAME})`),
|
|
31
|
+
// `git worktree add ../dir -b <name> origin/main` — the form docs/git-workflow.md recommends for
|
|
32
|
+
// starting a feature. It creates a branch just as surely as `checkout -b` does, and until this
|
|
33
|
+
// pattern existed it walked straight past the cap, the reserved-suffix check and the sub-branch
|
|
34
|
+
// check. `(?:\S+\s+)*?` absorbs the path and any other flags, so the -b may precede or follow them.
|
|
35
|
+
new RegExp(String.raw `git\s+worktree\s+add\s+(?:\S+\s+)*?-[bB]\s+(${REF_NAME})`),
|
|
25
36
|
];
|
|
37
|
+
// ANY worktree creation, with or without -b. The no-`-b` forms (`git worktree add ../dir existing`,
|
|
38
|
+
// `--detach`) create no branch but DO create a worktree, so they spend the worktree budget and must
|
|
39
|
+
// still hit the cap.
|
|
40
|
+
const WORKTREE_ADD = /git\s+worktree\s+add\b/;
|
|
26
41
|
// A trailing `wp<number>` was the old squash-merge generation marker (base → basewp2 → basewp3).
|
|
27
42
|
// The tooling NO LONGER produces it — a sync now lands back on the same feature name — but the suffix
|
|
28
43
|
// stays RESERVED so a human branch can't collide with a leftover `…wpN` still floating in a consumer
|
|
@@ -37,6 +52,11 @@ const RESERVED_GENERATION_SUFFIX = /wp\d+$/;
|
|
|
37
52
|
// than the BLOCK pattern above, or a `git checkout -b x origin/main` that ends at a quote or backtick
|
|
38
53
|
// is seen as a branch creation but NOT as an origin/main one — recognised, then wrongly blocked.
|
|
39
54
|
const ORIGIN_MAIN_BASE = /git\s+(?:checkout\s+-[bB]|switch\s+-[cC])\s+\S+\s+origin\/main(?:\W|$)/;
|
|
55
|
+
// The worktree arm of the same allow: `git worktree add ../dir -b <name> origin/main`. Same fresh-main
|
|
56
|
+
// base, same reasoning — and in a worktree it is the ONLY workable base, since `git checkout main`
|
|
57
|
+
// fatals there. Kept separate from ORIGIN_MAIN_BASE because the argument shape differs (a path sits
|
|
58
|
+
// between the subcommand and the flags).
|
|
59
|
+
const WORKTREE_ORIGIN_MAIN_BASE = /git\s+worktree\s+add\s+(?:\S+\s+)*origin\/main(?:\W|$)/;
|
|
40
60
|
// Heredoc bodies: `<<EOF … \nEOF` / `<<-'EOF' … \nEOF`. Their content is DATA (a commit message, a
|
|
41
61
|
// file being written), never a command.
|
|
42
62
|
const HEREDOC_BODY = /<<-?\s*(['"]?)(\w+)\1[\s\S]*?^\t*\2\s*$/gm;
|
|
@@ -71,17 +91,24 @@ function checkMainIsUpToDate(ctx, requestedName) {
|
|
|
71
91
|
}
|
|
72
92
|
class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
|
|
73
93
|
constructor(config) { super(config, 'branch-creation-guard'); }
|
|
74
|
-
description = 'Block new-branch creation when main is stale, when branching off a non-main
|
|
75
|
-
'or when the
|
|
94
|
+
description = 'Block new-branch and new-worktree creation when main is stale, when branching off a non-main ' +
|
|
95
|
+
'branch, or when the branch/worktree count is at its cap (forces cleanup of dead ones).';
|
|
76
96
|
defaultOptions = {
|
|
77
97
|
subBranchNaming: DEFAULT_SUB_BRANCH_NAMING,
|
|
78
98
|
branchFormat: DEFAULT_BRANCH_FORMAT,
|
|
79
99
|
maxLocalBranches: DEFAULT_MAX_LOCAL_BRANCHES,
|
|
100
|
+
maxWorktrees: DEFAULT_MAX_WORKTREES,
|
|
80
101
|
};
|
|
81
|
-
|
|
82
|
-
|
|
102
|
+
worktrees = new rules_config_1.WorktreeService();
|
|
103
|
+
mergedBranches = new rules_config_1.MergedBranchesService(this.worktrees);
|
|
104
|
+
// Set by check() when (and only when) a cap is what blocked, so fixHint can render the reap
|
|
83
105
|
// instructions instead of the branch-naming ones. Same instance-field handoff pr-merge-guard uses.
|
|
106
|
+
// Two fields, because the two caps reap different things and their hints share no wording.
|
|
84
107
|
capCache = null;
|
|
108
|
+
worktreeCapCache = null;
|
|
109
|
+
// True when the blocked command was a `git worktree add`, so the recovery command we hand back is
|
|
110
|
+
// a worktree command and not a `git checkout -b` the user cannot use here.
|
|
111
|
+
worktreeAdd = false;
|
|
85
112
|
get branchFormat() {
|
|
86
113
|
return this.config.branchFormat ?? DEFAULT_BRANCH_FORMAT;
|
|
87
114
|
}
|
|
@@ -91,14 +118,28 @@ class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
|
|
|
91
118
|
get maxLocalBranches() {
|
|
92
119
|
return this.config.maxLocalBranches ?? DEFAULT_MAX_LOCAL_BRANCHES;
|
|
93
120
|
}
|
|
121
|
+
get maxWorktrees() {
|
|
122
|
+
return this.config.maxWorktrees ?? DEFAULT_MAX_WORKTREES;
|
|
123
|
+
}
|
|
124
|
+
// The recovery command for "base this off fresh main", in the flavour of whatever was blocked.
|
|
125
|
+
freshMainCommand(name) {
|
|
126
|
+
return this.worktreeAdd
|
|
127
|
+
? `git fetch origin main && git worktree add ../${name.replace(/\//g, '-')} -b ${name} origin/main`
|
|
128
|
+
: `git fetch origin main && git checkout -b ${name} origin/main`;
|
|
129
|
+
}
|
|
94
130
|
// Mode-aware fix hints. Branches off main follow branchFormat — never the sub-branch
|
|
95
131
|
// convention. The sub-branch affordance only appears under mode 'ON'; 'ON_NO_SUBBRANCHES'
|
|
96
132
|
// hard-blocks it and points instead at the ignoreModifiedUntilEpoch escape hatch.
|
|
97
133
|
get fixHint() {
|
|
134
|
+
if (this.worktreeCapCache)
|
|
135
|
+
return this.worktreeCapFixHint(this.worktreeCapCache);
|
|
98
136
|
if (this.capCache)
|
|
99
137
|
return this.capFixHint(this.capCache);
|
|
138
|
+
const create = this.worktreeAdd
|
|
139
|
+
? 'Create it off fresh main: git fetch origin main && git worktree add ../<dir> -b <name> origin/main'
|
|
140
|
+
: 'Create it off fresh main from anywhere (incl. a worktree): git fetch origin main && git checkout -b <name> origin/main';
|
|
100
141
|
const options = [
|
|
101
|
-
new fix_hint_1.Option(
|
|
142
|
+
new fix_hint_1.Option(create, true),
|
|
102
143
|
new fix_hint_1.Option(`Name a branch off main per branch-creation-guard.branchFormat: ${this.branchFormat}`),
|
|
103
144
|
];
|
|
104
145
|
if (this.config.mode === 'ON_NO_SUBBRANCHES') {
|
|
@@ -134,27 +175,35 @@ class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
|
|
|
134
175
|
}
|
|
135
176
|
check(ctx) {
|
|
136
177
|
this.capCache = null;
|
|
178
|
+
this.worktreeCapCache = null;
|
|
137
179
|
// Match against the command with heredoc bodies and prose-in-quotes removed. A commit message
|
|
138
180
|
// that merely MENTIONS a branch command is not a branch command.
|
|
139
181
|
const command = this.stripNonCommandText(ctx.command);
|
|
140
182
|
const requestedName = extractBranchName(command);
|
|
141
|
-
|
|
183
|
+
this.worktreeAdd = WORKTREE_ADD.test(command);
|
|
184
|
+
// A worktree add with no -b creates no branch, but it DOES spend the worktree budget, so it must
|
|
185
|
+
// survive this early-out and reach the worktree cap below.
|
|
186
|
+
if (!requestedName && !this.worktreeAdd)
|
|
142
187
|
return [];
|
|
143
|
-
if (RESERVED_GENERATION_SUFFIX.test(requestedName)) {
|
|
188
|
+
if (requestedName && RESERVED_GENERATION_SUFFIX.test(requestedName)) {
|
|
144
189
|
return [new types_1.Violation(1, truncate(ctx.command), `Branch name '${requestedName}' ends in 'wp<number>', which is reserved for the ` +
|
|
145
190
|
`squash-merge tool's generation marker (base → basewp2 → basewp3). ` +
|
|
146
191
|
`Rename it to a plain feature branch. ${this.branchFormat}.`)];
|
|
147
192
|
}
|
|
148
|
-
|
|
149
|
-
// is the normal, always-permitted path, so a cap check placed after it would never once fire.
|
|
150
|
-
const capViolation = this.checkBranchCap(ctx);
|
|
193
|
+
const capViolation = this.checkCaps(ctx, requestedName !== null);
|
|
151
194
|
if (capViolation)
|
|
152
195
|
return [capViolation];
|
|
196
|
+
// `git worktree add` of an EXISTING branch (or --detach) creates no branch: the cap above was the
|
|
197
|
+
// only rule that applies to it. Nothing left to check.
|
|
198
|
+
if (!requestedName)
|
|
199
|
+
return [];
|
|
153
200
|
// Explicitly basing off origin/main is always allowed — it creates the branch from fresh main
|
|
154
201
|
// regardless of the current branch, and is the ONLY way that also works inside a linked worktree
|
|
155
202
|
// (where `git checkout main` fatals). Reserved-name check above still applies.
|
|
156
203
|
if (ORIGIN_MAIN_BASE.test(command))
|
|
157
204
|
return [];
|
|
205
|
+
if (this.worktreeAdd && WORKTREE_ORIGIN_MAIN_BASE.test(command))
|
|
206
|
+
return [];
|
|
158
207
|
const currentBranch = (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
|
|
159
208
|
cwd: ctx.workspaceRoot,
|
|
160
209
|
encoding: 'utf8',
|
|
@@ -165,16 +214,35 @@ class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
|
|
|
165
214
|
// Not on main: creating this branch would stack it on a feature branch (a sub-branch).
|
|
166
215
|
if (this.config.mode === 'ON_NO_SUBBRANCHES') {
|
|
167
216
|
return [new types_1.Violation(1, truncate(ctx.command), `You are on '${currentBranch}', not main. Create the branch OFF origin/main instead of ` +
|
|
168
|
-
`stacking it on this branch:
|
|
217
|
+
`stacking it on this branch: ${this.freshMainCommand(requestedName)} ` +
|
|
169
218
|
`(works here and inside a worktree). ${this.branchFormat}. ` +
|
|
170
219
|
`You can temporarily turn this off if you truly need a sub-branch by setting ` +
|
|
171
220
|
`branch-creation-guard.ignoreModifiedUntilEpoch (a future epoch) in webpieces.config.json.`)];
|
|
172
221
|
}
|
|
173
222
|
return [new types_1.Violation(1, truncate(ctx.command), `You are on '${currentBranch}', not main. Branches must be created from fresh main: ` +
|
|
174
|
-
|
|
223
|
+
`${this.freshMainCommand(requestedName)}. ${this.branchFormat}. ` +
|
|
175
224
|
`If you truly need a stacked sub-branch (requires human approval), name it per ` +
|
|
176
225
|
`branch-creation-guard.subBranchNaming ('${this.subBranchNaming}').`)];
|
|
177
226
|
}
|
|
227
|
+
/**
|
|
228
|
+
* Both budgets, in the order that produces the most useful complaint.
|
|
229
|
+
*
|
|
230
|
+
* Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,
|
|
231
|
+
* always-permitted path, so a cap checked after it would never once fire.
|
|
232
|
+
*
|
|
233
|
+
* Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the
|
|
234
|
+
* worktree is the thing the command was actually trying to make, so it is the thing to talk about.
|
|
235
|
+
*/
|
|
236
|
+
checkCaps(ctx, createsBranch) {
|
|
237
|
+
if (this.worktreeAdd) {
|
|
238
|
+
const worktreeViolation = this.checkWorktreeCap(ctx);
|
|
239
|
+
if (worktreeViolation)
|
|
240
|
+
return worktreeViolation;
|
|
241
|
+
}
|
|
242
|
+
if (createsBranch)
|
|
243
|
+
return this.checkBranchCap(ctx);
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
178
246
|
/**
|
|
179
247
|
* The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing
|
|
180
248
|
* keeping the local branch list bounded.
|
|
@@ -184,7 +252,12 @@ class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
|
|
|
184
252
|
* so the cap starts enforcing on its own.
|
|
185
253
|
*/
|
|
186
254
|
checkBranchCap(ctx) {
|
|
187
|
-
|
|
255
|
+
// PARKED branches only — a branch checked out in a worktree is the worktree cap's problem, and
|
|
256
|
+
// counting it twice would let five worktrees exhaust the branch budget on their own.
|
|
257
|
+
const held = this.worktrees.heldBranches(ctx.workspaceRoot);
|
|
258
|
+
const parked = this.mergedBranches.localBranches(ctx.workspaceRoot)
|
|
259
|
+
.filter((branch) => !held.has(branch));
|
|
260
|
+
const count = parked.length;
|
|
188
261
|
if (count < this.maxLocalBranches)
|
|
189
262
|
return null;
|
|
190
263
|
const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);
|
|
@@ -195,8 +268,32 @@ class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
|
|
|
195
268
|
const detail = reapable > 0
|
|
196
269
|
? `${String(reapable)} of them are dead (merged, or holding no commits) and can be deleted right now.`
|
|
197
270
|
: 'None of them are dead, so none can be auto-reaped — see the options below.';
|
|
198
|
-
return new types_1.Violation(1, truncate(ctx.command), `You have ${String(count)} local branches
|
|
199
|
-
`is ${String(this.maxLocalBranches)}.
|
|
271
|
+
return new types_1.Violation(1, truncate(ctx.command), `You have ${String(count)} parked local branches (not counting any checked out in a worktree); ` +
|
|
272
|
+
`the cap (branch-creation-guard.maxLocalBranches) is ${String(this.maxLocalBranches)}. ` +
|
|
273
|
+
`${detail} Clean up before creating another.`);
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a
|
|
277
|
+
* worktree list we cannot classify (no cache on disk) blocks nothing.
|
|
278
|
+
*
|
|
279
|
+
* Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the
|
|
280
|
+
* budget for it would just silently cost you one worktree.
|
|
281
|
+
*/
|
|
282
|
+
checkWorktreeCap(ctx) {
|
|
283
|
+
const count = this.worktrees.linkedWorktrees(ctx.workspaceRoot).length;
|
|
284
|
+
if (count < this.maxWorktrees)
|
|
285
|
+
return null;
|
|
286
|
+
const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);
|
|
287
|
+
if (!cache)
|
|
288
|
+
return null;
|
|
289
|
+
this.worktreeCapCache = cache;
|
|
290
|
+
const reapable = cache.worktrees.filter((tree) => tree.deletable).length;
|
|
291
|
+
const detail = reapable > 0
|
|
292
|
+
? `${String(reapable)} of them are dead (merged branch, no commits, or a missing directory) ` +
|
|
293
|
+
'and can be removed right now.'
|
|
294
|
+
: 'None of them are dead, so none can be auto-reaped — see the options below.';
|
|
295
|
+
return new types_1.Violation(1, truncate(ctx.command), `You have ${String(count)} linked worktrees; the cap (branch-creation-guard.maxWorktrees) ` +
|
|
296
|
+
`is ${String(this.maxWorktrees)}. ${detail} Clean up before creating another.`);
|
|
200
297
|
}
|
|
201
298
|
/**
|
|
202
299
|
* The reap instructions. `deletable` is PRECOMPUTED in the cache, and every entry earned its place
|
|
@@ -225,6 +322,49 @@ class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
|
|
|
225
322
|
return new fix_hint_1.FixHint('Too many local branches — reap the dead ones before creating another.', 'Full detail (deletable + spared, with per-branch reasons) is in .webpieces/merged-branches.json, ' +
|
|
226
323
|
`refreshed ${cache.timestamp || 'never'}.${kept} Pick one:`, options);
|
|
227
324
|
}
|
|
325
|
+
/**
|
|
326
|
+
* The worktree reap instructions.
|
|
327
|
+
*
|
|
328
|
+
* The command ORDER is load-bearing and is the whole reason this is generated rather than described:
|
|
329
|
+
* 1. `git worktree prune` — clears the admin data of worktrees whose directory is already gone.
|
|
330
|
+
* `git worktree remove` FAILS on those, so it cannot be the first step.
|
|
331
|
+
* 2. `git worktree remove <path>` — one path per invocation; git takes no path list here.
|
|
332
|
+
* 3. `git branch -D <names>` — only now. git flatly refuses to delete a branch that is still
|
|
333
|
+
* checked out in a worktree, so a branch delete placed before the removal fails, and because
|
|
334
|
+
* it is one multi-name command it takes every other branch in the list down with it.
|
|
335
|
+
*/
|
|
336
|
+
worktreeCapFixHint(cache) {
|
|
337
|
+
const options = [];
|
|
338
|
+
const dead = cache.worktrees.filter((tree) => tree.deletable);
|
|
339
|
+
if (dead.length > 0) {
|
|
340
|
+
const steps = ['git worktree prune'];
|
|
341
|
+
for (const tree of dead) {
|
|
342
|
+
// A prunable worktree has no directory left to remove — step 1 already handled it.
|
|
343
|
+
if (tree.path !== '')
|
|
344
|
+
steps.push(`git worktree remove ${tree.path}`);
|
|
345
|
+
}
|
|
346
|
+
const branches = dead
|
|
347
|
+
.map((tree) => tree.branch)
|
|
348
|
+
.filter((branch) => branch !== '');
|
|
349
|
+
if (branches.length > 0)
|
|
350
|
+
steps.push(`git branch -D ${branches.join(' ')}`);
|
|
351
|
+
options.push(new fix_hint_1.Option(`Remove these ${String(dead.length)} dead worktrees — each holds a branch backed by a MERGED ` +
|
|
352
|
+
'PR, a branch with no commits of its own, or a directory that is already gone, so no work ' +
|
|
353
|
+
'can be lost (see merged-branches.json for the per-worktree reason). Run it in this order ' +
|
|
354
|
+
`(prune first, branches last — git refuses to delete a branch a worktree still holds): ${steps.join(' && ')}`, true));
|
|
355
|
+
}
|
|
356
|
+
options.push(new fix_hint_1.Option('If you genuinely need more worktrees in flight, raise branch-creation-guard.maxWorktrees ' +
|
|
357
|
+
'in webpieces.config.json.'));
|
|
358
|
+
options.push(new fix_hint_1.Option('To bypass this once, set branch-creation-guard.ignoreModifiedUntilEpoch (a future epoch) ' +
|
|
359
|
+
'in webpieces.config.json.'));
|
|
360
|
+
const spared = cache.worktrees.length - dead.length;
|
|
361
|
+
const kept = spared > 0
|
|
362
|
+
? ` ${String(spared)} worktree(s) were deliberately SPARED (locked, holding unmerged work, or ` +
|
|
363
|
+
'the one you are standing in) — do not remove those; a human decides.'
|
|
364
|
+
: '';
|
|
365
|
+
return new fix_hint_1.FixHint('Too many worktrees — reap the dead ones before creating another.', 'Full detail (deletable + spared, with per-worktree reasons) is in .webpieces/merged-branches.json, ' +
|
|
366
|
+
`refreshed ${cache.timestamp || 'never'}.${kept} Pick one:`, options);
|
|
367
|
+
}
|
|
228
368
|
}
|
|
229
369
|
exports.BranchCreationGuardRule = BranchCreationGuardRule;
|
|
230
370
|
//# sourceMappingURL=branch-creation-guard.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"branch-creation-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/branch-creation-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAKiC;AAGjC,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAA8C;AAE9C,8EAA8E;AAC9E,+FAA+F;AAC/F,kGAAkG;AAClG,MAAM,qBAAqB,GACvB,4HAA4H,CAAC;AACjI,MAAM,yBAAyB,GAAG,sCAAsC,CAAC;AAEzE,qGAAqG;AACrG,+EAA+E;AAC/E,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAErC,oGAAoG;AACpG,kGAAkG;AAClG,mGAAmG;AACnG,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAA,6BAA6B,CAAC;A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C;YAC7B,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,KAAsB,EAAU,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YACpF,OAAO,CAAC,IAAI,CAAC,IAAI,iBAAM,CACnB,gBAAgB,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,wDAAwD;gBAC5F,yFAAyF;gBACzF,qCAAqC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EACtD,IAAI,CACP,CAAC,CAAC;QACP,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,IAAI,iBAAM,CACnB,8FAA8F;YAC9F,2BAA2B,CAC9B,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,IAAI,iBAAM,CACnB,2FAA2F;YAC3F,2BAA2B,CAC9B,CAAC,CAAC;QAEH,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC;YAC9B,CAAC,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,oEAAoE;gBACjG,uCAAuC;YACzC,CAAC,CAAC,EAAE,CAAC;QAET,OAAO,IAAI,kBAAO,CACd,uEAAuE,EACvE,mGAAmG;YACnG,aAAa,KAAK,CAAC,SAAS,IAAI,OAAO,IAAI,IAAI,YAAY,EAC3D,OAAO,CACV,CAAC;IACN,CAAC;CACJ;AAnND,0DAmNC","sourcesContent":["import { execSync } from 'child_process';\n\nimport {\n BranchCreationGuardConfig,\n DeletableBranch,\n MergedBranchesCache,\n MergedBranchesService,\n} from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint, Option } from '../fix-hint';\n\n// Defaults used when the rule has no explicit value in webpieces.config.json.\n// branchFormat is a human sentence telling the AI how to name a branch created off main; it is\n// intentionally NOT the sub-branch convention (sub-branches are a separate, human-approved path).\nconst DEFAULT_BRANCH_FORMAT =\n 'Name it {whoami}/<short-feature-description> — lowercase, no version numbers, no sub/ prefix (e.g. dean/upgrade-webpieces)';\nconst DEFAULT_SUB_BRANCH_NAMING = 'feature/<ticket>/<short-description>';\n\n// Hard cap on local feature branches. Enforced at CREATION because that is the one moment cleanup is\n// both cheap and obviously worth it — reaping happens over time, never \"ASAP\".\nconst DEFAULT_MAX_LOCAL_BRANCHES = 5;\n\n// A plausible git ref name. Deliberately NOT `[^\\s-]` — that class matches shell metacharacters, so\n// `git branch | wc -l` (a read-only LISTING, piped) was parsed as \"create a branch named `|`\" and\n// blocked. Cleanup work necessarily reads and deletes branches, so a listing must never trip this.\nconst REF_NAME = String.raw`[A-Za-z0-9][A-Za-z0-9_./-]*`;\n\nconst BRANCH_PATTERNS: RegExp[] = [\n new RegExp(String.raw`git\\s+checkout\\s+-[bB]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+switch\\s+-[cC]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+branch\\s+(?!-)(${REF_NAME})`),\n];\n\n// A trailing `wp<number>` was the old squash-merge generation marker (base → basewp2 → basewp3).\n// The tooling NO LONGER produces it — a sync now lands back on the same feature name — but the suffix\n// stays RESERVED so a human branch can't collide with a leftover `…wpN` still floating in a consumer\n// repo mid-transition. Block it at creation time and steer the name back to the plain feature form.\nconst RESERVED_GENERATION_SUFFIX = /wp\\d+$/;\n\n// A branch-creation command that explicitly bases off origin/main (e.g. `git checkout -b feat\n// origin/main`). This is exactly the fresh-main base the guard wants, and it works from ANY current\n// branch or linked worktree — main need not (and in a worktree cannot) be checked out here. Allowed\n// unconditionally so the recovery messages can safely tell you to run it from a worktree.\n//\n// The trailing check is `\\W|$`, not `\\s|$`: the ALLOW pattern must not be stricter about delimiters\n// than the BLOCK pattern above, or a `git checkout -b x origin/main` that ends at a quote or backtick\n// is seen as a branch creation but NOT as an origin/main one — recognised, then wrongly blocked.\nconst ORIGIN_MAIN_BASE = /git\\s+(?:checkout\\s+-[bB]|switch\\s+-[cC])\\s+\\S+\\s+origin\\/main(?:\\W|$)/;\n\n// Heredoc bodies: `<<EOF … \\nEOF` / `<<-'EOF' … \\nEOF`. Their content is DATA (a commit message, a\n// file being written), never a command.\nconst HEREDOC_BODY = /<<-?\\s*(['\"]?)(\\w+)\\1[\\s\\S]*?^\\t*\\2\\s*$/gm;\n\n// A single- or double-quoted span.\nconst QUOTED_SPAN = /'([^']*)'|\"([^\"]*)\"/g;\n\nfunction extractBranchName(command: string): string | null {\n for (const pattern of BRANCH_PATTERNS) {\n const m = pattern.exec(command);\n if (m) return m[1];\n }\n return null;\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nfunction checkMainIsUpToDate(ctx: BashContext, requestedName: string): readonly Violation[] {\n execSync('git fetch origin main --quiet', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n });\n const countStr = execSync('git rev-list HEAD..origin/main --count', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n const count = parseInt(countStr, 10);\n if (count > 0) {\n return [new V(\n 1,\n truncate(ctx.command),\n `Local main is ${count} commit(s) behind origin/main. Run 'git pull origin main' first, then retry creating branch '${requestedName}'.`,\n )];\n }\n return [];\n}\n\nexport class BranchCreationGuardRule extends BashRuleBase<BranchCreationGuardConfig> {\n constructor(config: BranchCreationGuardConfig) { super(config, 'branch-creation-guard'); }\n\n readonly description =\n 'Block new-branch creation when main is stale, when branching off a non-main branch, ' +\n 'or when the local branch count is at its cap (forces cleanup of already-merged branches).';\n override readonly defaultOptions = {\n subBranchNaming: DEFAULT_SUB_BRANCH_NAMING,\n branchFormat: DEFAULT_BRANCH_FORMAT,\n maxLocalBranches: DEFAULT_MAX_LOCAL_BRANCHES,\n };\n\n private readonly mergedBranches = new MergedBranchesService();\n\n // Set by check() when (and only when) the cap is what blocked, so fixHint can render the reap\n // instructions instead of the branch-naming ones. Same instance-field handoff pr-merge-guard uses.\n private capCache: MergedBranchesCache | null = null;\n\n private get branchFormat(): string {\n return this.config.branchFormat ?? DEFAULT_BRANCH_FORMAT;\n }\n\n private get subBranchNaming(): string {\n return this.config.subBranchNaming ?? DEFAULT_SUB_BRANCH_NAMING;\n }\n\n private get maxLocalBranches(): number {\n return this.config.maxLocalBranches ?? DEFAULT_MAX_LOCAL_BRANCHES;\n }\n\n // Mode-aware fix hints. Branches off main follow branchFormat — never the sub-branch\n // convention. The sub-branch affordance only appears under mode 'ON'; 'ON_NO_SUBBRANCHES'\n // hard-blocks it and points instead at the ignoreModifiedUntilEpoch escape hatch.\n get fixHint(): FixHint {\n if (this.capCache) return this.capFixHint(this.capCache);\n\n const options = [\n new Option(\"Create it off fresh main from anywhere (incl. a worktree): git fetch origin main && git checkout -b <name> origin/main\", true),\n new Option(`Name a branch off main per branch-creation-guard.branchFormat: ${this.branchFormat}`),\n ];\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n options.push(new Option(\n 'Sub-branches (branching off another feature branch) are disabled. To temporarily allow one, set ' +\n \"branch-creation-guard.ignoreModifiedUntilEpoch to a future epoch in webpieces.config.json\",\n ));\n } else {\n options.push(new Option(\n `If you truly need a stacked sub-branch (requires human approval), name it per branch-creation-guard.subBranchNaming: ${this.subBranchNaming}`,\n ));\n }\n return new FixHint(\n 'Cannot create this branch (main is stale, or branching off a non-main branch).',\n 'Create your branch from an up-to-date main. Pick one:',\n options,\n );\n }\n\n /**\n * Strip the parts of a shell command that are DATA rather than executable commands, so the guard\n * stops reading prose as instructions.\n *\n * This guard regex-scans the raw command string and has no notion of quoting, so\n * `git commit -m \"... git checkout -b foo ...\"` — or any heredoc commit message that mentions a\n * branch command — was parsed as an actual branch creation and blocked. That bit three separate\n * times while building the branch cap, including on the cap's own commit. It matters far more now\n * that the cap check runs BEFORE the origin/main allow: at the cap, a merely-MENTIONED branch\n * command would block your commit.\n *\n * A quoted span whose content has no whitespace is kept verbatim (it is a single token — the name\n * in `git checkout -b \"dean/foo\"`), so quoting a branch name cannot smuggle a creation past the\n * guard. Anything with whitespace inside quotes is prose, and collapses to a space.\n */\n private stripNonCommandText(command: string): string {\n const withoutHeredocs = command.replace(HEREDOC_BODY, ' ');\n return withoutHeredocs.replace(QUOTED_SPAN, (match: string, single?: string, double?: string): string => {\n const content = single ?? double ?? '';\n return /\\s/.test(content) ? ' ' : content;\n });\n }\n\n check(ctx: BashContext): readonly Violation[] {\n this.capCache = null;\n // Match against the command with heredoc bodies and prose-in-quotes removed. A commit message\n // that merely MENTIONS a branch command is not a branch command.\n const command = this.stripNonCommandText(ctx.command);\n const requestedName = extractBranchName(command);\n if (!requestedName) return [];\n\n if (RESERVED_GENERATION_SUFFIX.test(requestedName)) {\n return [new V(\n 1,\n truncate(ctx.command),\n `Branch name '${requestedName}' ends in 'wp<number>', which is reserved for the ` +\n `squash-merge tool's generation marker (base → basewp2 → basewp3). ` +\n `Rename it to a plain feature branch. ${this.branchFormat}.`,\n )];\n }\n\n // The cap is checked BEFORE the origin/main allow below — `git checkout -b <name> origin/main`\n // is the normal, always-permitted path, so a cap check placed after it would never once fire.\n const capViolation = this.checkBranchCap(ctx);\n if (capViolation) return [capViolation];\n\n // Explicitly basing off origin/main is always allowed — it creates the branch from fresh main\n // regardless of the current branch, and is the ONLY way that also works inside a linked worktree\n // (where `git checkout main` fatals). Reserved-name check above still applies.\n if (ORIGIN_MAIN_BASE.test(command)) return [];\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n\n if (currentBranch === 'main') {\n return checkMainIsUpToDate(ctx, requestedName);\n }\n\n // Not on main: creating this branch would stack it on a feature branch (a sub-branch).\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n return [new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Create the branch OFF origin/main instead of ` +\n `stacking it on this branch: git fetch origin main && git checkout -b ${requestedName} origin/main ` +\n `(works here and inside a worktree). ${this.branchFormat}. ` +\n `You can temporarily turn this off if you truly need a sub-branch by setting ` +\n `branch-creation-guard.ignoreModifiedUntilEpoch (a future epoch) in webpieces.config.json.`,\n )];\n }\n\n return [new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Branches must be created from fresh main: ` +\n `git fetch origin main && git checkout -b ${requestedName} origin/main. ${this.branchFormat}. ` +\n `If you truly need a stacked sub-branch (requires human approval), name it per ` +\n `branch-creation-guard.subBranchNaming ('${this.subBranchNaming}').`,\n )];\n }\n\n /**\n * The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing\n * keeping the local branch list bounded.\n *\n * Fails OPEN when the cache is absent (fresh clone, `gh` unavailable, refresher hasn't run yet):\n * never block on data we don't have. The detached refresher regenerates it within one hook call,\n * so the cap starts enforcing on its own.\n */\n private checkBranchCap(ctx: BashContext): Violation | null {\n const count = this.mergedBranches.localBranches(ctx.workspaceRoot).length;\n if (count < this.maxLocalBranches) return null;\n\n const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!cache) return null;\n\n this.capCache = cache;\n const reapable = cache.deletable.length;\n const detail = reapable > 0\n ? `${String(reapable)} of them are dead (merged, or holding no commits) and can be deleted right now.`\n : 'None of them are dead, so none can be auto-reaped — see the options below.';\n\n return new V(\n 1,\n truncate(ctx.command),\n `You have ${String(count)} local branches; the cap (branch-creation-guard.maxLocalBranches) ` +\n `is ${String(this.maxLocalBranches)}. ${detail} Clean up before creating another.`,\n );\n }\n\n /**\n * The reap instructions. `deletable` is PRECOMPUTED in the cache, and every entry earned its place\n * by one of exactly two proofs: a MERGED PR (the work is in main), or zero commits of its own\n * (there is no work). Deleting the list cannot lose anything — so just run the command.\n *\n * The wording must not overstate that: the list is NOT uniformly \"merged PR\" branches, and a\n * message that tells an agent to run `git branch -D` has to be exactly true about why that's safe.\n */\n private capFixHint(cache: MergedBranchesCache): FixHint {\n const options: Option[] = [];\n\n if (cache.deletable.length > 0) {\n const names = cache.deletable.map((entry: DeletableBranch): string => entry.branch);\n options.push(new Option(\n `Delete these ${String(names.length)} dead branches — each is either backed by a MERGED PR ` +\n `or has no commits of its own, so no work can be lost (see merged-branches.json for the ` +\n `per-branch reason): git branch -D ${names.join(' ')}`,\n true,\n ));\n }\n\n options.push(new Option(\n 'If you genuinely need more branches in flight, raise branch-creation-guard.maxLocalBranches ' +\n 'in webpieces.config.json.',\n ));\n options.push(new Option(\n 'To bypass this once, set branch-creation-guard.ignoreModifiedUntilEpoch (a future epoch) ' +\n 'in webpieces.config.json.',\n ));\n\n const kept = cache.keep.length > 0\n ? ` ${String(cache.keep.length)} unmerged branch(es) with real commits were deliberately SPARED — ` +\n 'do not delete those; a human decides.'\n : '';\n\n return new FixHint(\n 'Too many local branches — reap the dead ones before creating another.',\n 'Full detail (deletable + spared, with per-branch reasons) is in .webpieces/merged-branches.json, ' +\n `refreshed ${cache.timestamp || 'never'}.${kept} Pick one:`,\n options,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"branch-creation-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/branch-creation-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAOiC;AAGjC,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAA8C;AAE9C,8EAA8E;AAC9E,+FAA+F;AAC/F,kGAAkG;AAClG,MAAM,qBAAqB,GACvB,4HAA4H,CAAC;AACjI,MAAM,yBAAyB,GAAG,sCAAsC,CAAC;AAEzE,qGAAqG;AACrG,+EAA+E;AAC/E,EAAE;AACF,uGAAuG;AACvG,sGAAsG;AACtG,uGAAuG;AACvG,sCAAsC;AACtC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,oGAAoG;AACpG,kGAAkG;AAClG,mGAAmG;AACnG,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAA,6BAA6B,CAAC;AAEzD,MAAM,eAAe,GAAa;I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C3F,2BAA2B,CAC9B,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,IAAI,iBAAM,CACnB,2FAA2F;YAC3F,2BAA2B,CAC9B,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QACpD,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC;YACnB,CAAC,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,2EAA2E;gBAC7F,sEAAsE;YACxE,CAAC,CAAC,EAAE,CAAC;QAET,OAAO,IAAI,kBAAO,CACd,kEAAkE,EAClE,qGAAqG;YACrG,aAAa,KAAK,CAAC,SAAS,IAAI,OAAO,IAAI,IAAI,YAAY,EAC3D,OAAO,CACV,CAAC;IACN,CAAC;CACJ;AAlWD,0DAkWC","sourcesContent":["import { execSync } from 'child_process';\n\nimport {\n BranchCreationGuardConfig,\n DeletableBranch,\n DeletableWorktree,\n MergedBranchesCache,\n MergedBranchesService,\n WorktreeService,\n} from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint, Option } from '../fix-hint';\n\n// Defaults used when the rule has no explicit value in webpieces.config.json.\n// branchFormat is a human sentence telling the AI how to name a branch created off main; it is\n// intentionally NOT the sub-branch convention (sub-branches are a separate, human-approved path).\nconst DEFAULT_BRANCH_FORMAT =\n 'Name it {whoami}/<short-feature-description> — lowercase, no version numbers, no sub/ prefix (e.g. dean/upgrade-webpieces)';\nconst DEFAULT_SUB_BRANCH_NAMING = 'feature/<ticket>/<short-description>';\n\n// Hard cap on local feature branches. Enforced at CREATION because that is the one moment cleanup is\n// both cheap and obviously worth it — reaping happens over time, never \"ASAP\".\n//\n// The branch cap counts PARKED branches only — branches not checked out in any worktree. Worktree-held\n// branches are counted by the worktree cap instead. Two budgets, because they are not substitutes: if\n// held branches also spent the branch budget, five worktrees would leave room for zero branches and no\n// branch could ever be created again.\nconst DEFAULT_MAX_LOCAL_BRANCHES = 5;\nconst DEFAULT_MAX_WORKTREES = 5;\n\n// A plausible git ref name. Deliberately NOT `[^\\s-]` — that class matches shell metacharacters, so\n// `git branch | wc -l` (a read-only LISTING, piped) was parsed as \"create a branch named `|`\" and\n// blocked. Cleanup work necessarily reads and deletes branches, so a listing must never trip this.\nconst REF_NAME = String.raw`[A-Za-z0-9][A-Za-z0-9_./-]*`;\n\nconst BRANCH_PATTERNS: RegExp[] = [\n new RegExp(String.raw`git\\s+checkout\\s+-[bB]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+switch\\s+-[cC]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+branch\\s+(?!-)(${REF_NAME})`),\n // `git worktree add ../dir -b <name> origin/main` — the form docs/git-workflow.md recommends for\n // starting a feature. It creates a branch just as surely as `checkout -b` does, and until this\n // pattern existed it walked straight past the cap, the reserved-suffix check and the sub-branch\n // check. `(?:\\S+\\s+)*?` absorbs the path and any other flags, so the -b may precede or follow them.\n new RegExp(String.raw`git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*?-[bB]\\s+(${REF_NAME})`),\n];\n\n// ANY worktree creation, with or without -b. The no-`-b` forms (`git worktree add ../dir existing`,\n// `--detach`) create no branch but DO create a worktree, so they spend the worktree budget and must\n// still hit the cap.\nconst WORKTREE_ADD = /git\\s+worktree\\s+add\\b/;\n\n// A trailing `wp<number>` was the old squash-merge generation marker (base → basewp2 → basewp3).\n// The tooling NO LONGER produces it — a sync now lands back on the same feature name — but the suffix\n// stays RESERVED so a human branch can't collide with a leftover `…wpN` still floating in a consumer\n// repo mid-transition. Block it at creation time and steer the name back to the plain feature form.\nconst RESERVED_GENERATION_SUFFIX = /wp\\d+$/;\n\n// A branch-creation command that explicitly bases off origin/main (e.g. `git checkout -b feat\n// origin/main`). This is exactly the fresh-main base the guard wants, and it works from ANY current\n// branch or linked worktree — main need not (and in a worktree cannot) be checked out here. Allowed\n// unconditionally so the recovery messages can safely tell you to run it from a worktree.\n//\n// The trailing check is `\\W|$`, not `\\s|$`: the ALLOW pattern must not be stricter about delimiters\n// than the BLOCK pattern above, or a `git checkout -b x origin/main` that ends at a quote or backtick\n// is seen as a branch creation but NOT as an origin/main one — recognised, then wrongly blocked.\nconst ORIGIN_MAIN_BASE = /git\\s+(?:checkout\\s+-[bB]|switch\\s+-[cC])\\s+\\S+\\s+origin\\/main(?:\\W|$)/;\n\n// The worktree arm of the same allow: `git worktree add ../dir -b <name> origin/main`. Same fresh-main\n// base, same reasoning — and in a worktree it is the ONLY workable base, since `git checkout main`\n// fatals there. Kept separate from ORIGIN_MAIN_BASE because the argument shape differs (a path sits\n// between the subcommand and the flags).\nconst WORKTREE_ORIGIN_MAIN_BASE = /git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*origin\\/main(?:\\W|$)/;\n\n// Heredoc bodies: `<<EOF … \\nEOF` / `<<-'EOF' … \\nEOF`. Their content is DATA (a commit message, a\n// file being written), never a command.\nconst HEREDOC_BODY = /<<-?\\s*(['\"]?)(\\w+)\\1[\\s\\S]*?^\\t*\\2\\s*$/gm;\n\n// A single- or double-quoted span.\nconst QUOTED_SPAN = /'([^']*)'|\"([^\"]*)\"/g;\n\nfunction extractBranchName(command: string): string | null {\n for (const pattern of BRANCH_PATTERNS) {\n const m = pattern.exec(command);\n if (m) return m[1];\n }\n return null;\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nfunction checkMainIsUpToDate(ctx: BashContext, requestedName: string): readonly Violation[] {\n execSync('git fetch origin main --quiet', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n });\n const countStr = execSync('git rev-list HEAD..origin/main --count', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n const count = parseInt(countStr, 10);\n if (count > 0) {\n return [new V(\n 1,\n truncate(ctx.command),\n `Local main is ${count} commit(s) behind origin/main. Run 'git pull origin main' first, then retry creating branch '${requestedName}'.`,\n )];\n }\n return [];\n}\n\nexport class BranchCreationGuardRule extends BashRuleBase<BranchCreationGuardConfig> {\n constructor(config: BranchCreationGuardConfig) { super(config, 'branch-creation-guard'); }\n\n readonly description =\n 'Block new-branch and new-worktree creation when main is stale, when branching off a non-main ' +\n 'branch, or when the branch/worktree count is at its cap (forces cleanup of dead ones).';\n override readonly defaultOptions = {\n subBranchNaming: DEFAULT_SUB_BRANCH_NAMING,\n branchFormat: DEFAULT_BRANCH_FORMAT,\n maxLocalBranches: DEFAULT_MAX_LOCAL_BRANCHES,\n maxWorktrees: DEFAULT_MAX_WORKTREES,\n };\n\n private readonly worktrees = new WorktreeService();\n private readonly mergedBranches = new MergedBranchesService(this.worktrees);\n\n // Set by check() when (and only when) a cap is what blocked, so fixHint can render the reap\n // instructions instead of the branch-naming ones. Same instance-field handoff pr-merge-guard uses.\n // Two fields, because the two caps reap different things and their hints share no wording.\n private capCache: MergedBranchesCache | null = null;\n private worktreeCapCache: MergedBranchesCache | null = null;\n\n // True when the blocked command was a `git worktree add`, so the recovery command we hand back is\n // a worktree command and not a `git checkout -b` the user cannot use here.\n private worktreeAdd = false;\n\n private get branchFormat(): string {\n return this.config.branchFormat ?? DEFAULT_BRANCH_FORMAT;\n }\n\n private get subBranchNaming(): string {\n return this.config.subBranchNaming ?? DEFAULT_SUB_BRANCH_NAMING;\n }\n\n private get maxLocalBranches(): number {\n return this.config.maxLocalBranches ?? DEFAULT_MAX_LOCAL_BRANCHES;\n }\n\n private get maxWorktrees(): number {\n return this.config.maxWorktrees ?? DEFAULT_MAX_WORKTREES;\n }\n\n // The recovery command for \"base this off fresh main\", in the flavour of whatever was blocked.\n private freshMainCommand(name: string): string {\n return this.worktreeAdd\n ? `git fetch origin main && git worktree add ../${name.replace(/\\//g, '-')} -b ${name} origin/main`\n : `git fetch origin main && git checkout -b ${name} origin/main`;\n }\n\n // Mode-aware fix hints. Branches off main follow branchFormat — never the sub-branch\n // convention. The sub-branch affordance only appears under mode 'ON'; 'ON_NO_SUBBRANCHES'\n // hard-blocks it and points instead at the ignoreModifiedUntilEpoch escape hatch.\n get fixHint(): FixHint {\n if (this.worktreeCapCache) return this.worktreeCapFixHint(this.worktreeCapCache);\n if (this.capCache) return this.capFixHint(this.capCache);\n\n const create = this.worktreeAdd\n ? 'Create it off fresh main: git fetch origin main && git worktree add ../<dir> -b <name> origin/main'\n : 'Create it off fresh main from anywhere (incl. a worktree): git fetch origin main && git checkout -b <name> origin/main';\n\n const options = [\n new Option(create, true),\n new Option(`Name a branch off main per branch-creation-guard.branchFormat: ${this.branchFormat}`),\n ];\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n options.push(new Option(\n 'Sub-branches (branching off another feature branch) are disabled. To temporarily allow one, set ' +\n \"branch-creation-guard.ignoreModifiedUntilEpoch to a future epoch in webpieces.config.json\",\n ));\n } else {\n options.push(new Option(\n `If you truly need a stacked sub-branch (requires human approval), name it per branch-creation-guard.subBranchNaming: ${this.subBranchNaming}`,\n ));\n }\n return new FixHint(\n 'Cannot create this branch (main is stale, or branching off a non-main branch).',\n 'Create your branch from an up-to-date main. Pick one:',\n options,\n );\n }\n\n /**\n * Strip the parts of a shell command that are DATA rather than executable commands, so the guard\n * stops reading prose as instructions.\n *\n * This guard regex-scans the raw command string and has no notion of quoting, so\n * `git commit -m \"... git checkout -b foo ...\"` — or any heredoc commit message that mentions a\n * branch command — was parsed as an actual branch creation and blocked. That bit three separate\n * times while building the branch cap, including on the cap's own commit. It matters far more now\n * that the cap check runs BEFORE the origin/main allow: at the cap, a merely-MENTIONED branch\n * command would block your commit.\n *\n * A quoted span whose content has no whitespace is kept verbatim (it is a single token — the name\n * in `git checkout -b \"dean/foo\"`), so quoting a branch name cannot smuggle a creation past the\n * guard. Anything with whitespace inside quotes is prose, and collapses to a space.\n */\n private stripNonCommandText(command: string): string {\n const withoutHeredocs = command.replace(HEREDOC_BODY, ' ');\n return withoutHeredocs.replace(QUOTED_SPAN, (match: string, single?: string, double?: string): string => {\n const content = single ?? double ?? '';\n return /\\s/.test(content) ? ' ' : content;\n });\n }\n\n check(ctx: BashContext): readonly Violation[] {\n this.capCache = null;\n this.worktreeCapCache = null;\n // Match against the command with heredoc bodies and prose-in-quotes removed. A commit message\n // that merely MENTIONS a branch command is not a branch command.\n const command = this.stripNonCommandText(ctx.command);\n const requestedName = extractBranchName(command);\n this.worktreeAdd = WORKTREE_ADD.test(command);\n\n // A worktree add with no -b creates no branch, but it DOES spend the worktree budget, so it must\n // survive this early-out and reach the worktree cap below.\n if (!requestedName && !this.worktreeAdd) return [];\n\n if (requestedName && RESERVED_GENERATION_SUFFIX.test(requestedName)) {\n return [new V(\n 1,\n truncate(ctx.command),\n `Branch name '${requestedName}' ends in 'wp<number>', which is reserved for the ` +\n `squash-merge tool's generation marker (base → basewp2 → basewp3). ` +\n `Rename it to a plain feature branch. ${this.branchFormat}.`,\n )];\n }\n\n const capViolation = this.checkCaps(ctx, requestedName !== null);\n if (capViolation) return [capViolation];\n\n // `git worktree add` of an EXISTING branch (or --detach) creates no branch: the cap above was the\n // only rule that applies to it. Nothing left to check.\n if (!requestedName) return [];\n\n // Explicitly basing off origin/main is always allowed — it creates the branch from fresh main\n // regardless of the current branch, and is the ONLY way that also works inside a linked worktree\n // (where `git checkout main` fatals). Reserved-name check above still applies.\n if (ORIGIN_MAIN_BASE.test(command)) return [];\n if (this.worktreeAdd && WORKTREE_ORIGIN_MAIN_BASE.test(command)) return [];\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n\n if (currentBranch === 'main') {\n return checkMainIsUpToDate(ctx, requestedName);\n }\n\n // Not on main: creating this branch would stack it on a feature branch (a sub-branch).\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n return [new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Create the branch OFF origin/main instead of ` +\n `stacking it on this branch: ${this.freshMainCommand(requestedName)} ` +\n `(works here and inside a worktree). ${this.branchFormat}. ` +\n `You can temporarily turn this off if you truly need a sub-branch by setting ` +\n `branch-creation-guard.ignoreModifiedUntilEpoch (a future epoch) in webpieces.config.json.`,\n )];\n }\n\n return [new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Branches must be created from fresh main: ` +\n `${this.freshMainCommand(requestedName)}. ${this.branchFormat}. ` +\n `If you truly need a stacked sub-branch (requires human approval), name it per ` +\n `branch-creation-guard.subBranchNaming ('${this.subBranchNaming}').`,\n )];\n }\n\n /**\n * Both budgets, in the order that produces the most useful complaint.\n *\n * Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,\n * always-permitted path, so a cap checked after it would never once fire.\n *\n * Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the\n * worktree is the thing the command was actually trying to make, so it is the thing to talk about.\n */\n private checkCaps(ctx: BashContext, createsBranch: boolean): Violation | null {\n if (this.worktreeAdd) {\n const worktreeViolation = this.checkWorktreeCap(ctx);\n if (worktreeViolation) return worktreeViolation;\n }\n if (createsBranch) return this.checkBranchCap(ctx);\n return null;\n }\n\n /**\n * The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing\n * keeping the local branch list bounded.\n *\n * Fails OPEN when the cache is absent (fresh clone, `gh` unavailable, refresher hasn't run yet):\n * never block on data we don't have. The detached refresher regenerates it within one hook call,\n * so the cap starts enforcing on its own.\n */\n private checkBranchCap(ctx: BashContext): Violation | null {\n // PARKED branches only — a branch checked out in a worktree is the worktree cap's problem, and\n // counting it twice would let five worktrees exhaust the branch budget on their own.\n const held = this.worktrees.heldBranches(ctx.workspaceRoot);\n const parked = this.mergedBranches.localBranches(ctx.workspaceRoot)\n .filter((branch: string): boolean => !held.has(branch));\n const count = parked.length;\n if (count < this.maxLocalBranches) return null;\n\n const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!cache) return null;\n\n this.capCache = cache;\n const reapable = cache.deletable.length;\n const detail = reapable > 0\n ? `${String(reapable)} of them are dead (merged, or holding no commits) and can be deleted right now.`\n : 'None of them are dead, so none can be auto-reaped — see the options below.';\n\n return new V(\n 1,\n truncate(ctx.command),\n `You have ${String(count)} parked local branches (not counting any checked out in a worktree); ` +\n `the cap (branch-creation-guard.maxLocalBranches) is ${String(this.maxLocalBranches)}. ` +\n `${detail} Clean up before creating another.`,\n );\n }\n\n /**\n * The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a\n * worktree list we cannot classify (no cache on disk) blocks nothing.\n *\n * Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the\n * budget for it would just silently cost you one worktree.\n */\n private checkWorktreeCap(ctx: BashContext): Violation | null {\n const count = this.worktrees.linkedWorktrees(ctx.workspaceRoot).length;\n if (count < this.maxWorktrees) return null;\n\n const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!cache) return null;\n\n this.worktreeCapCache = cache;\n const reapable = cache.worktrees.filter((tree: DeletableWorktree): boolean => tree.deletable).length;\n const detail = reapable > 0\n ? `${String(reapable)} of them are dead (merged branch, no commits, or a missing directory) ` +\n 'and can be removed right now.'\n : 'None of them are dead, so none can be auto-reaped — see the options below.';\n\n return new V(\n 1,\n truncate(ctx.command),\n `You have ${String(count)} linked worktrees; the cap (branch-creation-guard.maxWorktrees) ` +\n `is ${String(this.maxWorktrees)}. ${detail} Clean up before creating another.`,\n );\n }\n\n /**\n * The reap instructions. `deletable` is PRECOMPUTED in the cache, and every entry earned its place\n * by one of exactly two proofs: a MERGED PR (the work is in main), or zero commits of its own\n * (there is no work). Deleting the list cannot lose anything — so just run the command.\n *\n * The wording must not overstate that: the list is NOT uniformly \"merged PR\" branches, and a\n * message that tells an agent to run `git branch -D` has to be exactly true about why that's safe.\n */\n private capFixHint(cache: MergedBranchesCache): FixHint {\n const options: Option[] = [];\n\n if (cache.deletable.length > 0) {\n const names = cache.deletable.map((entry: DeletableBranch): string => entry.branch);\n options.push(new Option(\n `Delete these ${String(names.length)} dead branches — each is either backed by a MERGED PR ` +\n `or has no commits of its own, so no work can be lost (see merged-branches.json for the ` +\n `per-branch reason): git branch -D ${names.join(' ')}`,\n true,\n ));\n }\n\n options.push(new Option(\n 'If you genuinely need more branches in flight, raise branch-creation-guard.maxLocalBranches ' +\n 'in webpieces.config.json.',\n ));\n options.push(new Option(\n 'To bypass this once, set branch-creation-guard.ignoreModifiedUntilEpoch (a future epoch) ' +\n 'in webpieces.config.json.',\n ));\n\n const kept = cache.keep.length > 0\n ? ` ${String(cache.keep.length)} unmerged branch(es) with real commits were deliberately SPARED — ` +\n 'do not delete those; a human decides.'\n : '';\n\n return new FixHint(\n 'Too many local branches — reap the dead ones before creating another.',\n 'Full detail (deletable + spared, with per-branch reasons) is in .webpieces/merged-branches.json, ' +\n `refreshed ${cache.timestamp || 'never'}.${kept} Pick one:`,\n options,\n );\n }\n\n /**\n * The worktree reap instructions.\n *\n * The command ORDER is load-bearing and is the whole reason this is generated rather than described:\n * 1. `git worktree prune` — clears the admin data of worktrees whose directory is already gone.\n * `git worktree remove` FAILS on those, so it cannot be the first step.\n * 2. `git worktree remove <path>` — one path per invocation; git takes no path list here.\n * 3. `git branch -D <names>` — only now. git flatly refuses to delete a branch that is still\n * checked out in a worktree, so a branch delete placed before the removal fails, and because\n * it is one multi-name command it takes every other branch in the list down with it.\n */\n private worktreeCapFixHint(cache: MergedBranchesCache): FixHint {\n const options: Option[] = [];\n const dead = cache.worktrees.filter((tree: DeletableWorktree): boolean => tree.deletable);\n\n if (dead.length > 0) {\n const steps = ['git worktree prune'];\n for (const tree of dead) {\n // A prunable worktree has no directory left to remove — step 1 already handled it.\n if (tree.path !== '') steps.push(`git worktree remove ${tree.path}`);\n }\n const branches = dead\n .map((tree: DeletableWorktree): string => tree.branch)\n .filter((branch: string): boolean => branch !== '');\n if (branches.length > 0) steps.push(`git branch -D ${branches.join(' ')}`);\n\n options.push(new Option(\n `Remove these ${String(dead.length)} dead worktrees — each holds a branch backed by a MERGED ` +\n 'PR, a branch with no commits of its own, or a directory that is already gone, so no work ' +\n 'can be lost (see merged-branches.json for the per-worktree reason). Run it in this order ' +\n `(prune first, branches last — git refuses to delete a branch a worktree still holds): ${steps.join(' && ')}`,\n true,\n ));\n }\n\n options.push(new Option(\n 'If you genuinely need more worktrees in flight, raise branch-creation-guard.maxWorktrees ' +\n 'in webpieces.config.json.',\n ));\n options.push(new Option(\n 'To bypass this once, set branch-creation-guard.ignoreModifiedUntilEpoch (a future epoch) ' +\n 'in webpieces.config.json.',\n ));\n\n const spared = cache.worktrees.length - dead.length;\n const kept = spared > 0\n ? ` ${String(spared)} worktree(s) were deliberately SPARED (locked, holding unmerged work, or ` +\n 'the one you are standing in) — do not remove those; a human decides.'\n : '';\n\n return new FixHint(\n 'Too many worktrees — reap the dead ones before creating another.',\n 'Full detail (deletable + spared, with per-worktree reasons) is in .webpieces/merged-branches.json, ' +\n `refreshed ${cache.timestamp || 'never'}.${kept} Pick one:`,\n options,\n );\n }\n}\n"]}
|