@webpieces/ai-hook-rules 0.4.770 → 0.4.771

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.
@@ -1 +1 @@
1
- {"version":3,"file":"main-freshness.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/main-freshness.ts"],"names":[],"mappings":";;;AAAA,iDAA0C;AAI1C;;;;;;;;;;GAUG;AACH,MAAa,aAAa;IACtB;;;;;;;;;;;;;;OAcG;IACH,kBAAkB,CAAC,aAAqB,EAAE,MAAc;QACpD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE;YAC7E,GAAG,EAAE,aAAa;YAClB,QAAQ,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACrC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACtC,OAAO,IAAI,CAAC,CAAC,4DAA4D;IAC7E,CAAC;IAED;;;OAGG;IACH,SAAS,CAAC,MAAsB;QAC5B,MAAM,MAAM,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1G,OAAO,SAAS,MAAM,CAAC,MAAM,cAAc,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,eAAe,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,WAAW,MAAM,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC;IAClK,CAAC;CACJ;AAlCD,sCAkCC","sourcesContent":["import { spawnSync } from 'child_process';\n\nimport { MainSyncStatus } from '@webpieces/rules-config';\n\n/**\n * The two primitives every \"is local `main` stale?\" ladder is built out of: the ANCESTRY test, and the\n * one-line cache summary the decision log records beside the verdict.\n *\n * ONE implementation, because two guards now ask the same question of the same cache —\n * `read-stale-guard` for the Read tool (rows 6/7) and `stale-main-bash-guard` for Bash. The ladders\n * themselves deliberately stay in the guards: each exit's `reason` string is a LITERAL there, which is\n * what `l2-matrix.spec.ts` scrapes to prove every exit maps to a row. What must not be written twice is\n * the predicate — a second copy of the ancestry rule is exactly how the two halves of one row start\n * disagreeing about whether a pull has landed.\n */\nexport class MainFreshness {\n /**\n * Is `commit` an ancestor of (i.e. already contained in) HEAD? Local-only and fast — no network.\n *\n * ANCESTRY, NOT HASH EQUALITY, and this is the single most important line in the freshness story.\n * The cached `originMain` is written by the detached refresher and is arbitrarily old, so\n * `local !== origin` stays true for a while AFTER a successful pull — which would spin the agent\n * forever against a hash nobody can reach. Asking \"does local main already CONTAIN the cached\n * origin/main?\" flips the instant the pull lands, with no refresher round-trip.\n *\n * spawnSync, not execSync, precisely because the EXIT CODE is the answer and three outcomes must be\n * told apart: 0 = ancestor (up to date), 1 = cleanly NOT an ancestor (genuinely behind), anything\n * else = git could not answer (bad/pruned object, not a repo) which must fail OPEN. execSync\n * collapses 1 and \"git broke\" into the same thrown Error, so it cannot make that call. The\n * arg-array form also means the commit hash is never parsed by a shell.\n */\n containsOriginMain(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; // unknown/failed → treat as \"contained\" so the guard allows\n }\n\n /**\n * The async-written cache that drove this decision, as one log field — so a wrong allow/block is\n * traceable to the exact (possibly stale) `main-sync-status.json` that produced it.\n */\n summarize(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} localMain=${status.localMain.slice(0, 8)} originMain=${status.originMain.slice(0, 8)} merged=${merged} ts=${status.timestamp}`;\n }\n}\n"]}
1
+ {"version":3,"file":"main-freshness.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/main-freshness.ts"],"names":[],"mappings":";;;AAAA,iDAA0C;AAI1C;;;;;;;;;;GAUG;AACH,MAAa,aAAa;IACtB,kGAAkG;IAClG,oBAAoB,CAAC,MAAsB,EAAE,gBAAwB;QACjE,MAAM,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;QACpC,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC;YAAE,OAAO,IAAI,CAAC;QAC5E,OAAO,MAAM,IAAI,gBAAgB,CAAC;IACtC,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,kBAAkB,CAAC,aAAqB,EAAE,MAAc;QACpD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE;YAC7E,GAAG,EAAE,aAAa;YAClB,QAAQ,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACrC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACtC,OAAO,IAAI,CAAC,CAAC,4DAA4D;IAC7E,CAAC;IAED;;;OAGG;IACH,SAAS,CAAC,MAAsB;QAC5B,MAAM,MAAM,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1G,MAAM,MAAM,GAAG,MAAM,CAAC,aAAa,KAAK,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;QAClF,OAAO,SAAS,MAAM,CAAC,MAAM,cAAc,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,eAAe,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,WAAW,MAAM,WAAW,MAAM,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC;IACnL,CAAC;CACJ;AA1CD,sCA0CC","sourcesContent":["import { spawnSync } from 'child_process';\n\nimport { MainSyncStatus } from '@webpieces/rules-config';\n\n/**\n * The two primitives every \"is local `main` stale?\" ladder is built out of: the ANCESTRY test, and the\n * one-line cache summary the decision log records beside the verdict.\n *\n * ONE implementation, because two guards now ask the same question of the same cache —\n * `read-stale-guard` for the Read tool (rows 6/7) and `stale-main-bash-guard` for Bash. The ladders\n * themselves deliberately stay in the guards: each exit's `reason` string is a LITERAL there, which is\n * what `l2-matrix.spec.ts` scrapes to prove every exit maps to a row. What must not be written twice is\n * the predicate — a second copy of the ancestry rule is exactly how the two halves of one row start\n * disagreeing about whether a pull has landed.\n */\nexport class MainFreshness {\n /** Null means the async cache predates the count or could not establish it: callers fail open. */\n isWithinAllowedDrift(status: MainSyncStatus, maxCommitsBehind: number): boolean | null {\n const behind = status.commitsBehind;\n if (behind === null || !Number.isInteger(behind) || behind < 0) return null;\n return behind <= maxCommitsBehind;\n }\n\n /**\n * Is `commit` an ancestor of (i.e. already contained in) HEAD? Local-only and fast — no network.\n *\n * ANCESTRY, NOT HASH EQUALITY, and this is the single most important line in the freshness story.\n * The cached `originMain` is written by the detached refresher and is arbitrarily old, so\n * `local !== origin` stays true for a while AFTER a successful pull — which would spin the agent\n * forever against a hash nobody can reach. Asking \"does local main already CONTAIN the cached\n * origin/main?\" flips the instant the pull lands, with no refresher round-trip.\n *\n * spawnSync, not execSync, precisely because the EXIT CODE is the answer and three outcomes must be\n * told apart: 0 = ancestor (up to date), 1 = cleanly NOT an ancestor (genuinely behind), anything\n * else = git could not answer (bad/pruned object, not a repo) which must fail OPEN. execSync\n * collapses 1 and \"git broke\" into the same thrown Error, so it cannot make that call. The\n * arg-array form also means the commit hash is never parsed by a shell.\n */\n containsOriginMain(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; // unknown/failed → treat as \"contained\" so the guard allows\n }\n\n /**\n * The async-written cache that drove this decision, as one log field — so a wrong allow/block is\n * traceable to the exact (possibly stale) `main-sync-status.json` that produced it.\n */\n summarize(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n const behind = status.commitsBehind === null ? '?' : String(status.commitsBehind);\n return `cache=${status.branch} localMain=${status.localMain.slice(0, 8)} originMain=${status.originMain.slice(0, 8)} behind=${behind} merged=${merged} ts=${status.timestamp}`;\n }\n}\n"]}
@@ -5,7 +5,7 @@ import { FixHint } from '../fix-hint';
5
5
  /**
6
6
  * Blocks READS while the checked-out branch is a stale place to read from. TWO states:
7
7
  *
8
- * A. on `main`, and local main is BEHIND origin/main
8
+ * A. on `main`, and local main is farther BEHIND origin/main than the configured tolerance
9
9
  * B. on a feature branch whose PR is ALREADY MERGED (a pre-merge snapshot; origin/main has moved
10
10
  * past it and a squash merge means its HEAD is not even an ancestor of main)
11
11
  *
@@ -38,7 +38,7 @@ import { FixHint } from '../fix-hint';
38
38
  * entirely alone let a session `cat`/`grep`/`ls` the same stale tree the Read block was rejecting,
39
39
  * for a whole session, while the logs read "read-stale-guard handled". stale-main-bash-guard is the
40
40
  * State-A Bash counterpart (as merged-branch-bash-guard is State B's): in the SAME state this guard
41
- * blocks — `main`, KNOWN BEHIND `origin/main` by the ancestry test below — it default-denies Bash and
41
+ * blocks — `main`, KNOWN BEYOND the cached commit-distance tolerance below — it default-denies Bash and
42
42
  * allowlists only the commands that get you out, so the cure is never blocked and this guard can stay
43
43
  * simple and Read-only.
44
44
  *
@@ -66,7 +66,7 @@ import { FixHint } from '../fix-hint';
66
66
  export declare class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardConfig> {
67
67
  constructor(config: BranchStateGuardConfig);
68
68
  private readonly freshness;
69
- readonly description = "Block reads on a branch that is stale to read from \u2014 a `main` behind origin/main, or a feature branch whose PR is already merged.";
69
+ readonly description = "Block reads on a branch that is stale to read from \u2014 a `main` beyond its configured commit-distance tolerance, or a feature branch whose PR is already merged.";
70
70
  readonly files: string[];
71
71
  readonly defaultOptions: {
72
72
  hangTimeoutMinutes: number;
@@ -100,7 +100,6 @@ export declare class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardCon
100
100
  private checkMergedBranch;
101
101
  private mergedMessage;
102
102
  private isConfigFile;
103
- private behindCount;
104
103
  private staleMainMessage;
105
104
  private cacheSummary;
106
105
  /**
@@ -24,7 +24,7 @@ const tree_recovery_1 = require("./tree-recovery");
24
24
  /**
25
25
  * Blocks READS while the checked-out branch is a stale place to read from. TWO states:
26
26
  *
27
- * A. on `main`, and local main is BEHIND origin/main
27
+ * A. on `main`, and local main is farther BEHIND origin/main than the configured tolerance
28
28
  * B. on a feature branch whose PR is ALREADY MERGED (a pre-merge snapshot; origin/main has moved
29
29
  * past it and a squash merge means its HEAD is not even an ancestor of main)
30
30
  *
@@ -57,7 +57,7 @@ const tree_recovery_1 = require("./tree-recovery");
57
57
  * entirely alone let a session `cat`/`grep`/`ls` the same stale tree the Read block was rejecting,
58
58
  * for a whole session, while the logs read "read-stale-guard handled". stale-main-bash-guard is the
59
59
  * State-A Bash counterpart (as merged-branch-bash-guard is State B's): in the SAME state this guard
60
- * blocks — `main`, KNOWN BEHIND `origin/main` by the ancestry test below — it default-denies Bash and
60
+ * blocks — `main`, KNOWN BEYOND the cached commit-distance tolerance below — it default-denies Bash and
61
61
  * allowlists only the commands that get you out, so the cure is never blocked and this guard can stay
62
62
  * simple and Read-only.
63
63
  *
@@ -86,16 +86,16 @@ class ReadStaleGuardRule extends rule_base_1.FileRuleBase {
86
86
  constructor(config) { super(config, 'read-stale-guard', rules_config_1.BRANCH_STATE_GUARD_KEY); }
87
87
  // The ancestry test and the cache summary, shared with stale-main-bash-guard — see main-freshness.ts.
88
88
  freshness = new main_freshness_1.MainFreshness();
89
- description = 'Block reads on a branch that is stale to read from — a `main` behind origin/main, or a feature branch whose PR is already merged.';
89
+ description = 'Block reads on a branch that is stale to read from — a `main` beyond its configured commit-distance tolerance, or a feature branch whose PR is already merged.';
90
90
  files = ['**/*'];
