@webpieces/agent-workflow-rules 0.4.971 → 0.4.973

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":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAmE;AACnE,mDAA2D;AAE3D,sEAAsI;AAGtI,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAa,sBAAuB,SAAQ,2BAAoC;IAC5E,wFAAwF;IACxF,mGAAmG;IACnG,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,sBAAsB,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAErG,WAAW,GAAG,kHAAkH,CAAC;IACxH,KAAK,GAAG,CAAC,MAAM,CAAC,CAAC;IACjB,cAAc,GAAG;QAC/B,sBAAsB,EAAE,wBAAwB;QAChD,kBAAkB,EAAE,iDAA4B;KACnD,CAAC;IACO,OAAO,GAAG,IAAI,sBAAO,CAC1B,oDAAoD,EACpD,2EAA2E,EAC3E;QACI,IAAI,qBAAM,CAAC,4EAA4E,EAAE,IAAI,CAAC;QAC9F,IAAI,qBAAM,CAAC,mWAAmW,CAAC;QAC/W,IAAI,qBAAM,CAAC,kLAAkL,CAAC;KACjM,CACJ,CAAC;IAEF,KAAK,CAAC,GAAgB;QAClB,2FAA2F;QAC3F,IAAI,GAAG,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC;YAAE,OAAO,EAAE,C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IAAA,wCAAmB,EAAC,MAAM,CAAC,MAAM,CAAC;YACrC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;SAC5D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACJ;AA/PD,wDA+PC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { SyncFlowGuidance, Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig } from \"../../configs/main-sync-guard-configs\";\nimport { DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * States 2–4 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\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 check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\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 // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\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 // Reached only when the branch is NOT merged, HAS a fork point and does NOT conflict. The\n // last two are pure git; only the first depends on the forge, which is why an unreachable\n // forge downgrades this to an abstention rather than leaving it a clean approval.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\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('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n\n /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
1
+ {"version":3,"file":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAmE;AACnE,mDAA2D;AAE3D,sEAAsJ;AAGtJ,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAa,sBAAuB,SAAQ,2BAAoC;IAC5E,wFAAwF;IACxF,mGAAmG;IACnG,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,sBAAsB,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAC7F,QAAQ,GAAG,IAAI,mCAAc,EAAE,CAAC;IAExC,WAAW,GAAG,kHAAkH,CAAC;IACxH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C,iCAAiC;SAC5E,CAAC,CAAC;QACH,6FAA6F;QAC7F,2FAA2F;QAC3F,2DAA2D;QAC3D,MAAM,QAAQ,GAAG,IAAI,+BAAgB,EAAE,CAAC;QACxC,+FAA+F;QAC/F,0EAA0E;QAC1E,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YAChB,OAAO,MAAM;iBACR,MAAM,CAAC;gBACJ,gBAAgB,MAAM,iEAAiE;gBACvF,gEAAgE;gBAChE,EAAE;aACL,CAAC;iBACD,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;iBACzB,MAAM,CAAC,CAAC,EAAE,EAAE,GAAG,QAAQ,CAAC,gBAAgB,EAAE,CAAC,CAAC;iBAC5C,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;iBAClB,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,MAAM;aACR,MAAM,CAAC;YACJ,yFAAyF;YACzF,kEAAkE;YAClE,EAAE;SACL,CAAC;aACD,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;aACxB,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;aAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IAEO,kBAAkB,CAAC,MAAkB;QACzC,OAAO;YACH,MAAM,CAAC,MAAM,EAAE;YACf,qFAAqF;YACrF,sFAAsF;YACtF,EAAE;YACF,GAAG,IAAA,wCAAmB,EAAC,MAAM,CAAC,MAAM,CAAC;YACrC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;SAC5D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACJ;AAxQD,wDAwQC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { SyncFlowGuidance, Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig } from \"../../configs/main-sync-guard-configs\";\nimport { BranchIdentity, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * States 2–4 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n private readonly branches = new BranchIdentity();\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\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 check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\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 // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n if (this.branches.isHotfix(branch)) return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)', this.treeSummary(judgedRoot)); // L2 row 14 (#1371): every state below cures BY main\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\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 // Reached only when the branch is NOT merged, HAS a fork point and does NOT conflict. The\n // last two are pure git; only the first depends on the forge, which is why an unreachable\n // forge downgrades this to an abstention rather than leaving it a clean approval.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\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 /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */\n private exempt(ctx: FileContext, branch: string, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_EXEMPT', 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('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n\n /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
@@ -35,6 +35,7 @@ export declare class MergedBranchBashGuardRule extends BashRuleBase<BranchStateG
35
35
  constructor(config: BranchStateGuardConfig);
36
36
  private readonly scanner;
37
37
  private readonly recoveryList;
38
+ private readonly branches;
38
39
  readonly description: string;
39
40
  readonly defaultOptions: {
40
41
  hangTimeoutMinutes: number;
@@ -55,6 +56,8 @@ export declare class MergedBranchBashGuardRule extends BashRuleBase<BranchStateG
55
56
  */
56
57
  private failOpen;
57
58
  private allow;
59
+ /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */
60
+ private exempt;
58
61
  private block;
59
62
  private truncate;
60
63
  private logDecision;
@@ -52,6 +52,7 @@ class MergedBranchBashGuardRule extends hook_runtime_2.BashRuleBase {
52
52
  // ROW 4, the skip list — shared with stale-main-bash-guard so the two states cannot drift apart
53
53
  // about what "gets you out" means. See recovery-allowlist.ts.
54
54
  recoveryList = new recovery_allowlist_1.RecoveryAllowlist(this.scanner);
55
+ branches = new repo_workflow_core_1.BranchIdentity();
55
56
  description = 'Block ordinary Bash on an already-merged branch (allowlisting only recovery/cleanup and ' +
56
57
  'read-only inspection commands), so a session cannot proceed on a stale post-merge branch.';
57
58
  defaultOptions = {
@@ -67,6 +68,10 @@ class MergedBranchBashGuardRule extends hook_runtime_2.BashRuleBase {
67
68
  // Can't determine the branch (not a git repo, git unavailable) → never block. Fail-open.
68
69
  if (branch === null)
69
70
  return this.failOpen(ctx, branch, 'branch-undeterminable');
71
+ // A `/hotfix/` branch never takes main (issue #1371): its only cure here — branch off origin/main —
72
+ // would ship unpromoted main to production. L2 row 14: exempt.
73
+ if (this.branches.isHotfix(branch))
74
+ return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)');
70
75
  // Keep the shared cache warm for the next call. Detached; never blocks this command. (The
71
76
  // runner also warms it, but only when feature-branch-guard is loaded — do it here too so this
72
77
  // guard is self-sufficient when that one is off.)
@@ -130,6 +135,11 @@ class MergedBranchBashGuardRule extends hook_runtime_2.BashRuleBase {
130
135
  this.logDecision(ctx, branch, 'ALLOW', reason, cache);
131
136
  return [];
132
137
  }
138
+ /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */
139
+ exempt(ctx, branch, reason) {
140
+ this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, '-');
141
+ return [];
142
+ }
133
143
  block(ctx, branch, reason, message, cache = '-') {
134
144
  this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);
135
145
  // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.
@@ -1 +1 @@
1
- {"version":3,"file":"merged-branch-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/merged-branch-bash-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAE3D,sEAAiH;AAGjH,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAAyD;AACzD,mEAA8D;AAC9D,mDAA+C;AAC/C,6DAAyD;AAEzD;;;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,MAAM,OAAO,GAAG,IAAA,wCAAwB,EAAC,IAAA,yCAAyB,EAAC,GAAG,CAAC,aAAa,CAAC,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC;QAChH,OAAO,CAAC,IAAI,wBAAC,CAAC,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC;IACrE,CAAC;IAEO,QAAQ,CAAC,CAAS;QACtB,MAAM,GAAG,GAAG,GAAG,CAAC;QAChB,OAAO,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;IACvD,CAAC;IAEO,WAAW,CAAC,GAAgB,EAAE,MAAqB,EAAE,OAAgB,EAAE,MAAc,EAAE,KAAa;QACxG,IAAA,+BAAgB,EACZ,GAAG,CAAC,aAAa,EACjB,IAAI,4BAAa,CAAC,0BAA0B,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,4BAAa,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,CACtJ,CAAC;IACN,CAAC;IAEO,aAAa,CAAC,aAAqB;QACvC,OAAO,4BAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;CACJ;AA5HD,8DA4HC;AAED,sGAAsG;AACtG,qGAAqG;AACrG,uGAAuG;AACvG,kGAAkG;AAClG,kGAAkG;AAClG,sGAAsG;AACtG,uGAAuG","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig } from \"../../configs/main-sync-guard-configs\";\nimport { DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { TreeRecovery } from './tree-recovery';\nimport { RecoveryAllowlist } from './recovery-allowlist';\n\n/**\n * The BASH half of the merged-branch protection — the gap that let a whole session run on an\n * already-merged branch.\n *\n * feature-branch-guard blocks Write/Edit and read-stale-guard blocks the Read tool when the\n * checked-out branch's PR is already merged into main, but BOTH are file-scoped: a `runBash()` command\n * never reaches either. So an agent that only ran shell — `scripts/local.sh start lang` (boots\n * servers), `cat`/`ls` of repo files, git — sailed through, even though the very same\n * `branchAlreadyMerged` flag was loaded and logged on the Bash path (the `calls/` stream →\n * `merged=PR#…`). It was computed and thrown away; nothing consulted it for a block.\n *\n * Those two file guards intentionally leave Bash alone (\"every cure is a Bash command, so Bash is the\n * escape hatch — never wedge it\"). This guard therefore DEFAULT-DENIES Bash on a merged branch but\n * allowlists exactly the commands that get you OFF the branch (the fresh-start / cleanup git commands,\n * switching away, read-only orientation, wp-* cleanup, installs). The redirect it returns names those\n * same commands, so following it can never re-trip the guard — the agent is redirected, not wedged.\n *\n * FAIL-OPEN like its siblings: branch undeterminable, no cache yet, or a cache for a DIFFERENT branch\n * → allow. The cache is per-branch (`status.branch` is the branch it was computed FOR), so acting on\n * another branch's snapshot is never allowed.\n *\n * On the DELIBERATELY-UNFIXED staleness window: the cache is only as fresh as the last detached\n * refresh, so for a few seconds after a merge lands mid-session it can still read `merged=NO` and this\n * guard fails open. That window is tiny and self-closing — agents burst tool calls every few seconds\n * and every Bash call re-triggers the refresh, so `branchAlreadyMerged` flips within 1–3 calls and the\n * next command is caught. Closing it synchronously would require the slow `gh pr list` on the blocking\n * path (the thing the whole cache design avoids) and would mean blocking on stale/uncertain data,\n * which violates the fail-open principle every one of these guards is built on. Not worth it.\n */\nexport class MergedBranchBashGuardRule extends BashRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'merged-branch-bash-guard', BRANCH_STATE_GUARD_KEY); }\n\n private readonly scanner = new CommandScanner();\n // ROW 4, the skip list — shared with stale-main-bash-guard so the two states cannot drift apart\n // about what \"gets you out\" means. See recovery-allowlist.ts.\n private readonly recoveryList = new RecoveryAllowlist(this.scanner);\n\n readonly description =\n 'Block ordinary Bash on an already-merged branch (allowlisting only recovery/cleanup and ' +\n 'read-only inspection commands), so a session cannot proceed on a stale post-merge branch.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'This branch is already merged into main — do not keep working here.',\n 'Get onto a fresh branch off origin/main, then retry:',\n [\n new Option('git fetch origin main && git checkout -b <new-branch> origin/main (in a worktree: git worktree add ../<dir> -b <new> origin/main). Then re-run your command.', true),\n new Option('Still allowed here: recovery/cleanup git, read-only git status|log|diff|show|branch, gh GENERALLY (it talks to GitHub, not to this tree — but not gh repo clone / pr checkout / run download, which write local files), curl/wget without -o/-O or a > redirect, switching branches/worktrees, pnpm wp-sync-main and pnpm wp-cleanup, and installs/upgrades.'),\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 check(ctx: BashContext): readonly Violation[] {\n const branch = this.currentBranch(ctx.workspaceRoot);\n // Can't determine the branch (not a git repo, git unavailable) → never block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command. (The\n // runner also warms it, but only when feature-branch-guard is loaded — do it here too so this\n // guard is self-sufficient when that one is off.)\n triggerMainSyncRefresh(ctx.workspaceRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(ctx.workspaceRoot, branch);\n // No cache yet (first command of the session), or a branch this refresh has not seen → allow;\n // the refresh we just spawned populates it.\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.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\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 // For THIS guard the merged flag is the ONLY block condition, so an unreachable forge means\n // it is fully abstaining — the state it exists to catch cannot be observed at all.\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\n // Merged. Allow ONLY when every segment of the command is a recovery / cleanup / read-only\n // inspection command — anything else (servers, builds, tests, cat/ls of repo files, git writes)\n // is denied with the redirect.\n if (this.recoveryList.isFullyRecovery(ctx)) {\n return this.allow(ctx, branch, 'merged-branch recovery/inspection (allowlisted)', cache);\n }\n\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n return this.block(ctx, branch, `already-merged PR#${pr}`, this.mergedMessage(ctx.workspaceRoot, branch, status.mergedPr), cache);\n }\n\n private mergedMessage(workspaceRoot: string, branch: string, mergedPr: string): string {\n return new MergedBranchMessage(workspaceRoot).forBash(\n branch, mergedPr, new TreeRecovery().kindOf(workspaceRoot), workspaceRoot,\n );\n }\n\n // One-line summary of the async-written cache that drove this decision (mirrors the file guards),\n // so a wrong allow/block is traceable to the exact main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n private block(ctx: BashContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // 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, this.truncate(ctx.command), message + pointer)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('merged-branch-bash-guard', 'Bash', ctx.command, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n\n// git subcommands that are recovery/cleanup OR read-only orientation, and so stay allowed on a merged\n// branch. Everything NOT here (commit, merge, rebase, push, reset, add, restore, clean, cherry-pick,\n// …) is a \"keep working\" operation and is denied with the redirect. `worktree` covers add/remove/prune\n// (branch-creation-guard governs which worktree adds are legal); `branch` covers listing and `-D`\n// cleanup (branch-creation-guard governs creation); `pull` is the on-main update, itself gated by\n// redirect-how-to-merge-main. Reading git METADATA (log/diff/show) is fine — it is not the stale FILE\n// CONTENT that `cat` would surface, which is exactly why `git grep` (reads tracked content) is absent.\n"]}
1
+ {"version":3,"file":"merged-branch-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/merged-branch-bash-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAE3D,sEAAiI;AAGjI,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAAyD;AACzD,mEAA8D;AAC9D,mDAA+C;AAC/C,6DAAyD;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,yBAA0B,SAAQ,2BAAoC;IAC/E,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,0BAA0B,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAEjG,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC;IAChD,gGAAgG;IAChG,8DAA8D;IAC7C,YAAY,GAAG,IAAI,sCAAiB,CAAC,IAAI,CAAC,OAAO,CA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ieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig } from \"../../configs/main-sync-guard-configs\";\nimport { BranchIdentity, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { TreeRecovery } from './tree-recovery';\nimport { RecoveryAllowlist } from './recovery-allowlist';\n\n/**\n * The BASH half of the merged-branch protection — the gap that let a whole session run on an\n * already-merged branch.\n *\n * feature-branch-guard blocks Write/Edit and read-stale-guard blocks the Read tool when the\n * checked-out branch's PR is already merged into main, but BOTH are file-scoped: a `runBash()` command\n * never reaches either. So an agent that only ran shell — `scripts/local.sh start lang` (boots\n * servers), `cat`/`ls` of repo files, git — sailed through, even though the very same\n * `branchAlreadyMerged` flag was loaded and logged on the Bash path (the `calls/` stream →\n * `merged=PR#…`). It was computed and thrown away; nothing consulted it for a block.\n *\n * Those two file guards intentionally leave Bash alone (\"every cure is a Bash command, so Bash is the\n * escape hatch — never wedge it\"). This guard therefore DEFAULT-DENIES Bash on a merged branch but\n * allowlists exactly the commands that get you OFF the branch (the fresh-start / cleanup git commands,\n * switching away, read-only orientation, wp-* cleanup, installs). The redirect it returns names those\n * same commands, so following it can never re-trip the guard — the agent is redirected, not wedged.\n *\n * FAIL-OPEN like its siblings: branch undeterminable, no cache yet, or a cache for a DIFFERENT branch\n * → allow. The cache is per-branch (`status.branch` is the branch it was computed FOR), so acting on\n * another branch's snapshot is never allowed.\n *\n * On the DELIBERATELY-UNFIXED staleness window: the cache is only as fresh as the last detached\n * refresh, so for a few seconds after a merge lands mid-session it can still read `merged=NO` and this\n * guard fails open. That window is tiny and self-closing — agents burst tool calls every few seconds\n * and every Bash call re-triggers the refresh, so `branchAlreadyMerged` flips within 1–3 calls and the\n * next command is caught. Closing it synchronously would require the slow `gh pr list` on the blocking\n * path (the thing the whole cache design avoids) and would mean blocking on stale/uncertain data,\n * which violates the fail-open principle every one of these guards is built on. Not worth it.\n */\nexport class MergedBranchBashGuardRule extends BashRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'merged-branch-bash-guard', BRANCH_STATE_GUARD_KEY); }\n\n private readonly scanner = new CommandScanner();\n // ROW 4, the skip list — shared with stale-main-bash-guard so the two states cannot drift apart\n // about what \"gets you out\" means. See recovery-allowlist.ts.\n private readonly recoveryList = new RecoveryAllowlist(this.scanner);\n private readonly branches = new BranchIdentity();\n\n readonly description =\n 'Block ordinary Bash on an already-merged branch (allowlisting only recovery/cleanup and ' +\n 'read-only inspection commands), so a session cannot proceed on a stale post-merge branch.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'This branch is already merged into main — do not keep working here.',\n 'Get onto a fresh branch off origin/main, then retry:',\n [\n new Option('git fetch origin main && git checkout -b <new-branch> origin/main (in a worktree: git worktree add ../<dir> -b <new> origin/main). Then re-run your command.', true),\n new Option('Still allowed here: recovery/cleanup git, read-only git status|log|diff|show|branch, gh GENERALLY (it talks to GitHub, not to this tree — but not gh repo clone / pr checkout / run download, which write local files), curl/wget without -o/-O or a > redirect, switching branches/worktrees, pnpm wp-sync-main and pnpm wp-cleanup, and installs/upgrades.'),\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 check(ctx: BashContext): readonly Violation[] {\n const branch = this.currentBranch(ctx.workspaceRoot);\n // Can't determine the branch (not a git repo, git unavailable) → never block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n // A `/hotfix/` branch never takes main (issue #1371): its only cure here — branch off origin/main —\n // would ship unpromoted main to production. L2 row 14: exempt.\n if (this.branches.isHotfix(branch)) return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command. (The\n // runner also warms it, but only when feature-branch-guard is loaded — do it here too so this\n // guard is self-sufficient when that one is off.)\n triggerMainSyncRefresh(ctx.workspaceRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(ctx.workspaceRoot, branch);\n // No cache yet (first command of the session), or a branch this refresh has not seen → allow;\n // the refresh we just spawned populates it.\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.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\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 // For THIS guard the merged flag is the ONLY block condition, so an unreachable forge means\n // it is fully abstaining — the state it exists to catch cannot be observed at all.\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\n // Merged. Allow ONLY when every segment of the command is a recovery / cleanup / read-only\n // inspection command — anything else (servers, builds, tests, cat/ls of repo files, git writes)\n // is denied with the redirect.\n if (this.recoveryList.isFullyRecovery(ctx)) {\n return this.allow(ctx, branch, 'merged-branch recovery/inspection (allowlisted)', cache);\n }\n\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n return this.block(ctx, branch, `already-merged PR#${pr}`, this.mergedMessage(ctx.workspaceRoot, branch, status.mergedPr), cache);\n }\n\n private mergedMessage(workspaceRoot: string, branch: string, mergedPr: string): string {\n return new MergedBranchMessage(workspaceRoot).forBash(\n branch, mergedPr, new TreeRecovery().kindOf(workspaceRoot), workspaceRoot,\n );\n }\n\n // One-line summary of the async-written cache that drove this decision (mirrors the file guards),\n // so a wrong allow/block is traceable to the exact main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: BashContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */\n private exempt(ctx: BashContext, branch: string, reason: string): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, '-');\n return [];\n }\n\n private block(ctx: BashContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // 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, this.truncate(ctx.command), message + pointer)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('merged-branch-bash-guard', 'Bash', ctx.command, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n\n// git subcommands that are recovery/cleanup OR read-only orientation, and so stay allowed on a merged\n// branch. Everything NOT here (commit, merge, rebase, push, reset, add, restore, clean, cherry-pick,\n// …) is a \"keep working\" operation and is denied with the redirect. `worktree` covers add/remove/prune\n// (branch-creation-guard governs which worktree adds are legal); `branch` covers listing and `-D`\n// cleanup (branch-creation-guard governs creation); `pull` is the on-main update, itself gated by\n// redirect-how-to-merge-main. Reading git METADATA (log/diff/show) is fine — it is not the stale FILE\n// CONTENT that `cat` would surface, which is exactly why `git grep` (reads tracked content) is absent.\n"]}
@@ -66,6 +66,7 @@ import { FixHint } from '@webpieces/hook-runtime';
66
66
  export declare class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardConfig> {
67
67
  constructor(config: BranchStateGuardConfig);
68
68
  private readonly freshness;
69
+ private readonly branches;
69
70
  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
71
  readonly files: string[];
71
72
  readonly defaultOptions: {
@@ -114,6 +115,8 @@ export declare class ReadStaleGuardRule extends FileRuleBase<BranchStateGuardCon
114
115
  */
115
116
  private failOpen;
116
117
  private allow;
118
+ /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */
119
+ private exempt;
117
120
  private block;
118
121
  private logDecision;
119
122
  /**
@@ -85,6 +85,7 @@ class ReadStaleGuardRule extends hook_runtime_2.FileRuleBase {
85
85
  constructor(config) { super(config, 'read-stale-guard', policy_keys_1.BRANCH_STATE_GUARD_KEY); }
86
86
  // The ancestry test and the cache summary, shared with stale-main-bash-guard — see main-freshness.ts.
87
87
  freshness = new main_freshness_1.MainFreshness();
88
+ branches = new repo_workflow_core_1.BranchIdentity();
88
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.';
89
90
  files = ['**/*'];
90
91
  defaultOptions = {
@@ -121,6 +122,10 @@ class ReadStaleGuardRule extends hook_runtime_2.FileRuleBase {
121
122
  // nothing to judge. Matrix row 14 — abstain, and say WHY rather than logging a cache miss.
122
123
  if (branch === 'HEAD')
123
124
  return this.failOpen(ctx, branch, 'detached-head');
125
+ // A `/hotfix/` branch never takes main (issue #1371), so "merged" and "stale" are not states it can
126
+ // be cured out of by branching off main. L2 row 14: exempt.
127
+ if (this.branches.isHotfix(branch))
128
+ return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)');
124
129
  // Keep the shared cache warm for the next call. Detached; never blocks this read. Fired for
125
130
  // BOTH states — the merged-branch signal comes out of that same cache. Rooted at the JUDGED
126
131
  // tree so the entry refreshed is the one this guard reads.
@@ -259,6 +264,11 @@ class ReadStaleGuardRule extends hook_runtime_2.FileRuleBase {
259
264
  this.logDecision(ctx, branch, 'ALLOW', reason, cache);
260
265
  return [];
261
266
  }
267
+ /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */
268
+ exempt(ctx, branch, reason) {
269
+ this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, '-');
270
+ return [];
271
+ }
262
272
  block(ctx, branch, reason, message, cache = '-') {
263
273
  this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);
264
274
  // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.
@@ -1 +1 @@
1
- {"version":3,"file":"read-stale-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/read-stale-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAC3D,mFAA2G;AAC3G,sEAAiH;AAGjH,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,6DAAwD;AACxD,qDAAiD;AACjD,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACH,MAAa,kBAAmB,SAAQ,2BAAoC;IACxE,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,kBAAkB,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAE1G,sGAAsG;IACrF,SAAS,GAAG,IAAI,8BAAa,EAAE,CAAC;IAExC,WAAW,GAAG,gKAAgK,CAAC;IACtK,KAAK,GAAG,CAAC,MAAM,CAAC,CAAC;IACjB,cAAc,GAAG;QAC/B,kBAAkB,EAAE,iDAA4B;KACnD,CAAC;IACO,OAAO,GAAG,IAAI,sBAAO,CAC1B,8FAA8F,EAC9F,qDAAqD,EACrD;QACI,IAAI,qBAAM,CAAC,6VAA6V,EAAE,IAAI,CAAC;QAC/W,IAAI,qBAAM,CAAC,mJAAmJ,CAAC;QAC/J,IAAI,qBAAM,CAAC,0MAA0M,CAAC;QAC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AA,yCAAyB,EAAC,GAAG,CAAC,aAAa,CAAC,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC;QAChH,OAAO,CAAC,IAAI,wBAAC,CAAC,CAAC,EAAE,GAAG,CAAC,YAAY,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC;IAC3D,CAAC;IAEO,WAAW,CAAC,GAAgB,EAAE,MAAqB,EAAE,OAAgB,EAAE,MAAc,EAAE,KAAa;QACxG,IAAA,+BAAgB,EACZ,GAAG,CAAC,aAAa,EACjB,IAAI,4BAAa,CAAC,kBAAkB,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,YAAY,EAAE,MAAM,IAAI,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,4BAAa,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,CACrJ,CAAC;IACN,CAAC;IAED;;;;OAIG;IACK,aAAa,CAAC,aAAqB;QACvC,OAAO,4BAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;CACJ;AAjOD,gDAiOC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig, DEFAULT_MAX_COMMITS_BEHIND } from \"../../configs/main-sync-guard-configs\";\nimport { DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\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 for it. This runs on EVERY read, so it is the one call\n * whose cost matters most: `GitCheckout.branch()` reads the worktree's own HEAD file (primary clone\n * and linked worktree alike, detached HEAD included) with no git process at all (#1355).\n */\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"read-stale-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/read-stale-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAiD;AACjD,mDAA2D;AAC3D,mFAA2G;AAC3G,sEAAiI;AAGjI,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,6DAAwD;AACxD,qDAAiD;AACjD,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACH,MAAa,kBAAmB,SAAQ,2BAAoC;IACxE,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,kBAAkB,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAE1G,sGAAsG;IACrF,SAAS,GAAG,IAAI,8BAAa,EAAE,CAAC;IAChC,QAAQ,GAAG,IAAI,mCAAc,EAAE,CAAC;IAExC,WAAW,GAAG,gKAAgK,CAAC;IACtK,KAAK,GAAG,CAAC,MAAM,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K,aAAa,CAAC,aAAqB;QACvC,OAAO,4BAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;CACJ;AA3OD,gDA2OC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig, DEFAULT_MAX_COMMITS_BEHIND } from \"../../configs/main-sync-guard-configs\";\nimport { BranchIdentity, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\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 '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\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 private readonly branches = new BranchIdentity();\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 // A `/hotfix/` branch never takes main (issue #1371), so \"merged\" and \"stale\" are not states it can\n // be cured out of by branching off main. L2 row 14: exempt.\n if (this.branches.isHotfix(branch)) return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)');\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 /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */\n private exempt(ctx: FileContext, branch: string, reason: string): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, '-');\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 for it. This runs on EVERY read, so it is the one call\n * whose cost matters most: `GitCheckout.branch()` reads the worktree's own HEAD file (primary clone\n * and linked worktree alike, detached HEAD included) with no git process at all (#1355).\n */\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n}\n"]}
@@ -6,6 +6,7 @@ export declare class RedirectHowToMergeMainRule extends BashRuleBase<PrLifecycle
6
6
  private readonly scanner;
7
7
  private readonly recovery;
8
8
  private readonly switches;
9
+ private readonly branches;
9
10
  constructor(config: PrLifecycleGuardConfig);
10
11
  readonly description = "Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.";
11
12
  readonly fixHint: FixHint;
@@ -13,4 +14,5 @@ export declare class RedirectHowToMergeMainRule extends BashRuleBase<PrLifecycle
13
14
  private checkSegment;
14
15
  private checkPull;
15
16
  private block;
17
+ private hotfixBlock;
16
18
  }
