@webpieces/ai-hook-rules 0.4.540 → 0.4.541

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.4.540",
3
+ "version": "0.4.541",
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",
@@ -32,7 +32,7 @@
32
32
  "directory": "packages/tooling/ai-hook-rules"
33
33
  },
34
34
  "dependencies": {
35
- "@webpieces/rules-config": "0.4.540"
35
+ "@webpieces/rules-config": "0.4.541"
36
36
  },
37
37
  "publishConfig": {
38
38
  "access": "public"
@@ -3,7 +3,44 @@ import type { BashContext, Violation } from '../types';
3
3
  import { BashRuleBase } from '../rule-base';
4
4
  import { FixHint } from '../fix-hint';
5
5
  /**
6
- * The BASH half of the STALE-MAIN protection (read-stale-guard's State A).
6
+ * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:
7
+ * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that
8
+ * contains the damage once it is already there.
9
+ *
10
+ * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────
11
+ *
12
+ * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.
13
+ * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this
14
+ * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157
15
+ * commits behind** origin. That checkout did not merely produce stale files — it reverted:
16
+ *
17
+ * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;
18
+ * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy
19
+ * whose message stated the drift BACKWARDS ("your installed webpieces is older than required")
20
+ * and named a single cure, `pnpm install`;
21
+ * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match
22
+ * the stale pin, and had to undo it with the `git pull` that should have come first.
23
+ *
24
+ * The shim on current main already diagnoses drift correctly — it distinguishes "the pin is newer"
25
+ * from "the pin is stale, and `pnpm install` would downgrade you". None of that helped, because the
26
+ * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout
27
+ * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive
28
+ * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.
29
+ *
30
+ * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the
31
+ * checkout, so the only `main` it could measure is the one it is about to leave. The interesting
32
+ * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap
33
+ * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when
34
+ * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.
35
+ *
36
+ * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`
37
+ * appears anywhere in the SAME command.
38
+ * ALLOWED `git checkout main && git pull origin main`, the pairing this forces, which is the
39
+ * exact line the post-merge cleanup flow already prescribes.
40
+ * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,
41
+ * `git checkout -- <file>`, and any other branch.
42
+ *
43
+ * ── REACTIVE: content-reading Bash on a stale `main` ─────────────────────────────────────────────
7
44
  *
8
45
  * read-stale-guard blocks the Read tool when local `main` is behind origin/main — but it looks at
9
46
  * nothing else, deliberately: "every cure is a Bash command, so Bash is the escape hatch — never
@@ -35,12 +72,27 @@ import { FixHint } from '../fix-hint';
35
72
  export declare class StaleMainBashGuardRule extends BashRuleBase<StaleMainBashGuardConfig> {
36
73
  constructor(config: StaleMainBashGuardConfig);
37
74
  private readonly scanner;
75
+ private readonly recovery;
38
76
  readonly description: string;
39
77
  readonly defaultOptions: {
40
78
  hangTimeoutMinutes: number;
41
79
  };
42
80
  readonly fixHint: FixHint;
43
81
  check(ctx: BashContext): readonly Violation[];
82
+ /**
83
+ * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same
84
+ * command, or null. The pull is looked for across the WHOLE command, not the matched segment,
85
+ * because `git checkout main && git pull origin main` splits into two segments and the pairing is
86
+ * the point.
87
+ */
88
+ 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
+ private pairingMessage;
44
96
  private staleContentRead;
45
97
  private contains;
46
98
  private isDirty;
@@ -12,8 +12,46 @@ const decision_log_1 = require("../decision-log");
12
12
  const command_scan_1 = require("../command-scan");
13
13
  const stale_main_message_1 = require("./stale-main-message");
14
14
  const content_read_scan_1 = require("./content-read-scan");
15
+ const tree_recovery_1 = require("./tree-recovery");
15
16
  /**
16
- * The BASH half of the STALE-MAIN protection (read-stale-guard's State A).
17
+ * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:
18
+ * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that
19
+ * contains the damage once it is already there.
20
+ *
21
+ * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────
22
+ *
23
+ * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.
24
+ * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this
25
+ * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157
26
+ * commits behind** origin. That checkout did not merely produce stale files — it reverted:
27
+ *
28
+ * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;
29
+ * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy
30
+ * whose message stated the drift BACKWARDS ("your installed webpieces is older than required")
31
+ * and named a single cure, `pnpm install`;
32
+ * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match
33
+ * the stale pin, and had to undo it with the `git pull` that should have come first.
34
+ *
35
+ * The shim on current main already diagnoses drift correctly — it distinguishes "the pin is newer"
36
+ * from "the pin is stale, and `pnpm install` would downgrade you". None of that helped, because the
37
+ * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout
38
+ * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive
39
+ * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.
40
+ *
41
+ * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the
42
+ * checkout, so the only `main` it could measure is the one it is about to leave. The interesting
43
+ * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap
44
+ * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when
45
+ * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.
46
+ *
47
+ * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`
48
+ * appears anywhere in the SAME command.
49
+ * ALLOWED `git checkout main && git pull origin main`, the pairing this forces, which is the
50
+ * exact line the post-merge cleanup flow already prescribes.
51
+ * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,
52
+ * `git checkout -- <file>`, and any other branch.
53
+ *
54
+ * ── REACTIVE: content-reading Bash on a stale `main` ─────────────────────────────────────────────
17
55
  *
18
56
  * read-stale-guard blocks the Read tool when local `main` is behind origin/main — but it looks at
19
57
  * nothing else, deliberately: "every cure is a Bash command, so Bash is the escape hatch — never
@@ -45,17 +83,28 @@ const content_read_scan_1 = require("./content-read-scan");
45
83
  class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
46
84
  constructor(config) { super(config, 'stale-main-bash-guard'); }
47
85
  scanner = new command_scan_1.CommandScanner();
48
- description = 'Block content-reading Bash (cat/grep/ls/…) while local main is behind origin/main, so a ' +
49
- 'session cannot reason over a stale tree through the side door the Read-tool block leaves open.';
86
+ recovery = new tree_recovery_1.TreeRecovery();
87
+ description = 'Block a bare `git checkout main` (chain the pull into the same command), and block ' +
88
+ 'content-reading Bash (cat/grep/ls/…) while local main is behind origin/main — so a session ' +
89
+ 'neither lands on a stale main nor reasons over one through the side door the Read block leaves.';
50
90
  defaultOptions = {
51
91
  hangTimeoutMinutes: rules_config_1.DEFAULT_HANG_TIMEOUT_MINUTES,
52
92
  };
53
- fixHint = new fix_hint_1.FixHint('You are on main and main is behind origin/main reading files here gives you stale content.', 'Update main first, then re-run your command:', [
54
- new fix_hint_1.Option('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.', true),
55
- new fix_hint_1.Option('Still allowed right now: builds, tests, installs, the pull itself, all git/gh METADATA (status|log|diff|show|branch), every Write/Edit, and reading webpieces.config.json.'),
93
+ 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:', [
94
+ new fix_hint_1.Option('git checkout main && git pull origin main (the pull must be in the SAME command).', true),
95
+ 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.'),
96
+ 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'),
97
+ 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.'),
56
98
  new fix_hint_1.Option('Disable in webpieces.config.json under hookGuards → stale-main-bash-guard (mode OFF) if intentional.'),
57
99
  ]);
58
100
  check(ctx) {
101
+ // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout
102
+ // below: those all ask "is the main we are ON stale?", and this asks about the main we are
103
+ // about to MOVE TO — a different branch, and one no cache can describe yet.
104
+ const bare = this.bareCheckoutOfMain(ctx);
105
+ if (bare !== null) {
106
+ return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');
107
+ }
59
108
  const branch = this.currentBranch(ctx.workspaceRoot);
60
109
  if (branch === null)
61
110
  return this.allow(ctx, branch, 'branch-undeterminable (fail-open)');
@@ -87,6 +136,49 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
87
136
  return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)', cache);
88
137
  return this.block(ctx, branch, `stale-main content read (${reader})`, this.staleMessage(ctx.workspaceRoot), cache);
89
138
  }
139
+ /**
140
+ * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same
141
+ * command, or null. The pull is looked for across the WHOLE command, not the matched segment,
142
+ * because `git checkout main && git pull origin main` splits into two segments and the pairing is
143
+ * the point.
144
+ */
145
+ bareCheckoutOfMain(ctx) {
146
+ for (const segment of this.scanner.commandSegments(ctx.command)) {
147
+ if (!this.scanner.invokesGit(segment, 'checkout') && !this.scanner.invokesGit(segment, 'switch'))
148
+ continue;
149
+ if (!this.switchesToMainBranch(segment))
150
+ continue;
151
+ return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;
152
+ }
153
+ return null;
154
+ }
155
+ /**
156
+ * True only for landing ON the branch. `-b`/`-B`/`-c`/`-C` CREATE a branch, so
157
+ * `git checkout -b x origin/main` is current by construction and never blocked; a `--` turns the
158
+ * rest into pathspecs, so `git checkout -- main` restores a FILE named main and moves no branch.
159
+ */
160
+ switchesToMainBranch(segment) {
161
+ const words = this.scanner.words(segment);
162
+ for (let i = 0; i < words.length; i++) {
163
+ const word = words[i];
164
+ if (word === '--')
165
+ return false;
166
+ if (/^-[bBcC]$/.test(word))
167
+ return false;
168
+ if (i > 1 && word === 'main')
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+ pairingMessage(ctx) {
174
+ const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\n');
175
+ return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had. '
176
+ + 'That is not only stale FILES — it also reverts `package.json`\'s @webpieces pin and the '
177
+ + 'guard shim under `.claude/webpieces/`, so the very hook that would diagnose the resulting '
178
+ + 'version drift is replaced by an older copy that reports it BACKWARDS and names the cure '
179
+ + 'that makes it worse. Chain the pull into the same command, leaving no window in which you '
180
+ + 'are on a stale main:\n' + steps;
181
+ }
90
182
  // The first segment that would read stale workspace content, or null when none does. The RAW
91
183
  // command is scanned, not commandCode: this is a blocklist-shaped guard, so stripping quoted
92
184
  // prose can only ever block LESS (see BashContext.commandCode).
@@ -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,kDAAkE;AAClE,kDAAiD;AACjD,6DAAwD;AACxD,2DAAsD;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAa,sBAAuB,SAAQ,wBAAsC;IAC9E,YAAY,MAAgC,IAAI,KAAK,CAAC,MAAM,EAAE,uBAAuB,CAAC,CAAC,CAAC,CAAC;IAExE,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC;IAEvC,WAAW,GAChB,0FAA0F;QAC1F,gGAAgG,CAAC;IACnF,cAAc,GAAG;QAC/B,kBAAkB,EAAE,2CAA4B;KACnD,CAAC;IACO,OAAO,GAAG,IAAI,kBAAO,CAC1B,8FAA8F,EAC9F,8CAA8C,EAC9C;QACI,IAAI,iBAAM,CAAC,+LAA+L,EAAE,IAAI,CAAC;QACjN,IAAI,iBAAM,CAAC,4KAA4K,CAAC;QACxL,IAAI,iBAAM,CAAC,sGAAsG,CAAC;K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,OAA0B,EAAE,MAAc,EAAE,KAAa;QAClH,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,CAAC,CAC/G,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;AAtJD,wDAsJC","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 } from '../decision-log';\nimport { CommandScanner } from '../command-scan';\nimport { StaleMainMessage } from './stale-main-message';\nimport { ContentReadScan } from './content-read-scan';\n\n/**\n * The BASH half of the STALE-MAIN protection (read-stale-guard's State A).\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\n readonly description =\n 'Block content-reading Bash (cat/grep/ls/…) while local main is behind origin/main, so a ' +\n 'session cannot reason over a stale tree through the side door the Read-tool block leaves open.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are on main and main is behind origin/main — reading files here gives you stale content.',\n 'Update main first, then re-run your command:',\n [\n new Option('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.', true),\n new Option('Still allowed right now: 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 const branch = this.currentBranch(ctx.workspaceRoot);\n if (branch === null) return this.allow(ctx, branch, 'branch-undeterminable (fail-open)');\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);\n if (status === null) return this.allow(ctx, branch, 'no-sync-cache (fail-open)', 'cache=none');\n\n const cache = this.cacheSummary(status);\n if (status.branch !== 'main') return this.allow(ctx, branch, 'stale-cross-branch-cache (fail-open)', cache);\n // Offline / origin unresolvable — we have nothing to be stale RELATIVE TO.\n if (status.originMain === '') return this.allow(ctx, branch, 'origin-main-unknown (fail-open)', 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.allow(ctx, branch, 'dirty-tree-on-main (fail-open)', 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 // 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 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', 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: 'ALLOW' | 'BLOCK', 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),\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,kDAAkE;AAClE,kDAAiD;AACjD,6DAAwD;AACxD,2DAAsD;AACtD,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AACH,MAAa,sBAAuB,SAAQ,wBAAsC;IAC9E,YAAY,MA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AM,IAAI,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAC/G,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;AA3MD,wDA2MC","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 } from '../decision-log';\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.allow(ctx, branch, 'branch-undeterminable (fail-open)');\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);\n if (status === null) return this.allow(ctx, branch, 'no-sync-cache (fail-open)', 'cache=none');\n\n const cache = this.cacheSummary(status);\n if (status.branch !== 'main') return this.allow(ctx, branch, 'stale-cross-branch-cache (fail-open)', cache);\n // Offline / origin unresolvable — we have nothing to be stale RELATIVE TO.\n if (status.originMain === '') return this.allow(ctx, branch, 'origin-main-unknown (fail-open)', 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.allow(ctx, branch, 'dirty-tree-on-main (fail-open)', 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 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', 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: 'ALLOW' | 'BLOCK', 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),\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"]}