91
91
  defaultOptions = {
92
92
  hangTimeoutMinutes: rules_config_1.DEFAULT_HANG_TIMEOUT_MINUTES,
93
93
  };
94
94
  fixHint = new fix_hint_1.FixHint('This branch is stale to read from — reading it would give you pre-merge/out-of-date content.', 'Get onto current code before reading anything else:', [
95
- new rules_config_1.Option('On main, behind origin/main → pnpm wp-sync-main (CLEAN TREE ONLY), or git checkout -b <new-branch> origin/main which works with UNCOMMITTED CHANGES and brings them along. On an already-merged branch → git fetch origin main && git checkout -b <new-branch> origin/main, which likewise carries your edits. Then retry the read.', true),
95
+ new rules_config_1.Option('On main, beyond branch-state-guard.maxCommitsBehind → pnpm wp-sync-main (CLEAN TREE ONLY), or git checkout -b <new-branch> origin/main which works with UNCOMMITTED CHANGES and brings them along. On an already-merged branch → git fetch origin main && git checkout -b <new-branch> origin/main, which likewise carries your edits. Then retry the read.', true),
96
96
  new rules_config_1.Option('If a checkout -b refuses because origin/main changed the same files you edited: git stash (never blocked), redo the checkout, then git stash pop.'),
97
97
  new rules_config_1.Option("If pnpm wp-sync-main dies with 'fatal: Cannot fast-forward to multiple branches', .git/FETCH_HEAD holds a duplicate line — run 'git fetch --prune origin main' to rewrite it cleanly, then run it again."),
98
- new rules_config_1.Option('Still allowed right now: reading webpieces.config.json, and the Bash commands that get you OUT or tell you where you are — git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs. Everything ELSE through Bash is blocked in this same state (a main that is behind → stale-main-bash-guard; a merged branch → merged-branch-bash-guard), and Write/Edit on main is blocked by feature-branch-guard however current main is. There is no side door: get onto a branch off origin/main.'),
98
+ new rules_config_1.Option('Still allowed right now: reading webpieces.config.json, and the Bash commands that get you OUT or tell you where you are — git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs. Everything ELSE through Bash is blocked in this same state (a main beyond maxCommitsBehind → stale-main-bash-guard; a merged branch → merged-branch-bash-guard), and Write/Edit on main is blocked by feature-branch-guard however current main is. There is no side door: get onto a branch off origin/main.'),
99
99
  new rules_config_1.Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),
100
100
  ]);
