@webpieces/ai-hook-rules 0.4.628 → 0.4.630
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 +2 -2
- package/src/core/rules/branch-switch-scan.d.ts +38 -0
- package/src/core/rules/branch-switch-scan.js +127 -0
- package/src/core/rules/branch-switch-scan.js.map +1 -0
- package/src/core/rules/redirect-how-to-merge-main.d.ts +1 -0
- package/src/core/rules/redirect-how-to-merge-main.js +30 -32
- package/src/core/rules/redirect-how-to-merge-main.js.map +1 -1
- package/src/core/rules/stale-main-bash-guard.d.ts +1 -6
- package/src/core/rules/stale-main-bash-guard.js +22 -29
- package/src/core/rules/stale-main-bash-guard.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/ai-hook-rules",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.630",
|
|
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",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"directory": "packages/tooling/ai-hook-rules"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@webpieces/rules-config": "0.4.
|
|
28
|
+
"@webpieces/rules-config": "0.4.630"
|
|
29
29
|
},
|
|
30
30
|
"publishConfig": {
|
|
31
31
|
"access": "public"
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { CommandScanner } from '../command-scan';
|
|
2
|
+
/**
|
|
3
|
+
* The branch a checkout/switch lands on, and whether that command CREATES it.
|
|
4
|
+
*
|
|
5
|
+
* `created` is load-bearing rather than cosmetic: `git checkout -b x origin/main` lands on a branch
|
|
6
|
+
* that is current by construction (nothing to be stale about), whereas landing on an EXISTING local
|
|
7
|
+
* `main` is exactly the stale-checkout hazard. Data-only, so a class (per CLAUDE.md).
|
|
8
|
+
*/
|
|
9
|
+
export declare class BranchSwitch {
|
|
10
|
+
branch: string;
|
|
11
|
+
created: boolean;
|
|
12
|
+
constructor(branch: string, created: boolean);
|
|
13
|
+
}
|
|
14
|
+
export declare class BranchSwitchScan {
|
|
15
|
+
private readonly scanner;
|
|
16
|
+
constructor(scanner?: CommandScanner);
|
|
17
|
+
/**
|
|
18
|
+
* The branch this segment switches to, or null when the segment does not land on a branch at all:
|
|
19
|
+
* a different command, no target word, `git checkout -` (the previous branch — unknowable here),
|
|
20
|
+
* or anything after `--` (which ends option parsing, making the rest PATHSPECS, so
|
|
21
|
+
* `git checkout -- main` restores a FILE named main and moves no branch).
|
|
22
|
+
*
|
|
23
|
+
* Flag-tolerant by construction: every leading flag is walked past, so `-q`, `--quiet`,
|
|
24
|
+
* `--no-track`, `--detach` and friends change nothing about which word is the target.
|
|
25
|
+
*/
|
|
26
|
+
targetOf(segment: string): BranchSwitch | null;
|
|
27
|
+
/**
|
|
28
|
+
* True only for landing on an EXISTING branch named `main` — the form that can hand you a stale
|
|
29
|
+
* tree, and the form `git checkout main && git pull origin main` uses. `-b`/`-B`/`-c`/`-C` are
|
|
30
|
+
* excluded because they create the branch here and now.
|
|
31
|
+
*/
|
|
32
|
+
landsOnExistingMain(segment: string): boolean;
|
|
33
|
+
/** The same question for a target already parsed (switchesIn). One spelling, two entry shapes. */
|
|
34
|
+
isExistingMain(target: BranchSwitch): boolean;
|
|
35
|
+
/** Every segment of a whole command that lands on a branch, in order. */
|
|
36
|
+
switchesIn(command: string): readonly BranchSwitch[];
|
|
37
|
+
private createdBranch;
|
|
38
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BranchSwitchScan = exports.BranchSwitch = void 0;
|
|
4
|
+
const command_scan_1 = require("../command-scan");
|
|
5
|
+
/**
|
|
6
|
+
* "Which branch does this `git checkout` / `git switch` land me on?" — the ONE place that question is
|
|
7
|
+
* answered, for every guard that asks it.
|
|
8
|
+
*
|
|
9
|
+
* It used to be answered by two regexes in redirect-how-to-merge-main
|
|
10
|
+
* (`/git\s+(?:checkout|switch)\s+main\b/` to EXEMPT main, and a negative-lookahead twin to catch a
|
|
11
|
+
* feature switch) and by a third, hand-rolled word walk in stale-main-bash-guard. The regex pair
|
|
12
|
+
* assumed the branch name is the token immediately after the subcommand, so ONE flag broke it:
|
|
13
|
+
*
|
|
14
|
+
* git checkout main → exempted (correct)
|
|
15
|
+
* git checkout -q main → `main` no longer follows `checkout`, so the exemption MISSED, the
|
|
16
|
+
* lookahead concluded the target was not main, and the command was
|
|
17
|
+
* blocked with "this switches to a feature branch and then pulls main
|
|
18
|
+
* into it" — the exact opposite of what it does.
|
|
19
|
+
*
|
|
20
|
+
* That block landed on the cure stale-main-bash-guard itself prescribes, so the two guards
|
|
21
|
+
* contradicted each other and a human had to route around both to update main. The fix is not a
|
|
22
|
+
* cleverer regex: it is to TOKENIZE (CommandScanner already does the hard part) and walk the flags,
|
|
23
|
+
* which is also why it must exist once rather than three times.
|
|
24
|
+
*
|
|
25
|
+
* Deliberately NOT "does the string contain main" — over-matching here is worse than the original
|
|
26
|
+
* bug, because `git checkout -b feature/main-thing` and `git checkout -- main.ts` would then read as
|
|
27
|
+
* "switching to main" and be EXEMPTED from a guard whose whole job is to catch a feature-branch pull.
|
|
28
|
+
*/
|
|
29
|
+
const CREATE_FLAGS = new Set(['-b', '-B', '-c', '-C', '--orphan']);
|
|
30
|
+
// Non-creating flags that consume the FOLLOWING token, so its value is never mistaken for the target.
|
|
31
|
+
const FLAGS_WITH_VALUE = new Set(['--conflict', '--pathspec-from-file', '--start-point']);
|
|
32
|
+
/**
|
|
33
|
+
* The branch a checkout/switch lands on, and whether that command CREATES it.
|
|
34
|
+
*
|
|
35
|
+
* `created` is load-bearing rather than cosmetic: `git checkout -b x origin/main` lands on a branch
|
|
36
|
+
* that is current by construction (nothing to be stale about), whereas landing on an EXISTING local
|
|
37
|
+
* `main` is exactly the stale-checkout hazard. Data-only, so a class (per CLAUDE.md).
|
|
38
|
+
*/
|
|
39
|
+
class BranchSwitch {
|
|
40
|
+
branch;
|
|
41
|
+
created;
|
|
42
|
+
constructor(branch, created) {
|
|
43
|
+
this.branch = branch;
|
|
44
|
+
this.created = created;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
exports.BranchSwitch = BranchSwitch;
|
|
48
|
+
class BranchSwitchScan {
|
|
49
|
+
scanner;
|
|
50
|
+
constructor(scanner = new command_scan_1.CommandScanner()) {
|
|
51
|
+
this.scanner = scanner;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The branch this segment switches to, or null when the segment does not land on a branch at all:
|
|
55
|
+
* a different command, no target word, `git checkout -` (the previous branch — unknowable here),
|
|
56
|
+
* or anything after `--` (which ends option parsing, making the rest PATHSPECS, so
|
|
57
|
+
* `git checkout -- main` restores a FILE named main and moves no branch).
|
|
58
|
+
*
|
|
59
|
+
* Flag-tolerant by construction: every leading flag is walked past, so `-q`, `--quiet`,
|
|
60
|
+
* `--no-track`, `--detach` and friends change nothing about which word is the target.
|
|
61
|
+
*/
|
|
62
|
+
targetOf(segment) {
|
|
63
|
+
const subcommand = this.scanner.gitSubcommand(segment);
|
|
64
|
+
if (subcommand !== 'checkout' && subcommand !== 'switch')
|
|
65
|
+
return null;
|
|
66
|
+
const words = this.scanner.words(segment);
|
|
67
|
+
const args = words.slice(words.indexOf(subcommand) + 1);
|
|
68
|
+
for (let i = 0; i < args.length; i++) {
|
|
69
|
+
const word = args[i];
|
|
70
|
+
if (word === '--')
|
|
71
|
+
return null;
|
|
72
|
+
if (word === '-')
|
|
73
|
+
return null;
|
|
74
|
+
const created = this.createdBranch(args, i);
|
|
75
|
+
if (created !== null)
|
|
76
|
+
return created;
|
|
77
|
+
if (FLAGS_WITH_VALUE.has(word)) {
|
|
78
|
+
i++;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (word.startsWith('-'))
|
|
82
|
+
continue;
|
|
83
|
+
return new BranchSwitch(word, false);
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* True only for landing on an EXISTING branch named `main` — the form that can hand you a stale
|
|
89
|
+
* tree, and the form `git checkout main && git pull origin main` uses. `-b`/`-B`/`-c`/`-C` are
|
|
90
|
+
* excluded because they create the branch here and now.
|
|
91
|
+
*/
|
|
92
|
+
landsOnExistingMain(segment) {
|
|
93
|
+
const target = this.targetOf(segment);
|
|
94
|
+
return target !== null && this.isExistingMain(target);
|
|
95
|
+
}
|
|
96
|
+
/** The same question for a target already parsed (switchesIn). One spelling, two entry shapes. */
|
|
97
|
+
isExistingMain(target) {
|
|
98
|
+
return target.branch === 'main' && !target.created;
|
|
99
|
+
}
|
|
100
|
+
/** Every segment of a whole command that lands on a branch, in order. */
|
|
101
|
+
switchesIn(command) {
|
|
102
|
+
const found = [];
|
|
103
|
+
for (const segment of this.scanner.commandSegments(command)) {
|
|
104
|
+
const target = this.targetOf(segment);
|
|
105
|
+
if (target !== null)
|
|
106
|
+
found.push(target);
|
|
107
|
+
}
|
|
108
|
+
return found;
|
|
109
|
+
}
|
|
110
|
+
// `-b <name>` / `--orphan=<name>` — the new branch's name, or null when this word creates nothing.
|
|
111
|
+
createdBranch(args, i) {
|
|
112
|
+
const word = args[i];
|
|
113
|
+
if (CREATE_FLAGS.has(word)) {
|
|
114
|
+
const name = args[i + 1];
|
|
115
|
+
if (name === undefined || name.startsWith('-'))
|
|
116
|
+
return null;
|
|
117
|
+
return new BranchSwitch(name, true);
|
|
118
|
+
}
|
|
119
|
+
const equals = word.indexOf('=');
|
|
120
|
+
if (equals > 0 && CREATE_FLAGS.has(word.slice(0, equals))) {
|
|
121
|
+
return new BranchSwitch(word.slice(equals + 1), true);
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
exports.BranchSwitchScan = BranchSwitchScan;
|
|
127
|
+
//# sourceMappingURL=branch-switch-scan.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"branch-switch-scan.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/branch-switch-scan.ts"],"names":[],"mappings":";;;AAAA,kDAAiD;AAEjD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,YAAY,GAAwB,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC;AAExF,sGAAsG;AACtG,MAAM,gBAAgB,GAAwB,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,sBAAsB,EAAE,eAAe,CAAC,CAAC,CAAC;AAE/G;;;;;;GAMG;AACH,MAAa,YAAY;IACrB,MAAM,CAAS;IACf,OAAO,CAAU;IAEjB,YAAY,MAAc,EAAE,OAAgB;QACxC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AARD,oCAQC;AAED,MAAa,gBAAgB;IACI;IAA7B,YAA6B,UAA0B,IAAI,6BAAc,EAAE;QAA9C,YAAO,GAAP,OAAO,CAAuC;IAAG,CAAC;IAE/E;;;;;;;;OAQG;IACH,QAAQ,CAAC,OAAe;QACpB,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QACvD,IAAI,UAAU,KAAK,UAAU,IAAI,UAAU,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAEtE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC1C,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,C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G,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YACtC,IAAI,MAAM,KAAK,IAAI;gBAAE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,mGAAmG;IAC3F,aAAa,CAAC,IAAuB,EAAE,CAAS;QACpD,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACrB,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACzB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACzB,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;gBAAE,OAAO,IAAI,CAAC;YAC5D,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACxC,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,MAAM,GAAG,CAAC,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC;YACxD,OAAO,IAAI,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AAvED,4CAuEC","sourcesContent":["import { CommandScanner } from '../command-scan';\n\n/**\n * \"Which branch does this `git checkout` / `git switch` land me on?\" — the ONE place that question is\n * answered, for every guard that asks it.\n *\n * It used to be answered by two regexes in redirect-how-to-merge-main\n * (`/git\\s+(?:checkout|switch)\\s+main\\b/` to EXEMPT main, and a negative-lookahead twin to catch a\n * feature switch) and by a third, hand-rolled word walk in stale-main-bash-guard. The regex pair\n * assumed the branch name is the token immediately after the subcommand, so ONE flag broke it:\n *\n * git checkout main → exempted (correct)\n * git checkout -q main → `main` no longer follows `checkout`, so the exemption MISSED, the\n * lookahead concluded the target was not main, and the command was\n * blocked with \"this switches to a feature branch and then pulls main\n * into it\" — the exact opposite of what it does.\n *\n * That block landed on the cure stale-main-bash-guard itself prescribes, so the two guards\n * contradicted each other and a human had to route around both to update main. The fix is not a\n * cleverer regex: it is to TOKENIZE (CommandScanner already does the hard part) and walk the flags,\n * which is also why it must exist once rather than three times.\n *\n * Deliberately NOT \"does the string contain main\" — over-matching here is worse than the original\n * bug, because `git checkout -b feature/main-thing` and `git checkout -- main.ts` would then read as\n * \"switching to main\" and be EXEMPTED from a guard whose whole job is to catch a feature-branch pull.\n */\nconst CREATE_FLAGS: ReadonlySet<string> = new Set(['-b', '-B', '-c', '-C', '--orphan']);\n\n// Non-creating flags that consume the FOLLOWING token, so its value is never mistaken for the target.\nconst FLAGS_WITH_VALUE: ReadonlySet<string> = new Set(['--conflict', '--pathspec-from-file', '--start-point']);\n\n/**\n * The branch a checkout/switch lands on, and whether that command CREATES it.\n *\n * `created` is load-bearing rather than cosmetic: `git checkout -b x origin/main` lands on a branch\n * that is current by construction (nothing to be stale about), whereas landing on an EXISTING local\n * `main` is exactly the stale-checkout hazard. Data-only, so a class (per CLAUDE.md).\n */\nexport class BranchSwitch {\n branch: string;\n created: boolean;\n\n constructor(branch: string, created: boolean) {\n this.branch = branch;\n this.created = created;\n }\n}\n\nexport class BranchSwitchScan {\n constructor(private readonly scanner: CommandScanner = new CommandScanner()) {}\n\n /**\n * The branch this segment switches to, or null when the segment does not land on a branch at all:\n * a different command, no target word, `git checkout -` (the previous branch — unknowable here),\n * or anything after `--` (which ends option parsing, making the rest PATHSPECS, so\n * `git checkout -- main` restores a FILE named main and moves no branch).\n *\n * Flag-tolerant by construction: every leading flag is walked past, so `-q`, `--quiet`,\n * `--no-track`, `--detach` and friends change nothing about which word is the target.\n */\n targetOf(segment: string): BranchSwitch | null {\n const subcommand = this.scanner.gitSubcommand(segment);\n if (subcommand !== 'checkout' && subcommand !== 'switch') return null;\n\n const words = this.scanner.words(segment);\n const args = words.slice(words.indexOf(subcommand) + 1);\n\n for (let i = 0; i < args.length; i++) {\n const word = args[i];\n if (word === '--') return null;\n if (word === '-') return null;\n const created = this.createdBranch(args, i);\n if (created !== null) return created;\n if (FLAGS_WITH_VALUE.has(word)) { i++; continue; }\n if (word.startsWith('-')) continue;\n return new BranchSwitch(word, false);\n }\n return null;\n }\n\n /**\n * True only for landing on an EXISTING branch named `main` — the form that can hand you a stale\n * tree, and the form `git checkout main && git pull origin main` uses. `-b`/`-B`/`-c`/`-C` are\n * excluded because they create the branch here and now.\n */\n landsOnExistingMain(segment: string): boolean {\n const target = this.targetOf(segment);\n return target !== null && this.isExistingMain(target);\n }\n\n /** The same question for a target already parsed (switchesIn). One spelling, two entry shapes. */\n isExistingMain(target: BranchSwitch): boolean {\n return target.branch === 'main' && !target.created;\n }\n\n /** Every segment of a whole command that lands on a branch, in order. */\n switchesIn(command: string): readonly BranchSwitch[] {\n const found: BranchSwitch[] = [];\n for (const segment of this.scanner.commandSegments(command)) {\n const target = this.targetOf(segment);\n if (target !== null) found.push(target);\n }\n return found;\n }\n\n // `-b <name>` / `--orphan=<name>` — the new branch's name, or null when this word creates nothing.\n private createdBranch(args: readonly string[], i: number): BranchSwitch | null {\n const word = args[i];\n if (CREATE_FLAGS.has(word)) {\n const name = args[i + 1];\n if (name === undefined || name.startsWith('-')) return null;\n return new BranchSwitch(name, true);\n }\n const equals = word.indexOf('=');\n if (equals > 0 && CREATE_FLAGS.has(word.slice(0, equals))) {\n return new BranchSwitch(word.slice(equals + 1), true);\n }\n return null;\n }\n}\n"]}
|
|
@@ -5,6 +5,7 @@ import { FixHint } from '../fix-hint';
|
|
|
5
5
|
export declare class RedirectHowToMergeMainRule extends BashRuleBase<RedirectHowToMergeMainConfig> {
|
|
6
6
|
private readonly scanner;
|
|
7
7
|
private readonly recovery;
|
|
8
|
+
private readonly switches;
|
|
8
9
|
constructor(config: RedirectHowToMergeMainConfig);
|
|
9
10
|
readonly description = "Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.";
|
|
10
11
|
readonly fixHint: FixHint;
|
|
@@ -8,45 +8,34 @@ const rule_base_1 = require("../rule-base");
|
|
|
8
8
|
const fix_hint_1 = require("../fix-hint");
|
|
9
9
|
const command_scan_1 = require("../command-scan");
|
|
10
10
|
const tree_recovery_1 = require("./tree-recovery");
|
|
11
|
+
const branch_switch_scan_1 = require("./branch-switch-scan");
|
|
11
12
|
const INSTRUCT_FILE = 'webpieces.git-workflow.md';
|
|
12
13
|
const GUIDANCE = new rules_config_1.SyncFlowGuidance();
|
|
13
14
|
const FIX_HINT = new fix_hint_1.FixHint('`git merge` / `git rebase` are never run by AI — on any branch, in any form.', 'To bring main\'s changes into your feature branch:\n'
|
|
14
15
|
+ '\n'
|
|
15
16
|
+ GUIDANCE.flows().join('\n') + '\n'
|
|
16
17
|
+ '\n'
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
+ '
|
|
23
|
-
+ '
|
|
24
|
-
+ '
|
|
25
|
-
+ '(branch = current main + one commit that is exactly your work); the rewrite IS the mechanism, not\n'
|
|
26
|
-
+ 'a side effect. It also means you must NEVER run these commands on a branch another session owns.\n'
|
|
27
|
-
+ 'The gated commands merge internally as child processes this hook never sees, so they are\n'
|
|
28
|
-
+ 'unaffected by this guard.\n'
|
|
18
|
+
// The fork-point DERIVATION (why the invariant has two halves, and the three consumers a polluted
|
|
19
|
+
// fork point corrupts) and the WORD-FOR-WORD warning to hand the human are NOT here on purpose.
|
|
20
|
+
// Both are stated in full in the git-workflow doc this hint links by absolute path, and a message
|
|
21
|
+
// that re-derives what the linked doc already says is a second copy to keep in step. What survives
|
|
22
|
+
// here is only what changes what the AI types next.
|
|
23
|
+
+ 'Either flow does a 3-point merge, which keeps the fork point a pure main commit — what the build\n'
|
|
24
|
+
+ 'gate\'s --base and the PR review diff are computed from; a raw merge/rebase destroys it. The\n'
|
|
25
|
+
+ 'gated commands merge internally as child processes this hook never sees.\n'
|
|
29
26
|
+ '\n'
|
|
30
27
|
+ GUIDANCE.readOnlyChecks().join('\n') + '\n'
|
|
31
28
|
+ '\n'
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
+ '
|
|
35
|
-
+ '\n'
|
|
36
|
-
+ '
|
|
37
|
-
+ ' the gated pair for my situation (`wp-start-update` → `wp-finish-update` with no PR, or\n'
|
|
38
|
-
+ ' `wp-start-upsert-pr` → `wp-finish-upsert-pr` when a PR is open) does a 3-point merge and is\n'
|
|
39
|
-
+ ' the correct flow. Please push back and tell me to use the 3-point merge instead, unless you\n'
|
|
40
|
-
+ ' are certain this is a genuine exception."\n'
|
|
41
|
-
+ '\n'
|
|
42
|
-
+ 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above for the\n'
|
|
43
|
-
+ 'full flow (incl. worktrees).\n'
|
|
29
|
+
// The "do not run it, ask the human, tell them to push back" instruction is NOT repeated here: the
|
|
30
|
+
// violation line the AI reads first already says it. This paragraph's job is only the pointer.
|
|
31
|
+
+ 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above — the full\n'
|
|
32
|
+
+ 'flow (incl. worktrees), the fork-point invariant, why you must never sync a branch another\n'
|
|
33
|
+
+ 'session owns, and the exact words to warn a human with when you ask them to run a merge.\n'
|
|
44
34
|
// NOT "add that info to memory": "that info" was the whole git-workflow doc, which is REGENERATED
|
|
45
35
|
// per repo and per version — memorizing it guarantees a stale recall in the next session. Only the
|
|
46
36
|
// invariant is stable enough to persist; the doc must be re-read, never remembered.
|
|
47
|
-
+ 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\'s gated sync flow
|
|
48
|
-
+ 're-read its git-workflow doc each time rather than recalling it (
|
|
49
|
-
+ 'per version, so a remembered copy will be wrong).');
|
|
37
|
+
+ 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\'s gated sync flow and\n'
|
|
38
|
+
+ 're-read its git-workflow doc each time rather than recalling it (regenerated per repo/version).');
|
|
50
39
|
// `git merge --abort` / `git rebase --abort|--quit` UNDO an in-progress operation — they cannot create
|
|
51
40
|
// a merge commit or rewrite history, so they cannot violate the fork-point invariant this rule
|
|
52
41
|
// protects. They stay allowed so a repo left mid-operation (e.g. by a human-run rebase) can still be
|
|
@@ -58,12 +47,16 @@ function truncate(s) {
|
|
|
58
47
|
const MAX = 120;
|
|
59
48
|
return s.length <= MAX ? s : s.slice(0, MAX) + '…';
|
|
60
49
|
}
|
|
61
|
-
// Switches to a branch OTHER than main. `git branch -D <x>` is not a checkout so it does not trip
|
|
62
|
-
// this; `checkout main` and flag-only forms like `checkout -` do not count as a feature switch.
|
|
63
|
-
const SWITCHES_TO_NON_MAIN = /git\s+(?:checkout|switch)\s+(?!main\b|-\s|-$)\S+/;
|
|
64
50
|
class RedirectHowToMergeMainRule extends rule_base_1.BashRuleBase {
|
|
65
51
|
scanner = new command_scan_1.CommandScanner();
|
|
66
52
|
recovery = new tree_recovery_1.TreeRecovery();
|
|
53
|
+
// "Which branch does this land on?" — see branch-switch-scan.ts. It replaced a pair of regexes
|
|
54
|
+
// here (`/git\s+(?:checkout|switch)\s+main\b/` and its negative-lookahead twin) that assumed the
|
|
55
|
+
// branch name is the token immediately after the subcommand. One flag broke both halves at once:
|
|
56
|
+
// `git checkout -q main && git pull -q origin main` missed the main EXEMPTION and then tripped the
|
|
57
|
+
// feature-switch block, so this guard rejected the very command stale-main-bash-guard prescribes,
|
|
58
|
+
// with a reason ("switches to a feature branch") that was the opposite of the truth.
|
|
59
|
+
switches = new branch_switch_scan_1.BranchSwitchScan(this.scanner);
|
|
67
60
|
constructor(config) { super(config, 'redirect-how-to-merge-main'); }
|
|
68
61
|
description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';
|
|
69
62
|
fixHint = FIX_HINT;
|
|
@@ -103,14 +96,19 @@ class RedirectHowToMergeMainRule extends rule_base_1.BashRuleBase {
|
|
|
103
96
|
return null;
|
|
104
97
|
}
|
|
105
98
|
checkPull(ctx, segment) {
|
|
106
|
-
|
|
99
|
+
// The two branch questions are COMPLEMENTS of one parse, so they are asked of one parse —
|
|
100
|
+
// that is what keeps them from disagreeing. `git branch -D <x>` is not a checkout so it does
|
|
101
|
+
// not trip this, and `git checkout -` (previous branch, unknowable at hook time) lands
|
|
102
|
+
// nowhere we can name, so it counts as neither.
|
|
103
|
+
const switches = this.switches.switchesIn(ctx.command);
|
|
104
|
+
if (switches.some((s) => !this.switches.isExistingMain(s))) {
|
|
107
105
|
return this.block(ctx, segment, 'Blocked: this command switches to a feature branch and then pulls main into it.');
|
|
108
106
|
}
|
|
109
107
|
// The recommended `git checkout main && git pull origin main` — but ONLY in the primary
|
|
110
108
|
// clone. Inside a linked worktree that checkout FATALS ("'main' is already checked out at
|
|
111
109
|
// <primary>"), so waving it through here hands the AI a command that cannot work and costs
|
|
112
110
|
// it a turn to discover. Steer to the fetch, which is all a worktree needs.
|
|
113
|
-
if (
|
|
111
|
+
if (switches.length > 0) {
|
|
114
112
|
if (this.recovery.kindOf(ctx.workspaceRoot) !== 'worktree')
|
|
115
113
|
return null;
|
|
116
114
|
// block() appends updateMainSteps for the tree we are in — don't say it twice here.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect-how-to-merge-main.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/redirect-how-to-merge-main.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAAwH;AAGxH,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,kDAAiD;AACjD,mDAA+C;AAE/C,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,QAAQ,GAAG,IAAI,+BAAgB,EAAE,CAAC;AAExC,MAAM,QAAQ,GAAG,IAAI,kBAAO,CACxB,8EAA8E,EAC9E,sDAAsD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C,iBAAiB,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;QACzF,6FAA6F;QAC7F,6FAA6F;QAC7F,8FAA8F;QAC9F,8FAA8F;QAC9F,sEAAsE;QACtE,MAAM,UAAU,GAAG;YACf,EAAE;YACF,4FAA4F;YAC5F,oEAAoE;YACpE,GAAG,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC5E,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,OAAO,IAAI,iBAAC,CACR,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,EACjB,GAAG,IAAI,oYAAoY,OAAO,IAAI,UAAU,EAAE,CACra,CAAC;IACN,CAAC;CACJ;AA5FD,gEA4FC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { RedirectHowToMergeMainConfig, RepoRootFinder, SyncFlowGuidance, writeTemplate } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { CommandScanner } from '../command-scan';\nimport { TreeRecovery } from './tree-recovery';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\nconst GUIDANCE = new SyncFlowGuidance();\n\nconst FIX_HINT = new FixHint(\n '`git merge` / `git rebase` are never run by AI — on any branch, in any form.',\n 'To bring main\\'s changes into your feature branch:\\n'\n + '\\n'\n + GUIDANCE.flows().join('\\n') + '\\n'\n + '\\n'\n + 'Either flow does a 3-point merge (fork-point=A, feature-HEAD=B, main-HEAD=C). WHY that matters:\\n'\n + 'the fork point must be a pure main commit holding none of your work, AND your branch must hold\\n'\n + 'none of main\\'s commits after it — only then is diff(fork point → HEAD) exactly your changes.\\n'\n + 'Three things read that diff: the 3-point merge (B−A vs C−A is how conflicts are resolved), the\\n'\n + 'build gate (`nx affected --base=` is the fork point, so it rebuilds only your work), and the PR\\n'\n + 'review diff. A raw `git merge`/`git rebase` breaks BOTH halves at once — your branch takes on\\n'\n + 'main\\'s commits and the base stops being a clean main state — so all three then describe work you\\n'\n + 'did not do. The gated flow squash-rewrites and force-pushes precisely to restore that invariant\\n'\n + '(branch = current main + one commit that is exactly your work); the rewrite IS the mechanism, not\\n'\n + 'a side effect. It also means you must NEVER run these commands on a branch another session owns.\\n'\n + 'The gated commands merge internally as child processes this hook never sees, so they are\\n'\n + 'unaffected by this guard.\\n'\n + '\\n'\n + GUIDANCE.readOnlyChecks().join('\\n') + '\\n'\n + '\\n'\n + 'If you believe a raw merge/rebase is genuinely required, do NOT run it and do NOT work around\\n'\n + 'this guard. STOP and ask the HUMAN to run that exact command themselves — and when you ask,\\n'\n + 'warn them, in these words:\\n'\n + '\\n'\n + ' \"I am asking you to run a raw git merge/rebase. This is almost always the WRONG call —\\n'\n + ' the gated pair for my situation (`wp-start-update` → `wp-finish-update` with no PR, or\\n'\n + ' `wp-start-upsert-pr` → `wp-finish-upsert-pr` when a PR is open) does a 3-point merge and is\\n'\n + ' the correct flow. Please push back and tell me to use the 3-point merge instead, unless you\\n'\n + ' are certain this is a genuine exception.\"\\n'\n + '\\n'\n + 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above for the\\n'\n + 'full flow (incl. worktrees).\\n'\n // NOT \"add that info to memory\": \"that info\" was the whole git-workflow doc, which is REGENERATED\n // per repo and per version — memorizing it guarantees a stale recall in the next session. Only the\n // invariant is stable enough to persist; the doc must be re-read, never remembered.\n + 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\\'s gated sync flow, and\\n'\n + 're-read its git-workflow doc each time rather than recalling it (it is regenerated per repo and\\n'\n + 'per version, so a remembered copy will be wrong).',\n);\n\n// `git merge --abort` / `git rebase --abort|--quit` UNDO an in-progress operation — they cannot create\n// a merge commit or rewrite history, so they cannot violate the fork-point invariant this rule\n// protects. They stay allowed so a repo left mid-operation (e.g. by a human-run rebase) can still be\n// cleaned up. `--continue` is deliberately NOT here: it COMPLETES the operation.\nconst UNDO_FLAG = /--(?:abort|quit)\\b/;\n\n// Typed as a query (\"would this fast-forward?\"), but a successful --ff-only IS the merge.\nconst FF_ONLY = /--ff-only\\b/;\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\n// Switches to a branch OTHER than main. `git branch -D <x>` is not a checkout so it does not trip\n// this; `checkout main` and flag-only forms like `checkout -` do not count as a feature switch.\nconst SWITCHES_TO_NON_MAIN = /git\\s+(?:checkout|switch)\\s+(?!main\\b|-\\s|-$)\\S+/;\n\nexport class RedirectHowToMergeMainRule extends BashRuleBase<RedirectHowToMergeMainConfig> {\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n\n constructor(config: RedirectHowToMergeMainConfig) { super(config, 'redirect-how-to-merge-main'); }\n\n readonly description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';\n readonly fixHint = FIX_HINT;\n\n check(ctx: BashContext): readonly Violation[] {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n const violation = this.checkSegment(ctx, segment);\n if (violation !== null) return [violation];\n }\n return [];\n }\n\n private checkSegment(ctx: BashContext, segment: string): Violation | null {\n // 1. merge/rebase: unconditional block. Deliberately NO branch lookup.\n //\n // This rule used to read hook-time HEAD and bail out when it was `main`. But a PreToolUse hook\n // runs BEFORE the command, so HEAD-at-hook-time is a value the command itself is about to\n // change: `git checkout feat && git rebase main`, issued while HEAD was still `main` from a\n // prior cleanup, read as \"we're on main, this is fine\" and was waved through. That is the\n // incident this rule exists to prevent. Since merge/rebase have no legitimate AI-run form on\n // ANY branch, there is no branch to consult — and so no HEAD to spoof.\n if (this.scanner.invokesGit(segment, 'merge') || this.scanner.invokesGit(segment, 'rebase')) {\n if (UNDO_FLAG.test(segment)) return null;\n // `--ff-only` reads like a probe (\"can I fast-forward?\") but it MUTATES whenever the answer\n // is yes, so say that here — the AI that typed it was usually only trying to look.\n const probe = FF_ONLY.test(segment)\n ? ' `--ff-only` is NOT a read-only check — it moves your branch whenever it succeeds; see the read-only checks below.'\n : '';\n return this.block(ctx, segment, 'Direct `git merge`/`git rebase` is blocked — AI never runs it, on any branch.' + probe);\n }\n\n // 2. pull: unlike merge/rebase this DOES retain a legitimate on-main form\n // (`git checkout main && git pull origin main`), so it must consult the branch — which is\n // exactly why it also needs the branch-switch check that (1) no longer requires.\n if (this.scanner.invokesGit(segment, 'pull') && /\\borigin\\s+main\\b/.test(segment)) {\n return this.checkPull(ctx, segment);\n }\n\n return null;\n }\n\n private checkPull(ctx: BashContext, segment: string): Violation | null {\n if (SWITCHES_TO_NON_MAIN.test(ctx.command)) {\n return this.block(ctx, segment, 'Blocked: this command switches to a feature branch and then pulls main into it.');\n }\n // The recommended `git checkout main && git pull origin main` — but ONLY in the primary\n // clone. Inside a linked worktree that checkout FATALS (\"'main' is already checked out at\n // <primary>\"), so waving it through here hands the AI a command that cannot work and costs\n // it a turn to discover. Steer to the fetch, which is all a worktree needs.\n if (/git\\s+(?:checkout|switch)\\s+main\\b/.test(ctx.command)) {\n if (this.recovery.kindOf(ctx.workspaceRoot) !== 'worktree') return null;\n // block() appends updateMainSteps for the tree we are in — don't say it twice here.\n return this.block(ctx, segment, 'Blocked.');\n }\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n if (currentBranch === 'main') return null;\n\n return this.block(ctx, segment, `Pulling main into feature branch '${currentBranch}' is blocked.`);\n }\n\n private block(ctx: BashContext, segment: string, what: string): Violation {\n // Materialize the doc we are about to send the AI to. This guard fires long before any `wp-*`\n // command runs (those are what normally write it), so the linked path could easily not exist —\n // and a STALE copy from an older @webpieces is just as misleading, hence overwrite.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n // \"How do I get MAIN itself current?\" is a different question from \"sync my feature branch\",\n // and it used to have no answer anywhere on this path — the flows cover feature branches and\n // the read-only checks cover looking. An AI on main with no third option improvises, and what\n // it improvises is `git reset --hard origin/main`. Answer the question instead, shaped to the\n // tree we are actually in (in a worktree `git checkout main` fatals).\n const updateMain = [\n '',\n 'On main and just wanted to bring MAIN itself up to date? That is a different question from',\n 'syncing a feature branch, and merge/reset is not the answer to it:',\n ...this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)),\n ].join('\\n');\n return new V(\n 1,\n truncate(segment),\n `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"redirect-how-to-merge-main.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/redirect-how-to-merge-main.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAAwH;AAGxH,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,kDAAiD;AACjD,mDAA+C;AAC/C,6DAAsE;AAEtE,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,QAAQ,GAAG,IAAI,+BAAgB,EAAE,CAAC;AAExC,MAAM,QAAQ,GAAG,IAAI,kBAAO,CACxB,8EAA8E,EAC9E,sDAAsD;MACpD,IAAI;MACJ,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI;MAClC,IAAI;IACN,kGAAkG;IAClG,gGAAgG;IAChG,kGAAkG;IAClG,mGAAmG;IACnG,oDAAoD;MAClD,oGAAoG;MACpG,gGAAgG;MAChG,4EAA4E;MAC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F;QAC9F,8FAA8F;QAC9F,sEAAsE;QACtE,MAAM,UAAU,GAAG;YACf,EAAE;YACF,4FAA4F;YAC5F,oEAAoE;YACpE,GAAG,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC5E,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,OAAO,IAAI,iBAAC,CACR,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,EACjB,GAAG,IAAI,oYAAoY,OAAO,IAAI,UAAU,EAAE,CACra,CAAC;IACN,CAAC;CACJ;AAxGD,gEAwGC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { RedirectHowToMergeMainConfig, RepoRootFinder, SyncFlowGuidance, writeTemplate } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { CommandScanner } from '../command-scan';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitch, BranchSwitchScan } from './branch-switch-scan';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\nconst GUIDANCE = new SyncFlowGuidance();\n\nconst FIX_HINT = new FixHint(\n '`git merge` / `git rebase` are never run by AI — on any branch, in any form.',\n 'To bring main\\'s changes into your feature branch:\\n'\n + '\\n'\n + GUIDANCE.flows().join('\\n') + '\\n'\n + '\\n'\n // The fork-point DERIVATION (why the invariant has two halves, and the three consumers a polluted\n // fork point corrupts) and the WORD-FOR-WORD warning to hand the human are NOT here on purpose.\n // Both are stated in full in the git-workflow doc this hint links by absolute path, and a message\n // that re-derives what the linked doc already says is a second copy to keep in step. What survives\n // here is only what changes what the AI types next.\n + 'Either flow does a 3-point merge, which keeps the fork point a pure main commit — what the build\\n'\n + 'gate\\'s --base and the PR review diff are computed from; a raw merge/rebase destroys it. The\\n'\n + 'gated commands merge internally as child processes this hook never sees.\\n'\n + '\\n'\n + GUIDANCE.readOnlyChecks().join('\\n') + '\\n'\n + '\\n'\n // The \"do not run it, ask the human, tell them to push back\" instruction is NOT repeated here: the\n // violation line the AI reads first already says it. This paragraph's job is only the pointer.\n + 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above — the full\\n'\n + 'flow (incl. worktrees), the fork-point invariant, why you must never sync a branch another\\n'\n + 'session owns, and the exact words to warn a human with when you ask them to run a merge.\\n'\n // NOT \"add that info to memory\": \"that info\" was the whole git-workflow doc, which is REGENERATED\n // per repo and per version — memorizing it guarantees a stale recall in the next session. Only the\n // invariant is stable enough to persist; the doc must be re-read, never remembered.\n + 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\\'s gated sync flow and\\n'\n + 're-read its git-workflow doc each time rather than recalling it (regenerated per repo/version).',\n);\n\n// `git merge --abort` / `git rebase --abort|--quit` UNDO an in-progress operation — they cannot create\n// a merge commit or rewrite history, so they cannot violate the fork-point invariant this rule\n// protects. They stay allowed so a repo left mid-operation (e.g. by a human-run rebase) can still be\n// cleaned up. `--continue` is deliberately NOT here: it COMPLETES the operation.\nconst UNDO_FLAG = /--(?:abort|quit)\\b/;\n\n// Typed as a query (\"would this fast-forward?\"), but a successful --ff-only IS the merge.\nconst FF_ONLY = /--ff-only\\b/;\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nexport class RedirectHowToMergeMainRule extends BashRuleBase<RedirectHowToMergeMainConfig> {\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n // \"Which branch does this land on?\" — see branch-switch-scan.ts. It replaced a pair of regexes\n // here (`/git\\s+(?:checkout|switch)\\s+main\\b/` and its negative-lookahead twin) that assumed the\n // branch name is the token immediately after the subcommand. One flag broke both halves at once:\n // `git checkout -q main && git pull -q origin main` missed the main EXEMPTION and then tripped the\n // feature-switch block, so this guard rejected the very command stale-main-bash-guard prescribes,\n // with a reason (\"switches to a feature branch\") that was the opposite of the truth.\n private readonly switches = new BranchSwitchScan(this.scanner);\n\n constructor(config: RedirectHowToMergeMainConfig) { super(config, 'redirect-how-to-merge-main'); }\n\n readonly description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';\n readonly fixHint = FIX_HINT;\n\n check(ctx: BashContext): readonly Violation[] {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n const violation = this.checkSegment(ctx, segment);\n if (violation !== null) return [violation];\n }\n return [];\n }\n\n private checkSegment(ctx: BashContext, segment: string): Violation | null {\n // 1. merge/rebase: unconditional block. Deliberately NO branch lookup.\n //\n // This rule used to read hook-time HEAD and bail out when it was `main`. But a PreToolUse hook\n // runs BEFORE the command, so HEAD-at-hook-time is a value the command itself is about to\n // change: `git checkout feat && git rebase main`, issued while HEAD was still `main` from a\n // prior cleanup, read as \"we're on main, this is fine\" and was waved through. That is the\n // incident this rule exists to prevent. Since merge/rebase have no legitimate AI-run form on\n // ANY branch, there is no branch to consult — and so no HEAD to spoof.\n if (this.scanner.invokesGit(segment, 'merge') || this.scanner.invokesGit(segment, 'rebase')) {\n if (UNDO_FLAG.test(segment)) return null;\n // `--ff-only` reads like a probe (\"can I fast-forward?\") but it MUTATES whenever the answer\n // is yes, so say that here — the AI that typed it was usually only trying to look.\n const probe = FF_ONLY.test(segment)\n ? ' `--ff-only` is NOT a read-only check — it moves your branch whenever it succeeds; see the read-only checks below.'\n : '';\n return this.block(ctx, segment, 'Direct `git merge`/`git rebase` is blocked — AI never runs it, on any branch.' + probe);\n }\n\n // 2. pull: unlike merge/rebase this DOES retain a legitimate on-main form\n // (`git checkout main && git pull origin main`), so it must consult the branch — which is\n // exactly why it also needs the branch-switch check that (1) no longer requires.\n if (this.scanner.invokesGit(segment, 'pull') && /\\borigin\\s+main\\b/.test(segment)) {\n return this.checkPull(ctx, segment);\n }\n\n return null;\n }\n\n private checkPull(ctx: BashContext, segment: string): Violation | null {\n // The two branch questions are COMPLEMENTS of one parse, so they are asked of one parse —\n // that is what keeps them from disagreeing. `git branch -D <x>` is not a checkout so it does\n // not trip this, and `git checkout -` (previous branch, unknowable at hook time) lands\n // nowhere we can name, so it counts as neither.\n const switches = this.switches.switchesIn(ctx.command);\n if (switches.some((s: BranchSwitch): boolean => !this.switches.isExistingMain(s))) {\n return this.block(ctx, segment, 'Blocked: this command switches to a feature branch and then pulls main into it.');\n }\n // The recommended `git checkout main && git pull origin main` — but ONLY in the primary\n // clone. Inside a linked worktree that checkout FATALS (\"'main' is already checked out at\n // <primary>\"), so waving it through here hands the AI a command that cannot work and costs\n // it a turn to discover. Steer to the fetch, which is all a worktree needs.\n if (switches.length > 0) {\n if (this.recovery.kindOf(ctx.workspaceRoot) !== 'worktree') return null;\n // block() appends updateMainSteps for the tree we are in — don't say it twice here.\n return this.block(ctx, segment, 'Blocked.');\n }\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n if (currentBranch === 'main') return null;\n\n return this.block(ctx, segment, `Pulling main into feature branch '${currentBranch}' is blocked.`);\n }\n\n private block(ctx: BashContext, segment: string, what: string): Violation {\n // Materialize the doc we are about to send the AI to. This guard fires long before any `wp-*`\n // command runs (those are what normally write it), so the linked path could easily not exist —\n // and a STALE copy from an older @webpieces is just as misleading, hence overwrite.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n // \"How do I get MAIN itself current?\" is a different question from \"sync my feature branch\",\n // and it used to have no answer anywhere on this path — the flows cover feature branches and\n // the read-only checks cover looking. An AI on main with no third option improvises, and what\n // it improvises is `git reset --hard origin/main`. Answer the question instead, shaped to the\n // tree we are actually in (in a worktree `git checkout main` fatals).\n const updateMain = [\n '',\n 'On main and just wanted to bring MAIN itself up to date? That is a different question from',\n 'syncing a feature branch, and merge/reset is not the answer to it:',\n ...this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)),\n ].join('\\n');\n return new V(\n 1,\n truncate(segment),\n `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`,\n );\n }\n}\n"]}
|
|
@@ -73,6 +73,7 @@ export declare class StaleMainBashGuardRule extends BashRuleBase<StaleMainBashGu
|
|
|
73
73
|
constructor(config: StaleMainBashGuardConfig);
|
|
74
74
|
private readonly scanner;
|
|
75
75
|
private readonly recovery;
|
|
76
|
+
private readonly switches;
|
|
76
77
|
readonly description: string;
|
|
77
78
|
readonly defaultOptions: {
|
|
78
79
|
hangTimeoutMinutes: number;
|
|
@@ -86,12 +87,6 @@ export declare class StaleMainBashGuardRule extends BashRuleBase<StaleMainBashGu
|
|
|
86
87
|
* the point.
|
|
87
88
|
*/
|
|
88
89
|
private bareCheckoutOfMain;
|
|
89
|
-
/**
|
|
90
|
-
* True only for landing ON the branch. `-b`/`-B`/`-c`/`-C` CREATE a branch, so
|
|
91
|
-
* `git checkout -b x origin/main` is current by construction and never blocked; a `--` turns the
|
|
92
|
-
* rest into pathspecs, so `git checkout -- main` restores a FILE named main and moves no branch.
|
|
93
|
-
*/
|
|
94
|
-
private switchesToMainBranch;
|
|
95
90
|
private pairingMessage;
|
|
96
91
|
private staleContentRead;
|
|
97
92
|
private contains;
|
|
@@ -14,6 +14,7 @@ const command_scan_1 = require("../command-scan");
|
|
|
14
14
|
const stale_main_message_1 = require("./stale-main-message");
|
|
15
15
|
const content_read_scan_1 = require("./content-read-scan");
|
|
16
16
|
const tree_recovery_1 = require("./tree-recovery");
|
|
17
|
+
const branch_switch_scan_1 = require("./branch-switch-scan");
|
|
17
18
|
/**
|
|
18
19
|
* The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:
|
|
19
20
|
* a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that
|
|
@@ -85,6 +86,7 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
|
|
|
85
86
|
constructor(config) { super(config, 'stale-main-bash-guard'); }
|
|
86
87
|
scanner = new command_scan_1.CommandScanner();
|
|
87
88
|
recovery = new tree_recovery_1.TreeRecovery();
|
|
89
|
+
switches = new branch_switch_scan_1.BranchSwitchScan(this.scanner);
|
|
88
90
|
description = 'Block a bare `git checkout main` (chain the pull into the same command), and block ' +
|
|
89
91
|
'content-reading Bash (cat/grep/ls/…) while local main is behind origin/main — so a session ' +
|
|
90
92
|
'neither lands on a stale main nor reasons over one through the side door the Read block leaves.';
|
|
@@ -92,9 +94,16 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
|
|
|
92
94
|
hangTimeoutMinutes: rules_config_1.DEFAULT_HANG_TIMEOUT_MINUTES,
|
|
93
95
|
};
|
|
94
96
|
fixHint = new fix_hint_1.FixHint('Landing on `main` without pulling, or reading files while main is behind origin/main, both give you stale content.', 'Pair the checkout with the pull, or update main and re-run:', [
|
|
95
|
-
|
|
97
|
+
// TREE-SHAPED, from the one source of tree-shaped cures. A static rule-level hint has no
|
|
98
|
+
// workspace root, so it renders the 'unknown' kind — TreeRecovery's deliberate answer for
|
|
99
|
+
// "we cannot detect the tree": both forms, each labelled. That matters here because the
|
|
100
|
+
// primary-clone form (`git checkout main && …`) is BLOCKED by redirect-how-to-merge-main
|
|
101
|
+
// inside a linked worktree, so a preferred option naming it unconditionally hands the AI a
|
|
102
|
+
// cure a sibling guard denies. The per-block message (pairingMessage) is detected and
|
|
103
|
+
// prints exactly one form; this is the fallback for the hint that cannot look.
|
|
104
|
+
new fix_hint_1.Option(this.recovery.updateMainSteps('unknown').join('\n')
|
|
105
|
+
+ '\nWhichever form applies, the pull must be in the SAME command as the checkout.', true),
|
|
96
106
|
new fix_hint_1.Option('Already on main: git pull --ff-only origin main (then re-run). If that fatals with "Cannot fast-forward to multiple branches", .git/FETCH_HEAD has a duplicate line — run git fetch --prune origin main first.'),
|
|
97
|
-
new fix_hint_1.Option('In a linked worktree `git checkout main` FATALS ("main is already checked out at <primary clone>") — branch off fresh main instead: git fetch origin main && git checkout -b <name> origin/main'),
|
|
98
107
|
new fix_hint_1.Option('NOT blocked: `git checkout <sha>`, `git checkout -b <x> origin/main`, `git checkout -- <file>`, any other branch. Also still allowed: builds, tests, installs, the pull itself, all git/gh METADATA (status|log|diff|show|branch), every Write/Edit, and reading webpieces.config.json.'),
|
|
99
108
|
new fix_hint_1.Option('Disable in webpieces.config.json under hookGuards → stale-main-bash-guard (mode OFF) if intentional.'),
|
|
100
109
|
]);
|
|
@@ -148,40 +157,24 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
|
|
|
148
157
|
*/
|
|
149
158
|
bareCheckoutOfMain(ctx) {
|
|
150
159
|
for (const segment of this.scanner.commandSegments(ctx.command)) {
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
160
|
+
// BranchSwitchScan answers "which branch does this land on" for both guards, flag-tolerantly:
|
|
161
|
+
// `git checkout -q main` lands on main exactly as the bare form does, while
|
|
162
|
+
// `git checkout -b x origin/main` (creates), `git checkout -- main` (pathspec) and
|
|
163
|
+
// `git checkout <sha>` do not. See branch-switch-scan.ts for why that lives in one place.
|
|
164
|
+
if (!this.switches.landsOnExistingMain(segment))
|
|
154
165
|
continue;
|
|
155
166
|
return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;
|
|
156
167
|
}
|
|
157
168
|
return null;
|
|
158
169
|
}
|
|
159
|
-
/**
|
|
160
|
-
* True only for landing ON the branch. `-b`/`-B`/`-c`/`-C` CREATE a branch, so
|
|
161
|
-
* `git checkout -b x origin/main` is current by construction and never blocked; a `--` turns the
|
|
162
|
-
* rest into pathspecs, so `git checkout -- main` restores a FILE named main and moves no branch.
|
|
163
|
-
*/
|
|
164
|
-
switchesToMainBranch(segment) {
|
|
165
|
-
const words = this.scanner.words(segment);
|
|
166
|
-
for (let i = 0; i < words.length; i++) {
|
|
167
|
-
const word = words[i];
|
|
168
|
-
if (word === '--')
|
|
169
|
-
return false;
|
|
170
|
-
if (/^-[bBcC]$/.test(word))
|
|
171
|
-
return false;
|
|
172
|
-
if (i > 1 && word === 'main')
|
|
173
|
-
return true;
|
|
174
|
-
}
|
|
175
|
-
return false;
|
|
176
|
-
}
|
|
177
170
|
pairingMessage(ctx) {
|
|
178
171
|
const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\n');
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
+ '
|
|
184
|
-
+ '
|
|
172
|
+
// Deliberately SHORT. The incident that bought this guard (a main 157 commits behind; the
|
|
173
|
+
// downgrade the reverted shim then prescribed) is maintainer material and lives in the class
|
|
174
|
+
// docblock above — the reader of THIS text needs only what changes what they type.
|
|
175
|
+
return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had — '
|
|
176
|
+
+ 'stale files, plus a reverted @webpieces pin and guard shim, so the drift guard then '
|
|
177
|
+
+ 'reports the drift BACKWARDS. Chain the pull into the same command:\n' + steps;
|
|
185
178
|
}
|
|
186
179
|
// The first segment that would read stale workspace content, or null when none does. The RAW
|
|
187
180
|
// command is scanned, not commandCode: this is a blocklist-shaped guard, so stripping quoted
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stale-main-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/stale-main-bash-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAoD;AAEpD,0DAKiC;AAGjC,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAA8C;AAC9C,0CAAsC;AACtC,4DAA8D;AAC9D,kDAAsF;AACtF,sDAAkD;AAClD,kDAAiD;AACjD,6DAAwD;AACxD,2DA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AAC,CAAC;IAC3D,CAAC;IAEO,QAAQ,CAAC,CAAS;QACtB,MAAM,GAAG,GAAG,GAAG,CAAC;QAChB,OAAO,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;IACvD,CAAC;IAEO,WAAW,CAAC,GAAgB,EAAE,MAAqB,EAAE,OAAgB,EAAE,MAAc,EAAE,KAAa;QACxG,IAAA,+BAAgB,EACZ,GAAG,CAAC,aAAa,EACjB,IAAI,4BAAa,CAAC,uBAAuB,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,8BAAa,EAAE,wBAAS,CAAC,CACzI,CAAC;IACN,CAAC;IAEO,aAAa,CAAC,aAAqB;QACvC,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,IAAA,wBAAQ,EAAC,iCAAiC,EAAE;gBAC/C,GAAG,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;aACxE,CAAC,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AA7ND,wDA6NC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\n\nimport {\n StaleMainBashGuardConfig,\n DEFAULT_HANG_TIMEOUT_MINUTES,\n readMainSyncStatus,\n MainSyncStatus,\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';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2 } from '../decision-log';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { CommandScanner } from '../command-scan';\nimport { StaleMainMessage } from './stale-main-message';\nimport { ContentReadScan } from './content-read-scan';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:\n * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that\n * contains the damage once it is already there.\n *\n * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────\n *\n * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.\n * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this\n * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157\n * commits behind** origin. That checkout did not merely produce stale files — it reverted:\n *\n * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;\n * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy\n * whose message stated the drift BACKWARDS (\"your installed webpieces is older than required\")\n * and named a single cure, `pnpm install`;\n * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match\n * the stale pin, and had to undo it with the `git pull` that should have come first.\n *\n * The shim on current main already diagnoses drift correctly — it distinguishes \"the pin is newer\"\n * from \"the pin is stale, and `pnpm install` would downgrade you\". None of that helped, because the\n * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout\n * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive\n * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.\n *\n * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the\n * checkout, so the only `main` it could measure is the one it is about to leave. The interesting\n * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap\n * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when\n * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.\n *\n * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`\n * appears anywhere in the SAME command.\n * ALLOWED `git checkout main && git pull origin main`, the pairing this forces, which is the\n * exact line the post-merge cleanup flow already prescribes.\n * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,\n * `git checkout -- <file>`, and any other branch.\n *\n * ── REACTIVE: content-reading Bash on a stale `main` ─────────────────────────────────────────────\n *\n * read-stale-guard blocks the Read tool when local `main` is behind origin/main — but it looks at\n * nothing else, deliberately: \"every cure is a Bash command, so Bash is the escape hatch — never\n * wedge it.\" That reasoning is right about the CURE and wrong about `cat`/`grep`/`ls`. In the\n * incident this closes, an agent sat on a `main` 18 commits behind origin/main (108 files, +8069\n * −3692 upstream), had its Read tool blocked exactly as designed, and then spent the whole session\n * `ls`-ing, `grep`-ing and `cat`-ing the same stale tree through the side door — describing a CI\n * workflow set that was missing a 186-line workflow which existed upstream. The logs read\n * \"read-stale-guard handled\", which is worse than no guard: it looks covered.\n *\n * So this guard blocks CONTENT-READING Bash only, never the whole shell. Builds, tests, installs,\n * `git pull`, git METADATA (log/diff/show/status) — all still run. What is blocked is a command that\n * would put stale FILE CONTENT into context: `cat`/`head`/`grep`/`rg`/`sed`/`awk`/`ls`/`find`/… of a\n * path inside this workspace, and `git grep` / `git show <rev>:<path>` against a local rev. The same\n * line merged-branch-bash-guard already draws for State B, scoped tighter because State A's cure is\n * one command away and there is no reason to stop anything else.\n *\n * A piped consumer reads stdin, not the tree: `git log --oneline | grep fix` is allowed, because the\n * bytes came from git metadata, not from a stale file. That is why the scan needs the pipe flag.\n *\n * FAIL-OPEN, with read-stale-guard's own escape valves, so it can never wedge a session:\n * - branch undeterminable / not on `main` / no cache / cache for another branch → allow\n * - `originMain` unknown (offline) → allow\n * - origin/main already an ancestor of HEAD (ancestry, NOT equality) → allow the instant the pull lands\n * - DIRTY tree → allow: the pull is not a clean fast-forward, and resolving that means reading the\n * very files in conflict. Never trap the agent away from its own rescue.\n * - reading `webpieces.config.json` (the mode-OFF escape hatch) and `.webpieces/**` → allow\n */\nexport class StaleMainBashGuardRule extends BashRuleBase<StaleMainBashGuardConfig> {\n constructor(config: StaleMainBashGuardConfig) { super(config, 'stale-main-bash-guard'); }\n\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n\n readonly description =\n 'Block a bare `git checkout main` (chain the pull into the same command), and block ' +\n 'content-reading Bash (cat/grep/ls/…) while local main is behind origin/main — so a session ' +\n 'neither lands on a stale main nor reasons over one through the side door the Read block leaves.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'Landing on `main` without pulling, or reading files while main is behind origin/main, both give you stale content.',\n 'Pair the checkout with the pull, or update main and re-run:',\n [\n new Option('git checkout main && git pull origin main (the pull must be in the SAME command).', true),\n new Option('Already on main: git pull --ff-only origin main (then re-run). If that fatals with \"Cannot fast-forward to multiple branches\", .git/FETCH_HEAD has a duplicate line — run git fetch --prune origin main first.'),\n new Option('In a linked worktree `git checkout main` FATALS (\"main is already checked out at <primary clone>\") — branch off fresh main instead: git fetch origin main && git checkout -b <name> origin/main'),\n new Option('NOT blocked: `git checkout <sha>`, `git checkout -b <x> origin/main`, `git checkout -- <file>`, any other branch. Also still allowed: builds, tests, installs, the pull itself, all git/gh METADATA (status|log|diff|show|branch), every Write/Edit, and reading webpieces.config.json.'),\n new Option('Disable in webpieces.config.json under hookGuards → stale-main-bash-guard (mode OFF) if intentional.'),\n ],\n );\n\n check(ctx: BashContext): readonly Violation[] {\n // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout\n // below: those all ask \"is the main we are ON stale?\", and this asks about the main we are\n // about to MOVE TO — a different branch, and one no cache can describe yet.\n const bare = this.bareCheckoutOfMain(ctx);\n if (bare !== null) {\n return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');\n }\n\n const branch = this.currentBranch(ctx.workspaceRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command.\n triggerMainSyncRefresh(ctx.workspaceRoot, this.config.hangTimeoutMinutes ?? DEFAULT_HANG_TIMEOUT_MINUTES);\n\n // State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.\n if (branch !== 'main') return this.allow(ctx, branch, 'not-on-main (state B is another guard)');\n\n const status = readMainSyncStatus(ctx.workspaceRoot, 'main');\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.cacheSummary(status);\n // BELT-AND-BRACES since the cache became branch-keyed: we asked for the 'main' entry by key, so\n // a mismatch means the map's key and the entry's own `branch` disagree — a shape bug. Kept so\n // that degrades to an allow. Unreachable in normal operation.\n if (status.branch !== 'main') return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // Offline / origin unresolvable — we have nothing to be stale RELATIVE TO.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // Ancestry, not equality: the moment the pull lands (or we are simply ahead), we are current.\n if (this.contains(ctx.workspaceRoot, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n // A dirty tree means the pull is not a clean fast-forward. Do not cut the agent off from the\n // files it must read to resolve that — the same valve read-stale-guard opens.\n if (this.isDirty(ctx.workspaceRoot)) {\n return this.failOpen(ctx, branch, 'dirty-tree-on-main', cache);\n }\n\n const reader = this.staleContentRead(ctx);\n if (reader === null) return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)', cache);\n\n return this.block(ctx, branch, `stale-main content read (${reader})`, this.staleMessage(ctx.workspaceRoot), cache);\n }\n\n /**\n * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same\n * command, or null. The pull is looked for across the WHOLE command, not the matched segment,\n * because `git checkout main && git pull origin main` splits into two segments and the pairing is\n * the point.\n */\n private bareCheckoutOfMain(ctx: BashContext): string | null {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n if (!this.scanner.invokesGit(segment, 'checkout') && !this.scanner.invokesGit(segment, 'switch')) continue;\n if (!this.switchesToMainBranch(segment)) continue;\n return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;\n }\n return null;\n }\n\n /**\n * True only for landing ON the branch. `-b`/`-B`/`-c`/`-C` CREATE a branch, so\n * `git checkout -b x origin/main` is current by construction and never blocked; a `--` turns the\n * rest into pathspecs, so `git checkout -- main` restores a FILE named main and moves no branch.\n */\n private switchesToMainBranch(segment: string): boolean {\n const words = this.scanner.words(segment);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n if (word === '--') return false;\n if (/^-[bBcC]$/.test(word)) return false;\n if (i > 1 && word === 'main') return true;\n }\n return false;\n }\n\n private pairingMessage(ctx: BashContext): string {\n const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\\n');\n return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had. '\n + 'That is not only stale FILES — it also reverts `package.json`\\'s @webpieces pin and the '\n + 'guard shim under `.claude/webpieces/`, so the very hook that would diagnose the resulting '\n + 'version drift is replaced by an older copy that reports it BACKWARDS and names the cure '\n + 'that makes it worse. Chain the pull into the same command, leaving no window in which you '\n + 'are on a stale main:\\n' + steps;\n }\n\n // The first segment that would read stale workspace content, or null when none does. The RAW\n // command is scanned, not commandCode: this is a blocklist-shaped guard, so stripping quoted\n // prose can only ever block LESS (see BashContext.commandCode).\n private staleContentRead(ctx: BashContext): string | null {\n const scan = new ContentReadScan(this.scanner, ctx.workspaceRoot, ctx.effectiveCwd);\n for (const segment of this.scanner.segmentsWithPipes(ctx.command)) {\n const hit = scan.readsStaleContent(segment);\n if (hit !== null) return hit;\n }\n return null;\n }\n\n // Is `commit` already contained in HEAD? Exit code IS the answer, so spawnSync: 0 = ancestor,\n // 1 = genuinely behind, anything else = git could not tell → fail OPEN. (Mirrors read-stale-guard.)\n private contains(workspaceRoot: string, commit: string): boolean {\n const result = spawnSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], {\n cwd: workspaceRoot,\n encoding: 'utf8',\n });\n if (result.status === 0) return true;\n if (result.status === 1) return false;\n return true;\n }\n\n private isDirty(workspaceRoot: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const out = execSync('git status --porcelain', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n });\n return out.trim().length > 0;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return true; // cannot tell → assume dirty, the fail-OPEN direction here\n }\n }\n\n private staleMessage(workspaceRoot: string): string {\n return new StaleMainMessage(workspaceRoot).forBash(this.behindCount(workspaceRoot));\n }\n\n private behindCount(workspaceRoot: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const out = execSync('git rev-list --count HEAD..origin/main', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n return /^\\d+$/.test(out) ? out : '?';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '?';\n }\n }\n\n private cacheSummary(status: MainSyncStatus): string {\n return `cache=${status.branch} localMain=${status.localMain.slice(0, 8)} originMain=${status.originMain.slice(0, 8)} ts=${status.timestamp}`;\n }\n\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n private block(ctx: BashContext, branch: string, reason: string, message: string, cache: string): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n return [new V(1, this.truncate(ctx.command), message)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('stale-main-bash-guard', 'Bash', ctx.command, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, MATRIX_L2),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stale-main-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/stale-main-bash-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAoD;AAEpD,0DAKiC;AAGjC,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAA8C;AAC9C,0CAAsC;AACtC,4DAA8D;AAC9D,kDAAsF;AACtF,sDAAkD;AAClD,kDAAiD;AACjD,6DAAwD;AACxD,2DAAsD;AACtD,mDAA+C;AAC/C,6DAAwD;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AACH,MAAa,sBAAuB,SAAQ,wBAAsC;IAC9E,YAAY,MAAgC,IAAI,KA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ACvC,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,IAAA,wBAAQ,EAAC,iCAAiC,EAAE;gBAC/C,GAAG,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;aACxE,CAAC,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AAxND,wDAwNC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\n\nimport {\n StaleMainBashGuardConfig,\n DEFAULT_HANG_TIMEOUT_MINUTES,\n readMainSyncStatus,\n MainSyncStatus,\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';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2 } from '../decision-log';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { CommandScanner } from '../command-scan';\nimport { StaleMainMessage } from './stale-main-message';\nimport { ContentReadScan } from './content-read-scan';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitchScan } from './branch-switch-scan';\n\n/**\n * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:\n * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that\n * contains the damage once it is already there.\n *\n * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────\n *\n * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.\n * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this\n * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157\n * commits behind** origin. That checkout did not merely produce stale files — it reverted:\n *\n * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;\n * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy\n * whose message stated the drift BACKWARDS (\"your installed webpieces is older than required\")\n * and named a single cure, `pnpm install`;\n * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match\n * the stale pin, and had to undo it with the `git pull` that should have come first.\n *\n * The shim on current main already diagnoses drift correctly — it distinguishes \"the pin is newer\"\n * from \"the pin is stale, and `pnpm install` would downgrade you\". None of that helped, because the\n * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout\n * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive\n * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.\n *\n * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the\n * checkout, so the only `main` it could measure is the one it is about to leave. The interesting\n * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap\n * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when\n * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.\n *\n * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`\n * appears anywhere in the SAME command.\n * ALLOWED `git checkout main && git pull origin main`, the pairing this forces, which is the\n * exact line the post-merge cleanup flow already prescribes.\n * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,\n * `git checkout -- <file>`, and any other branch.\n *\n * ── REACTIVE: content-reading Bash on a stale `main` ─────────────────────────────────────────────\n *\n * read-stale-guard blocks the Read tool when local `main` is behind origin/main — but it looks at\n * nothing else, deliberately: \"every cure is a Bash command, so Bash is the escape hatch — never\n * wedge it.\" That reasoning is right about the CURE and wrong about `cat`/`grep`/`ls`. In the\n * incident this closes, an agent sat on a `main` 18 commits behind origin/main (108 files, +8069\n * −3692 upstream), had its Read tool blocked exactly as designed, and then spent the whole session\n * `ls`-ing, `grep`-ing and `cat`-ing the same stale tree through the side door — describing a CI\n * workflow set that was missing a 186-line workflow which existed upstream. The logs read\n * \"read-stale-guard handled\", which is worse than no guard: it looks covered.\n *\n * So this guard blocks CONTENT-READING Bash only, never the whole shell. Builds, tests, installs,\n * `git pull`, git METADATA (log/diff/show/status) — all still run. What is blocked is a command that\n * would put stale FILE CONTENT into context: `cat`/`head`/`grep`/`rg`/`sed`/`awk`/`ls`/`find`/… of a\n * path inside this workspace, and `git grep` / `git show <rev>:<path>` against a local rev. The same\n * line merged-branch-bash-guard already draws for State B, scoped tighter because State A's cure is\n * one command away and there is no reason to stop anything else.\n *\n * A piped consumer reads stdin, not the tree: `git log --oneline | grep fix` is allowed, because the\n * bytes came from git metadata, not from a stale file. That is why the scan needs the pipe flag.\n *\n * FAIL-OPEN, with read-stale-guard's own escape valves, so it can never wedge a session:\n * - branch undeterminable / not on `main` / no cache / cache for another branch → allow\n * - `originMain` unknown (offline) → allow\n * - origin/main already an ancestor of HEAD (ancestry, NOT equality) → allow the instant the pull lands\n * - DIRTY tree → allow: the pull is not a clean fast-forward, and resolving that means reading the\n * very files in conflict. Never trap the agent away from its own rescue.\n * - reading `webpieces.config.json` (the mode-OFF escape hatch) and `.webpieces/**` → allow\n */\nexport class StaleMainBashGuardRule extends BashRuleBase<StaleMainBashGuardConfig> {\n constructor(config: StaleMainBashGuardConfig) { super(config, 'stale-main-bash-guard'); }\n\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n private readonly switches = new BranchSwitchScan(this.scanner);\n\n readonly description =\n 'Block a bare `git checkout main` (chain the pull into the same command), and block ' +\n 'content-reading Bash (cat/grep/ls/…) while local main is behind origin/main — so a session ' +\n 'neither lands on a stale main nor reasons over one through the side door the Read block leaves.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'Landing on `main` without pulling, or reading files while main is behind origin/main, both give you stale content.',\n 'Pair the checkout with the pull, or update main and re-run:',\n [\n // TREE-SHAPED, from the one source of tree-shaped cures. A static rule-level hint has no\n // workspace root, so it renders the 'unknown' kind — TreeRecovery's deliberate answer for\n // \"we cannot detect the tree\": both forms, each labelled. That matters here because the\n // primary-clone form (`git checkout main && …`) is BLOCKED by redirect-how-to-merge-main\n // inside a linked worktree, so a preferred option naming it unconditionally hands the AI a\n // cure a sibling guard denies. The per-block message (pairingMessage) is detected and\n // prints exactly one form; this is the fallback for the hint that cannot look.\n new Option(this.recovery.updateMainSteps('unknown').join('\\n')\n + '\\nWhichever form applies, the pull must be in the SAME command as the checkout.', true),\n new Option('Already on main: git pull --ff-only origin main (then re-run). If that fatals with \"Cannot fast-forward to multiple branches\", .git/FETCH_HEAD has a duplicate line — run git fetch --prune origin main first.'),\n new Option('NOT blocked: `git checkout <sha>`, `git checkout -b <x> origin/main`, `git checkout -- <file>`, any other branch. Also still allowed: builds, tests, installs, the pull itself, all git/gh METADATA (status|log|diff|show|branch), every Write/Edit, and reading webpieces.config.json.'),\n new Option('Disable in webpieces.config.json under hookGuards → stale-main-bash-guard (mode OFF) if intentional.'),\n ],\n );\n\n check(ctx: BashContext): readonly Violation[] {\n // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout\n // below: those all ask \"is the main we are ON stale?\", and this asks about the main we are\n // about to MOVE TO — a different branch, and one no cache can describe yet.\n const bare = this.bareCheckoutOfMain(ctx);\n if (bare !== null) {\n return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');\n }\n\n const branch = this.currentBranch(ctx.workspaceRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command.\n triggerMainSyncRefresh(ctx.workspaceRoot, this.config.hangTimeoutMinutes ?? DEFAULT_HANG_TIMEOUT_MINUTES);\n\n // State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.\n if (branch !== 'main') return this.allow(ctx, branch, 'not-on-main (state B is another guard)');\n\n const status = readMainSyncStatus(ctx.workspaceRoot, 'main');\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.cacheSummary(status);\n // BELT-AND-BRACES since the cache became branch-keyed: we asked for the 'main' entry by key, so\n // a mismatch means the map's key and the entry's own `branch` disagree — a shape bug. Kept so\n // that degrades to an allow. Unreachable in normal operation.\n if (status.branch !== 'main') return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // Offline / origin unresolvable — we have nothing to be stale RELATIVE TO.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // Ancestry, not equality: the moment the pull lands (or we are simply ahead), we are current.\n if (this.contains(ctx.workspaceRoot, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n // A dirty tree means the pull is not a clean fast-forward. Do not cut the agent off from the\n // files it must read to resolve that — the same valve read-stale-guard opens.\n if (this.isDirty(ctx.workspaceRoot)) {\n return this.failOpen(ctx, branch, 'dirty-tree-on-main', cache);\n }\n\n const reader = this.staleContentRead(ctx);\n if (reader === null) return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)', cache);\n\n return this.block(ctx, branch, `stale-main content read (${reader})`, this.staleMessage(ctx.workspaceRoot), cache);\n }\n\n /**\n * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same\n * command, or null. The pull is looked for across the WHOLE command, not the matched segment,\n * because `git checkout main && git pull origin main` splits into two segments and the pairing is\n * the point.\n */\n private bareCheckoutOfMain(ctx: BashContext): string | null {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n // BranchSwitchScan answers \"which branch does this land on\" for both guards, flag-tolerantly:\n // `git checkout -q main` lands on main exactly as the bare form does, while\n // `git checkout -b x origin/main` (creates), `git checkout -- main` (pathspec) and\n // `git checkout <sha>` do not. See branch-switch-scan.ts for why that lives in one place.\n if (!this.switches.landsOnExistingMain(segment)) continue;\n return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;\n }\n return null;\n }\n\n private pairingMessage(ctx: BashContext): string {\n const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\\n');\n // Deliberately SHORT. The incident that bought this guard (a main 157 commits behind; the\n // downgrade the reverted shim then prescribed) is maintainer material and lives in the class\n // docblock above — the reader of THIS text needs only what changes what they type.\n return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had — '\n + 'stale files, plus a reverted @webpieces pin and guard shim, so the drift guard then '\n + 'reports the drift BACKWARDS. Chain the pull into the same command:\\n' + steps;\n }\n\n // The first segment that would read stale workspace content, or null when none does. The RAW\n // command is scanned, not commandCode: this is a blocklist-shaped guard, so stripping quoted\n // prose can only ever block LESS (see BashContext.commandCode).\n private staleContentRead(ctx: BashContext): string | null {\n const scan = new ContentReadScan(this.scanner, ctx.workspaceRoot, ctx.effectiveCwd);\n for (const segment of this.scanner.segmentsWithPipes(ctx.command)) {\n const hit = scan.readsStaleContent(segment);\n if (hit !== null) return hit;\n }\n return null;\n }\n\n // Is `commit` already contained in HEAD? Exit code IS the answer, so spawnSync: 0 = ancestor,\n // 1 = genuinely behind, anything else = git could not tell → fail OPEN. (Mirrors read-stale-guard.)\n private contains(workspaceRoot: string, commit: string): boolean {\n const result = spawnSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], {\n cwd: workspaceRoot,\n encoding: 'utf8',\n });\n if (result.status === 0) return true;\n if (result.status === 1) return false;\n return true;\n }\n\n private isDirty(workspaceRoot: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const out = execSync('git status --porcelain', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n });\n return out.trim().length > 0;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return true; // cannot tell → assume dirty, the fail-OPEN direction here\n }\n }\n\n private staleMessage(workspaceRoot: string): string {\n return new StaleMainMessage(workspaceRoot).forBash(this.behindCount(workspaceRoot));\n }\n\n private behindCount(workspaceRoot: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const out = execSync('git rev-list --count HEAD..origin/main', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n return /^\\d+$/.test(out) ? out : '?';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return '?';\n }\n }\n\n private cacheSummary(status: MainSyncStatus): string {\n return `cache=${status.branch} localMain=${status.localMain.slice(0, 8)} originMain=${status.originMain.slice(0, 8)} ts=${status.timestamp}`;\n }\n\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n private block(ctx: BashContext, branch: string, reason: string, message: string, cache: string): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n return [new V(1, this.truncate(ctx.command), message)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('stale-main-bash-guard', 'Bash', ctx.command, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, MATRIX_L2),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
|