@@ -10,6 +10,7 @@ const hook_runtime_3 = require("@webpieces/hook-runtime");
10
10
  const hook_runtime_4 = require("@webpieces/hook-runtime");
11
11
  const tree_recovery_1 = require("./tree-recovery");
12
12
  const branch_switch_scan_1 = require("./branch-switch-scan");
13
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
13
14
  const INSTRUCT_FILE = 'webpieces.git-workflow.md';
14
15
  const GUIDANCE = new rules_config_1.SyncFlowGuidance();
15
16
  const FIX_HINT = new hook_runtime_3.FixHint('`git merge` / `git rebase` are never run by AI — on any branch, in any form.', 'To bring main\'s changes into your feature branch:\n'
@@ -64,6 +65,7 @@ class RedirectHowToMergeMainRule extends hook_runtime_2.BashRuleBase {
64
65
  // feature-switch block, so this guard rejected the very command stale-main-bash-guard prescribes,
65
66
  // with a reason ("switches to a feature branch") that was the opposite of the truth.
66
67
  switches = new branch_switch_scan_1.BranchSwitchScan(this.scanner);
68
+ branches = new repo_workflow_core_1.BranchIdentity();
67
69
  constructor(config) { super(config, 'redirect-how-to-merge-main', policy_keys_1.PR_LIFECYCLE_GUARD_KEY); }
68
70
  description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';
69
71
  fixHint = FIX_HINT;
@@ -130,9 +132,17 @@ class RedirectHowToMergeMainRule extends hook_runtime_2.BashRuleBase {
130
132
  const currentBranch = tooling_common_1.gitCheckout.requireBranch(ctx.workspaceRoot);
131
133
  if (currentBranch === 'main')
132
134
  return null;
133
- return this.block(ctx, segment, `Pulling main into feature branch '${currentBranch}' is blocked.`);
135
+ const kind = this.branches.isHotfix(currentBranch) ? 'hotfix branch' : 'feature branch';
136
+ return this.block(ctx, segment, `Pulling main into ${kind} '${currentBranch}' is blocked.`);
134
137
  }
135
138
  block(ctx, segment, what) {
139
+ // A `/hotfix/` branch is cut from the PRODUCTION sha (issue #1371). The block itself is unchanged
140
+ // there — a raw merge is even more wrong — but the cure below is a way to bring MAIN in, which a
141
+ // hotfix must never do, so on that branch the message names the hotfix route instead. The branch
142
+ // read decides only the WORDS, never the verdict (see checkSegment on why the verdict reads none).
143
+ const branch = tooling_common_1.gitCheckout.branch(ctx.workspaceRoot);
144
+ if (branch !== null && this.branches.isHotfix(branch))
145
+ return this.hotfixBlock(segment, what, branch);
136
146
  // Materialize the doc we are about to send the AI to. This guard fires long before any `wp-*`
137
147
  // command runs (those are what normally write it), so the linked path could easily not exist —
138
148
  // and a STALE copy from an older @webpieces is just as misleading, hence overwrite.
@@ -151,6 +161,9 @@ class RedirectHowToMergeMainRule extends hook_runtime_2.BashRuleBase {
151
161
  ].join('\n');
152
162
  return new hook_runtime_1.Violation(1, truncate(segment), `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`);
153
163
  }
164
+ hotfixBlock(segment, what, branch) {
165
+ return new hook_runtime_1.Violation(1, truncate(segment), `${what} '${branch}' is a /hotfix/ branch, cut from the production sha: it NEVER takes main — not by a raw merge or rebase, and not by the gated 3-point flows (\`wp-start-update\` / \`wp-start-upsert-pr\`) printed below either. Those are for feature branches; on this branch any of them would ship unpromoted main to production. Make the fix on this branch alone, then publish it with \`pnpm wp-upsert-hotfix-pr\` (hotfix-ci, no merge from main, one fast-forward push).`);
166
+ }
154
167
  }
155
168
  exports.RedirectHowToMergeMainRule = RedirectHowToMergeMainRule;
156
169
  //# sourceMappingURL=redirect-how-to-merge-main.js.map