101
101
  /**
@@ -154,6 +154,12 @@ class ReadStaleGuardRule extends rule_base_1.FileRuleBase {
154
154
  if (this.freshness.containsOriginMain(judged.root, status.originMain)) {
155
155
  return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);
156
156
  }
157
+ const maxCommitsBehind = this.config.maxCommitsBehind ?? rules_config_1.DEFAULT_MAX_COMMITS_BEHIND;
158
+ const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);
159
+ if (withinThreshold === null)
160
+ return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);
161
+ if (withinThreshold)
162
+ return this.allow(ctx, branch, 'within-max-commits-behind', cache);
157
163
  // NO DIRTY VALVE. It used to fail open here, on the argument that the prescribed in-place pull
158
164
  // is not a clean fast-forward on a dirty tree. That argument was about the MESSAGE, not the row:
159
165
  // row 6's cure cell has always offered `git checkout -b <new> origin/main` as an alternative,
@@ -162,7 +168,7 @@ class ReadStaleGuardRule extends rule_base_1.FileRuleBase {
162
168
  // (StaleMainMessage.forReads), so the cure an agent reads is one it can actually run.
163
169
  // Residual, same as row 8: if origin/main touched the files you edited, git refuses the switch
164
170
  // — `git stash` is on the skip list and clears it. Two steps worst case, never a dead end.
165
- return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(judged), cache);
171
+ return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(judged, status.commitsBehind ?? 0), cache);
166
172
  }
167
173
  /**
168
174
  * State B — a feature branch whose PR is already merged. Reads a PRE-MERGE snapshot, so every
@@ -223,30 +229,13 @@ class ReadStaleGuardRule extends rule_base_1.FileRuleBase {
223
229
  isConfigFile(relativePath) {
224
230
  return relativePath === 'webpieces.config.json';
225
231
  }
226
- // How far behind we are, for the message. Best-effort — a bare "behind" reads fine without it.
227
- behindCount(workspaceRoot) {
228
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
229
- try {
230
- const out = (0, child_process_1.execSync)('git rev-list --count HEAD..origin/main', {
231
- cwd: workspaceRoot,
232
- encoding: 'utf8',
233
- stdio: ['pipe', 'pipe', 'pipe'],
234
- }).trim();
235
- return /^\d+$/.test(out) ? out : '?';
236
- }
237
- catch (err) {
238
- const error = (0, to_error_1.toError)(err);
239
- void error;
240
- return '?';
241
- }
242
- }
243
232
  // StaleMainMessage's remaining consumer. It used to be shared with stale-main-bash-guard so the two
244
233
  // halves of the State-A block could never prescribe different cures; that guard now blocks on the
245
234
  // BRANCH (row 5) rather than on staleness and carries its own message, so this is the only caller.
246
- staleMainMessage(judged) {
235
+ staleMainMessage(judged, commitsBehind) {
247
236
  return [
248
237
  judged.header(),
249
- new stale_main_message_1.StaleMainMessage(judged.root).forReads(this.behindCount(judged.root)),
238
+ new stale_main_message_1.StaleMainMessage(judged.root).forReads(String(commitsBehind)),
250
239
  judged.redirectNote([judged.pnpmCure('wp-sync-main')]),
251
240
  ].join('\n');
252
241
  }
@@ -1 +1 @@
1
- {"version":3,"file":"read-stale-guard.js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,CAAC,CAAC,WAAW,EAAE;gBAAE,OAAO,IAAI,CAAC;YACrD,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;YACxE,MAAM,KAAK,GAAG,4BAA4B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACtD,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,uCAAuC;QAC3E,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;AAnRD,gDAmRC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, MainSyncStatus, Option } from '@webpieces/rules-config';\n\nimport type { FileContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { FileRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { TargetTreeResolver } from '../target-tree';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { StaleMainMessage } from './stale-main-message';\nimport { MainFreshness } from './main-freshness';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Blocks READS while the checked-out branch is a stale place to read from. TWO states:\n *\n * A. on `main`, and local main is BEHIND origin/main\n * B. on a feature branch whose PR is ALREADY MERGED (a pre-merge snapshot; origin/main has moved\n * past it and a squash merge means its HEAD is not even an ancestor of main)\n *\n * WHY READ, of all tools: either state means the AI reads stale FILE CONTENT and then reasons,\n * plans and writes against code that no longer exists upstream. Blocking the write is too late —\n * the bad premise is already in context. So the block lands on the read. (feature-branch-guard\n * blocks the WRITE in state B; this guard is the read-side half of that same protection, and the\n * two share one recovery message via MergedBranchMessage.)\n *\n * THERE IS NO DIRTY-TREE ASYMMETRY, and there is no dirty-tree valve in either state. Both used to\n * fail open on uncommitted work; both now block. The argument for the state-A valve was that its cure,\n * an in-place pull, is not a fast-forward on a dirty tree — true, but that is a fact about the\n * MESSAGE, which printed only the pull. Row 6 has always carried a second cure, `git checkout -b <new>\n * origin/main`, and that one CARRIES uncommitted changes onto the new branch, so the work comes with\n * you and nothing is trapped. StaleMainMessage now prints both, labelled with which survives a dirty\n * tree, so the block no longer has to be suppressed to keep the printed cure runnable. State B's valve\n * never had an argument at all — its cure was always the branch form.\n *\n * Residual, in both states: if `origin/main` changed the same files you edited, git refuses the switch.\n * `git stash` is on the L2 skip list and is never blocked, so the path out is stash → branch → pop.\n *\n * WHY THIS CANNOT WEDGE: the block is scoped to Read ONLY. Every cure — `pnpm wp-sync-main`,\n * `pnpm install`, any webpieces upgrade — is a Bash command, and this guard never looks at Bash.\n * So there is no command allowlist to maintain and no way to lock the agent out of its own fix.\n * (Every `wp-*` bin is on the L2 skip list, and the pull it wraps is explicitly permitted on main by\n * redirect-how-to-merge-main, which returns null when the branch IS main — the guards are\n * complementary, not stacked.)\n *\n * That scoping is also this guard's HOLE, and it is closed elsewhere rather than here: leaving Bash\n * entirely alone let a session `cat`/`grep`/`ls` the same stale tree the Read block was rejecting,\n * for a whole session, while the logs read \"read-stale-guard handled\". stale-main-bash-guard is the\n * State-A Bash counterpart (as merged-branch-bash-guard is State B's): in the SAME state this guard\n * blocks — `main`, KNOWN BEHIND `origin/main` by the ancestry test below — it default-denies Bash and\n * allowlists only the commands that get you out, so the cure is never blocked and this guard can stay\n * simple and Read-only.\n *\n * Everything here is FAIL-OPEN on data we could not ESTABLISH. A guard that blocks reads on bad data\n * is far worse than one that misses; every unknown resolves to \"allow\". Note the dual, which is what\n * the deleted dirty valve violated: never fail open on data you DID establish. A dirty tree is not an\n * unknown — it is a known state with a known cure. The three deliberate escape valves:\n *\n * 1. CACHE LAG — we do NOT compare hashes for equality. The cached `originMain` is written by\n * the detached refresher and is arbitrarily old, so `local !== origin` stays\n * true for a while AFTER a successful pull, which would spin the agent forever.\n * Instead: is the cached origin/main an ANCESTOR of local main? If local main\n * already contains it, we are not behind. That flips the instant the pull lands,\n * with no refresher round-trip. This is the single most important line here.\n * 2. CONFIG READ — webpieces.config.json stays readable so the agent can always read-then-edit\n * it to set `mode: OFF`. Its EDIT is already bypassed in runner.ts + hook-core;\n * this closes the read half of that same escape hatch.\n * 3. NO DATA — no cache, cache for another branch, empty originMain (offline), or no local\n * main at all (fresh clone / worktree) → allow.\n *\n * Runs from the Read fast path in hook-core (Read is neither a file-edit nor a bash payload, so it\n * never reaches the runner's rule loop). Fires the detached refresher on every call, which is also\n * what makes reads keep the shared main-sync cache warm for feature-branch-guard.\n */\nexport class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'read-stale-guard', BRANCH_STATE_GUARD_KEY); }\n\n // The ancestry test and the cache summary, shared with stale-main-bash-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n\n readonly description = 'Block reads on a branch that is stale to read from — a `main` behind origin/main, or a feature branch whose PR is already merged.';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'This branch is stale to read from — reading it would give you pre-merge/out-of-date content.',\n 'Get onto current code before reading anything else:',\n [\n new Option('On main, behind origin/main → pnpm wp-sync-main (CLEAN TREE ONLY), or git checkout -b <new-branch> origin/main which works with UNCOMMITTED CHANGES and brings them along. On an already-merged branch → git fetch origin main && git checkout -b <new-branch> origin/main, which likewise carries your edits. Then retry the read.', true),\n new Option('If a checkout -b refuses because origin/main changed the same files you edited: git stash (never blocked), redo the checkout, then git stash pop.'),\n new Option(\"If pnpm wp-sync-main dies with 'fatal: Cannot fast-forward to multiple branches', .git/FETCH_HEAD holds a duplicate line — run 'git fetch --prune origin main' to rewrite it cleanly, then run it again.\"),\n new Option('Still allowed right now: reading webpieces.config.json, and the Bash commands that get you OUT or tell you where you are — git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs. Everything ELSE through Bash is blocked in this same state (a main that is behind → stale-main-bash-guard; a merged branch → merged-branch-bash-guard), and Write/Edit on main is blocked by feature-branch-guard however current main is. There is no side door: get onto a branch off origin/main.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n /**\n * WHICH TREE is judged — the one that owns the FILE BEING READ, resolved by git through\n * TargetTreeResolver, never by `ctx.workspaceRoot`. Same fix and same reasoning as\n * feature-branch-guard's (issue #851): `ctx.workspaceRoot` is the walk-up from the SESSION's cwd, so\n * a main-session Read of a file inside an agent worktree was judged on the PRIMARY clone's branch —\n * and a `main` that the primary happened to be sitting on would close reads of another tree's\n * feature branch.\n */\n check(ctx: FileContext): readonly Violation[] {\n // Outside the workspace root — no jurisdiction.\n if (ctx.relativePath.startsWith('..')) return [];\n\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A nested clone under `repositories/**` is out of scope, exactly as it is on the bash path.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n // Mid-rebase in the target tree: no branch name, so no key into the branch-keyed cache and\n // nothing to judge. Matrix row 14 — abstain, and say WHY rather than logging a cache miss.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this read. Fired for\n // BOTH states — the merged-branch signal comes out of that same cache. Rooted at the JUDGED\n // tree so the entry refreshed is the one this guard reads.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n // Escape valve 3 — the read half of the config escape hatch. Ahead of BOTH states' blocks so\n // the agent can always read-then-edit the file that turns this guard off.\n if (this.isConfigFile(ctx.relativePath)) return this.allow(ctx, branch, 'webpieces-config-read (escape hatch)');\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n return branch === 'main'\n ? this.checkStaleMain(ctx, judged)\n : this.checkMergedBranch(ctx, judged);\n }\n\n // State A — on main, possibly behind origin/main.\n private checkStaleMain(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, '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, or no local main to compare against.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // Escape valve 2 — ancestry, NOT equality. See the class comment.\n if (this.freshness.containsOriginMain(judged.root, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n // NO DIRTY VALVE. It used to fail open here, on the argument that the prescribed in-place pull\n // is not a clean fast-forward on a dirty tree. That argument was about the MESSAGE, not the row:\n // row 6's cure cell has always offered `git checkout -b <new> origin/main` as an alternative,\n // and THAT works dirty — it carries uncommitted changes onto the new branch and lands you on\n // current code, which is the whole point. The message now leads with it when the tree is dirty\n // (StaleMainMessage.forReads), so the cure an agent reads is one it can actually run.\n // Residual, same as row 8: if origin/main touched the files you edited, git refuses the switch\n // — `git stash` is on the skip list and clears it. Two steps worst case, never a dead end.\n return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(judged), cache);\n }\n\n /**\n * State B — a feature branch whose PR is already merged. Reads a PRE-MERGE snapshot, so every\n * plan built from it is built on code origin/main has moved past.\n *\n * `branchAlreadyMerged` comes straight from the shared cache (the refresher's `gh pr list --state\n * merged`), so this path spawns nothing. No `gh` / offline → `mergedPr` is '' → not merged → allow,\n * which is the fail-open direction for free.\n *\n * NO DIRTY-TREE VALVE. `git checkout -b <new> origin/main` carries uncommitted changes onto the\n * fresh branch, so the work comes with you and there is nothing to rescue by reading. When it does\n * NOT (an overlapping change landed in main, so git refuses the switch), `git stash` is on the L2\n * skip list and is never blocked: stash → branch → pop. The valve that used to sit here was drift\n * from the documented design, not a decision — this docblock described the strict behaviour for\n * releases while the code failed open.\n */\n private checkMergedBranch(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, branch);\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: the entry was looked up BY `branch`, so\n // a mismatch is a shape bug rather than the old \"cache is for another branch\" state. Kept so\n // such a bug degrades to an allow. Unreachable in normal operation. (A branch the refresh has\n // not seen yet is the `status === null` case above — still fail-open.)\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval, or the trail cannot tell a policy\n // that is protecting something from one that is quietly standing down.\n if (!status.branchAlreadyMerged) {\n return status.forgeReachable\n ? this.allow(ctx, branch, 'clean-feature-branch', cache)\n : this.failOpen(ctx, branch, 'no-forge', cache);\n }\n // NO DIRTY VALVE — and this one never had an argument behind it at all. Row 8's cure is\n // `git fetch origin main && git checkout -b <new> origin/main`, which carries uncommitted work\n // with you, so a dirty tree traps nobody. The valve was code drift from the documented design;\n // read-stale-guard's own class comment said so while the code did the opposite.\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n return this.block(\n ctx,\n branch,\n `already-merged PR#${pr}`,\n this.mergedMessage(judged, status.mergedPr),\n cache,\n );\n }\n\n // The merged-branch text, told in the flavour of the tree we are standing in: a linked worktree\n // is told to open a NEW worktree off origin/main and reap this dead one; the primary clone is\n // told to branch off origin/main. Neither is ever told to `git checkout main` (fatal in a\n // worktree). Detection is one statSync — see WorktreeService.isLinkedWorktree.\n private mergedMessage(judged: JudgedTree, mergedPr: string): string {\n const recovery = new TreeRecovery();\n const body = new MergedBranchMessage(judged.root).forReads(\n judged.branch, mergedPr, recovery.kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately — see feature-branch-guard.alreadyMergedMessage for the\n // argument. MergedBranchMessage already aims its commands at the judged root through `atRoot`\n // and prints the WORKTREE flavour of the cure when the judged tree is one.\n return [judged.header(), body].join('\\n');\n }\n\n\n private isConfigFile(relativePath: string): boolean {\n return relativePath === 'webpieces.config.json';\n }\n\n // How far behind we are, for the message. Best-effort — a bare \"behind\" reads fine without it.\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,\n encoding: 'utf8',\n 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 // StaleMainMessage's remaining consumer. It used to be shared with stale-main-bash-guard so the two\n // halves of the State-A block could never prescribe different cures; that guard now blocks on the\n // BRANCH (row 5) rather than on staleness and carries its own message, so this is the only caller.\n private staleMainMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n new StaleMainMessage(judged.root).forReads(this.behindCount(judged.root)),\n judged.redirectNote([judged.pnpmCure('wp-sync-main')]),\n ].join('\\n');\n }\n\n private cacheSummary(status: MainSyncStatus): string {\n return this.freshness.summarize(status);\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: FileContext, 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: FileContext, 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: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('read-stale-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n /**\n * The current branch, WITHOUT spawning git on the common path.\n *\n * This runs on EVERY read, so it is the one call whose cost actually matters. Spawning\n * `git rev-parse --abbrev-ref HEAD` measures ~12ms — essentially all process-spawn overhead —\n * whereas `.git/HEAD` is a single tiny file whose read is microseconds. On a feature branch\n * (the overwhelmingly common case) that file read is the ONLY work this guard does before\n * short-circuiting, so reads stay effectively free.\n *\n * Falls back to spawning git whenever `.git/HEAD` cannot answer authoritatively:\n * - `.git` is a FILE, not a dir → we are in a worktree and HEAD lives elsewhere\n * - detached HEAD → the file holds a raw sha, not a `ref:` line\n * - anything unreadable/unexpected\n * The fallback is correct in all those cases; it is just slower, and they are rare.\n */\n private currentBranch(workspaceRoot: string): string | null {\n const fromHead = this.branchFromGitHead(workspaceRoot);\n if (fromHead !== null) return fromHead;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n 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 // Parse `.git/HEAD` (\"ref: refs/heads/<branch>\"). null = cannot answer, caller must fall back.\n private branchFromGitHead(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const gitPath = path.join(workspaceRoot, '.git');\n // A worktree/submodule has `.git` as a file pointing at the real gitdir — HEAD is not here.\n if (!fs.statSync(gitPath).isDirectory()) return null;\n const head = fs.readFileSync(path.join(gitPath, 'HEAD'), 'utf8').trim();\n const match = /^ref:\\s*refs\\/heads\\/(.+)$/.exec(head);\n return match ? match[1] : null; // no match = detached HEAD → fall back\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"read-stale-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/read-stale-guard.ts"],"names":[],"mappings":";;;;AAAA,iDAAyC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AA4B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACtD,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,uCAAuC;QAC3E,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;AAzQD,gDAyQC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, DEFAULT_MAX_COMMITS_BEHIND, readMainSyncStatus, MainSyncStatus, Option } from '@webpieces/rules-config';\n\nimport type { FileContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { FileRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { TargetTreeResolver } from '../target-tree';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { StaleMainMessage } from './stale-main-message';\nimport { MainFreshness } from './main-freshness';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Blocks READS while the checked-out branch is a stale place to read from. TWO states:\n *\n * A. on `main`, and local main is farther BEHIND origin/main than the configured tolerance\n * B. on a feature branch whose PR is ALREADY MERGED (a pre-merge snapshot; origin/main has moved\n * past it and a squash merge means its HEAD is not even an ancestor of main)\n *\n * WHY READ, of all tools: either state means the AI reads stale FILE CONTENT and then reasons,\n * plans and writes against code that no longer exists upstream. Blocking the write is too late —\n * the bad premise is already in context. So the block lands on the read. (feature-branch-guard\n * blocks the WRITE in state B; this guard is the read-side half of that same protection, and the\n * two share one recovery message via MergedBranchMessage.)\n *\n * THERE IS NO DIRTY-TREE ASYMMETRY, and there is no dirty-tree valve in either state. Both used to\n * fail open on uncommitted work; both now block. The argument for the state-A valve was that its cure,\n * an in-place pull, is not a fast-forward on a dirty tree — true, but that is a fact about the\n * MESSAGE, which printed only the pull. Row 6 has always carried a second cure, `git checkout -b <new>\n * origin/main`, and that one CARRIES uncommitted changes onto the new branch, so the work comes with\n * you and nothing is trapped. StaleMainMessage now prints both, labelled with which survives a dirty\n * tree, so the block no longer has to be suppressed to keep the printed cure runnable. State B's valve\n * never had an argument at all — its cure was always the branch form.\n *\n * Residual, in both states: if `origin/main` changed the same files you edited, git refuses the switch.\n * `git stash` is on the L2 skip list and is never blocked, so the path out is stash → branch → pop.\n *\n * WHY THIS CANNOT WEDGE: the block is scoped to Read ONLY. Every cure — `pnpm wp-sync-main`,\n * `pnpm install`, any webpieces upgrade — is a Bash command, and this guard never looks at Bash.\n * So there is no command allowlist to maintain and no way to lock the agent out of its own fix.\n * (Every `wp-*` bin is on the L2 skip list, and the pull it wraps is explicitly permitted on main by\n * redirect-how-to-merge-main, which returns null when the branch IS main — the guards are\n * complementary, not stacked.)\n *\n * That scoping is also this guard's HOLE, and it is closed elsewhere rather than here: leaving Bash\n * entirely alone let a session `cat`/`grep`/`ls` the same stale tree the Read block was rejecting,\n * for a whole session, while the logs read \"read-stale-guard handled\". stale-main-bash-guard is the\n * State-A Bash counterpart (as merged-branch-bash-guard is State B's): in the SAME state this guard\n * blocks — `main`, KNOWN BEYOND the cached commit-distance tolerance below — it default-denies Bash and\n * allowlists only the commands that get you out, so the cure is never blocked and this guard can stay\n * simple and Read-only.\n *\n * Everything here is FAIL-OPEN on data we could not ESTABLISH. A guard that blocks reads on bad data\n * is far worse than one that misses; every unknown resolves to \"allow\". Note the dual, which is what\n * the deleted dirty valve violated: never fail open on data you DID establish. A dirty tree is not an\n * unknown — it is a known state with a known cure. The three deliberate escape valves:\n *\n * 1. CACHE LAG — we do NOT compare hashes for equality. The cached `originMain` is written by\n * the detached refresher and is arbitrarily old, so `local !== origin` stays\n * true for a while AFTER a successful pull, which would spin the agent forever.\n * Instead: is the cached origin/main an ANCESTOR of local main? If local main\n * already contains it, we are not behind. That flips the instant the pull lands,\n * with no refresher round-trip. This is the single most important line here.\n * 2. CONFIG READ — webpieces.config.json stays readable so the agent can always read-then-edit\n * it to set `mode: OFF`. Its EDIT is already bypassed in runner.ts + hook-core;\n * this closes the read half of that same escape hatch.\n * 3. NO DATA — no cache, cache for another branch, empty originMain (offline), or no local\n * main at all (fresh clone / worktree) → allow.\n *\n * Runs from the Read fast path in hook-core (Read is neither a file-edit nor a bash payload, so it\n * never reaches the runner's rule loop). Fires the detached refresher on every call, which is also\n * what makes reads keep the shared main-sync cache warm for feature-branch-guard.\n */\nexport class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'read-stale-guard', BRANCH_STATE_GUARD_KEY); }\n\n // The ancestry test and the cache summary, shared with stale-main-bash-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n\n readonly description = 'Block reads on a branch that is stale to read from — a `main` beyond its configured commit-distance tolerance, or a feature branch whose PR is already merged.';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'This branch is stale to read from — reading it would give you pre-merge/out-of-date content.',\n 'Get onto current code before reading anything else:',\n [\n new Option('On main, beyond branch-state-guard.maxCommitsBehind → pnpm wp-sync-main (CLEAN TREE ONLY), or git checkout -b <new-branch> origin/main which works with UNCOMMITTED CHANGES and brings them along. On an already-merged branch → git fetch origin main && git checkout -b <new-branch> origin/main, which likewise carries your edits. Then retry the read.', true),\n new Option('If a checkout -b refuses because origin/main changed the same files you edited: git stash (never blocked), redo the checkout, then git stash pop.'),\n new Option(\"If pnpm wp-sync-main dies with 'fatal: Cannot fast-forward to multiple branches', .git/FETCH_HEAD holds a duplicate line — run 'git fetch --prune origin main' to rewrite it cleanly, then run it again.\"),\n new Option('Still allowed right now: reading webpieces.config.json, and the Bash commands that get you OUT or tell you where you are — git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs. Everything ELSE through Bash is blocked in this same state (a main beyond maxCommitsBehind → stale-main-bash-guard; a merged branch → merged-branch-bash-guard), and Write/Edit on main is blocked by feature-branch-guard however current main is. There is no side door: get onto a branch off origin/main.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n /**\n * WHICH TREE is judged — the one that owns the FILE BEING READ, resolved by git through\n * TargetTreeResolver, never by `ctx.workspaceRoot`. Same fix and same reasoning as\n * feature-branch-guard's (issue #851): `ctx.workspaceRoot` is the walk-up from the SESSION's cwd, so\n * a main-session Read of a file inside an agent worktree was judged on the PRIMARY clone's branch —\n * and a `main` that the primary happened to be sitting on would close reads of another tree's\n * feature branch.\n */\n check(ctx: FileContext): readonly Violation[] {\n // Outside the workspace root — no jurisdiction.\n if (ctx.relativePath.startsWith('..')) return [];\n\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A nested clone under `repositories/**` is out of scope, exactly as it is on the bash path.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n // Mid-rebase in the target tree: no branch name, so no key into the branch-keyed cache and\n // nothing to judge. Matrix row 14 — abstain, and say WHY rather than logging a cache miss.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this read. Fired for\n // BOTH states — the merged-branch signal comes out of that same cache. Rooted at the JUDGED\n // tree so the entry refreshed is the one this guard reads.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n // Escape valve 3 — the read half of the config escape hatch. Ahead of BOTH states' blocks so\n // the agent can always read-then-edit the file that turns this guard off.\n if (this.isConfigFile(ctx.relativePath)) return this.allow(ctx, branch, 'webpieces-config-read (escape hatch)');\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n return branch === 'main'\n ? this.checkStaleMain(ctx, judged)\n : this.checkMergedBranch(ctx, judged);\n }\n\n // State A — on main, possibly behind origin/main.\n private checkStaleMain(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, '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, or no local main to compare against.\n if (status.originMain === '') return this.failOpen(ctx, branch, 'origin-main-unknown', cache);\n\n // Escape valve 2 — ancestry, NOT equality. See the class comment.\n if (this.freshness.containsOriginMain(judged.root, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n const maxCommitsBehind = this.config.maxCommitsBehind ?? DEFAULT_MAX_COMMITS_BEHIND;\n const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);\n if (withinThreshold === null) return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);\n if (withinThreshold) return this.allow(ctx, branch, 'within-max-commits-behind', cache);\n\n // NO DIRTY VALVE. It used to fail open here, on the argument that the prescribed in-place pull\n // is not a clean fast-forward on a dirty tree. That argument was about the MESSAGE, not the row:\n // row 6's cure cell has always offered `git checkout -b <new> origin/main` as an alternative,\n // and THAT works dirty — it carries uncommitted changes onto the new branch and lands you on\n // current code, which is the whole point. The message now leads with it when the tree is dirty\n // (StaleMainMessage.forReads), so the cure an agent reads is one it can actually run.\n // Residual, same as row 8: if origin/main touched the files you edited, git refuses the switch\n // — `git stash` is on the skip list and clears it. Two steps worst case, never a dead end.\n return this.block(\n ctx, branch, 'on-stale-main',\n this.staleMainMessage(judged, status.commitsBehind ?? 0), cache);\n }\n\n /**\n * State B — a feature branch whose PR is already merged. Reads a PRE-MERGE snapshot, so every\n * plan built from it is built on code origin/main has moved past.\n *\n * `branchAlreadyMerged` comes straight from the shared cache (the refresher's `gh pr list --state\n * merged`), so this path spawns nothing. No `gh` / offline → `mergedPr` is '' → not merged → allow,\n * which is the fail-open direction for free.\n *\n * NO DIRTY-TREE VALVE. `git checkout -b <new> origin/main` carries uncommitted changes onto the\n * fresh branch, so the work comes with you and there is nothing to rescue by reading. When it does\n * NOT (an overlapping change landed in main, so git refuses the switch), `git stash` is on the L2\n * skip list and is never blocked: stash → branch → pop. The valve that used to sit here was drift\n * from the documented design, not a decision — this docblock described the strict behaviour for\n * releases while the code failed open.\n */\n private checkMergedBranch(ctx: FileContext, judged: JudgedTree): readonly Violation[] {\n const branch = judged.branch;\n const status = readMainSyncStatus(judged.root, branch);\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: the entry was looked up BY `branch`, so\n // a mismatch is a shape bug rather than the old \"cache is for another branch\" state. Kept so\n // such a bug degrades to an allow. Unreachable in normal operation. (A branch the refresh has\n // not seen yet is the `status === null` case above — still fail-open.)\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval, or the trail cannot tell a policy\n // that is protecting something from one that is quietly standing down.\n if (!status.branchAlreadyMerged) {\n return status.forgeReachable\n ? this.allow(ctx, branch, 'clean-feature-branch', cache)\n : this.failOpen(ctx, branch, 'no-forge', cache);\n }\n // NO DIRTY VALVE — and this one never had an argument behind it at all. Row 8's cure is\n // `git fetch origin main && git checkout -b <new> origin/main`, which carries uncommitted work\n // with you, so a dirty tree traps nobody. The valve was code drift from the documented design;\n // read-stale-guard's own class comment said so while the code did the opposite.\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n return this.block(\n ctx,\n branch,\n `already-merged PR#${pr}`,\n this.mergedMessage(judged, status.mergedPr),\n cache,\n );\n }\n\n // The merged-branch text, told in the flavour of the tree we are standing in: a linked worktree\n // is told to open a NEW worktree off origin/main and reap this dead one; the primary clone is\n // told to branch off origin/main. Neither is ever told to `git checkout main` (fatal in a\n // worktree). Detection is one statSync — see WorktreeService.isLinkedWorktree.\n private mergedMessage(judged: JudgedTree, mergedPr: string): string {\n const recovery = new TreeRecovery();\n const body = new MergedBranchMessage(judged.root).forReads(\n judged.branch, mergedPr, recovery.kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately — see feature-branch-guard.alreadyMergedMessage for the\n // argument. MergedBranchMessage already aims its commands at the judged root through `atRoot`\n // and prints the WORKTREE flavour of the cure when the judged tree is one.\n return [judged.header(), body].join('\\n');\n }\n\n\n private isConfigFile(relativePath: string): boolean {\n return relativePath === 'webpieces.config.json';\n }\n\n // StaleMainMessage's remaining consumer. It used to be shared with stale-main-bash-guard so the two\n // halves of the State-A block could never prescribe different cures; that guard now blocks on the\n // BRANCH (row 5) rather than on staleness and carries its own message, so this is the only caller.\n private staleMainMessage(judged: JudgedTree, commitsBehind: number): string {\n return [\n judged.header(),\n new StaleMainMessage(judged.root).forReads(String(commitsBehind)),\n judged.redirectNote([judged.pnpmCure('wp-sync-main')]),\n ].join('\\n');\n }\n\n private cacheSummary(status: MainSyncStatus): string {\n return this.freshness.summarize(status);\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: FileContext, 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: FileContext, 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: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('read-stale-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n /**\n * The current branch, WITHOUT spawning git on the common path.\n *\n * This runs on EVERY read, so it is the one call whose cost actually matters. Spawning\n * `git rev-parse --abbrev-ref HEAD` measures ~12ms — essentially all process-spawn overhead —\n * whereas `.git/HEAD` is a single tiny file whose read is microseconds. On a feature branch\n * (the overwhelmingly common case) that file read is the ONLY work this guard does before\n * short-circuiting, so reads stay effectively free.\n *\n * Falls back to spawning git whenever `.git/HEAD` cannot answer authoritatively:\n * - `.git` is a FILE, not a dir → we are in a worktree and HEAD lives elsewhere\n * - detached HEAD → the file holds a raw sha, not a `ref:` line\n * - anything unreadable/unexpected\n * The fallback is correct in all those cases; it is just slower, and they are rare.\n */\n private currentBranch(workspaceRoot: string): string | null {\n const fromHead = this.branchFromGitHead(workspaceRoot);\n if (fromHead !== null) return fromHead;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n 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 // Parse `.git/HEAD` (\"ref: refs/heads/<branch>\"). null = cannot answer, caller must fall back.\n private branchFromGitHead(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const gitPath = path.join(workspaceRoot, '.git');\n // A worktree/submodule has `.git` as a file pointing at the real gitdir — HEAD is not here.\n if (!fs.statSync(gitPath).isDirectory()) return null;\n const head = fs.readFileSync(path.join(gitPath, 'HEAD'), 'utf8').trim();\n const match = /^ref:\\s*refs\\/heads\\/(.+)$/.exec(head);\n return match ? match[1] : null; // no match = detached HEAD → fall back\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
@@ -43,11 +43,12 @@ import { FixHint } from '../fix-hint';
43
43
  * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,
