@webpieces/ai-hook-rules 0.4.696 → 0.4.698
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/core/command-scan.d.ts +21 -9
- package/src/core/command-scan.js +18 -16
- package/src/core/command-scan.js.map +1 -1
- package/src/core/l2-doc.js +27 -2
- package/src/core/l2-doc.js.map +1 -1
- package/src/core/l2-rows.d.ts +1 -1
- package/src/core/l2-rows.js +18 -4
- package/src/core/l2-rows.js.map +1 -1
- package/src/core/read-only-inspection.js +1 -1
- package/src/core/read-only-inspection.js.map +1 -1
- package/src/core/rules/build-output-pipe-scan.js +2 -2
- package/src/core/rules/build-output-pipe-scan.js.map +1 -1
- package/src/core/rules/content-read-scan.js +1 -1
- package/src/core/rules/content-read-scan.js.map +1 -1
- package/src/core/rules/cure-prefix-scan.d.ts +64 -0
- package/src/core/rules/cure-prefix-scan.js +133 -0
- package/src/core/rules/cure-prefix-scan.js.map +1 -0
- package/src/core/rules/read-stale-guard.d.ts +5 -4
- package/src/core/rules/read-stale-guard.js +9 -8
- package/src/core/rules/read-stale-guard.js.map +1 -1
- package/src/core/rules/recovery-allowlist.js +1 -1
- package/src/core/rules/recovery-allowlist.js.map +1 -1
- package/src/core/rules/shell-segment-scan.js +1 -1
- package/src/core/rules/shell-segment-scan.js.map +1 -1
- package/src/core/rules/stale-main-bash-guard.d.ts +28 -0
- package/src/core/rules/stale-main-bash-guard.js +45 -1
- package/src/core/rules/stale-main-bash-guard.js.map +1 -1
- package/src/core/rules/stale-main-message.d.ts +19 -8
- package/src/core/rules/stale-main-message.js +25 -13
- package/src/core/rules/stale-main-message.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stale-main-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/stale-main-bash-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAAmJ;AAGnJ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D,IAAI,CAAC;YACD,OAAO,IAAA,wBAAQ,EAAC,iCAAiC,EAAE;gBAC/C,GAAG,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;aACxE,CAAC,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AA9ND,wDA8NC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, Option } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { CommandScanner } from '../command-scan';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitchScan } from './branch-switch-scan';\nimport { RecoveryAllowlist } from './recovery-allowlist';\nimport { MainFreshness } from './main-freshness';\n\n/**\n * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:\n * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that\n * contains the damage once it is already there.\n *\n * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────\n *\n * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.\n * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this\n * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157\n * commits behind** origin. That checkout did not merely produce stale files — it reverted:\n *\n * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;\n * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy\n * whose message stated the drift BACKWARDS (\"your installed webpieces is older than required\")\n * and named a single cure, `pnpm install`;\n * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match\n * the stale pin, and had to undo it with the `git pull` that should have come first.\n *\n * The shim on current main already diagnoses drift correctly — it distinguishes \"the pin is newer\"\n * from \"the pin is stale, and `pnpm install` would downgrade you\". None of that helped, because the\n * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout\n * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive\n * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.\n *\n * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the\n * checkout, so the only `main` it could measure is the one it is about to leave. The interesting\n * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap\n * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when\n * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.\n *\n * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`\n * appears anywhere in the SAME command.\n * ALLOWED `git checkout main && git pull origin main`, the pairing this forces — and\n * `pnpm wp-checkout-clean-main`, which IS that pairing with the cleanup and the\n * orphan-directory sweep welded on. The message prescribes the one command; the raw pair\n * stays legal because it is plain git and because it is the L0 recovery cure, where\n * `node_modules` is the thing in doubt and no `pnpm` bin can be relied on.\n * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,\n * `git checkout -- <file>`, and any other branch.\n *\n * ── ROWS 6/7: the block fires only once `main` is KNOWN STALE ────────────────────────────────\n *\n * The finding is not \"you are on `main`\" — it is **\"what you would read here is out of date\"**. So the\n * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only\n * when local `main` is known to be BEHIND `origin/main`. Unknown → allow. Current → allow.\n *\n * WHY, when this guard spent a release judging the branch alone: because the branch alone denies\n * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly\n * where the prescribed cure leaves you. An agent lands a PR, runs `pnpm wp-checkout-clean-main` — the\n * command this repo tells it to run — and the next `curl`, `gh pr close` or test run is refused by a\n * guard whose own name says STALE. The tool that got it there could not be the cure for being there,\n * and the refusal had nothing to do with staleness, which is the confusion reported from the field.\n *\n * THE ASYMMETRY WITH `E` IS DELIBERATE, and the docblocks that argued `B` should track `E` were right\n * about the mechanism and wrong about the policy. A WRITE on `main` creates work in the wrong place\n * whatever `main`'s freshness — unreviewable, and unrevertable as a unit — so feature-branch-guard\n * stays unconditional and keeps its one `git rev-parse`. A READ or a BUILD on a CURRENT `main` harms\n * nothing, and blocking it strands the agent at the exact moment the prescribed cure put it there.\n * Same tree, different hazard, so one precondition was never right for both.\n *\n * THE ANCESTRY TEST, NOT HASH EQUALITY. `MainFreshness.containsOriginMain` asks \"does local `main`\n * already contain the cached `origin/main`?\", so the block lifts the instant a pull lands rather than\n * waiting for the detached refresher to catch up. It is the SAME object read-stale-guard uses — one\n * implementation, so the Read and Bash halves of one state can never disagree about whether the pull\n * took.\n *\n * FAIL-OPEN ON EVERYTHING NOT ESTABLISHED, logged as `ALLOW_FAIL_OPEN` so abstentions stay countable:\n * no cache (the first call of every session), a cache for another branch, an empty `originMain`\n * (offline), no local `main` at all (fresh clone / worktree), branch undeterminable. The refresher is\n * fired detached on every call to keep the cache warm for the NEXT one; it is never waited on, and no\n * synchronous `git fetch` is ever run on the blocking path.\n *\n * THE POLARITY INSIDE THE BLOCKED STATE IS UNCHANGED: default-DENY plus row 4's skip list, the shape\n * merged-branch-bash-guard uses for state B, via the same shared RecoveryAllowlist. A content-read\n * BLOCKLIST could not replace it — enumerating readers catches `cat` and `grep`, and structurally\n * cannot catch `pnpm install`, `npx expo install`, a formatter, codegen or a `>` redirect: commands\n * whose stated purpose is something else and whose effect is to modify tracked files. What changed is\n * WHEN that polarity applies, not the polarity.\n *\n * BLOCKED on a `main` known to be BEHIND: anything not on the skip list — builds, tests,\n * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.\n * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the\n * blocked state, everything that gets you OUT or tells you where you are:\n * `git checkout -b <new> origin/main`, `git switch`, `git pull`/`fetch`,\n * `git status|log|diff|show|branch`, `git stash`, `gh` (it talks to GitHub, not to this\n * tree), `curl`/`wget`, every `wp-*` bin, installs.\n *\n * There is no dirty-tree valve here and none in read-stale-guard either: the cure is\n * `git checkout -b`, which CARRIES uncommitted work onto the new branch, so a dirty tree traps nobody\n * in any L2 state. (`git stash` covers the residual where origin/main touched the same files.)\n */\nexport class StaleMainBashGuardRule extends BashRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'stale-main-bash-guard', BRANCH_STATE_GUARD_KEY); }\n\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n private readonly switches = new BranchSwitchScan(this.scanner);\n // ROW 4, the skip list — the SAME instance-shape merged-branch-bash-guard uses, so the two states\n // cannot drift apart about what \"gets you out\" means. See recovery-allowlist.ts.\n private readonly recoveryList = new RecoveryAllowlist(this.scanner);\n // The ancestry test and the cache summary, shared with read-stale-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n\n readonly description =\n 'Block a bare `git checkout main` (use `pnpm wp-checkout-clean-main`, or chain the pull into ' +\n 'the same command), and — once local main is KNOWN to be behind origin/main — block Bash ' +\n 'there, allowlisting only the commands that get you off it. A main that is current, or whose ' +\n 'freshness is unknown, is left alone.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'Landing on `main` without pulling, or working on `main` at all, both put your work somewhere it does not belong.',\n 'Get onto a feature branch, or go to main with the one command that pulls it too:',\n [\n // TREE-SHAPED, from the one source of tree-shaped cures. A static rule-level hint has no\n // workspace root, so it renders the 'unknown' kind — TreeRecovery's deliberate answer for\n // \"we cannot detect the tree\": both forms, each labelled. That matters here because the\n // primary-clone form goes to `main`, and a linked worktree has no `main` to go to — it is\n // checked out in the primary clone — so a preferred option naming it unconditionally hands\n // the AI a cure that cannot work where it is standing. The per-block message\n // (pairingMessage) is detected and prints exactly one form; this is the fallback for the\n // hint that cannot look.\n new Option(this.recovery.updateMainSteps('unknown').join('\\n')\n + '\\nIf you hand-roll the git instead, the pull must be in the SAME command as the checkout.', true),\n new Option('Already on main: git pull --ff-only origin main (then re-run). If that fatals with \"Cannot fast-forward to multiple branches\", .git/FETCH_HEAD has a duplicate line — run git fetch --prune origin main first.'),\n new Option('Still allowed: every BASH command, on a main that is current or whose freshness is not known — this guard only closes once local main is known to be BEHIND origin/main. (Write/Edit on main is a different policy and is blocked by feature-branch-guard however current main is.) In that state you keep the Read tool while main is current (read-stale-guard closes it when main falls behind, because stale reads are worthless) plus everything that gets you OUT or tells you where you are: git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs, and reading webpieces.config.json.'),\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 // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout\n // below: those all ask \"is the main we are ON stale?\", and this asks about the main we are\n // about to MOVE TO — a different branch, and one no cache can describe yet.\n const bare = this.bareCheckoutOfMain(ctx);\n if (bare !== null) {\n return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');\n }\n\n const branch = this.currentBranch(ctx.workspaceRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command.\n triggerMainSyncRefresh(ctx.workspaceRoot, hangTimeoutOf(this.config));\n\n // State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.\n if (branch !== 'main') return this.allow(ctx, branch, 'not-on-main (state B is another guard)');\n\n // ROW 4 — the skip list, ahead of the block, so no command that gets you OUT is ever denied.\n if (this.recoveryList.isFullyRecovery(ctx)) {\n return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)');\n }\n\n return this.checkFreshness(ctx, branch);\n }\n\n /**\n * ROWS 6/7 — block ONLY when local `main` is KNOWN to be behind `origin/main`.\n *\n * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and\n * that is on purpose — the Read and the Bash halves of one state must not disagree about whether\n * `main` is stale. What differs is the VERDICT SHAPE once it is stale, because a Read names one\n * file and a Bash command is opaque: the Read is judged per file, Bash is default-deny plus the\n * row 4 skip list already applied above.\n *\n * Every exit that is not \"established BEHIND\" is an ALLOW, and the not-established ones are\n * `ALLOW_FAIL_OPEN` so they stay countable. A guard that cannot see the state judges nothing.\n */\n private checkFreshness(ctx: BashContext, branch: string): readonly Violation[] {\n const status = readMainSyncStatus(ctx.workspaceRoot, 'main');\n // The first call of every session, and every call while another worktree holds the refresh\n // lock. The refresher fired above populates it for the NEXT call; nothing waits here.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.freshness.summarize(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 // ANCESTRY, not equality — the line that makes a pull take effect immediately. See\n // MainFreshness.containsOriginMain.\n if (this.freshness.containsOriginMain(ctx.workspaceRoot, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n // ESTABLISHED BEHIND. Now — and only now — the default-deny polarity applies.\n return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(ctx.workspaceRoot), cache);\n }\n\n /**\n * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same\n * command, or null. The pull is looked for across the WHOLE command, not the matched segment,\n * because `git checkout main && git pull origin main` splits into two segments and the pairing is\n * the point.\n */\n private bareCheckoutOfMain(ctx: BashContext): string | null {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n // BranchSwitchScan answers \"which branch does this land on\" for both guards, flag-tolerantly:\n // `git checkout -q main` lands on main exactly as the bare form does, while\n // `git checkout -b x origin/main` (creates), `git checkout -- main` (pathspec) and\n // `git checkout <sha>` do not. See branch-switch-scan.ts for why that lives in one place.\n if (!this.switches.landsOnExistingMain(segment)) continue;\n return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;\n }\n return null;\n }\n\n /**\n * The stale-`main` deny. Deliberately SHORT, and now deliberately ABOUT STALENESS — which is what\n * the guard's name promised all along.\n *\n * The two versions before this one are both instructive. The oldest opened with how many commits\n * behind `main` was, which invited the wrong cure: an agent that reads \"behind\" reaches for a pull,\n * lands on a CURRENT `main`, and is still on `main`. The one after it swung the other way and said\n * `main` is not a place to work \"whether or not it is current\" — true of a WRITE, but this guard\n * does not see writes, and it made every refusal on a freshly-pulled `main` unanswerable.\n *\n * So the text says what is now actually true and nothing more: local `main` is BEHIND, so what you\n * read here is out of date; Bash is default-deny in this state rather than a list of readers,\n * because a command's stated purpose never says whether it also WRITES; and the branch cure fetches,\n * so it makes the reads true as well as moving the work somewhere reviewable. Reading `main` to PLAN\n * stays legitimate — on a CURRENT `main` nothing here fires at all.\n *\n * ONE cure, and it is the dirty-safe one, the same call feature-branch-guard made: `git checkout -b`\n * carries uncommitted work onto the new branch. (Row 6 also lists the pull, and read-stale-guard\n * prints it, because a Read really can be cured by staying put. A Bash session cannot — the next\n * command is as likely to write as to read.)\n */\n private staleMainMessage(workspaceRoot: string): string {\n return 'Blocked: local `main` is BEHIND origin/main, so what you would read here is out of '\n + 'date and a plan built on it is built on code upstream has moved past. A CURRENT main is '\n + 'not blocked — reading main to PLAN is fine, and this fires only once being behind is '\n + 'established. Bash is default-deny in this state rather than a list of readers, because a '\n + \"command's stated purpose never says whether it also WRITES. The feature branch is the \"\n + 'unit of work in any case: reviewable, revertable — and the cure fetches, so it makes '\n + 'your reads true as well as moving you off main.\\n'\n + `Start a branch (uncommitted work comes with you):\\n cd '${workspaceRoot}' && git fetch origin main && git checkout -b <new-branch> origin/main`;\n }\n\n private pairingMessage(ctx: BashContext): string {\n const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\\n');\n // Deliberately SHORT. The incident that bought this guard (a main 157 commits behind; the\n // downgrade the reverted shim then prescribed) is maintainer material and lives in the class\n // docblock above — the reader of THIS text needs only what changes what they type.\n return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had — '\n + 'stale files, plus a reverted @webpieces pin and guard shim, so the drift guard then '\n + 'reports the drift BACKWARDS. Go to main with the one command that also pulls it:\\n' + steps;\n }\n\n\n\n\n\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, the same way an L0 block does. The doc is written\n // LAZILY here rather than up front: only a blocked agent needs it, and this is the one path\n // that knows the row it should be opened at.\n const row = matrixL2Row(reason).row;\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), 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('stale-main-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 // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stale-main-bash-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/stale-main-bash-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAAmJ;AAGnJ,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,0CAAsC;AACtC,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,sDAAkD;AAClD,kDAAiD;AACjD,mDAA+C;AAC/C,6DAAwD;AACxD,6DAAyD;AACzD,qDAAiD;AACjD,yDAAgE;AAEhE;;;;;;;;;;;;;;;;;;;;;;;;;;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AC,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,uBAAuB,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,8BAAa,EAAE,IAAA,0BAAW,EAAC,MAAM,CAAC,CAAC,CACnJ,CAAC;IACN,CAAC;IAEO,aAAa,CAAC,aAAqB;QACvC,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,IAAA,wBAAQ,EAAC,iCAAiC,EAAE;gBAC/C,GAAG,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;aACxE,CAAC,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AApQD,wDAoQC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, Option } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { CommandScanner } from '../command-scan';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitchScan } from './branch-switch-scan';\nimport { RecoveryAllowlist } from './recovery-allowlist';\nimport { MainFreshness } from './main-freshness';\nimport { CurePrefixScan, CurePrefix } from './cure-prefix-scan';\n\n/**\n * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:\n * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that\n * contains the damage once it is already there.\n *\n * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────\n *\n * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.\n * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this\n * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157\n * commits behind** origin. That checkout did not merely produce stale files — it reverted:\n *\n * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;\n * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy\n * whose message stated the drift BACKWARDS (\"your installed webpieces is older than required\")\n * and named a single cure, `pnpm install`;\n * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match\n * the stale pin, and had to undo it with the `git pull` that should have come first.\n *\n * The shim on current main already diagnoses drift correctly — it distinguishes \"the pin is newer\"\n * from \"the pin is stale, and `pnpm install` would downgrade you\". None of that helped, because the\n * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout\n * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive\n * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.\n *\n * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the\n * checkout, so the only `main` it could measure is the one it is about to leave. The interesting\n * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap\n * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when\n * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.\n *\n * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`\n * appears anywhere in the SAME command.\n * ALLOWED `git checkout main && git pull origin main`, the pairing this forces — and\n * `pnpm wp-checkout-clean-main`, which IS that pairing with the cleanup and the\n * orphan-directory sweep welded on. The message prescribes the one command; the raw pair\n * stays legal because it is plain git and because it is the L0 recovery cure, where\n * `node_modules` is the thing in doubt and no `pnpm` bin can be relied on.\n * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,\n * `git checkout -- <file>`, and any other branch.\n *\n * ── ROWS 6/7: the block fires only once `main` is KNOWN STALE ────────────────────────────────\n *\n * The finding is not \"you are on `main`\" — it is **\"what you would read here is out of date\"**. So the\n * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only\n * when local `main` is known to be BEHIND `origin/main`. Unknown → allow. Current → allow.\n *\n * WHY, when this guard spent a release judging the branch alone: because the branch alone denies\n * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly\n * where the prescribed cure leaves you. An agent lands a PR, runs `pnpm wp-checkout-clean-main` — the\n * command this repo tells it to run — and the next `curl`, `gh pr close` or test run is refused by a\n * guard whose own name says STALE. The tool that got it there could not be the cure for being there,\n * and the refusal had nothing to do with staleness, which is the confusion reported from the field.\n *\n * THE ASYMMETRY WITH `E` IS DELIBERATE, and the docblocks that argued `B` should track `E` were right\n * about the mechanism and wrong about the policy. A WRITE on `main` creates work in the wrong place\n * whatever `main`'s freshness — unreviewable, and unrevertable as a unit — so feature-branch-guard\n * stays unconditional and keeps its one `git rev-parse`. A READ or a BUILD on a CURRENT `main` harms\n * nothing, and blocking it strands the agent at the exact moment the prescribed cure put it there.\n * Same tree, different hazard, so one precondition was never right for both.\n *\n * THE ANCESTRY TEST, NOT HASH EQUALITY. `MainFreshness.containsOriginMain` asks \"does local `main`\n * already contain the cached `origin/main`?\", so the block lifts the instant a pull lands rather than\n * waiting for the detached refresher to catch up. It is the SAME object read-stale-guard uses — one\n * implementation, so the Read and Bash halves of one state can never disagree about whether the pull\n * took.\n *\n * FAIL-OPEN ON EVERYTHING NOT ESTABLISHED, logged as `ALLOW_FAIL_OPEN` so abstentions stay countable:\n * no cache (the first call of every session), a cache for another branch, an empty `originMain`\n * (offline), no local `main` at all (fresh clone / worktree), branch undeterminable. The refresher is\n * fired detached on every call to keep the cache warm for the NEXT one; it is never waited on, and no\n * synchronous `git fetch` is ever run on the blocking path.\n *\n * THE POLARITY INSIDE THE BLOCKED STATE IS UNCHANGED: default-DENY plus row 4's skip list, the shape\n * merged-branch-bash-guard uses for state B, via the same shared RecoveryAllowlist. A content-read\n * BLOCKLIST could not replace it — enumerating readers catches `cat` and `grep`, and structurally\n * cannot catch `pnpm install`, `npx expo install`, a formatter, codegen or a `>` redirect: commands\n * whose stated purpose is something else and whose effect is to modify tracked files. What changed is\n * WHEN that polarity applies, not the polarity.\n *\n * BLOCKED on a `main` known to be BEHIND: anything not on the skip list — builds, tests,\n * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.\n * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the\n * blocked state, everything that gets you OUT or tells you where you are:\n * `git checkout -b <new> origin/main`, `git switch`, `git pull`/`fetch`,\n * `git status|log|diff|show|branch`, `git stash`, `gh` (it talks to GitHub, not to this\n * tree), `curl`/`wget`, every `wp-*` bin, installs.\n *\n * ── ROWS 12/13: the cure may be COMPOSED with the work, but only with `&&` ───────────────────────\n *\n * `pnpm wp-checkout-clean-main && cat src/app.ts` is allowed and `pnpm wp-checkout-clean-main ; cat\n * src/app.ts` is not, and the difference is the shell's rather than this guard's: `&&` short-circuits,\n * so the work cannot run when the cure failed — the exact property the block is here to guarantee. `;`\n * discards the exit code and runs the work anyway. See cure-prefix-scan.ts for the measured shapes.\n *\n * There is no dirty-tree valve here and none in read-stale-guard either: the cure is\n * `git checkout -b`, which CARRIES uncommitted work onto the new branch, so a dirty tree traps nobody\n * in any L2 state. (`git stash` covers the residual where origin/main touched the same files.)\n */\nexport class StaleMainBashGuardRule extends BashRuleBase<BranchStateGuardConfig> {\n constructor(config: BranchStateGuardConfig) { super(config, 'stale-main-bash-guard', BRANCH_STATE_GUARD_KEY); }\n\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n private readonly switches = new BranchSwitchScan(this.scanner);\n // ROW 4, the skip list — the SAME instance-shape merged-branch-bash-guard uses, so the two states\n // cannot drift apart about what \"gets you out\" means. See recovery-allowlist.ts.\n private readonly recoveryList = new RecoveryAllowlist(this.scanner);\n // The ancestry test and the cache summary, shared with read-stale-guard — see main-freshness.ts.\n private readonly freshness = new MainFreshness();\n // ROWS 12/13 — `<cure> && <work>` vs `<cure> ; <work>`. See cure-prefix-scan.ts.\n private readonly curePrefix = new CurePrefixScan(this.scanner);\n\n readonly description =\n 'Block a bare `git checkout main` (use `pnpm wp-checkout-clean-main`, or chain the pull into ' +\n 'the same command), and — once local main is KNOWN to be behind origin/main — block Bash ' +\n 'there, allowlisting only the commands that get you off it. A main that is current, or whose ' +\n 'freshness is unknown, is left alone.';\n override readonly defaultOptions = {\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'Landing on `main` without pulling, or working on `main` at all, both put your work somewhere it does not belong.',\n 'Get onto a feature branch, or go to main with the one command that pulls it too:',\n [\n // TREE-SHAPED, from the one source of tree-shaped cures. A static rule-level hint has no\n // workspace root, so it renders the 'unknown' kind — TreeRecovery's deliberate answer for\n // \"we cannot detect the tree\": both forms, each labelled. That matters here because the\n // primary-clone form goes to `main`, and a linked worktree has no `main` to go to — it is\n // checked out in the primary clone — so a preferred option naming it unconditionally hands\n // the AI a cure that cannot work where it is standing. The per-block message\n // (pairingMessage) is detected and prints exactly one form; this is the fallback for the\n // hint that cannot look.\n new Option(this.recovery.updateMainSteps('unknown').join('\\n')\n + '\\nIf you hand-roll the git instead, the pull must be in the SAME command as the checkout.', true),\n new Option('Already on main: pnpm wp-checkout-clean-main (then re-run) — it pulls main and takes the trash out in the one command this repo prescribes. You may chain your command onto it with && (pnpm wp-checkout-clean-main && <your command>), which is skipped if the pull fails; a ; instead runs your command anyway and is refused.'),\n new Option('Still allowed: every BASH command, on a main that is current or whose freshness is not known — this guard only closes once local main is known to be BEHIND origin/main. (Write/Edit on main is a different policy and is blocked by feature-branch-guard however current main is.) In that state you keep the Read tool while main is current (read-stale-guard closes it when main falls behind, because stale reads are worthless) plus everything that gets you OUT or tells you where you are: git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs, and reading webpieces.config.json.'),\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 // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout\n // below: those all ask \"is the main we are ON stale?\", and this asks about the main we are\n // about to MOVE TO — a different branch, and one no cache can describe yet.\n const bare = this.bareCheckoutOfMain(ctx);\n if (bare !== null) {\n return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');\n }\n\n const branch = this.currentBranch(ctx.workspaceRoot);\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable');\n\n // Keep the shared cache warm for the next call. Detached; never blocks this command.\n triggerMainSyncRefresh(ctx.workspaceRoot, hangTimeoutOf(this.config));\n\n // State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.\n if (branch !== 'main') return this.allow(ctx, branch, 'not-on-main (state B is another guard)');\n\n // ROW 4 — the skip list, ahead of the block, so no command that gets you OUT is ever denied.\n if (this.recoveryList.isFullyRecovery(ctx)) {\n return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)');\n }\n\n return this.checkFreshness(ctx, branch);\n }\n\n /**\n * ROWS 6/7 — block ONLY when local `main` is KNOWN to be behind `origin/main`.\n *\n * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and\n * that is on purpose — the Read and the Bash halves of one state must not disagree about whether\n * `main` is stale. What differs is the VERDICT SHAPE once it is stale, because a Read names one\n * file and a Bash command is opaque: the Read is judged per file, Bash is default-deny plus the\n * row 4 skip list already applied above.\n *\n * Every exit that is not \"established BEHIND\" is an ALLOW, and the not-established ones are\n * `ALLOW_FAIL_OPEN` so they stay countable. A guard that cannot see the state judges nothing.\n */\n private checkFreshness(ctx: BashContext, branch: string): readonly Violation[] {\n const status = readMainSyncStatus(ctx.workspaceRoot, 'main');\n // The first call of every session, and every call while another worktree holds the refresh\n // lock. The refresher fired above populates it for the NEXT call; nothing waits here.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = this.freshness.summarize(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 // ANCESTRY, not equality — the line that makes a pull take effect immediately. See\n // MainFreshness.containsOriginMain.\n if (this.freshness.containsOriginMain(ctx.workspaceRoot, status.originMain)) {\n return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);\n }\n\n // ESTABLISHED BEHIND. Now — and only now — the default-deny polarity applies.\n return this.judgeComposition(ctx, branch, cache);\n }\n\n /**\n * ROWS 12/13 — `<cure> && <work>` is allowed; `<cure> ; <work>` is not.\n *\n * The distinction is the shell's, not this guard's invention. `&&` short-circuits, so the work\n * cannot run when the cure exits non-zero — which is precisely the property the block exists to\n * guarantee, already enforced by the interpreter. Refusing it bought nothing and cost a round\n * trip, and the fleet audit files that as a TOOLING defect.\n *\n * `;` discards the exit code and runs the work regardless, and it was measured with\n * `>/dev/null 2>&1` on the cure in 7 of 9 observed cases — so the failure was invisible as well as\n * ignored. The two-step is genuinely safer there: the NEXT tool call is a fresh evaluation that\n * recomputes `localMain` against `originMain`, so a pull that failed re-blocks. An allowed `;`\n * compound never gets that second look.\n */\n private judgeComposition(ctx: BashContext, branch: string, cache: string): readonly Violation[] {\n const prefix = this.curePrefix.classify(ctx.command);\n if (prefix.kind === 'short-circuits') {\n return this.allow(ctx, branch, 'cure-prefixed, && short-circuits the work', cache);\n }\n if (prefix.kind === 'runs-anyway') {\n return this.block(ctx, branch, 'cure-prefixed, work runs anyway', this.compositionMessage(prefix), cache);\n }\n return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(ctx.workspaceRoot), cache);\n }\n\n /**\n * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same\n * command, or null. The pull is looked for across the WHOLE command, not the matched segment,\n * because `git checkout main && git pull origin main` splits into two segments and the pairing is\n * the point.\n */\n private bareCheckoutOfMain(ctx: BashContext): string | null {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n // BranchSwitchScan answers \"which branch does this land on\" for both guards, flag-tolerantly:\n // `git checkout -q main` lands on main exactly as the bare form does, while\n // `git checkout -b x origin/main` (creates), `git checkout -- main` (pathspec) and\n // `git checkout <sha>` do not. See branch-switch-scan.ts for why that lives in one place.\n if (!this.switches.landsOnExistingMain(segment)) continue;\n return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;\n }\n return null;\n }\n\n /**\n * The stale-`main` deny. Deliberately SHORT, and now deliberately ABOUT STALENESS — which is what\n * the guard's name promised all along.\n *\n * The two versions before this one are both instructive. The oldest opened with how many commits\n * behind `main` was, which invited the wrong cure: an agent that reads \"behind\" reaches for a pull,\n * lands on a CURRENT `main`, and is still on `main`. The one after it swung the other way and said\n * `main` is not a place to work \"whether or not it is current\" — true of a WRITE, but this guard\n * does not see writes, and it made every refusal on a freshly-pulled `main` unanswerable.\n *\n * So the text says what is now actually true and nothing more: local `main` is BEHIND, so what you\n * read here is out of date; Bash is default-deny in this state rather than a list of readers,\n * because a command's stated purpose never says whether it also WRITES; and the branch cure fetches,\n * so it makes the reads true as well as moving the work somewhere reviewable. Reading `main` to PLAN\n * stays legitimate — on a CURRENT `main` nothing here fires at all.\n *\n * ONE cure, and it is the dirty-safe one, the same call feature-branch-guard made: `git checkout -b`\n * carries uncommitted work onto the new branch. (Row 6 also lists the pull, and read-stale-guard\n * prints it, because a Read really can be cured by staying put. A Bash session cannot — the next\n * command is as likely to write as to read.)\n */\n private staleMainMessage(workspaceRoot: string): string {\n return 'Blocked: local `main` is BEHIND origin/main, so what you would read here is out of '\n + 'date and a plan built on it is built on code upstream has moved past. A CURRENT main is '\n + 'not blocked — reading main to PLAN is fine, and this fires only once being behind is '\n + 'established. Bash is default-deny in this state rather than a list of readers, because a '\n + \"command's stated purpose never says whether it also WRITES. The feature branch is the \"\n + 'unit of work in any case: reviewable, revertable — and the cure fetches, so it makes '\n + 'your reads true as well as moving you off main.\\n'\n + `Start a branch (uncommitted work comes with you):\\n cd '${workspaceRoot}' && git fetch origin main && git checkout -b <new-branch> origin/main`;\n }\n\n /**\n * ROW 13's deny. It NAMES the operator the agent typed, because the fix is a one-character edit\n * and an agent told only \"use `&&`\" has to diff the two spellings itself to find where.\n */\n private compositionMessage(prefix: CurePrefix): string {\n return `Your cure is joined with \\`${prefix.operator}\\` — the work runs even if the pull fails. `\n + 'Use `&&` so it is skipped:\\n'\n + '\\n pnpm wp-checkout-clean-main && <your command>\\n\\n'\n + 'Or run the cure alone and re-issue your command in the next call.';\n }\n\n private pairingMessage(ctx: BashContext): string {\n const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\\n');\n // Deliberately SHORT. The incident that bought this guard (a main 157 commits behind; the\n // downgrade the reverted shim then prescribed) is maintainer material and lives in the class\n // docblock above — the reader of THIS text needs only what changes what they type.\n return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had — '\n + 'stale files, plus a reverted @webpieces pin and guard shim, so the drift guard then '\n + 'reports the drift BACKWARDS. Go to main with the one command that also pulls it:\\n' + steps;\n }\n\n\n\n\n\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, the same way an L0 block does. The doc is written\n // LAZILY here rather than up front: only a blocked agent needs it, and this is the one path\n // that knows the row it should be opened at.\n const row = matrixL2Row(reason).row;\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), 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('stale-main-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 // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n}\n"]}
|
|
@@ -12,18 +12,29 @@
|
|
|
12
12
|
* One source of truth on purpose (same reason as MergedBranchMessage): the cure is an instruction the
|
|
13
13
|
* AI follows literally, so two drifting copies mean two behaviours for one repo state.
|
|
14
14
|
*
|
|
15
|
-
* Cure 1 is
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
15
|
+
* Cure 1 is `pnpm wp-checkout-clean-main`, the ONE command this repo names for "make local `main`
|
|
16
|
+
* current" — and it is now spelled that way here because it was not, which is the defect this file's
|
|
17
|
+
* last change fixed. Fleet-wide, this rule handed agents FOUR different refresh-main cures across 238
|
|
18
|
+
* prescriptions and the sanctioned one appeared in 6 of them; CLAUDE.md meanwhile names
|
|
19
|
+
* `pnpm wp-checkout-clean-main` and explicitly forbids hand-rolling the `git checkout main && git pull`
|
|
20
|
+
* pair, because that is the same command minus the orphan-directory sweep. Agents caught between the
|
|
21
|
+
* two authorities improvised hybrids — four distinct spellings observed — each costing a blocked round
|
|
22
|
+
* trip. A cure is an instruction the AI follows LITERALLY, so there is exactly one spelling of it.
|
|
23
|
+
*
|
|
24
|
+
* It still fast-forwards rather than merging (the command pulls `--ff-only`), which is what keeps this
|
|
25
|
+
* message clear of the merge redirect-how-to-merge-main exists to prevent, and it is still CLEAN-TREE
|
|
26
|
+
* ONLY. Cure 2 (`git checkout -b`) is what makes the message correct on a dirty tree, so both are
|
|
27
|
+
* printed and each is labelled.
|
|
28
|
+
*
|
|
29
|
+
* NOTE the intents stay SEPARATE. Cure 2 is not a spelling of cure 1: refreshing `main` in place and
|
|
30
|
+
* branching off fresh are different moves with different tree-state requirements, and collapsing them
|
|
31
|
+
* would hand a dirty tree a cure it cannot run.
|
|
21
32
|
*/
|
|
22
33
|
export declare class StaleMainMessage {
|
|
23
34
|
private readonly treeRoot;
|
|
24
35
|
/**
|
|
25
36
|
* `treeRoot` is the tree the guard JUDGED (which is NOT the shell's cwd when the command carried
|
|
26
|
-
* a leading `cd`). Pass it and
|
|
37
|
+
* a leading `cd`). Pass it and each cure is rendered as `cd <treeRoot> && <cure>`, naming the
|
|
27
38
|
* directory outright.
|
|
28
39
|
*
|
|
29
40
|
* WHY that matters here specifically: in the field this guard told an agent working in a worktree
|
|
@@ -36,7 +47,7 @@ export declare class StaleMainMessage {
|
|
|
36
47
|
* The diagnosis + BOTH cures.
|
|
37
48
|
*
|
|
38
49
|
* Two cures rather than one, and that is what let the dirty valve be deleted. The guard used to
|
|
39
|
-
* fail open on a dirty tree because the only cure it printed was
|
|
50
|
+
* fail open on a dirty tree because the only cure it printed was the in-place pull, which is
|
|
40
51
|
* not a clean fast-forward when there are local modifications — so the block was suppressed to
|
|
41
52
|
* avoid prescribing something that could not run.
|
|
42
53
|
*
|
|
@@ -16,18 +16,29 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
16
16
|
* One source of truth on purpose (same reason as MergedBranchMessage): the cure is an instruction the
|
|
17
17
|
* AI follows literally, so two drifting copies mean two behaviours for one repo state.
|
|
18
18
|
*
|
|
19
|
-
* Cure 1 is
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
19
|
+
* Cure 1 is `pnpm wp-checkout-clean-main`, the ONE command this repo names for "make local `main`
|
|
20
|
+
* current" — and it is now spelled that way here because it was not, which is the defect this file's
|
|
21
|
+
* last change fixed. Fleet-wide, this rule handed agents FOUR different refresh-main cures across 238
|
|
22
|
+
* prescriptions and the sanctioned one appeared in 6 of them; CLAUDE.md meanwhile names
|
|
23
|
+
* `pnpm wp-checkout-clean-main` and explicitly forbids hand-rolling the `git checkout main && git pull`
|
|
24
|
+
* pair, because that is the same command minus the orphan-directory sweep. Agents caught between the
|
|
25
|
+
* two authorities improvised hybrids — four distinct spellings observed — each costing a blocked round
|
|
26
|
+
* trip. A cure is an instruction the AI follows LITERALLY, so there is exactly one spelling of it.
|
|
27
|
+
*
|
|
28
|
+
* It still fast-forwards rather than merging (the command pulls `--ff-only`), which is what keeps this
|
|
29
|
+
* message clear of the merge redirect-how-to-merge-main exists to prevent, and it is still CLEAN-TREE
|
|
30
|
+
* ONLY. Cure 2 (`git checkout -b`) is what makes the message correct on a dirty tree, so both are
|
|
31
|
+
* printed and each is labelled.
|
|
32
|
+
*
|
|
33
|
+
* NOTE the intents stay SEPARATE. Cure 2 is not a spelling of cure 1: refreshing `main` in place and
|
|
34
|
+
* branching off fresh are different moves with different tree-state requirements, and collapsing them
|
|
35
|
+
* would hand a dirty tree a cure it cannot run.
|
|
25
36
|
*/
|
|
26
37
|
class StaleMainMessage {
|
|
27
38
|
treeRoot;
|
|
28
39
|
/**
|
|
29
40
|
* `treeRoot` is the tree the guard JUDGED (which is NOT the shell's cwd when the command carried
|
|
30
|
-
* a leading `cd`). Pass it and
|
|
41
|
+
* a leading `cd`). Pass it and each cure is rendered as `cd <treeRoot> && <cure>`, naming the
|
|
31
42
|
* directory outright.
|
|
32
43
|
*
|
|
33
44
|
* WHY that matters here specifically: in the field this guard told an agent working in a worktree
|
|
@@ -42,7 +53,7 @@ class StaleMainMessage {
|
|
|
42
53
|
* The diagnosis + BOTH cures.
|
|
43
54
|
*
|
|
44
55
|
* Two cures rather than one, and that is what let the dirty valve be deleted. The guard used to
|
|
45
|
-
* fail open on a dirty tree because the only cure it printed was
|
|
56
|
+
* fail open on a dirty tree because the only cure it printed was the in-place pull, which is
|
|
46
57
|
* not a clean fast-forward when there are local modifications — so the block was suppressed to
|
|
47
58
|
* avoid prescribing something that could not run.
|
|
48
59
|
*
|
|
@@ -53,7 +64,7 @@ class StaleMainMessage {
|
|
|
53
64
|
* path, and no state in which the printed cure is unrunnable.
|
|
54
65
|
*/
|
|
55
66
|
common(behindCount) {
|
|
56
|
-
const
|
|
67
|
+
const refresh = 'pnpm wp-checkout-clean-main';
|
|
57
68
|
const branch = 'git checkout -b <new-branch> origin/main';
|
|
58
69
|
return [
|
|
59
70
|
`You are on main and main is ${behindCount} commit(s) behind origin/main.`,
|
|
@@ -62,15 +73,16 @@ class StaleMainMessage {
|
|
|
62
73
|
'longer exists upstream.',
|
|
63
74
|
'',
|
|
64
75
|
'Run ONE of these, then retry:',
|
|
65
|
-
` 1. ${this.treeRoot !== '' ? (0, rules_config_1.atRoot)(this.treeRoot,
|
|
66
|
-
' Updates main in place
|
|
67
|
-
'
|
|
76
|
+
` 1. ${this.treeRoot !== '' ? (0, rules_config_1.atRoot)(this.treeRoot, refresh) : refresh}`,
|
|
77
|
+
' Updates main in place — checkout, pull, reap dead branches/worktrees, sweep orphan',
|
|
78
|
+
' directories. CLEAN TREE ONLY: with tracked modifications the pull is not a',
|
|
79
|
+
' fast-forward and it will refuse.',
|
|
68
80
|
` 2. ${this.treeRoot !== '' ? (0, rules_config_1.atRoot)(this.treeRoot, branch) : branch}`,
|
|
69
81
|
' Works with UNCOMMITTED CHANGES — they come with you onto the new branch, and you',
|
|
70
82
|
' land on current code. Prefer this one if you have edits in flight, or if 1 refused.',
|
|
71
83
|
'',
|
|
72
84
|
'If 1 fatals with "Cannot fast-forward to multiple branches", .git/FETCH_HEAD holds a',
|
|
73
|
-
'duplicate entry — clear it with `git fetch --prune origin main`, then
|
|
85
|
+
'duplicate entry — clear it with `git fetch --prune origin main`, then run 1 again.',
|
|
74
86
|
'If 2 refuses because origin/main changed the same files you edited, run `git stash`',
|
|
75
87
|
'(never blocked), then 2 again, then `git stash pop`.',
|
|
76
88
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stale-main-message.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/stale-main-message.ts"],"names":[],"mappings":";;;AAAA,0DAAiD;AAEjD
|
|
1
|
+
{"version":3,"file":"stale-main-message.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/stale-main-message.ts"],"names":[],"mappings":";;;AAAA,0DAAiD;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAa,gBAAgB;IAWI;IAV7B;;;;;;;;;OASG;IACH,YAA6B,WAAmB,EAAE;QAArB,aAAQ,GAAR,QAAQ,CAAa;IAAG,CAAC;IAEtD;;;;;;;;;;;;;OAaG;IACK,MAAM,CAAC,WAAmB;QAC9B,MAAM,OAAO,GAAG,6BAA6B,CAAC;QAC9C,MAAM,MAAM,GAAG,0CAA0C,CAAC;QAC1D,OAAO;YACH,+BAA+B,WAAW,gCAAgC;YAC1E,GAAG,CAAC,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,sBAAsB,IAAI,CAAC,QAAQ,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YACvF,wFAAwF;YACxF,yBAAyB;YACzB,EAAE;YACF,+BAA+B;YAC/B,QAAQ,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,IAAA,qBAAM,EAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE;YACzE,yFAAyF;YACzF,iFAAiF;YACjF,uCAAuC;YACvC,QAAQ,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,IAAA,qBAAM,EAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE;YACvE,uFAAuF;YACvF,0FAA0F;YAC1F,EAAE;YACF,sFAAsF;YACtF,oFAAoF;YACpF,qFAAqF;YACrF,sDAAsD;SACzD,CAAC;IACN,CAAC;IAED,QAAQ,CAAC,WAAmB;QACxB,OAAO,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC;YACnC,EAAE;YACF,uCAAuC;YACvC,2FAA2F;YAC3F,mDAAmD;YACnD,oEAAoE;YACpE,0FAA0F;SAC7F,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,CAAC;CAEJ;AA/DD,4CA+DC","sourcesContent":["import { atRoot } from '@webpieces/rules-config';\n\n/**\n * The \"you are on a stale main\" text. ONE consumer today:\n *\n * - read-stale-guard blocks the Read tool → {@link StaleMainMessage.forReads}\n *\n * It had a second consumer, `forBash`, for the days when stale-main-bash-guard blocked CONTENT reads\n * on a stale main. That guard judges the SAME state again today (rows 6/7 — `main`, known behind), but\n * its verdict shape is different: default-deny plus the row 4 skip list rather than a per-file call,\n * and its cure is the branch form alone because a Bash session cannot be cured by staying put. So it\n * carries its own message and this variant was deleted rather than left as a second spelling.\n *\n * One source of truth on purpose (same reason as MergedBranchMessage): the cure is an instruction the\n * AI follows literally, so two drifting copies mean two behaviours for one repo state.\n *\n * Cure 1 is `pnpm wp-checkout-clean-main`, the ONE command this repo names for \"make local `main`\n * current\" — and it is now spelled that way here because it was not, which is the defect this file's\n * last change fixed. Fleet-wide, this rule handed agents FOUR different refresh-main cures across 238\n * prescriptions and the sanctioned one appeared in 6 of them; CLAUDE.md meanwhile names\n * `pnpm wp-checkout-clean-main` and explicitly forbids hand-rolling the `git checkout main && git pull`\n * pair, because that is the same command minus the orphan-directory sweep. Agents caught between the\n * two authorities improvised hybrids — four distinct spellings observed — each costing a blocked round\n * trip. A cure is an instruction the AI follows LITERALLY, so there is exactly one spelling of it.\n *\n * It still fast-forwards rather than merging (the command pulls `--ff-only`), which is what keeps this\n * message clear of the merge redirect-how-to-merge-main exists to prevent, and it is still CLEAN-TREE\n * ONLY. Cure 2 (`git checkout -b`) is what makes the message correct on a dirty tree, so both are\n * printed and each is labelled.\n *\n * NOTE the intents stay SEPARATE. Cure 2 is not a spelling of cure 1: refreshing `main` in place and\n * branching off fresh are different moves with different tree-state requirements, and collapsing them\n * would hand a dirty tree a cure it cannot run.\n */\nexport class StaleMainMessage {\n /**\n * `treeRoot` is the tree the guard JUDGED (which is NOT the shell's cwd when the command carried\n * a leading `cd`). Pass it and each cure is rendered as `cd <treeRoot> && <cure>`, naming the\n * directory outright.\n *\n * WHY that matters here specifically: in the field this guard told an agent working in a worktree\n * to `git pull` — which, run from wherever the next tool call happened to start, meant pulling the\n * PRIMARY CLONE, a tree that agent had been explicitly instructed not to touch. A remedy must\n * never mutate a tree other than the one the command targeted, and naming it is how you ensure it.\n */\n constructor(private readonly treeRoot: string = '') {}\n\n /**\n * The diagnosis + BOTH cures.\n *\n * Two cures rather than one, and that is what let the dirty valve be deleted. The guard used to\n * fail open on a dirty tree because the only cure it printed was the in-place pull, which is\n * not a clean fast-forward when there are local modifications — so the block was suppressed to\n * avoid prescribing something that could not run.\n *\n * The row always had a second cure (`git checkout -b <new> origin/main`), and that one works\n * DIRTY: it carries uncommitted changes onto the new branch and lands you on current code, which\n * is the whole objective. Printing it unconditionally means the message is correct in both tree\n * states, so nothing has to detect dirtiness — no extra `git status --porcelain` on the block\n * path, and no state in which the printed cure is unrunnable.\n */\n private common(behindCount: string): string[] {\n const refresh = 'pnpm wp-checkout-clean-main';\n const branch = 'git checkout -b <new-branch> origin/main';\n return [\n `You are on main and main is ${behindCount} commit(s) behind origin/main.`,\n ...(this.treeRoot !== '' ? [`Evaluated against: ${this.treeRoot} (branch main)`] : []),\n 'Anything you read here is STALE, and every plan built from it is built on code that no',\n 'longer exists upstream.',\n '',\n 'Run ONE of these, then retry:',\n ` 1. ${this.treeRoot !== '' ? atRoot(this.treeRoot, refresh) : refresh}`,\n ' Updates main in place — checkout, pull, reap dead branches/worktrees, sweep orphan',\n ' directories. CLEAN TREE ONLY: with tracked modifications the pull is not a',\n ' fast-forward and it will refuse.',\n ` 2. ${this.treeRoot !== '' ? atRoot(this.treeRoot, branch) : branch}`,\n ' Works with UNCOMMITTED CHANGES — they come with you onto the new branch, and you',\n ' land on current code. Prefer this one if you have edits in flight, or if 1 refused.',\n '',\n 'If 1 fatals with \"Cannot fast-forward to multiple branches\", .git/FETCH_HEAD holds a',\n 'duplicate entry — clear it with `git fetch --prune origin main`, then run 1 again.',\n 'If 2 refuses because origin/main changed the same files you edited, run `git stash`',\n '(never blocked), then 2 again, then `git stash pop`.',\n ];\n }\n\n forReads(behindCount: string): string {\n return this.common(behindCount).concat([\n '',\n 'Still allowed while this block is up:',\n ' - Bash that does not read repo files: builds, tests, installs, the pull itself, and all',\n ' git/gh METADATA (status|log|diff|show|branch)',\n ' - All Write/Edit (feature-branch-guard governs those separately)',\n ' - Reading and editing webpieces.config.json (set read-stale-guard mode OFF to disable)',\n ]).join('\\n');\n }\n\n}\n"]}
|