@webpieces/ai-hook-rules 0.4.684 → 0.4.686
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/l2-doc.js +35 -21
- package/src/core/l2-doc.js.map +1 -1
- package/src/core/l2-rows.d.ts +8 -5
- package/src/core/l2-rows.js +26 -17
- package/src/core/l2-rows.js.map +1 -1
- package/src/core/rules/feature-branch-guard.d.ts +21 -1
- package/src/core/rules/feature-branch-guard.js +21 -1
- package/src/core/rules/feature-branch-guard.js.map +1 -1
- package/src/core/rules/main-freshness.d.ts +35 -0
- package/src/core/rules/main-freshness.js +53 -0
- package/src/core/rules/main-freshness.js.map +1 -0
- package/src/core/rules/merged-branch-bash-guard.js +1 -1
- package/src/core/rules/merged-branch-bash-guard.js.map +1 -1
- package/src/core/rules/merged-branch-message.js +2 -1
- package/src/core/rules/merged-branch-message.js.map +1 -1
- package/src/core/rules/read-stale-guard.d.ts +5 -3
- package/src/core/rules/read-stale-guard.js +10 -24
- package/src/core/rules/read-stale-guard.js.map +1 -1
- package/src/core/rules/recovery-allowlist.d.ts +32 -1
- package/src/core/rules/recovery-allowlist.js +79 -21
- package/src/core/rules/recovery-allowlist.js.map +1 -1
- package/src/core/rules/shell-segment-scan.d.ts +10 -1
- package/src/core/rules/shell-segment-scan.js +9 -1
- package/src/core/rules/shell-segment-scan.js.map +1 -1
- package/src/core/rules/stale-main-bash-guard.d.ts +73 -47
- package/src/core/rules/stale-main-bash-guard.js +109 -83
- package/src/core/rules/stale-main-bash-guard.js.map +1 -1
- package/src/core/rules/stale-main-message.d.ts +4 -3
- package/src/core/rules/stale-main-message.js +4 -3
- 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,i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C,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;AAjND,wDAiNC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, 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';\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 * ── ROW 5: you are on `main`, and that is the whole finding ──────────────────────────────────────\n *\n * The second half USED to ask the main-sync cache whether `main` was BEHIND, and blocked only\n * CONTENT-READING Bash when it was. Both halves of that were wrong, and the table always said so —\n * row 5 reads `B E` / on `main` / block, with the cure `git checkout -b <new> origin/main`.\n *\n * FRESHNESS IS THE WRONG QUESTION *for the block*, though it is the reason the block costs nothing.\n * `main` is not a place to WORK even when it is perfectly current, so the cure is not `git pull` but\n * a new branch; gating the block on the cache meant a current `main` was treated as a fine place to\n * run a build, an installer or a codegen step. And when `main` IS behind, the other half applies —\n * reads taken here are out of date, so there is no state in which staying put is the better move.\n * That is what the deny text says out loud, so \"I was only reading\" stops being an argument.\n *\n * THE CACHE IS THE WRONG PRECONDITION. It is written by a fire-and-forget refresher that populates it\n * for the NEXT call, so the FIRST call of every session has none — and in a multi-worktree repo\n * another tree can hold the refresh lock indefinitely. A block that needs the cache is off exactly\n * when a session is starting, which is precisely when an agent is still standing on `main`. Row 5's\n * Write/Edit half (feature-branch-guard) has always been one `git rev-parse` for this reason; this is\n * `B` being brought into line with `E`, which is the table's own rule, not a new policy.\n *\n * A CONTENT-READ BLOCKLIST COULD NOT HAVE CAUGHT THE WRITES. Enumerating readers catches `cat` and\n * `grep`; it structurally cannot catch `pnpm install`, `npx expo install`, a formatter, codegen or a\n * `>` redirect — commands whose stated purpose is something else and whose effect is to modify\n * tracked files. On `main` the polarity is therefore DEFAULT-DENY plus row 4's skip list, the same\n * shape merged-branch-bash-guard uses for state B, and via the same shared RecoveryAllowlist.\n *\n * BLOCKED anything on `main` that is not on the skip list — builds, tests, installers,\n * formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.\n * ALLOWED everything that gets you OUT or tells you where you are: `git checkout -b <new>\n * origin/main`, `git switch`, `git pull`/`fetch`, `git status|log|diff|show|branch`,\n * `gh pr view|list|status|checks`, `git stash`, every `wp-*` bin, installs.\n *\n * FAIL-OPEN is preserved where it still means anything: branch undeterminable → allow. The cache\n * valves (`no-sync-cache`, `origin-main-unknown`) are gone from THIS guard because it no longer reads\n * the cache. 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\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 block Bash on ' +\n 'main outright — allowlisting only the commands that get you off it — so a session neither ' +\n 'lands on main nor works there, whether or not main happens to be current.';\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 on main: the Read tool, so you can read main while you PLAN (read-stale-guard closes it only once main falls BEHIND origin/main, 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, gh pr view|list|status|checks, git stash, 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 // ROW 5 — on `main`. NO CACHE IS READ ON THIS PATH, and that is the change.\n //\n // The old ladder asked the cache \"is main BEHIND?\" and only then blocked, and only content\n // READS. That made the whole Bash half of row 5 conditional on freshness, which is the wrong\n // question twice over:\n //\n // 1. Freshness is irrelevant to whether you should be working here. `main` is not a place to\n // work even when it is perfectly current — the cure is the same either way, and it is not\n // `git pull`, it is `git checkout -b`. Row 5's cure has always said so.\n // 2. The cache is populated by a FIRE-AND-FORGET refresher that fills it for the NEXT call,\n // so on the first call of every session there is none — and in a multi-worktree repo\n // another tree can hold the refresh lock indefinitely. A block that needs the cache is a\n // block that is off exactly when a session is starting, which is when an agent is most\n // likely to still be standing on `main`.\n //\n // So this is now one `git rev-parse` and a text scan, both of which fire on call #1 — the same\n // arrangement that has always governed row 5's Write/Edit half (feature-branch-guard). `B`\n // tracking `E` here is the table's own rule, not a new policy.\n //\n // The polarity flips with it: on `main` this is DEFAULT-DENY plus row 4's skip list, where it\n // used to be default-allow plus a content-read blocklist. That is what makes it catch the\n // commands a blocklist structurally cannot — an installer, a formatter or a codegen step that\n // WRITES tracked files while its stated purpose is something else. Blocking those was never\n // going to come from enumerating readers.\n return this.block(ctx, branch, 'on-main', this.onMainMessage(ctx.workspaceRoot), '-');\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 row 5 deny. Deliberately SHORT.\n *\n * The oldest version opened by reporting how many commits behind `main` was, which invited\n * exactly the wrong cure — an agent that reads \"behind\" reaches for `git pull`, ends up on a\n * CURRENT `main`, and is still on `main`. The finding is the branch, so that is said first.\n *\n * The version after that swung too far the other way: a flat \"`main` is not a place to work\",\n * printed in answer to a `grep`. That reads as overreach precisely because it is not true of\n * READING — an agent that has just landed a PR and is orienting itself on `main` is doing the\n * right thing, and the Read tool is deliberately left open for it (read-stale-guard closes it\n * only once `main` falls BEHIND). So the text now says three things the flat version could not:\n *\n * 1. reading `main` to PLAN is legitimate, and Bash is default-deny here only because a\n * command's stated purpose never says whether it also WRITES (row 5 use case 10);\n * 2. the FEATURE BRANCH is the unit of work — the positive form of the rule;\n * 3. STALENESS, which is the strongest argument and used to be missing entirely: if local\n * `main` is behind, the reads are out of date too, so \"I am only reading\" is not a reason\n * to skip the cure. The cure FETCHES, so it makes the reads true as well as moving you off\n * `main` — which is why judging on the branch alone, before freshness is known, is the\n * correct call rather than a crude approximation.\n */\n private onMainMessage(workspaceRoot: string): string {\n return 'Blocked: you are on `main`. Reading main to PLAN is fine — the Read tool stays open '\n + \"while main is current; Bash is default-deny here only because a command's stated \"\n + 'purpose never says whether it also WRITES. What main is not is a place to WORK: the '\n + 'feature branch is the unit of work, reviewable and revertable. Judged from the branch '\n + 'alone, before freshness is known — right either way: if main is BEHIND origin/main '\n + 'your reads are out of date too, so planning here is wasted as well. The cure fetches, '\n + 'so it makes 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;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2FG;AACH,MAAa,sBAAuB,SAAQ,wBAAoC;IAC5E,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,uBAAuB,EAAE,qCAAsB,CAAC,CAAC,CAAC,CAAC;IAE9F,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC;IAC/B,QAAQ,GAAG,IAAI,4BAAY,EAAE,CAAC;IAC9B,QAAQ,GAAG,IAAI,qCAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC/D,kGAAkG;IAClG,iFAAiF;IAChE,YAAY,GAAG,IAAI,sCAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACpE,iGAAiG;IAChF,SAAS,GAAG,IAAI,8BAAa,E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,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;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"]}
|
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
* - read-stale-guard blocks the Read tool → {@link StaleMainMessage.forReads}
|
|
5
5
|
*
|
|
6
6
|
* It had a second consumer, `forBash`, for the days when stale-main-bash-guard blocked CONTENT reads
|
|
7
|
-
* on a stale main. That guard
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* on a stale main. That guard judges the SAME state again today (rows 6/7 — `main`, known behind), but
|
|
8
|
+
* its verdict shape is different: default-deny plus the row 4 skip list rather than a per-file call,
|
|
9
|
+
* and its cure is the branch form alone because a Bash session cannot be cured by staying put. So it
|
|
10
|
+
* carries its own message and this variant was deleted rather than left as a second spelling.
|
|
10
11
|
*
|
|
11
12
|
* One source of truth on purpose (same reason as MergedBranchMessage): the cure is an instruction the
|
|
12
13
|
* AI follows literally, so two drifting copies mean two behaviours for one repo state.
|
|
@@ -8,9 +8,10 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
8
8
|
* - read-stale-guard blocks the Read tool → {@link StaleMainMessage.forReads}
|
|
9
9
|
*
|
|
10
10
|
* It had a second consumer, `forBash`, for the days when stale-main-bash-guard blocked CONTENT reads
|
|
11
|
-
* on a stale main. That guard
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* on a stale main. That guard judges the SAME state again today (rows 6/7 — `main`, known behind), but
|
|
12
|
+
* its verdict shape is different: default-deny plus the row 4 skip list rather than a per-file call,
|
|
13
|
+
* and its cure is the branch form alone because a Bash session cannot be cured by staying put. So it
|
|
14
|
+
* carries its own message and this variant was deleted rather than left as a second spelling.
|
|
14
15
|
*
|
|
15
16
|
* One source of truth on purpose (same reason as MergedBranchMessage): the cure is an instruction the
|
|
16
17
|
* AI follows literally, so two drifting copies mean two behaviours for one repo state.
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;GAoBG;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,IAAI,GAAG,gCAAgC,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,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE;YACnE,sFAAsF;YACtF,2CAA2C;YAC3C,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,mFAAmF;YACnF,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;AA9DD,4CA8DC","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 `--ff-only` deliberately. A plain `git pull` on a stale main can start a MERGE, which is\n * the one thing redirect-how-to-merge-main exists to keep an AI away from; `--ff-only` either\n * fast-forwards or fails loudly without touching anything. It used to be the ONLY cure printed, on the\n * strength of \"the block only fires when the tree is clean and behind\" — which stopped being true when\n * the dirty valve was deleted, and was the reason that valve existed. Cure 2 (`git checkout -b`) is\n * what makes the message correct on a dirty tree, so both are printed and each is labelled.\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 the cure is rendered as `cd <treeRoot> && git pull …`, 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 `git pull --ff-only`, 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 pull = 'git pull --ff-only origin 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, pull) : pull}`,\n ' Updates main in place. CLEAN TREE ONLY — with local modifications this is not a',\n ' fast-forward and git will refuse it.',\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 pull 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"]}
|