44
44
  * `git checkout -- <file>`, and any other branch.
45
45
  *
46
- * ── ROWS 6/7: the block fires only once `main` is KNOWN STALE ────────────────────────────────
46
+ * ── ROWS 6/7: the block fires only beyond the configured stale threshold ────────────────────
47
47
  *
48
48
  * The finding is not "you are on `main`" — it is **"what you would read here is out of date"**. So the
49
49
  * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only
50
- * when local `main` is known to be BEHIND `origin/main`. Unknown → allow. Current → allow.
50
+ * when cached `commitsBehind` is greater than `maxCommitsBehind`. Unknown → allow. At or below
51
+ * the threshold → allow. The detached refresher computes the count; this hot path never does.
51
52
  *
52
53
  * WHY, when this guard spent a release judging the branch alone: because the branch alone denies
53
54
  * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly
@@ -82,7 +83,7 @@ import { FixHint } from '../fix-hint';
82
83
  * whose stated purpose is something else and whose effect is to modify tracked files. What changed is
83
84
  * WHEN that polarity applies, not the polarity.
84
85
  *
85
- * BLOCKED on a `main` known to be BEHIND: anything not on the skip list — builds, tests,
86
+ * BLOCKED on a `main` known beyond the configured threshold: anything not on the skip list — builds, tests,
86
87
  * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.
