@webpieces/agent-workflow-rules 0.4.1028 → 0.4.1030
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 +7 -7
- package/src/core/l1-rows.js +1 -1
- package/src/core/l1-rows.js.map +1 -1
- package/src/core/l2-rows.js +4 -4
- package/src/core/l2-rows.js.map +1 -1
- package/src/core/rules/feature-branch-guard.js +1 -1
- package/src/core/rules/feature-branch-guard.js.map +1 -1
- package/src/core/rules/pr-creation-or-push-guard.js +4 -4
- package/src/core/rules/pr-creation-or-push-guard.js.map +1 -1
- package/src/core/rules/redirect-how-to-merge-main.js +2 -2
- package/src/core/rules/redirect-how-to-merge-main.js.map +1 -1
- package/src/core/rules/whole-repo-build-guard.js +2 -2
- package/src/core/rules/whole-repo-build-guard.js.map +1 -1
- package/src/core/version-sync.js +2 -2
- package/src/core/version-sync.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAmE;AACnE,mDAA2D;AAE3D,sEAAsJ;AAGtJ,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAC/C,uEAAiE;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AACH,MAAa,sBAAuB,SAAQ,2BAAoC;IAC5E,wFAAwF;IACxF,mGAAmG;IACnG,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,sBAAsB,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAC7F,QAAQ,GAA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I,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IAEO,kBAAkB,CAAC,MAAkB;QACzC,OAAO;YACH,MAAM,CAAC,MAAM,EAAE;YACf,qFAAqF;YACrF,sFAAsF;YACtF,EAAE;YACF,GAAG,IAAA,wCAAmB,EAAC,MAAM,CAAC,MAAM,CAAC;YACrC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;SAC5D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACJ;AAtTD,wDAsTC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { SyncFlowGuidance, Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig } from \"../../configs/main-sync-guard-configs\";\nimport { BranchIdentity, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\nimport { findUnvalidatedMerge } from './merge-in-progress-guard';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * 5. Branch more than `featureBranchMaxCommitsBehind` commits behind origin/main → block: update\n * from main (L2 row 15, issue #1431). Exempt while a 3-point merge is being resolved (row 3).\n * States 2–5 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n private readonly branches = new BranchIdentity();\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, or the branch is too far behind main, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n if (this.branches.isHotfix(branch)) return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)', this.treeSummary(judgedRoot)); // L2 row 14 (#1371): every state below cures BY main\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, branch, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\n // State 5: too far behind origin/main (L2 row 15). `null` = keep judging.\n const tooFarBehind = this.judgeBranchDistance(ctx, judged, status, cache);\n if (tooFarBehind !== null) return tooFarBehind;\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval. Only the merged flag depends on the\n // forge (fork point and collision are pure git), so an unreachable forge is an abstention.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * L2 ROW 15 (issue #1431): a FEATURE branch more than `featureBranchMaxCommitsBehind` commits behind\n * origin/main. Without it a branch could go stale for its whole life — old `@webpieces` pins, old\n * generated graphs, old neighbouring code — and only meet main at PR time, when the merge is as large\n * as it can get. Only Write/Edit are stopped (this guard is file-scoped and never sees Read or Bash),\n * so the agent can still look around and run the cure.\n *\n * Returns null when this row does not decide the call, so check() keeps judging (the healthy-branch\n * tail). An UNKNOWN distance — an older cache, or git could not count — also returns null: never\n * block on data that was not established, and the tail still logs the call.\n *\n * The threshold is read straight from config, with NO fallback: the field is schema-required, so a\n * config without it never loaded (.claude/rules/no-rule-defaults.md).\n */\n private judgeBranchDistance(ctx: FileContext, judged: JudgedTree, status: MainSyncStatus, cache: string): readonly Violation[] | null {\n const behind = status.headCommitsBehind;\n const max = this.config.featureBranchMaxCommitsBehind;\n if (behind === null || behind <= max) return null;\n const distance = `${cache} behind=${String(behind)} max=${String(max)}`;\n // Row 3: a 3-point merge is being resolved in this tree. The update this row demands is the\n // thing in progress, so blocking the edits that finish it would wedge the cure.\n if (findUnvalidatedMerge(judged.root) !== null) return this.exempt(ctx, judged.branch, 'merge-in-progress (L4 owns this state)', distance);\n return this.block(ctx, judged.branch, 'feature-branch-too-far-behind', this.tooFarBehindMessage(judged, behind, max, status.openPr), distance);\n }\n\n /**\n * The row-15 cure, told for the PR state the cache knows. An open PR removes the choice:\n * `wp-start-update` refuses there, so only the PR flow is printed. With no PR KNOWN (`openPr` is ''\n * both for \"none\" and for \"the forge could not be asked\") both are printed, with the condition.\n */\n private tooFarBehindMessage(judged: JudgedTree, behind: number, max: number, openPr: string): string {\n const lines = [\n judged.header(),\n `Blocked: \\`${judged.branch}\\` is ${String(behind)} commits behind origin/main, more than`\n + ` branch-state-guard.featureBranchMaxCommitsBehind=${String(max)}. Update from main before editing`\n + ' further, so you build and test against current code. Reads and Bash are still allowed.',\n ];\n if (openPr !== '') {\n lines.push(`An open PR (#${openPr}) tracks this branch, so update through the PR flow: ${judged.pnpmCure('wp-start-upsert-pr')}`);\n } else {\n lines.push(`No PR tracks this branch: ${judged.pnpmCure('wp-start-update')}`);\n lines.push(`If a PR does track it, use ${judged.pnpmCure('wp-start-upsert-pr')} instead (wp-start-update refuses there).`);\n }\n return lines.join('\\n');\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */\n private exempt(ctx: FileContext, branch: string, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, cache);\n return [];\n }\n\n private block(ctx: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n\n /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAAmE;AACnE,mDAA2D;AAE3D,sEAAsJ;AAGtJ,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,0DAAwD;AACxD,0DAA6D;AAC7D,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAC/C,uEAAiE;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AACH,MAAa,sBAAuB,SAAQ,2BAAoC;IAC5E,wFAAwF;IACxF,mGAAmG;IACnG,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,sBAAsB,EAAE,oCAAsB,CAAC,CAAC,CAAC,CAAC;IAC7F,QAAQ,GAAG,IAAI,mCAAc,EAAE,CAAC;IAExC,WAAW,GAAG,kHAAkH,CAAC;IACxH,KAAK,GAAG,CAAC,MAAM,CAAC,CAAC;IACjB,cAAc,GAAG;QAC/B,sBAAsB,EAAE,wBAAwB;QAChD,kBAAkB,EAAE,iDAA4B;KACnD,CAAC;IACO,OAAO,GAAG,IAAI,sBAAO,CAC1B,oDAAoD,EACpD,2EAA2E,EAC3E;QACI,IAAI,qBAAM,CAAC,4EAA4E,EAAE,IAAI,CAAC;QAC9F,IAAI,qBAAM,CAAC,4ZAA4Z,CAAC;QACxa,IAAI,qBAAM,CAAC,kLAAkL,CAAC;KACjM,CACJ,CAAC;IAEF,KAAK,CAAC,GAAgB;QAClB,2FAA2F;QAC3F,IAAI,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YAClC,GAAG,MAAM,CAAC,QAAQ,CAAC,oBAAoB,CAAC,iCAAiC;SAC5E,CAAC,CAAC;QACH,6FAA6F;QAC7F,2FAA2F;QAC3F,2DAA2D;QAC3D,MAAM,QAAQ,GAAG,IAAI,+BAAgB,EAAE,CAAC;QACxC,+FAA+F;QAC/F,0EAA0E;QAC1E,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YAChB,OAAO,MAAM;iBACR,MAAM,CAAC;gBACJ,gBAAgB,MAAM,iEAAiE;gBACvF,gEAAgE;gBAChE,EAAE;aACL,CAAC;iBACD,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;iBACzB,MAAM,CAAC,CAAC,EAAE,EAAE,GAAG,QAAQ,CAAC,gBAAgB,EAAE,CAAC,CAAC;iBAC5C,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;iBAClB,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,MAAM;aACR,MAAM,CAAC;YACJ,yFAAyF;YACzF,kEAAkE;YAClE,EAAE;SACL,CAAC;aACD,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;aACxB,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;aAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IAEO,kBAAkB,CAAC,MAAkB;QACzC,OAAO;YACH,MAAM,CAAC,MAAM,EAAE;YACf,qFAAqF;YACrF,sFAAsF;YACtF,EAAE;YACF,GAAG,IAAA,wCAAmB,EAAC,MAAM,CAAC,MAAM,CAAC;YACrC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;SAC5D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACJ;AAtTD,wDAsTC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { SyncFlowGuidance, Option } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../../policy-keys';\nimport { BranchStateGuardConfig } from \"../../configs/main-sync-guard-configs\";\nimport { BranchIdentity, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { FileContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { FileRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '@webpieces/rules-config';\nimport { TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\nimport { findUnvalidatedMerge } from './merge-in-progress-guard';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * 5. Branch more than `featureBranchMaxCommitsBehind` commits behind origin/main → block: update\n * from main (L2 row 15, issue #1431). Exempt while a 3-point merge is being resolved (row 3).\n * States 2–5 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n private readonly branches = new BranchIdentity();\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, or the branch is too far behind main, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr <tracker> <number>` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n if (this.branches.isHotfix(branch)) return this.exempt(ctx, branch, 'hotfix-branch (cut from production; main is never merged in)', this.treeSummary(judgedRoot)); // L2 row 14 (#1371): every state below cures BY main\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, branch, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\n // State 5: too far behind origin/main (L2 row 15). `null` = keep judging.\n const tooFarBehind = this.judgeBranchDistance(ctx, judged, status, cache);\n if (tooFarBehind !== null) return tooFarBehind;\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval. Only the merged flag depends on the\n // forge (fork point and collision are pure git), so an unreachable forge is an abstention.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * L2 ROW 15 (issue #1431): a FEATURE branch more than `featureBranchMaxCommitsBehind` commits behind\n * origin/main. Without it a branch could go stale for its whole life — old `@webpieces` pins, old\n * generated graphs, old neighbouring code — and only meet main at PR time, when the merge is as large\n * as it can get. Only Write/Edit are stopped (this guard is file-scoped and never sees Read or Bash),\n * so the agent can still look around and run the cure.\n *\n * Returns null when this row does not decide the call, so check() keeps judging (the healthy-branch\n * tail). An UNKNOWN distance — an older cache, or git could not count — also returns null: never\n * block on data that was not established, and the tail still logs the call.\n *\n * The threshold is read straight from config, with NO fallback: the field is schema-required, so a\n * config without it never loaded (.claude/rules/no-rule-defaults.md).\n */\n private judgeBranchDistance(ctx: FileContext, judged: JudgedTree, status: MainSyncStatus, cache: string): readonly Violation[] | null {\n const behind = status.headCommitsBehind;\n const max = this.config.featureBranchMaxCommitsBehind;\n if (behind === null || behind <= max) return null;\n const distance = `${cache} behind=${String(behind)} max=${String(max)}`;\n // Row 3: a 3-point merge is being resolved in this tree. The update this row demands is the\n // thing in progress, so blocking the edits that finish it would wedge the cure.\n if (findUnvalidatedMerge(judged.root) !== null) return this.exempt(ctx, judged.branch, 'merge-in-progress (L4 owns this state)', distance);\n return this.block(ctx, judged.branch, 'feature-branch-too-far-behind', this.tooFarBehindMessage(judged, behind, max, status.openPr), distance);\n }\n\n /**\n * The row-15 cure, told for the PR state the cache knows. An open PR removes the choice:\n * `wp-start-update` refuses there, so only the PR flow is printed. With no PR KNOWN (`openPr` is ''\n * both for \"none\" and for \"the forge could not be asked\") both are printed, with the condition.\n */\n private tooFarBehindMessage(judged: JudgedTree, behind: number, max: number, openPr: string): string {\n const lines = [\n judged.header(),\n `Blocked: \\`${judged.branch}\\` is ${String(behind)} commits behind origin/main, more than`\n + ` branch-state-guard.featureBranchMaxCommitsBehind=${String(max)}. Update from main before editing`\n + ' further, so you build and test against current code. Reads and Bash are still allowed.',\n ];\n if (openPr !== '') {\n lines.push(`An open PR (#${openPr}) tracks this branch, so update through the PR flow: ${judged.pnpmCure('wp-start-upsert-pr')}`);\n } else {\n lines.push(`No PR tracks this branch: ${judged.pnpmCure('wp-start-update')}`);\n lines.push(`If a PR does track it, use ${judged.pnpmCure('wp-start-upsert-pr')} instead (wp-start-update refuses there).`);\n }\n return lines.join('\\n');\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n /** The policy does not apply to this branch at all — logged `ALLOW_EXEMPT`, never confused with an approval. */\n private exempt(ctx: FileContext, branch: string, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_EXEMPT', reason, cache);\n return [];\n }\n\n private block(ctx: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n return gitCheckout.branch(workspaceRoot);\n }\n\n /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
|
|
@@ -24,7 +24,7 @@ function fixHintFor(upsertPrCommand) {
|
|
|
24
24
|
'LANDING ON MAIN (a PR, prod-quality, reviewed):\n' +
|
|
25
25
|
` ${upsertPrCommand}\n` +
|
|
26
26
|
' It updates the branch from main (3-point merge) and runs the real build (nx affected), then\n' +
|
|
27
|
-
' instructs you to write summary.json and run `pnpm wp-finish-upsert-pr
|
|
27
|
+
' instructs you to write summary.json and run `pnpm wp-finish-upsert-pr <tracker> <number>`, which assembles the\n' +
|
|
28
28
|
' dashboard and creates/updates the PR — and pushes for you. A failing build = no push, no PR.\n\n' +
|
|
29
29
|
'JUST WANT IT ON THE SHARED DEV SERVER (no PR, not landing on main):\n' +
|
|
30
30
|
` ${rules_config_1.WP_START_PUSH_DEV} → ${rules_config_1.WP_BUILD_PUSH_DEV} → ${rules_config_1.WP_FINISH_PUSH_DEV}\n` +
|
|
@@ -33,12 +33,12 @@ function fixHintFor(upsertPrCommand) {
|
|
|
33
33
|
" feature branch never acquires another developer's commits, which is the whole reason the copy\n" +
|
|
34
34
|
' exists. Do NOT open a PR to main just to test something in dev.\n\n' +
|
|
35
35
|
'ON A /hotfix/ BRANCH (cut from the production sha, so it must NOT take main):\n' +
|
|
36
|
-
' pnpm wp-upsert-hotfix-pr
|
|
36
|
+
' pnpm wp-upsert-hotfix-pr <tracker> <number>\n' +
|
|
37
37
|
' One command: hotfix-ci (build + test), no merge from main, one fast-forward push, then it\n' +
|
|
38
38
|
' creates or updates the bannered PR to main and never auto-merges it.\n\n' +
|
|
39
39
|
'All of them push internally as child processes this hook never sees, so the gated commands are\n' +
|
|
40
40
|
'unaffected by this guard. There is nothing to paste or attest to; the commands do the work.\n' +
|
|
41
|
-
'A HUMAN who has personally inspected the work may run `pnpm wp-human-post-pr
|
|
41
|
+
'A HUMAN who has personally inspected the work may run `pnpm wp-human-post-pr <tracker> <number>` themselves.\n' +
|
|
42
42
|
'That is an interactive human attestation and visibly skips automated build/review. AI must\n' +
|
|
43
43
|
"never run it for the human or answer `human` on the human's behalf.\n" +
|
|
44
44
|
'Full branch → update → PR flow: READ the instruct-ai git-workflow doc at the absolute path on the violation line above.\n' +
|
|
@@ -130,7 +130,7 @@ class PrCreationOrPushGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
130
130
|
];
|
|
131
131
|
}
|
|
132
132
|
return [
|
|
133
|
-
new hook_runtime_1.Violation(1, truncate(ctx.command), `Manual push / direct PR is blocked — AI uses the gated flow (${this.upsertPrCommand}). A human may personally run pnpm wp-human-post-pr
|
|
133
|
+
new hook_runtime_1.Violation(1, truncate(ctx.command), `Manual push / direct PR is blocked — AI uses the gated flow (${this.upsertPrCommand}). A human may personally run pnpm wp-human-post-pr <tracker> <number>; AI never answers its attestation. Full flow: READ ${docPath}.`),
|
|
134
134
|
];
|
|
135
135
|
}
|
|
136
136
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pr-creation-or-push-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/pr-creation-or-push-guard.ts"],"names":[],"mappings":";;;AAAA,0DAAqM;AACrM,mDAA2D;AAI3D,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAElD,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAElD;;;;;;;;;GASG;AACH,mKAAmK;AACnK,SAAS,UAAU,CAAC,eAAuB;IACvC,OAAO,IAAI,sBAAO,CACd,8DAA8D,EAC9D,oGAAoG;QAChG,4BAA4B;QAC5B,mDAAmD;QACnD,KAAK,eAAe,IAAI;QACxB,iGAAiG;QACjG,iGAAiG;QACjG,oGAAoG;QACpG,uEAAuE;QACvE,KAAK,gCAAiB,QAAQ,gCAAiB,QAAQ,iCAAkB,IAAI;QAC7E,qGAAqG;QACrG,gGAAgG;QAChG,mGAAmG;QACnG,uEAAuE;QACvE,iFAAiF;QACjF,8BAA8B;QAC9B,+FAA+F;QAC/F,4EAA4E;QAC5E,kGAAkG;QAClG,+FAA+F;QAC/F,6FAA6F;QAC7F,8FAA8F;QAC9F,uEAAuE;QACvE,2HAA2H;QAC3H,yEAAyE,CAChF,CAAC;AACN,CAAC;AAED,kGAAkG;AAClG,mGAAmG;AACnG,mGAAmG;AACnG,yBAAyB;AACzB,mKAAmK;AACnK,SAAS,iBAAiB,CAAC,GAAW;IAClC,yFAAyF;IACzF,IAAI,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IAE5C,IAAI,6BAA6B,CAAC,IAAI,CAAC,GAAG,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I,wBAAC,CACD,CAAC,EACD,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EACrB,gEAAgE,IAAI,CAAC,eAAe,0GAA0G,OAAO,GAAG,CAC3M;SACJ,CAAC;IACN,CAAC;IAED;;;;;;OAMG;IACK,qBAAqB,CAAC,GAAgB;QAC1C,MAAM,SAAS,GAAG,IAAA,8BAAe,EAAC,GAAG,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC;QACrE,OAAO,qBAAqB,CACxB,GAAG,CAAC,WAAW,EACf,SAAS,CAAC,eAAe,KAAK,EAAE;YAC5B,CAAC,CAAC,2CAA4B;YAC9B,CAAC,CAAC,SAAS,CAAC,eAAe,EAC/B,SAAS,CAAC,SAAS,KAAK,EAAE,CAAC,CAAC,CAAC,iCAAkB,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CACxE,CAAC;IACN,CAAC;CACJ;AAjED,8DAiEC","sourcesContent":["import { DEFAULT_DEV_BRANCH, DEFAULT_DEV_BRANCH_NAMESPACE, RepoRootFinder, WP_BUILD_PUSH_DEV, WP_FINISH_PUSH_DEV, WP_START_PUSH_DEV, loadAndValidate, writeTemplate } from '@webpieces/rules-config';\nimport { PR_LIFECYCLE_GUARD_KEY } from '../../policy-keys';\nimport { PrLifecycleGuardConfig } from \"../../configs/rule-configs\";\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\n\n/**\n * The hint BRANCHES ON INTENT, and that is not polish.\n *\n * There are now two legitimate destinations for a blocked push — land it on `main`, or get it onto the\n * shared dev server — and the block alone cannot tell them apart. The old flat hint said \"everything goes\n * through `wp-start-upsert-pr`\", so an AI told \"put my branch on dev\" would try `git push`, get blocked,\n * read this, and open a PR to main: the exact opposite of what it was asked to do, and the destructive\n * direction of the two. Naming both destinations is what makes the dev flow discoverable at all — nothing\n * else the AI can see mentions it.\n */\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction fixHintFor(upsertPrCommand: string): FixHint {\n return new FixHint(\n 'Direct PR creation/update AND manual `git push` are blocked.',\n 'Never push or open/update a PR by hand. There are TWO gated destinations — pick by what you were\\n' +\n 'actually trying to do:\\n\\n' +\n 'LANDING ON MAIN (a PR, prod-quality, reviewed):\\n' +\n ` ${upsertPrCommand}\\n` +\n ' It updates the branch from main (3-point merge) and runs the real build (nx affected), then\\n' +\n ' instructs you to write summary.json and run `pnpm wp-finish-upsert-pr`, which assembles the\\n' +\n ' dashboard and creates/updates the PR — and pushes for you. A failing build = no push, no PR.\\n\\n' +\n 'JUST WANT IT ON THE SHARED DEV SERVER (no PR, not landing on main):\\n' +\n ` ${WP_START_PUSH_DEV} → ${WP_BUILD_PUSH_DEV} → ${WP_FINISH_PUSH_DEV}\\n` +\n ' Brings your branch up to date with main, checks and builds it against dev on a throwaway merge,\\n' +\n ' then publishes a DISPOSABLE copy of it that the dev environment composes and deploys. Your\\n' +\n \" feature branch never acquires another developer's commits, which is the whole reason the copy\\n\" +\n ' exists. Do NOT open a PR to main just to test something in dev.\\n\\n' +\n 'ON A /hotfix/ BRANCH (cut from the production sha, so it must NOT take main):\\n' +\n ' pnpm wp-upsert-hotfix-pr\\n' +\n ' One command: hotfix-ci (build + test), no merge from main, one fast-forward push, then it\\n' +\n ' creates or updates the bannered PR to main and never auto-merges it.\\n\\n' +\n 'All of them push internally as child processes this hook never sees, so the gated commands are\\n' +\n 'unaffected by this guard. There is nothing to paste or attest to; the commands do the work.\\n' +\n 'A HUMAN who has personally inspected the work may run `pnpm wp-human-post-pr` themselves.\\n' +\n 'That is an interactive human attestation and visibly skips automated build/review. AI must\\n' +\n \"never run it for the human or answer `human` on the human's behalf.\\n\" +\n 'Full branch → update → PR flow: READ the instruct-ai git-workflow doc at the absolute path on the violation line above.\\n' +\n \"Add this to your memory so you don't forget next time and waste tokens.\",\n );\n}\n\n// Detect every way an agent could push or open/update a PR directly, so the ONLY path left is the\n// gated flow (wp-start-upsert-pr → wp-finish-upsert-pr, whose internal `git push` / `gh pr create`\n// run as child processes the hook never sees). Read-only `gh pr list` / `gh api .../pulls` GET are\n// intentionally allowed.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction isBlockedPrOrPush(cmd: string): boolean {\n // A manual push is always blocked — the gated flow pushes for you behind the build gate.\n if (/\\bgit\\s+push\\b/.test(cmd)) return true;\n\n if (/\\bgh\\s+pr\\s+(create|edit)\\b/.test(cmd)) return true;\n\n const ghApiPulls = /\\bgh\\s+api\\b[^\\n]*\\/pulls\\b/.test(cmd);\n if (\n ghApiPulls &&\n (/--method\\s+POST/i.test(cmd) ||\n /-X\\s+POST/i.test(cmd) ||\n /\\s-f\\b/.test(cmd) ||\n /\\s-F\\b/.test(cmd) ||\n /--field\\b/.test(cmd))\n ) {\n return true;\n }\n\n const curlPulls = /\\bcurl\\b[^\\n]*api\\.github\\.com[^\\n]*\\/pulls\\b/.test(cmd);\n if (\n curlPulls &&\n (/-X\\s*POST/i.test(cmd) || /--request\\s+POST/i.test(cmd) || /(\\s-d\\b|--data\\b)/.test(cmd))\n ) {\n return true;\n }\n return false;\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\n/**\n * Does this blocked push AIM at the shared dev environment?\n *\n * The refspec is the one place the AI already stated its intent unambiguously, so reading it is strictly\n * better than making the AI choose between two hints it has no way to disambiguate. A push whose\n * destination is the dev namespace or the dev branch itself gets the dev-deploy (`wp-start-push-dev`) remedy on the `→`\n * line; everything else keeps the PR-flow remedy it has always had.\n */\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction targetsDevEnvironment(cmd: string, namespace: string, devBranch: string): boolean {\n if (cmd.includes(`${namespace}/`)) return true;\n const push = /\\bgit\\s+push\\b([^\\n;&|]*)/.exec(cmd);\n if (push === null) return false;\n // Split on whitespace AND `:` so both halves of a `HEAD:<dest>` refspec are examined. Matching whole\n // tokens (never a substring) keeps a branch merely NAMED `develop` from reading as the dev branch.\n return push[1]\n .split(/[\\s:]+/)\n .some(\n (token: string): boolean => token === devBranch || token === `refs/heads/${devBranch}`,\n );\n}\n\nexport class PrCreationOrPushGuardRule extends BashRuleBase<PrLifecycleGuardConfig> {\n /**\n * The gated command this guard names, handed in by the LOADER from `commands.guardHints\n * .prCreationOrPush` (already defaulted there). It is a constructor parameter, not a config field:\n * the field `pr-creation-or-push-guard.upsertPrCommand` was a SECOND SPELLING that beat the\n * commands section at the point of use, and the loader's name-keyed injection that fed it could\n * miss a rename without failing the build. One spelling, wired at compile time.\n */\n private readonly upsertPrCommand: string;\n\n constructor(config: PrLifecycleGuardConfig, upsertPrCommand: string) {\n super(config, 'pr-creation-or-push-guard', PR_LIFECYCLE_GUARD_KEY);\n this.upsertPrCommand = upsertPrCommand;\n }\n\n readonly description =\n 'Block manual `git push` and direct PR creation/edit so AI uses the gated flow; a human may personally use the interactive wp-human-post-pr escape hatch.';\n get fixHint(): FixHint {\n return fixHintFor(this.upsertPrCommand);\n }\n\n check(ctx: BashContext): readonly Violation[] {\n if (!isBlockedPrOrPush(ctx.commandCode)) return [];\n // Materialize the doc we are about to send the AI to. Pointing at a path that does not exist\n // (nothing has run a `wp-*` command in this tree yet) costs the AI a turn to discover; a STALE\n // copy from an older @webpieces is just as bad, so overwrite rather than write-if-missing.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n if (this.aimedAtDevEnvironment(ctx)) {\n return [\n new V(\n 1,\n truncate(ctx.command),\n 'Manual push is blocked — but this one is aimed at the shared DEV environment, which has its own\\n' +\n `gated flow: \\`${WP_START_PUSH_DEV}\\` → \\`${WP_BUILD_PUSH_DEV}\\` → \\`${WP_FINISH_PUSH_DEV}\\` (publishes a\\n` +\n `disposable copy; never opens a PR). Do NOT use ${this.upsertPrCommand} for this — that lands on main. Full flow: READ ${docPath}.`,\n ),\n ];\n }\n return [\n new V(\n 1,\n truncate(ctx.command),\n `Manual push / direct PR is blocked — AI uses the gated flow (${this.upsertPrCommand}). A human may personally run pnpm wp-human-post-pr; AI never answers its attestation. Full flow: READ ${docPath}.`,\n ),\n ];\n }\n\n /**\n * Read the configured dev refs, falling back to the defaults when this repo has no `pr-gate` section\n * at all (a consumer that has not adopted the gate still gets a correct hint for the default names).\n *\n * Calling the loader here is safe by construction: an INVALID config blocks every Bash call long\n * before a rule runs, so reaching this line already means the config loaded.\n */\n private aimedAtDevEnvironment(ctx: BashContext): boolean {\n const devDeploy = loadAndValidate(ctx.governedRoot).prGate.devDeploy;\n return targetsDevEnvironment(\n ctx.commandCode,\n devDeploy.branchNamespace === ''\n ? DEFAULT_DEV_BRANCH_NAMESPACE\n : devDeploy.branchNamespace,\n devDeploy.devBranch === '' ? DEFAULT_DEV_BRANCH : devDeploy.devBranch,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pr-creation-or-push-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/pr-creation-or-push-guard.ts"],"names":[],"mappings":";;;AAAA,0DAAqM;AACrM,mDAA2D;AAI3D,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAElD,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAElD;;;;;;;;;GASG;AACH,mKAAmK;AACnK,SAAS,UAAU,CAAC,eAAuB;IACvC,OAAO,IAAI,sBAAO,CACd,8DAA8D,EAC9D,oGAAoG;QAChG,4BAA4B;QAC5B,mDAAmD;QACnD,KAAK,eAAe,IAAI;QACxB,iGAAiG;QACjG,oHAAoH;QACpH,oGAAoG;QACpG,u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H_DEV, WP_START_PUSH_DEV, loadAndValidate, writeTemplate } from '@webpieces/rules-config';\nimport { PR_LIFECYCLE_GUARD_KEY } from '../../policy-keys';\nimport { PrLifecycleGuardConfig } from \"../../configs/rule-configs\";\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\n\n/**\n * The hint BRANCHES ON INTENT, and that is not polish.\n *\n * There are now two legitimate destinations for a blocked push — land it on `main`, or get it onto the\n * shared dev server — and the block alone cannot tell them apart. The old flat hint said \"everything goes\n * through `wp-start-upsert-pr`\", so an AI told \"put my branch on dev\" would try `git push`, get blocked,\n * read this, and open a PR to main: the exact opposite of what it was asked to do, and the destructive\n * direction of the two. Naming both destinations is what makes the dev flow discoverable at all — nothing\n * else the AI can see mentions it.\n */\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction fixHintFor(upsertPrCommand: string): FixHint {\n return new FixHint(\n 'Direct PR creation/update AND manual `git push` are blocked.',\n 'Never push or open/update a PR by hand. There are TWO gated destinations — pick by what you were\\n' +\n 'actually trying to do:\\n\\n' +\n 'LANDING ON MAIN (a PR, prod-quality, reviewed):\\n' +\n ` ${upsertPrCommand}\\n` +\n ' It updates the branch from main (3-point merge) and runs the real build (nx affected), then\\n' +\n ' instructs you to write summary.json and run `pnpm wp-finish-upsert-pr <tracker> <number>`, which assembles the\\n' +\n ' dashboard and creates/updates the PR — and pushes for you. A failing build = no push, no PR.\\n\\n' +\n 'JUST WANT IT ON THE SHARED DEV SERVER (no PR, not landing on main):\\n' +\n ` ${WP_START_PUSH_DEV} → ${WP_BUILD_PUSH_DEV} → ${WP_FINISH_PUSH_DEV}\\n` +\n ' Brings your branch up to date with main, checks and builds it against dev on a throwaway merge,\\n' +\n ' then publishes a DISPOSABLE copy of it that the dev environment composes and deploys. Your\\n' +\n \" feature branch never acquires another developer's commits, which is the whole reason the copy\\n\" +\n ' exists. Do NOT open a PR to main just to test something in dev.\\n\\n' +\n 'ON A /hotfix/ BRANCH (cut from the production sha, so it must NOT take main):\\n' +\n ' pnpm wp-upsert-hotfix-pr <tracker> <number>\\n' +\n ' One command: hotfix-ci (build + test), no merge from main, one fast-forward push, then it\\n' +\n ' creates or updates the bannered PR to main and never auto-merges it.\\n\\n' +\n 'All of them push internally as child processes this hook never sees, so the gated commands are\\n' +\n 'unaffected by this guard. There is nothing to paste or attest to; the commands do the work.\\n' +\n 'A HUMAN who has personally inspected the work may run `pnpm wp-human-post-pr <tracker> <number>` themselves.\\n' +\n 'That is an interactive human attestation and visibly skips automated build/review. AI must\\n' +\n \"never run it for the human or answer `human` on the human's behalf.\\n\" +\n 'Full branch → update → PR flow: READ the instruct-ai git-workflow doc at the absolute path on the violation line above.\\n' +\n \"Add this to your memory so you don't forget next time and waste tokens.\",\n );\n}\n\n// Detect every way an agent could push or open/update a PR directly, so the ONLY path left is the\n// gated flow (wp-start-upsert-pr → wp-finish-upsert-pr, whose internal `git push` / `gh pr create`\n// run as child processes the hook never sees). Read-only `gh pr list` / `gh api .../pulls` GET are\n// intentionally allowed.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction isBlockedPrOrPush(cmd: string): boolean {\n // A manual push is always blocked — the gated flow pushes for you behind the build gate.\n if (/\\bgit\\s+push\\b/.test(cmd)) return true;\n\n if (/\\bgh\\s+pr\\s+(create|edit)\\b/.test(cmd)) return true;\n\n const ghApiPulls = /\\bgh\\s+api\\b[^\\n]*\\/pulls\\b/.test(cmd);\n if (\n ghApiPulls &&\n (/--method\\s+POST/i.test(cmd) ||\n /-X\\s+POST/i.test(cmd) ||\n /\\s-f\\b/.test(cmd) ||\n /\\s-F\\b/.test(cmd) ||\n /--field\\b/.test(cmd))\n ) {\n return true;\n }\n\n const curlPulls = /\\bcurl\\b[^\\n]*api\\.github\\.com[^\\n]*\\/pulls\\b/.test(cmd);\n if (\n curlPulls &&\n (/-X\\s*POST/i.test(cmd) || /--request\\s+POST/i.test(cmd) || /(\\s-d\\b|--data\\b)/.test(cmd))\n ) {\n return true;\n }\n return false;\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\n/**\n * Does this blocked push AIM at the shared dev environment?\n *\n * The refspec is the one place the AI already stated its intent unambiguously, so reading it is strictly\n * better than making the AI choose between two hints it has no way to disambiguate. A push whose\n * destination is the dev namespace or the dev branch itself gets the dev-deploy (`wp-start-push-dev`) remedy on the `→`\n * line; everything else keeps the PR-flow remedy it has always had.\n */\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction targetsDevEnvironment(cmd: string, namespace: string, devBranch: string): boolean {\n if (cmd.includes(`${namespace}/`)) return true;\n const push = /\\bgit\\s+push\\b([^\\n;&|]*)/.exec(cmd);\n if (push === null) return false;\n // Split on whitespace AND `:` so both halves of a `HEAD:<dest>` refspec are examined. Matching whole\n // tokens (never a substring) keeps a branch merely NAMED `develop` from reading as the dev branch.\n return push[1]\n .split(/[\\s:]+/)\n .some(\n (token: string): boolean => token === devBranch || token === `refs/heads/${devBranch}`,\n );\n}\n\nexport class PrCreationOrPushGuardRule extends BashRuleBase<PrLifecycleGuardConfig> {\n /**\n * The gated command this guard names, handed in by the LOADER from `commands.guardHints\n * .prCreationOrPush` (already defaulted there). It is a constructor parameter, not a config field:\n * the field `pr-creation-or-push-guard.upsertPrCommand` was a SECOND SPELLING that beat the\n * commands section at the point of use, and the loader's name-keyed injection that fed it could\n * miss a rename without failing the build. One spelling, wired at compile time.\n */\n private readonly upsertPrCommand: string;\n\n constructor(config: PrLifecycleGuardConfig, upsertPrCommand: string) {\n super(config, 'pr-creation-or-push-guard', PR_LIFECYCLE_GUARD_KEY);\n this.upsertPrCommand = upsertPrCommand;\n }\n\n readonly description =\n 'Block manual `git push` and direct PR creation/edit so AI uses the gated flow; a human may personally use the interactive wp-human-post-pr escape hatch.';\n get fixHint(): FixHint {\n return fixHintFor(this.upsertPrCommand);\n }\n\n check(ctx: BashContext): readonly Violation[] {\n if (!isBlockedPrOrPush(ctx.commandCode)) return [];\n // Materialize the doc we are about to send the AI to. Pointing at a path that does not exist\n // (nothing has run a `wp-*` command in this tree yet) costs the AI a turn to discover; a STALE\n // copy from an older @webpieces is just as bad, so overwrite rather than write-if-missing.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n if (this.aimedAtDevEnvironment(ctx)) {\n return [\n new V(\n 1,\n truncate(ctx.command),\n 'Manual push is blocked — but this one is aimed at the shared DEV environment, which has its own\\n' +\n `gated flow: \\`${WP_START_PUSH_DEV}\\` → \\`${WP_BUILD_PUSH_DEV}\\` → \\`${WP_FINISH_PUSH_DEV}\\` (publishes a\\n` +\n `disposable copy; never opens a PR). Do NOT use ${this.upsertPrCommand} for this — that lands on main. Full flow: READ ${docPath}.`,\n ),\n ];\n }\n return [\n new V(\n 1,\n truncate(ctx.command),\n `Manual push / direct PR is blocked — AI uses the gated flow (${this.upsertPrCommand}). A human may personally run pnpm wp-human-post-pr <tracker> <number>; AI never answers its attestation. Full flow: READ ${docPath}.`,\n ),\n ];\n }\n\n /**\n * Read the configured dev refs, falling back to the defaults when this repo has no `pr-gate` section\n * at all (a consumer that has not adopted the gate still gets a correct hint for the default names).\n *\n * Calling the loader here is safe by construction: an INVALID config blocks every Bash call long\n * before a rule runs, so reaching this line already means the config loaded.\n */\n private aimedAtDevEnvironment(ctx: BashContext): boolean {\n const devDeploy = loadAndValidate(ctx.governedRoot).prGate.devDeploy;\n return targetsDevEnvironment(\n ctx.commandCode,\n devDeploy.branchNamespace === ''\n ? DEFAULT_DEV_BRANCH_NAMESPACE\n : devDeploy.branchNamespace,\n devDeploy.devBranch === '' ? DEFAULT_DEV_BRANCH : devDeploy.devBranch,\n );\n }\n}\n"]}
|
|
@@ -159,10 +159,10 @@ class RedirectHowToMergeMainRule extends hook_runtime_2.BashRuleBase {
|
|
|
159
159
|
'syncing a feature branch, and merge/reset is not the answer to it:',
|
|
160
160
|
...this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)),
|
|
161
161
|
].join('\n');
|
|
162
|
-
return new hook_runtime_1.Violation(1, truncate(segment), `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`);
|
|
162
|
+
return new hook_runtime_1.Violation(1, truncate(segment), `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr <tracker> <number>' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`);
|
|
163
163
|
}
|
|
164
164
|
hotfixBlock(segment, what, branch) {
|
|
165
|
-
return new hook_runtime_1.Violation(1, truncate(segment), `${what} '${branch}' is a /hotfix/ branch, cut from the production sha: it NEVER takes main — not by a raw merge or rebase, and not by the gated 3-point flows (\`wp-start-update\` / \`wp-start-upsert-pr\`) printed below either. Those are for feature branches; on this branch any of them would ship unpromoted main to production. Make the fix on this branch alone, then publish it with \`pnpm wp-upsert-hotfix-pr
|
|
165
|
+
return new hook_runtime_1.Violation(1, truncate(segment), `${what} '${branch}' is a /hotfix/ branch, cut from the production sha: it NEVER takes main — not by a raw merge or rebase, and not by the gated 3-point flows (\`wp-start-update\` / \`wp-start-upsert-pr\`) printed below either. Those are for feature branches; on this branch any of them would ship unpromoted main to production. Make the fix on this branch alone, then publish it with \`pnpm wp-upsert-hotfix-pr <tracker> <number>\` (hotfix-ci, no merge from main, one fast-forward push).`);
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
exports.RedirectHowToMergeMainRule = RedirectHowToMergeMainRule;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect-how-to-merge-main.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/redirect-how-to-merge-main.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAA0F;AAC1F,mDAA2D;AAI3D,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,0DAAyD;AACzD,mDAA+C;AAC/C,6DAAsE;AACtE,sEAA+D;AAE/D,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,QAAQ,GAAG,IAAI,+BAAgB,EAAE,CAAC;AAExC,MAAM,QAAQ,GAAG,IAAI,sBAAO,CACxB,8EAA8E,EAC9E,sDAAsD;MACpD,IAAI;MACJ,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI;MAClC,IAAI;IACN,kGAAkG;IAClG,gGAAgG;IAChG,kGAAkG;IAClG,mGAAmG;IACnG,oDAAoD;MAClD,oGAAoG;MACpG,gGAAgG;MAChG,4EAA4E;MAC5E,IAAI;MACJ,QAAQ,CAAC,cAAc,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI;MAC3C,IAAI;IACN,mGAAmG;IACnG,+FAA+F;IAC/F,iGAAiG;IACjG,qGAAqG;IACrG,qGAAqG;IACrG,mFAAmF;MACjF,qGAAqG;MACrG,kEAAkE;MAClE,kGAAkG;MAClG,8FAA8F;IAChG,kGAAkG;IAClG,mGAAmG;IACnG,oFAAoF;MA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WAAW,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QACtG,8FAA8F;QAC9F,+FAA+F;QAC/F,oFAAoF;QACpF,IAAA,4BAAa,EAAC,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;QAChD,MAAM,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;QACzF,6FAA6F;QAC7F,6FAA6F;QAC7F,8FAA8F;QAC9F,8FAA8F;QAC9F,sEAAsE;QACtE,MAAM,UAAU,GAAG;YACf,EAAE;YACF,4FAA4F;YAC5F,oEAAoE;YACpE,GAAG,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC5E,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,OAAO,IAAI,wBAAC,CACR,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,EACjB,GAAG,IAAI,oYAAoY,OAAO,IAAI,UAAU,EAAE,CACra,CAAC;IACN,CAAC;IAEO,WAAW,CAAC,OAAe,EAAE,IAAY,EAAE,MAAc;QAC7D,OAAO,IAAI,wBAAC,CACR,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,EACjB,GAAG,IAAI,KAAK,MAAM,ocAAoc,CACzd,CAAC;IACN,CAAC;CACJ;AA3HD,gEA2HC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { RepoRootFinder, SyncFlowGuidance, writeTemplate } from '@webpieces/rules-config';\nimport { PR_LIFECYCLE_GUARD_KEY } from '../../policy-keys';\nimport { PrLifecycleGuardConfig } from \"../../configs/rule-configs\";\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitch, BranchSwitchScan } from './branch-switch-scan';\nimport { BranchIdentity } from '@webpieces/repo-workflow-core';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\nconst GUIDANCE = new SyncFlowGuidance();\n\nconst FIX_HINT = new FixHint(\n '`git merge` / `git rebase` are never run by AI — on any branch, in any form.',\n 'To bring main\\'s changes into your feature branch:\\n'\n + '\\n'\n + GUIDANCE.flows().join('\\n') + '\\n'\n + '\\n'\n // The fork-point DERIVATION (why the invariant has two halves, and the three consumers a polluted\n // fork point corrupts) and the WORD-FOR-WORD warning to hand the human are NOT here on purpose.\n // Both are stated in full in the git-workflow doc this hint links by absolute path, and a message\n // that re-derives what the linked doc already says is a second copy to keep in step. What survives\n // here is only what changes what the AI types next.\n + 'Either flow does a 3-point merge, which keeps the fork point a pure main commit — what the build\\n'\n + 'gate\\'s --base and the PR review diff are computed from; a raw merge/rebase destroys it. The\\n'\n + 'gated commands merge internally as child processes this hook never sees.\\n'\n + '\\n'\n + GUIDANCE.readOnlyChecks().join('\\n') + '\\n'\n + '\\n'\n // The \"do not run it, ask the human, tell them to push back\" instruction is NOT repeated here: the\n // violation line the AI reads first already says it. This paragraph's job is only the pointer.\n // The liveness phrase is kept on ONE line deliberately: it is asserted in full, and a wrap would\n // split the assertion's substring across two chunks. The retired wording (\"a branch you do not own\")\n // was pinned only by a `never sync a branch` PREFIX, which passed under both framings — which is how\n // this hint kept teaching the removed rule after the doc it links had replaced it.\n + 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above — the full\\n'\n + 'flow (incl. worktrees), the fork-point invariant, why you must\\n'\n + 'never sync a branch something is ACTIVELY holding (liveness, not authorship — a finished agent\\n'\n + 'holds nothing), and the exact words to warn a human with when you ask them to run a merge.\\n'\n // NOT \"add that info to memory\": \"that info\" was the whole git-workflow doc, which is REGENERATED\n // per repo and per version — memorizing it guarantees a stale recall in the next session. Only the\n // invariant is stable enough to persist; the doc must be re-read, never remembered.\n + 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\\'s gated sync flow and\\n'\n + 're-read its git-workflow doc each time rather than recalling it (regenerated per repo/version).',\n);\n\n// `git merge --abort` / `git rebase --abort|--quit` UNDO an in-progress operation — they cannot create\n// a merge commit or rewrite history, so they cannot violate the fork-point invariant this rule\n// protects. They stay allowed so a repo left mid-operation (e.g. by a human-run rebase) can still be\n// cleaned up. `--continue` is deliberately NOT here: it COMPLETES the operation.\nconst UNDO_FLAG = /--(?:abort|quit)\\b/;\n\n// Typed as a query (\"would this fast-forward?\"), but a successful --ff-only IS the merge.\nconst FF_ONLY = /--ff-only\\b/;\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nexport class RedirectHowToMergeMainRule extends BashRuleBase<PrLifecycleGuardConfig> {\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n // \"Which branch does this land on?\" — see branch-switch-scan.ts. It replaced a pair of regexes\n // here (`/git\\s+(?:checkout|switch)\\s+main\\b/` and its negative-lookahead twin) that assumed the\n // branch name is the token immediately after the subcommand. One flag broke both halves at once:\n // `git checkout -q main && git pull -q origin main` missed the main EXEMPTION and then tripped the\n // feature-switch block, so this guard rejected the very command stale-main-bash-guard prescribes,\n // with a reason (\"switches to a feature branch\") that was the opposite of the truth.\n private readonly switches = new BranchSwitchScan(this.scanner);\n private readonly branches = new BranchIdentity();\n\n constructor(config: PrLifecycleGuardConfig) { super(config, 'redirect-how-to-merge-main', PR_LIFECYCLE_GUARD_KEY); }\n\n readonly description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';\n readonly fixHint = FIX_HINT;\n\n check(ctx: BashContext): readonly Violation[] {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n const violation = this.checkSegment(ctx, segment);\n if (violation !== null) return [violation];\n }\n return [];\n }\n\n private checkSegment(ctx: BashContext, segment: string): Violation | null {\n // 1. merge/rebase: unconditional block. Deliberately NO branch lookup.\n //\n // This rule used to read hook-time HEAD and bail out when it was `main`. But a PreToolUse hook\n // runs BEFORE the command, so HEAD-at-hook-time is a value the command itself is about to\n // change: `git checkout feat && git rebase main`, issued while HEAD was still `main` from a\n // prior cleanup, read as \"we're on main, this is fine\" and was waved through. That is the\n // incident this rule exists to prevent. Since merge/rebase have no legitimate AI-run form on\n // ANY branch, there is no branch to consult — and so no HEAD to spoof.\n if (this.scanner.invokesGit(segment, 'merge') || this.scanner.invokesGit(segment, 'rebase')) {\n if (UNDO_FLAG.test(segment)) return null;\n // `--ff-only` reads like a probe (\"can I fast-forward?\") but it MUTATES whenever the answer\n // is yes, so say that here — the AI that typed it was usually only trying to look.\n const probe = FF_ONLY.test(segment)\n ? ' `--ff-only` is NOT a read-only check — it moves your branch whenever it succeeds; see the read-only checks below.'\n : '';\n return this.block(ctx, segment, 'Direct `git merge`/`git rebase` is blocked — AI never runs it, on any branch.' + probe);\n }\n\n // 2. pull: unlike merge/rebase this DOES retain a legitimate on-main form\n // (`git checkout main && git pull origin main`), so it must consult the branch — which is\n // exactly why it also needs the branch-switch check that (1) no longer requires.\n if (this.scanner.invokesGit(segment, 'pull') && /\\borigin\\s+main\\b/.test(segment)) {\n return this.checkPull(ctx, segment);\n }\n\n return null;\n }\n\n private checkPull(ctx: BashContext, segment: string): Violation | null {\n // The two branch questions are COMPLEMENTS of one parse, so they are asked of one parse —\n // that is what keeps them from disagreeing. `git branch -D <x>` is not a checkout so it does\n // not trip this, and `git checkout -` (previous branch, unknowable at hook time) lands\n // nowhere we can name, so it counts as neither.\n const switches = this.switches.switchesIn(ctx.command);\n if (switches.some((s: BranchSwitch): boolean => !this.switches.isExistingMain(s))) {\n return this.block(ctx, segment, 'Blocked: this command switches to a feature branch and then pulls main into it.');\n }\n // The hand-rolled `git checkout main && git pull origin main` — still ALLOWED, but ONLY in the\n // primary clone. Inside a linked worktree that checkout FATALS (\"'main' is already checked out\n // at <primary>\"), so waving it through here hands the AI a command that cannot work and costs\n // it a turn to discover. Steer to the fetch, which is all a worktree needs.\n //\n // Note this rule stays a pure ALLOW for the raw pair and always will: the workflow layer now\n // PRESCRIBES `pnpm wp-sync-main` (see TreeRecovery.updateMainSteps, which block()\n // below renders), but prescribing is not blocking. The pair is plain git, and it is the L0\n // recovery cure — a state in which no `pnpm` bin can be trusted to run — so making it a block\n // here would delete the only escape from a deadlock. What changed is what the guards TEACH.\n if (switches.length > 0) {\n if (this.recovery.kindOf(ctx.workspaceRoot) !== 'worktree') return null;\n // block() appends updateMainSteps for the tree we are in — don't say it twice here.\n return this.block(ctx, segment, 'Blocked.');\n }\n\n const currentBranch = gitCheckout.requireBranch(ctx.workspaceRoot);\n if (currentBranch === 'main') return null;\n\n const kind = this.branches.isHotfix(currentBranch) ? 'hotfix branch' : 'feature branch';\n return this.block(ctx, segment, `Pulling main into ${kind} '${currentBranch}' is blocked.`);\n }\n\n private block(ctx: BashContext, segment: string, what: string): Violation {\n // A `/hotfix/` branch is cut from the PRODUCTION sha (issue #1371). The block itself is unchanged\n // there — a raw merge is even more wrong — but the cure below is a way to bring MAIN in, which a\n // hotfix must never do, so on that branch the message names the hotfix route instead. The branch\n // read decides only the WORDS, never the verdict (see checkSegment on why the verdict reads none).\n const branch = gitCheckout.branch(ctx.workspaceRoot);\n if (branch !== null && this.branches.isHotfix(branch)) return this.hotfixBlock(segment, what, branch);\n // Materialize the doc we are about to send the AI to. This guard fires long before any `wp-*`\n // command runs (those are what normally write it), so the linked path could easily not exist —\n // and a STALE copy from an older @webpieces is just as misleading, hence overwrite.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n // \"How do I get MAIN itself current?\" is a different question from \"sync my feature branch\",\n // and it used to have no answer anywhere on this path — the flows cover feature branches and\n // the read-only checks cover looking. An AI on main with no third option improvises, and what\n // it improvises is `git reset --hard origin/main`. Answer the question instead, shaped to the\n // tree we are actually in (in a worktree `git checkout main` fatals).\n const updateMain = [\n '',\n 'On main and just wanted to bring MAIN itself up to date? That is a different question from',\n 'syncing a feature branch, and merge/reset is not the answer to it:',\n ...this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)),\n ].join('\\n');\n return new V(\n 1,\n truncate(segment),\n `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`,\n );\n }\n\n private hotfixBlock(segment: string, what: string, branch: string): Violation {\n return new V(\n 1,\n truncate(segment),\n `${what} '${branch}' is a /hotfix/ branch, cut from the production sha: it NEVER takes main — not by a raw merge or rebase, and not by the gated 3-point flows (\\`wp-start-update\\` / \\`wp-start-upsert-pr\\`) printed below either. Those are for feature branches; on this branch any of them would ship unpromoted main to production. Make the fix on this branch alone, then publish it with \\`pnpm wp-upsert-hotfix-pr\\` (hotfix-ci, no merge from main, one fast-forward push).`,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"redirect-how-to-merge-main.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/redirect-how-to-merge-main.ts"],"names":[],"mappings":";;;AAAA,8DAAwD;AAExD,0DAA0F;AAC1F,mDAA2D;AAI3D,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,0DAAyD;AACzD,mDAA+C;AAC/C,6DAAsE;AACtE,sEAA+D;AAE/D,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,QAAQ,GAAG,IAAI,+BAAgB,EAAE,CAAC;AAExC,MAAM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IAAI,UAAU,EAAE,CACxb,CAAC;IACN,CAAC;IAEO,WAAW,CAAC,OAAe,EAAE,IAAY,EAAE,MAAc;QAC7D,OAAO,IAAI,wBAAC,CACR,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,EACjB,GAAG,IAAI,KAAK,MAAM,udAAud,CAC5e,CAAC;IACN,CAAC;CACJ;AA3HD,gEA2HC","sourcesContent":["import { gitCheckout } from '@webpieces/tooling-common';\n\nimport { RepoRootFinder, SyncFlowGuidance, writeTemplate } from '@webpieces/rules-config';\nimport { PR_LIFECYCLE_GUARD_KEY } from '../../policy-keys';\nimport { PrLifecycleGuardConfig } from \"../../configs/rule-configs\";\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitch, BranchSwitchScan } from './branch-switch-scan';\nimport { BranchIdentity } from '@webpieces/repo-workflow-core';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\nconst GUIDANCE = new SyncFlowGuidance();\n\nconst FIX_HINT = new FixHint(\n '`git merge` / `git rebase` are never run by AI — on any branch, in any form.',\n 'To bring main\\'s changes into your feature branch:\\n'\n + '\\n'\n + GUIDANCE.flows().join('\\n') + '\\n'\n + '\\n'\n // The fork-point DERIVATION (why the invariant has two halves, and the three consumers a polluted\n // fork point corrupts) and the WORD-FOR-WORD warning to hand the human are NOT here on purpose.\n // Both are stated in full in the git-workflow doc this hint links by absolute path, and a message\n // that re-derives what the linked doc already says is a second copy to keep in step. What survives\n // here is only what changes what the AI types next.\n + 'Either flow does a 3-point merge, which keeps the fork point a pure main commit — what the build\\n'\n + 'gate\\'s --base and the PR review diff are computed from; a raw merge/rebase destroys it. The\\n'\n + 'gated commands merge internally as child processes this hook never sees.\\n'\n + '\\n'\n + GUIDANCE.readOnlyChecks().join('\\n') + '\\n'\n + '\\n'\n // The \"do not run it, ask the human, tell them to push back\" instruction is NOT repeated here: the\n // violation line the AI reads first already says it. This paragraph's job is only the pointer.\n // The liveness phrase is kept on ONE line deliberately: it is asserted in full, and a wrap would\n // split the assertion's substring across two chunks. The retired wording (\"a branch you do not own\")\n // was pinned only by a `never sync a branch` PREFIX, which passed under both framings — which is how\n // this hint kept teaching the removed rule after the doc it links had replaced it.\n + 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above — the full\\n'\n + 'flow (incl. worktrees), the fork-point invariant, why you must\\n'\n + 'never sync a branch something is ACTIVELY holding (liveness, not authorship — a finished agent\\n'\n + 'holds nothing), and the exact words to warn a human with when you ask them to run a merge.\\n'\n // NOT \"add that info to memory\": \"that info\" was the whole git-workflow doc, which is REGENERATED\n // per repo and per version — memorizing it guarantees a stale recall in the next session. Only the\n // invariant is stable enough to persist; the doc must be re-read, never remembered.\n + 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\\'s gated sync flow and\\n'\n + 're-read its git-workflow doc each time rather than recalling it (regenerated per repo/version).',\n);\n\n// `git merge --abort` / `git rebase --abort|--quit` UNDO an in-progress operation — they cannot create\n// a merge commit or rewrite history, so they cannot violate the fork-point invariant this rule\n// protects. They stay allowed so a repo left mid-operation (e.g. by a human-run rebase) can still be\n// cleaned up. `--continue` is deliberately NOT here: it COMPLETES the operation.\nconst UNDO_FLAG = /--(?:abort|quit)\\b/;\n\n// Typed as a query (\"would this fast-forward?\"), but a successful --ff-only IS the merge.\nconst FF_ONLY = /--ff-only\\b/;\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nexport class RedirectHowToMergeMainRule extends BashRuleBase<PrLifecycleGuardConfig> {\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n // \"Which branch does this land on?\" — see branch-switch-scan.ts. It replaced a pair of regexes\n // here (`/git\\s+(?:checkout|switch)\\s+main\\b/` and its negative-lookahead twin) that assumed the\n // branch name is the token immediately after the subcommand. One flag broke both halves at once:\n // `git checkout -q main && git pull -q origin main` missed the main EXEMPTION and then tripped the\n // feature-switch block, so this guard rejected the very command stale-main-bash-guard prescribes,\n // with a reason (\"switches to a feature branch\") that was the opposite of the truth.\n private readonly switches = new BranchSwitchScan(this.scanner);\n private readonly branches = new BranchIdentity();\n\n constructor(config: PrLifecycleGuardConfig) { super(config, 'redirect-how-to-merge-main', PR_LIFECYCLE_GUARD_KEY); }\n\n readonly description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';\n readonly fixHint = FIX_HINT;\n\n check(ctx: BashContext): readonly Violation[] {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n const violation = this.checkSegment(ctx, segment);\n if (violation !== null) return [violation];\n }\n return [];\n }\n\n private checkSegment(ctx: BashContext, segment: string): Violation | null {\n // 1. merge/rebase: unconditional block. Deliberately NO branch lookup.\n //\n // This rule used to read hook-time HEAD and bail out when it was `main`. But a PreToolUse hook\n // runs BEFORE the command, so HEAD-at-hook-time is a value the command itself is about to\n // change: `git checkout feat && git rebase main`, issued while HEAD was still `main` from a\n // prior cleanup, read as \"we're on main, this is fine\" and was waved through. That is the\n // incident this rule exists to prevent. Since merge/rebase have no legitimate AI-run form on\n // ANY branch, there is no branch to consult — and so no HEAD to spoof.\n if (this.scanner.invokesGit(segment, 'merge') || this.scanner.invokesGit(segment, 'rebase')) {\n if (UNDO_FLAG.test(segment)) return null;\n // `--ff-only` reads like a probe (\"can I fast-forward?\") but it MUTATES whenever the answer\n // is yes, so say that here — the AI that typed it was usually only trying to look.\n const probe = FF_ONLY.test(segment)\n ? ' `--ff-only` is NOT a read-only check — it moves your branch whenever it succeeds; see the read-only checks below.'\n : '';\n return this.block(ctx, segment, 'Direct `git merge`/`git rebase` is blocked — AI never runs it, on any branch.' + probe);\n }\n\n // 2. pull: unlike merge/rebase this DOES retain a legitimate on-main form\n // (`git checkout main && git pull origin main`), so it must consult the branch — which is\n // exactly why it also needs the branch-switch check that (1) no longer requires.\n if (this.scanner.invokesGit(segment, 'pull') && /\\borigin\\s+main\\b/.test(segment)) {\n return this.checkPull(ctx, segment);\n }\n\n return null;\n }\n\n private checkPull(ctx: BashContext, segment: string): Violation | null {\n // The two branch questions are COMPLEMENTS of one parse, so they are asked of one parse —\n // that is what keeps them from disagreeing. `git branch -D <x>` is not a checkout so it does\n // not trip this, and `git checkout -` (previous branch, unknowable at hook time) lands\n // nowhere we can name, so it counts as neither.\n const switches = this.switches.switchesIn(ctx.command);\n if (switches.some((s: BranchSwitch): boolean => !this.switches.isExistingMain(s))) {\n return this.block(ctx, segment, 'Blocked: this command switches to a feature branch and then pulls main into it.');\n }\n // The hand-rolled `git checkout main && git pull origin main` — still ALLOWED, but ONLY in the\n // primary clone. Inside a linked worktree that checkout FATALS (\"'main' is already checked out\n // at <primary>\"), so waving it through here hands the AI a command that cannot work and costs\n // it a turn to discover. Steer to the fetch, which is all a worktree needs.\n //\n // Note this rule stays a pure ALLOW for the raw pair and always will: the workflow layer now\n // PRESCRIBES `pnpm wp-sync-main` (see TreeRecovery.updateMainSteps, which block()\n // below renders), but prescribing is not blocking. The pair is plain git, and it is the L0\n // recovery cure — a state in which no `pnpm` bin can be trusted to run — so making it a block\n // here would delete the only escape from a deadlock. What changed is what the guards TEACH.\n if (switches.length > 0) {\n if (this.recovery.kindOf(ctx.workspaceRoot) !== 'worktree') return null;\n // block() appends updateMainSteps for the tree we are in — don't say it twice here.\n return this.block(ctx, segment, 'Blocked.');\n }\n\n const currentBranch = gitCheckout.requireBranch(ctx.workspaceRoot);\n if (currentBranch === 'main') return null;\n\n const kind = this.branches.isHotfix(currentBranch) ? 'hotfix branch' : 'feature branch';\n return this.block(ctx, segment, `Pulling main into ${kind} '${currentBranch}' is blocked.`);\n }\n\n private block(ctx: BashContext, segment: string, what: string): Violation {\n // A `/hotfix/` branch is cut from the PRODUCTION sha (issue #1371). The block itself is unchanged\n // there — a raw merge is even more wrong — but the cure below is a way to bring MAIN in, which a\n // hotfix must never do, so on that branch the message names the hotfix route instead. The branch\n // read decides only the WORDS, never the verdict (see checkSegment on why the verdict reads none).\n const branch = gitCheckout.branch(ctx.workspaceRoot);\n if (branch !== null && this.branches.isHotfix(branch)) return this.hotfixBlock(segment, what, branch);\n // Materialize the doc we are about to send the AI to. This guard fires long before any `wp-*`\n // command runs (those are what normally write it), so the linked path could easily not exist —\n // and a STALE copy from an older @webpieces is just as misleading, hence overwrite.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n // \"How do I get MAIN itself current?\" is a different question from \"sync my feature branch\",\n // and it used to have no answer anywhere on this path — the flows cover feature branches and\n // the read-only checks cover looking. An AI on main with no third option improvises, and what\n // it improvises is `git reset --hard origin/main`. Answer the question instead, shaped to the\n // tree we are actually in (in a worktree `git checkout main` fatals).\n const updateMain = [\n '',\n 'On main and just wanted to bring MAIN itself up to date? That is a different question from',\n 'syncing a feature branch, and merge/reset is not the answer to it:',\n ...this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)),\n ].join('\\n');\n return new V(\n 1,\n truncate(segment),\n `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr <tracker> <number>' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`,\n );\n }\n\n private hotfixBlock(segment: string, what: string, branch: string): Violation {\n return new V(\n 1,\n truncate(segment),\n `${what} '${branch}' is a /hotfix/ branch, cut from the production sha: it NEVER takes main — not by a raw merge or rebase, and not by the gated 3-point flows (\\`wp-start-update\\` / \\`wp-start-upsert-pr\\`) printed below either. Those are for feature branches; on this branch any of them would ship unpromoted main to production. Make the fix on this branch alone, then publish it with \\`pnpm wp-upsert-hotfix-pr <tracker> <number>\\` (hotfix-ci, no merge from main, one fast-forward push).`,\n );\n }\n}\n"]}
|
|
@@ -98,7 +98,7 @@ class WholeRepoBuildGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
98
98
|
get fixHint() {
|
|
99
99
|
const command = this.resolvedCommand !== '' ? this.resolvedCommand : this.buildCommandTemplate();
|
|
100
100
|
return new hook_runtime_3.FixHint('That command builds the WHOLE monorepo. Build only what your change affects.', 'Build the affected projects, or one project, or one spec file — never the workspace:\n' +
|
|
101
|
-
` pnpm wp-build # the gate's own build; runs: ${command}\n` +
|
|
101
|
+
` pnpm wp-build <tracker> <number> # the gate's own build; runs: ${command}\n` +
|
|
102
102
|
' pnpm nx run <project>:ci # one project\n' +
|
|
103
103
|
' pnpm exec vitest run <path> # one suite');
|
|
104
104
|
}
|
|
@@ -129,7 +129,7 @@ class WholeRepoBuildGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
129
129
|
// no cure at all.
|
|
130
130
|
message() {
|
|
131
131
|
return 'Blocked: that builds the WHOLE monorepo. Build only what your change affects:\n\n'
|
|
132
|
-
+ ` pnpm wp-build # runs: ${this.resolvedCommand}\n`
|
|
132
|
+
+ ` pnpm wp-build <tracker> <number> # runs: ${this.resolvedCommand}\n`
|
|
133
133
|
+ ' (its full output goes to a FILE — it prints "FullLog : <path>"; grep THAT instead of\n'
|
|
134
134
|
+ ' rebuilding. Never re-run a build to read a different slice of it.)\n\n'
|
|
135
135
|
+ 'Narrower still: pnpm nx run <project>:ci, or pnpm exec vitest run <path>.';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"whole-repo-build-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/whole-repo-build-guard.ts"],"names":[],"m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AAC,aAAa,EACjB,IAAI,4BAAa,CAAC,wBAAwB,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,4BAAa,EAAE,gCAAiB,CAAC,CAChI,CAAC;IACN,CAAC;CACJ;AAtID,0DAsIC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { DEFAULT_BUILD_COMMAND } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase, EmptyRuleConfig } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { L0_FAULT_NONE } from '@webpieces/rules-config';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2_UNROWED } from '../decision-log';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { WholeRepoBuildScan, WholeRepoBuildHit } from './whole-repo-build-scan';\n\n/**\n * Blocks a Bash command that would build or test the WHOLE monorepo, and hands back the narrow\n * command to run instead. Which shapes count is `WholeRepoBuildScan`'s job; this rule owns the\n * decision, the log line and the two refusal messages.\n *\n * ─── Why: SCOPE and AGREEMENT, not a speed claim ───────────────────────────────────────────────────\n * `nx affected --target=ci --base=<fork point>` is the command the PR gate itself runs\n * (`commands.pr-gate.buildCommand`), so a green local result is evidence about the gate. A whole-repo\n * build is a different, wider command whose green says nothing extra — it just also compiles projects\n * the change cannot reach.\n *\n * It is NOT automatically faster, and this guard deliberately does not claim it is. Measured on a\n * `core-util` change, `affected` selected the IDENTICAL 20 projects / 104 tasks as the whole-repo\n * build: a package at the BASE of the dependency graph prunes nothing. The pruning win is real for\n * LEAF projects and absent for base ones. The long builds people blamed on scope were caused by a cold\n * nx cache and by CPU contention between agents running full sweeps at once (measured: ~3.2x total\n * test time under contention) — neither of which a narrower target list fixes on its own.\n *\n * So what this guard buys is the scope being right by default. Building the world is never the\n * correct inner-loop move in a monorepo; the correct one has existed all along, and nothing stopped\n * the wide one.\n *\n * ─── The message is READ FROM CONFIG, and it is RESOLVED ───────────────────────────────────────────\n * The replacement command comes from `commands.pr-gate.buildCommand` (injected into this guard's\n * config by load-config), so the refusal follows the project when the gate command changes. The `$(…)`\n * in it is EXPANDED before printing: handing an agent `--base=$(git merge-base origin/main HEAD)` is\n * handing it a template, and a template pasted where no shell expands it produces a confusing failure\n * that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;\n * anything else is left verbatim.\n *\n * ─── ALWAYS ON, with no switch anywhere ─────────────────────────────────────────────────────────────\n * This guard used to be an experiment, OFF unless a machine opted in with\n * `experimental.whole-repo-build-guard` in `~/.webpieces/config.json`. A human ended that experiment on\n * issue #1494 (Dean, 2026-12-03: \"I think all our experiments are done honestly\" — `whole-repo-build-guard`\n * becomes \"permanent, always ON for everyone\"). The key is gone, the OFF branch is gone, and this guard\n * no longer reads the home config at all. A machine whose file still carries the key gets a one-line\n * notice from the loader that it can be deleted (`ENDED_EXPERIMENTS`) — never a rejection, because that\n * file is shared by every webpieces release on the machine.\n *\n * There is still NO webpieces.config.json entry, for a separate reason: a live incident. This guard\n * first shipped with `mode: 'ON'` by default AND a REQUIRED entry under `hookGuards`, and every\n * consumer that upgraded hit fault Y — EVERY Bash call blocked — for a feature they had never asked\n * for. The fault was the REQUIRED KEY: the failure was at config LOAD, before any command was judged.\n * A guard with no key at all cannot fail that way.\n *\n * ─── ONE message, because the gate now always captures ─────────────────────────────────────────────\n * There used to be two refusals here, chosen by `experimental.buildGateLogCapture`: one naming the\n * narrower build to run, and one saying \"do not build at all — stage ② already builds and you can READ\n * the result\". That key is gone, because capturing the build's full output to a file is no longer\n * optional. What survived is the FIRST of those, now carrying the log pointer the second one existed to\n * offer: a refusal still has to answer \"so what do I run?\", and \"run nothing\" is only an answer when the\n * caller was already inside the PR flow.\n *\n * ─── Humans are not affected, by construction ──────────────────────────────────────────────────────\n * This is a PreToolUse hook. It sees the AI's Bash tool calls and nothing else — a human typing\n * `pnpm run build-all` in their own terminal never reaches a hook, and the `build-all` script itself is\n * deliberately left in package.json for exactly that reason. The guard is about what the AI does in a\n * loop, not about the command being wrong for a person who chooses to run it once.\n */\nexport class WholeRepoBuildGuardRule extends BashRuleBase<EmptyRuleConfig> {\n /**\n * `affectedBuildCommand` is the project's gate command (`commands.pr-gate.buildCommand`), handed in\n * by the runner off the loaded config. It is a CONSTRUCTOR ARGUMENT rather than a config field\n * because this guard has no config entry to read one from — and that is the point.\n */\n constructor(private readonly affectedBuildCommand: string) {\n // configKey === name and is DELIBERATELY not a real key: this guard has no\n // webpieces.config.json entry at all (see RETIRED_CONFIG_KEYS), and it is loaded outside the\n // config-driven set so the fault-Y sync check never sees it. Naming it here keeps the\n // AbstractRule contract honest without putting the string in HOOK_GUARD_NAMES.\n super(new EmptyRuleConfig(), 'whole-repo-build-guard', 'whole-repo-build-guard');\n }\n\n private readonly scanner = new CommandScanner();\n\n readonly description =\n 'Block a whole-monorepo build (build-all, an unnarrowed nx run-many, nx affected with no ' +\n '--base, a bare vitest run) and name the affected-scoped command to run instead.';\n\n /**\n * The command this rule last printed, so the fix hint and the violation message are one string and\n * cannot disagree. Empty until check() runs (fixHint is also read without it), at which point the\n * getter falls back to the configured TEMPLATE — never to a second literal, which is exactly the\n * drift this guard's own docstring says a duplicated command string causes.\n */\n private resolvedCommand = '';\n\n get fixHint(): FixHint {\n const command = this.resolvedCommand !== '' ? this.resolvedCommand : this.buildCommandTemplate();\n return new FixHint(\n 'That command builds the WHOLE monorepo. Build only what your change affects.',\n 'Build the affected projects, or one project, or one spec file — never the workspace:\\n' +\n ` pnpm wp-build # the gate's own build; runs: ${command}\\n` +\n ' pnpm nx run <project>:ci # one project\\n' +\n ' pnpm exec vitest run <path> # one suite',\n );\n }\n\n check(ctx: BashContext): readonly Violation[] {\n // Blocklist-shaped, so match on commandCode: stripping heredocs and quoted prose can only ever\n // block LESS, and this repo's own commit messages are full of the command names above.\n const hit = new WholeRepoBuildScan(this.scanner, ctx.effectiveCwd === ctx.workspaceRoot)\n .firstHit(ctx.commandCode);\n if (hit === null) return this.allow(ctx, 'not-a-whole-repo-build');\n\n // Resolved ONCE, here, and read by both the violation message and the fix hint.\n this.resolvedCommand = this.resolvedBuildCommand(ctx.workspaceRoot);\n return this.block(ctx, hit, this.message());\n }\n\n // The whole refusal. Short on purpose: it is read mid-task by an agent that needs the ONE command\n // to run next, and a guard message long enough to skim is a guard message that gets skimmed.\n //\n // `pnpm wp-build` FIRST, with the command it resolves to shown beside it. One thing to type, and it\n // runs `commands.pr-gate.buildCommand` through the gate's own resolver — so this refusal can never\n // teach a command the gate does not run, however the project reconfigures it.\n //\n // The log note is attached to the `wp-build` line ONLY, and that placement is the whole point. A\n // `FullLog :` pointer is written by `GateLogFile.pointer`, which is reachable solely through\n // `BuildGateLog` / `StageOutputLog` — i.e. through the gate. A bare `nx run <project>:ci` or\n // `vitest run <path>` writes no such file, so a blanket \"whichever you run\" claim would send an\n // agent to grep a path that does not exist while this same message forbids the re-run that is its\n // only remaining option. A cure that names an artifact the command does not produce is worse than\n // no cure at all.\n private message(): string {\n return 'Blocked: that builds the WHOLE monorepo. Build only what your change affects:\\n\\n'\n + ` pnpm wp-build # runs: ${this.resolvedCommand}\\n`\n + ' (its full output goes to a FILE — it prints \"FullLog : <path>\"; grep THAT instead of\\n'\n + ' rebuilding. Never re-run a build to read a different slice of it.)\\n\\n'\n + 'Narrower still: pnpm nx run <project>:ci, or pnpm exec vitest run <path>.';\n }\n\n /**\n * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, handed to\n * the constructor by the runner, falling back to the same DEFAULT_BUILD_COMMAND the gate itself\n * falls back to. This guard never spells a build command of its own — a second copy is how a refusal\n * starts teaching a command the gate does not run.\n */\n private buildCommandTemplate(): string {\n return this.affectedBuildCommand.trim() === '' ? DEFAULT_BUILD_COMMAND : this.affectedBuildCommand;\n }\n\n /**\n * The configured build command with its `$(git …)` substitutions expanded, so what is printed is\n * runnable as-is. Expansion is limited to git, and any failure leaves the template untouched — a\n * guard may degrade its own message, never fail the tool call it is judging.\n */\n private resolvedBuildCommand(workspaceRoot: string): string {\n const template = this.buildCommandTemplate();\n return template.replace(/\\$\\(([^()]*)\\)/g, (match: string, inner: string): string => {\n const trimmed = inner.trim();\n if (!trimmed.startsWith('git ')) return match;\n const output = this.capture(trimmed, workspaceRoot);\n return output === null ? match : output;\n });\n }\n\n private capture(command: string, workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync(command, {\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 private allow(ctx: BashContext, reason: string): readonly Violation[] {\n this.logDecision(ctx, 'ALLOW', reason);\n return [];\n }\n\n private block(ctx: BashContext, hit: WholeRepoBuildHit, message: string): readonly Violation[] {\n // BLOCK_AI_CURE, not BLOCK_HUMAN: the cure is one command the agent runs itself, and the\n // refusal hands it over already resolved.\n this.logDecision(ctx, 'BLOCK_AI_CURE', hit.shape);\n return [new V(1, this.truncate(ctx.command), message)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, verdict: Verdict, reason: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('whole-repo-build-guard', 'Bash', ctx.command, '-', verdict, reason, '-', L0_FAULT_NONE, MATRIX_L2_UNROWED),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"whole-repo-build-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/whole-repo-build-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAAgE;AAGhE,0DAAyD;AACzD,0DAAwE;AACxE,0DAAkD;AAClD,iEAA6D;AAC7D,0D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AAE,MAAM,EAAE,GAAG,EAAE,4BAAa,EAAE,gCAAiB,CAAC,CAChI,CAAC;IACN,CAAC;CACJ;AAtID,0DAsIC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { DEFAULT_BUILD_COMMAND } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase, EmptyRuleConfig } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { L0_FAULT_NONE } from '@webpieces/rules-config';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2_UNROWED } from '../decision-log';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { WholeRepoBuildScan, WholeRepoBuildHit } from './whole-repo-build-scan';\n\n/**\n * Blocks a Bash command that would build or test the WHOLE monorepo, and hands back the narrow\n * command to run instead. Which shapes count is `WholeRepoBuildScan`'s job; this rule owns the\n * decision, the log line and the two refusal messages.\n *\n * ─── Why: SCOPE and AGREEMENT, not a speed claim ───────────────────────────────────────────────────\n * `nx affected --target=ci --base=<fork point>` is the command the PR gate itself runs\n * (`commands.pr-gate.buildCommand`), so a green local result is evidence about the gate. A whole-repo\n * build is a different, wider command whose green says nothing extra — it just also compiles projects\n * the change cannot reach.\n *\n * It is NOT automatically faster, and this guard deliberately does not claim it is. Measured on a\n * `core-util` change, `affected` selected the IDENTICAL 20 projects / 104 tasks as the whole-repo\n * build: a package at the BASE of the dependency graph prunes nothing. The pruning win is real for\n * LEAF projects and absent for base ones. The long builds people blamed on scope were caused by a cold\n * nx cache and by CPU contention between agents running full sweeps at once (measured: ~3.2x total\n * test time under contention) — neither of which a narrower target list fixes on its own.\n *\n * So what this guard buys is the scope being right by default. Building the world is never the\n * correct inner-loop move in a monorepo; the correct one has existed all along, and nothing stopped\n * the wide one.\n *\n * ─── The message is READ FROM CONFIG, and it is RESOLVED ───────────────────────────────────────────\n * The replacement command comes from `commands.pr-gate.buildCommand` (injected into this guard's\n * config by load-config), so the refusal follows the project when the gate command changes. The `$(…)`\n * in it is EXPANDED before printing: handing an agent `--base=$(git merge-base origin/main HEAD)` is\n * handing it a template, and a template pasted where no shell expands it produces a confusing failure\n * that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;\n * anything else is left verbatim.\n *\n * ─── ALWAYS ON, with no switch anywhere ─────────────────────────────────────────────────────────────\n * This guard used to be an experiment, OFF unless a machine opted in with\n * `experimental.whole-repo-build-guard` in `~/.webpieces/config.json`. A human ended that experiment on\n * issue #1494 (Dean, 2026-12-03: \"I think all our experiments are done honestly\" — `whole-repo-build-guard`\n * becomes \"permanent, always ON for everyone\"). The key is gone, the OFF branch is gone, and this guard\n * no longer reads the home config at all. A machine whose file still carries the key gets a one-line\n * notice from the loader that it can be deleted (`ENDED_EXPERIMENTS`) — never a rejection, because that\n * file is shared by every webpieces release on the machine.\n *\n * There is still NO webpieces.config.json entry, for a separate reason: a live incident. This guard\n * first shipped with `mode: 'ON'` by default AND a REQUIRED entry under `hookGuards`, and every\n * consumer that upgraded hit fault Y — EVERY Bash call blocked — for a feature they had never asked\n * for. The fault was the REQUIRED KEY: the failure was at config LOAD, before any command was judged.\n * A guard with no key at all cannot fail that way.\n *\n * ─── ONE message, because the gate now always captures ─────────────────────────────────────────────\n * There used to be two refusals here, chosen by `experimental.buildGateLogCapture`: one naming the\n * narrower build to run, and one saying \"do not build at all — stage ② already builds and you can READ\n * the result\". That key is gone, because capturing the build's full output to a file is no longer\n * optional. What survived is the FIRST of those, now carrying the log pointer the second one existed to\n * offer: a refusal still has to answer \"so what do I run?\", and \"run nothing\" is only an answer when the\n * caller was already inside the PR flow.\n *\n * ─── Humans are not affected, by construction ──────────────────────────────────────────────────────\n * This is a PreToolUse hook. It sees the AI's Bash tool calls and nothing else — a human typing\n * `pnpm run build-all` in their own terminal never reaches a hook, and the `build-all` script itself is\n * deliberately left in package.json for exactly that reason. The guard is about what the AI does in a\n * loop, not about the command being wrong for a person who chooses to run it once.\n */\nexport class WholeRepoBuildGuardRule extends BashRuleBase<EmptyRuleConfig> {\n /**\n * `affectedBuildCommand` is the project's gate command (`commands.pr-gate.buildCommand`), handed in\n * by the runner off the loaded config. It is a CONSTRUCTOR ARGUMENT rather than a config field\n * because this guard has no config entry to read one from — and that is the point.\n */\n constructor(private readonly affectedBuildCommand: string) {\n // configKey === name and is DELIBERATELY not a real key: this guard has no\n // webpieces.config.json entry at all (see RETIRED_CONFIG_KEYS), and it is loaded outside the\n // config-driven set so the fault-Y sync check never sees it. Naming it here keeps the\n // AbstractRule contract honest without putting the string in HOOK_GUARD_NAMES.\n super(new EmptyRuleConfig(), 'whole-repo-build-guard', 'whole-repo-build-guard');\n }\n\n private readonly scanner = new CommandScanner();\n\n readonly description =\n 'Block a whole-monorepo build (build-all, an unnarrowed nx run-many, nx affected with no ' +\n '--base, a bare vitest run) and name the affected-scoped command to run instead.';\n\n /**\n * The command this rule last printed, so the fix hint and the violation message are one string and\n * cannot disagree. Empty until check() runs (fixHint is also read without it), at which point the\n * getter falls back to the configured TEMPLATE — never to a second literal, which is exactly the\n * drift this guard's own docstring says a duplicated command string causes.\n */\n private resolvedCommand = '';\n\n get fixHint(): FixHint {\n const command = this.resolvedCommand !== '' ? this.resolvedCommand : this.buildCommandTemplate();\n return new FixHint(\n 'That command builds the WHOLE monorepo. Build only what your change affects.',\n 'Build the affected projects, or one project, or one spec file — never the workspace:\\n' +\n ` pnpm wp-build <tracker> <number> # the gate's own build; runs: ${command}\\n` +\n ' pnpm nx run <project>:ci # one project\\n' +\n ' pnpm exec vitest run <path> # one suite',\n );\n }\n\n check(ctx: BashContext): readonly Violation[] {\n // Blocklist-shaped, so match on commandCode: stripping heredocs and quoted prose can only ever\n // block LESS, and this repo's own commit messages are full of the command names above.\n const hit = new WholeRepoBuildScan(this.scanner, ctx.effectiveCwd === ctx.workspaceRoot)\n .firstHit(ctx.commandCode);\n if (hit === null) return this.allow(ctx, 'not-a-whole-repo-build');\n\n // Resolved ONCE, here, and read by both the violation message and the fix hint.\n this.resolvedCommand = this.resolvedBuildCommand(ctx.workspaceRoot);\n return this.block(ctx, hit, this.message());\n }\n\n // The whole refusal. Short on purpose: it is read mid-task by an agent that needs the ONE command\n // to run next, and a guard message long enough to skim is a guard message that gets skimmed.\n //\n // `pnpm wp-build` FIRST, with the command it resolves to shown beside it. One thing to type, and it\n // runs `commands.pr-gate.buildCommand` through the gate's own resolver — so this refusal can never\n // teach a command the gate does not run, however the project reconfigures it.\n //\n // The log note is attached to the `wp-build` line ONLY, and that placement is the whole point. A\n // `FullLog :` pointer is written by `GateLogFile.pointer`, which is reachable solely through\n // `BuildGateLog` / `StageOutputLog` — i.e. through the gate. A bare `nx run <project>:ci` or\n // `vitest run <path>` writes no such file, so a blanket \"whichever you run\" claim would send an\n // agent to grep a path that does not exist while this same message forbids the re-run that is its\n // only remaining option. A cure that names an artifact the command does not produce is worse than\n // no cure at all.\n private message(): string {\n return 'Blocked: that builds the WHOLE monorepo. Build only what your change affects:\\n\\n'\n + ` pnpm wp-build <tracker> <number> # runs: ${this.resolvedCommand}\\n`\n + ' (its full output goes to a FILE — it prints \"FullLog : <path>\"; grep THAT instead of\\n'\n + ' rebuilding. Never re-run a build to read a different slice of it.)\\n\\n'\n + 'Narrower still: pnpm nx run <project>:ci, or pnpm exec vitest run <path>.';\n }\n\n /**\n * The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, handed to\n * the constructor by the runner, falling back to the same DEFAULT_BUILD_COMMAND the gate itself\n * falls back to. This guard never spells a build command of its own — a second copy is how a refusal\n * starts teaching a command the gate does not run.\n */\n private buildCommandTemplate(): string {\n return this.affectedBuildCommand.trim() === '' ? DEFAULT_BUILD_COMMAND : this.affectedBuildCommand;\n }\n\n /**\n * The configured build command with its `$(git …)` substitutions expanded, so what is printed is\n * runnable as-is. Expansion is limited to git, and any failure leaves the template untouched — a\n * guard may degrade its own message, never fail the tool call it is judging.\n */\n private resolvedBuildCommand(workspaceRoot: string): string {\n const template = this.buildCommandTemplate();\n return template.replace(/\\$\\(([^()]*)\\)/g, (match: string, inner: string): string => {\n const trimmed = inner.trim();\n if (!trimmed.startsWith('git ')) return match;\n const output = this.capture(trimmed, workspaceRoot);\n return output === null ? match : output;\n });\n }\n\n private capture(command: string, workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync(command, {\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 private allow(ctx: BashContext, reason: string): readonly Violation[] {\n this.logDecision(ctx, 'ALLOW', reason);\n return [];\n }\n\n private block(ctx: BashContext, hit: WholeRepoBuildHit, message: string): readonly Violation[] {\n // BLOCK_AI_CURE, not BLOCK_HUMAN: the cure is one command the agent runs itself, and the\n // refusal hands it over already resolved.\n this.logDecision(ctx, 'BLOCK_AI_CURE', hit.shape);\n return [new V(1, this.truncate(ctx.command), message)];\n }\n\n private truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n }\n\n private logDecision(ctx: BashContext, verdict: Verdict, reason: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('whole-repo-build-guard', 'Bash', ctx.command, '-', verdict, reason, '-', L0_FAULT_NONE, MATRIX_L2_UNROWED),\n );\n }\n}\n"]}
|
package/src/core/version-sync.js
CHANGED
|
@@ -411,7 +411,7 @@ class VersionSyncGuard {
|
|
|
411
411
|
` 1. Release \`${branch}\` from this worktree (git refuses to check out a branch another`,
|
|
412
412
|
` worktree holds), then in the main tree: \`git switch ${branch} && pnpm install\` —`,
|
|
413
413
|
` that install puts the branch's OWN pinned release in charge of it.`,
|
|
414
|
-
` 2. Make the fix there and publish it with \`pnpm wp-upsert-hotfix-pr
|
|
414
|
+
` 2. Make the fix there and publish it with \`pnpm wp-upsert-hotfix-pr <tracker> <number>\`.`,
|
|
415
415
|
];
|
|
416
416
|
}
|
|
417
417
|
/**
|
|
@@ -426,7 +426,7 @@ class VersionSyncGuard {
|
|
|
426
426
|
` > ${this.show(quartet.worktree.pinned).trim()} — production's release — while the main tree ${tree.mainRoot} runs ${this.show(quartet.main.installed).trim()}.`,
|
|
427
427
|
` > A hotfix cannot run in a linked worktree, and its pin must not be raised. Please do this`,
|
|
428
428
|
` > hotfix in the MAIN tree: check \`${branch}\` out there, \`pnpm install\`, make the fix, and`,
|
|
429
|
-
` > publish it with \`pnpm wp-upsert-hotfix-pr
|
|
429
|
+
` > publish it with \`pnpm wp-upsert-hotfix-pr <tracker> <number>\`. Do NOT redo it in another worktree.`,
|
|
430
430
|
` Do NOT retry this call — RETRYING IS THE BUG. It re-fires this identical deny and buries the`,
|
|
431
431
|
` ask above; one subagent did it 13 times, 25 across that whole session.`,
|
|
432
432
|
...(aiType === 'codex' ? this.waitLines(aiType)
|