87
88
  * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the
88
89
  * blocked state, everything that gets you OUT or tells you where you are:
@@ -116,7 +117,7 @@ export declare class StaleMainBashGuardRule extends BashRuleBase<BranchStateGuar
116
117
  readonly fixHint: FixHint;
117
118
  check(ctx: BashContext): readonly Violation[];
118
119
  /**
119
- * ROWS 6/7 — block ONLY when local `main` is KNOWN to be behind `origin/main`.
120
+ * ROWS 6/7 — block ONLY when cached `commitsBehind` exceeds `maxCommitsBehind`.
120
121
  *
121
122
  * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and
122
123
  * that is on purpose — the Read and the Bash halves of one state must not disagree about whether
@@ -59,11 +59,12 @@ const cure_prefix_scan_1 = require("./cure-prefix-scan");
59
59
  * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,
60
60
  * `git checkout -- <file>`, and any other branch.
61
61
  *
62
- * ── ROWS 6/7: the block fires only once `main` is KNOWN STALE ────────────────────────────────
62
+ * ── ROWS 6/7: the block fires only beyond the configured stale threshold ────────────────────
63
63
  *
64
64
  * The finding is not "you are on `main`" — it is **"what you would read here is out of date"**. So the
65
65
  * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only
66
- * when local `main` is known to be BEHIND `origin/main`. Unknown → allow. Current → allow.
66
+ * when cached `commitsBehind` is greater than `maxCommitsBehind`. Unknown → allow. At or below
67
+ * the threshold → allow. The detached refresher computes the count; this hot path never does.
67
68
  *
68
69
  * WHY, when this guard spent a release judging the branch alone: because the branch alone denies
69
70
  * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly
@@ -98,7 +99,7 @@ const cure_prefix_scan_1 = require("./cure-prefix-scan");
98
99
  * whose stated purpose is something else and whose effect is to modify tracked files. What changed is
99
100
  * WHEN that polarity applies, not the polarity.
100
101
  *
101
- * BLOCKED on a `main` known to be BEHIND: anything not on the skip list — builds, tests,
102
+ * BLOCKED on a `main` known beyond the configured threshold: anything not on the skip list — builds, tests,
102
103
  * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.
103
104
  * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the
104
105
  * blocked state, everything that gets you OUT or tells you where you are:
@@ -130,7 +131,7 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
130
131
  // ROWS 12/13 — `<cure> && <work>` vs `<cure> ; <work>`. See cure-prefix-scan.ts.
131
132
  curePrefix = new cure_prefix_scan_1.CurePrefixScan(this.scanner);
132
133
  description = 'Block a bare `git checkout main` (use `pnpm wp-sync-main`, or chain the pull into ' +
133
- 'the same command), and — once local main is KNOWN to be behind origin/main — block Bash ' +
134
+ 'the same command), and — once local main is beyond maxCommitsBehind — block Bash ' +
134
135
  'there, allowlisting only the commands that get you off it. A main that is current, or whose ' +
135
136
  'freshness is unknown, is left alone.';
136
137
  defaultOptions = {
@@ -148,7 +149,7 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
148
149
  new rules_config_1.Option(this.recovery.updateMainSteps('unknown').join('\n')
149
150
  + '\nIf you hand-roll the git instead, the pull must be in the SAME command as the checkout.', true),
150
151
  new rules_config_1.Option('Already on main: pnpm wp-sync-main (then re-run) — it pulls main and takes the trash out in the one command this repo prescribes. You may chain your command onto it with && (pnpm wp-sync-main && <your command>), which is skipped if the pull fails; a ; instead runs your command anyway and is refused.'),
151
- new rules_config_1.Option('Still allowed: every BASH command, on a main that is current or whose freshness is not known — this guard only closes once local main is known to be BEHIND origin/main. (Write/Edit on main is a different policy and is blocked by feature-branch-guard however current main is.) In that state you keep the Read tool while main is current (read-stale-guard closes it when main falls behind, because stale reads are worthless) plus everything that gets you OUT or tells you where you are: git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs, and reading webpieces.config.json.'),
152
+ new rules_config_1.Option('Still allowed: every BASH command, on a main at or below branch-state-guard.maxCommitsBehind or whose commit distance is not known. (Write/Edit on main is a different policy and is blocked by feature-branch-guard however current main is.) Beyond that threshold you keep the commands that get you OUT or tell you where you are: git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs, and reading webpieces.config.json.'),
152
153
  new rules_config_1.Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),
153
154
  ]);
154
155
  check(ctx) {
@@ -174,7 +175,7 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
174
175
  return this.checkFreshness(ctx, branch);
175
176
  }
176
177
  /**
177
- * ROWS 6/7 — block ONLY when local `main` is KNOWN to be behind `origin/main`.
178
+ * ROWS 6/7 — block ONLY when cached `commitsBehind` exceeds `maxCommitsBehind`.
178
179
  *
179
180
  * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and
180
181
  * that is on purpose — the Read and the Bash halves of one state must not disagree about whether
@@ -205,8 +206,14 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
205
206
  if (this.freshness.containsOriginMain(ctx.workspaceRoot, status.originMain)) {
206
207
  return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);
207
208
  }
208
- // ESTABLISHED BEHIND. Now — and only now — the default-deny polarity applies.
209
- return this.judgeComposition(ctx, branch, cache);
209
+ const maxCommitsBehind = this.config.maxCommitsBehind ?? rules_config_1.DEFAULT_MAX_COMMITS_BEHIND;
210
+ const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);
211
+ if (withinThreshold === null)
212
+ return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);
213
+ if (withinThreshold)
214
+ return this.allow(ctx, branch, 'within-max-commits-behind', cache);
215
+ // ESTABLISHED BEYOND THE CONFIGURED THRESHOLD. Only now does default-deny apply.
216
+ return this.judgeComposition(ctx, branch, cache, status.commitsBehind ?? 0, maxCommitsBehind);
210
217
  }
211
218
  /**
212
219
  * ROWS 12/13 — `<cure> && <work>` is allowed; `<cure> ; <work>` is not.
@@ -222,7 +229,7 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
222
229
  * recomputes `localMain` against `originMain`, so a pull that failed re-blocks. An allowed `;`
223
230
  * compound never gets that second look.
224
231
  */
225
- judgeComposition(ctx, branch, cache) {
232
+ judgeComposition(ctx, branch, cache, commitsBehind, maxCommitsBehind) {
226
233
  const prefix = this.curePrefix.classify(ctx.command);
227
234
  if (prefix.kind === 'short-circuits') {
228
235
  return this.allow(ctx, branch, 'cure-prefixed, && short-circuits the work', cache);
@@ -230,7 +237,7 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
230
237
  if (prefix.kind === 'runs-anyway') {
231
238
  return this.block(ctx, branch, 'cure-prefixed, work runs anyway', this.compositionMessage(prefix), cache);
232
239
  }
233
- return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(ctx.workspaceRoot), cache);
240
+ return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(ctx.workspaceRoot, commitsBehind, maxCommitsBehind), cache);
234
241
  }
235
242
  /**
236
243
  * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same
@@ -271,8 +278,9 @@ class StaleMainBashGuardRule extends rule_base_1.BashRuleBase {
271
278
  * prints it, because a Read really can be cured by staying put. A Bash session cannot — the next
272
279
  * command is as likely to write as to read.)
273
280
  */
274
- staleMainMessage(workspaceRoot) {
275
- return 'Blocked: local `main` is BEHIND origin/main, so what you would read here is out of '
281
+ staleMainMessage(workspaceRoot, commitsBehind, maxCommitsBehind) {
282
+ return `Blocked: local \`main\` is ${commitsBehind} commits behind origin/main, exceeding `
283
+ + `branch-state-guard.maxCommitsBehind=${maxCommitsBehind}, so what you would read here is out of `
276
284
  + 'date and a plan built on it is built on code upstream has moved past. A CURRENT main is '
277
285
  + 'not blocked — reading main to PLAN is fine, and this fires only once being behind is '
278
286
  + 'established. Bash is default-deny in this state rather than a list of readers, because a '