@webpieces/agent-workflow-rules 0.4.1027 → 0.4.1029
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/decision-log.d.ts +2 -2
- package/src/core/decision-log.js +2 -2
- package/src/core/decision-log.js.map +1 -1
- 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.d.ts +11 -35
- package/src/core/rules/whole-repo-build-guard.js +14 -78
- package/src/core/rules/whole-repo-build-guard.js.map +1 -1
- package/src/core/runner.js +2 -3
- package/src/core/runner.js.map +1 -1
- package/src/core/version-sync.js +2 -2
- package/src/core/version-sync.js.map +1 -1
- package/src/rule-migrations.js +1 -1
- package/src/rule-migrations.js.map +1 -1
- package/src/safeguard-catalog.js +1 -1
- package/src/safeguard-catalog.js.map +1 -1
|
@@ -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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AAU,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,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;MAClF,kGAAkG;MAClG,iGAAiG,CACtG,CAAC;AAEF,uGAAuG;AACvG,+FAA+F;AAC/F,qGAAqG;AACrG,iFAAiF;AACjF,MAAM,SAAS,GAA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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,uZAAuZ,OAAO,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"]}
|
|
@@ -31,33 +31,20 @@ import { FixHint } from '@webpieces/hook-runtime';
|
|
|
31
31
|
* that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;
|
|
32
32
|
* anything else is left verbatim.
|
|
33
33
|
*
|
|
34
|
-
* ───
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
34
|
+
* ─── ALWAYS ON, with no switch anywhere ─────────────────────────────────────────────────────────────
|
|
35
|
+
* This guard used to be an experiment, OFF unless a machine opted in with
|
|
36
|
+
* `experimental.whole-repo-build-guard` in `~/.webpieces/config.json`. A human ended that experiment on
|
|
37
|
+
* issue #1494 (Dean, 2026-12-03: "I think all our experiments are done honestly" — `whole-repo-build-guard`
|
|
38
|
+
* becomes "permanent, always ON for everyone"). The key is gone, the OFF branch is gone, and this guard
|
|
39
|
+
* no longer reads the home config at all. A machine whose file still carries the key gets a one-line
|
|
40
|
+
* notice from the loader that it can be deleted (`ENDED_EXPERIMENTS`) — never a rejection, because that
|
|
41
|
+
* file is shared by every webpieces release on the machine.
|
|
38
42
|
*
|
|
39
|
-
*
|
|
40
|
-
* codebase ships OFF and stays OFF for two years. A flag that defaults ON is not an experiment — it is
|
|
41
|
-
* a shipped behaviour that skipped its soak period, and it changes what every agent on every machine
|
|
42
|
-
* can do the moment they upgrade. If few machines opt in, that is information about the experiment; it
|
|
43
|
-
* is not a reason to force it on everybody.
|
|
44
|
-
*
|
|
45
|
-
* There is also NO webpieces.config.json entry, for a separate reason: a live incident. This guard
|
|
43
|
+
* There is still NO webpieces.config.json entry, for a separate reason: a live incident. This guard
|
|
46
44
|
* first shipped with `mode: 'ON'` by default AND a REQUIRED entry under `hookGuards`, and every
|
|
47
45
|
* consumer that upgraded hit fault Y — EVERY Bash call blocked — for a feature they had never asked
|
|
48
|
-
* for. The fault was the REQUIRED KEY: the failure was at config LOAD, before any command was judged
|
|
49
|
-
*
|
|
50
|
-
* machine-local file is what makes the default state need no file, no key and no edit.
|
|
51
|
-
*
|
|
52
|
-
* Three states, and only three:
|
|
53
|
-
* - the file does not exist (essentially every machine), or exists without the key → the guard is
|
|
54
|
-
* OFF, and inert: no block, no log, no message. Every key in that file is optional, because it is
|
|
55
|
-
* MACHINE-GLOBAL and the repos on one machine pin different webpieces releases — a required key
|
|
56
|
-
* there is unsatisfiable (see home-config.ts).
|
|
57
|
-
* - the key is present → its boolean decides, and only `true` arms the guard.
|
|
58
|
-
* - the file exists and is unparseable, or a key it DOES define has the wrong type → HARD FAILURE
|
|
59
|
-
* naming the edit. That is a file somebody wrote wrongly, not one written for another release.
|
|
60
|
-
* Editing that file is an unconditional PASS in the guards, so the block is always self-curable.
|
|
46
|
+
* for. The fault was the REQUIRED KEY: the failure was at config LOAD, before any command was judged.
|
|
47
|
+
* A guard with no key at all cannot fail that way.
|
|
61
48
|
*
|
|
62
49
|
* ─── ONE message, because the gate now always captures ─────────────────────────────────────────────
|
|
63
50
|
* There used to be two refusals here, chosen by `experimental.buildGateLogCapture`: one naming the
|
|
@@ -82,9 +69,6 @@ export declare class WholeRepoBuildGuardRule extends BashRuleBase<EmptyRuleConfi
|
|
|
82
69
|
*/
|
|
83
70
|
constructor(affectedBuildCommand: string);
|
|
84
71
|
private readonly scanner;
|
|
85
|
-
private readonly homeConfig;
|
|
86
|
-
/** Set by check() when the home config is unreadable, so the fix hint names the same repair. */
|
|
87
|
-
private homeConfigError;
|
|
88
72
|
readonly description: string;
|
|
89
73
|
/**
|
|
90
74
|
* The command this rule last printed, so the fix hint and the violation message are one string and
|
|
@@ -95,14 +79,6 @@ export declare class WholeRepoBuildGuardRule extends BashRuleBase<EmptyRuleConfi
|
|
|
95
79
|
private resolvedCommand;
|
|
96
80
|
get fixHint(): FixHint;
|
|
97
81
|
check(ctx: BashContext): readonly Violation[];
|
|
98
|
-
/**
|
|
99
|
-
* The home config, or the Error explaining why it is unusable. NOT a boolean: "absent" is already
|
|
100
|
-
* folded into the returned HomeConfig (each key's default — for this guard, OFF), so the only thing
|
|
101
|
-
* left to distinguish is "present and wrong", which must be reported rather than swallowed.
|
|
102
|
-
*/
|
|
103
|
-
private loadHome;
|
|
104
|
-
private blockOnBrokenHomeConfig;
|
|
105
|
-
private brokenHomeConfigMessage;
|
|
106
82
|
private message;
|
|
107
83
|
/**
|
|
108
84
|
* The project's build command, unexpanded. ONE source: `commands.pr-gate.buildCommand`, handed to
|
|
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.WholeRepoBuildGuardRule = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
6
|
-
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
7
6
|
const hook_runtime_1 = require("@webpieces/hook-runtime");
|
|
8
7
|
const hook_runtime_2 = require("@webpieces/hook-runtime");
|
|
9
8
|
const hook_runtime_3 = require("@webpieces/hook-runtime");
|
|
@@ -42,33 +41,20 @@ const whole_repo_build_scan_1 = require("./whole-repo-build-scan");
|
|
|
42
41
|
* that reads like the guard's advice was wrong. Only `$(git …)` is expanded, and only read-only git;
|
|
43
42
|
* anything else is left verbatim.
|
|
44
43
|
*
|
|
45
|
-
* ───
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
44
|
+
* ─── ALWAYS ON, with no switch anywhere ─────────────────────────────────────────────────────────────
|
|
45
|
+
* This guard used to be an experiment, OFF unless a machine opted in with
|
|
46
|
+
* `experimental.whole-repo-build-guard` in `~/.webpieces/config.json`. A human ended that experiment on
|
|
47
|
+
* issue #1494 (Dean, 2026-12-03: "I think all our experiments are done honestly" — `whole-repo-build-guard`
|
|
48
|
+
* becomes "permanent, always ON for everyone"). The key is gone, the OFF branch is gone, and this guard
|
|
49
|
+
* no longer reads the home config at all. A machine whose file still carries the key gets a one-line
|
|
50
|
+
* notice from the loader that it can be deleted (`ENDED_EXPERIMENTS`) — never a rejection, because that
|
|
51
|
+
* file is shared by every webpieces release on the machine.
|
|
49
52
|
*
|
|
50
|
-
*
|
|
51
|
-
* codebase ships OFF and stays OFF for two years. A flag that defaults ON is not an experiment — it is
|
|
52
|
-
* a shipped behaviour that skipped its soak period, and it changes what every agent on every machine
|
|
53
|
-
* can do the moment they upgrade. If few machines opt in, that is information about the experiment; it
|
|
54
|
-
* is not a reason to force it on everybody.
|
|
55
|
-
*
|
|
56
|
-
* There is also NO webpieces.config.json entry, for a separate reason: a live incident. This guard
|
|
53
|
+
* There is still NO webpieces.config.json entry, for a separate reason: a live incident. This guard
|
|
57
54
|
* first shipped with `mode: 'ON'` by default AND a REQUIRED entry under `hookGuards`, and every
|
|
58
55
|
* consumer that upgraded hit fault Y — EVERY Bash call blocked — for a feature they had never asked
|
|
59
|
-
* for. The fault was the REQUIRED KEY: the failure was at config LOAD, before any command was judged
|
|
60
|
-
*
|
|
61
|
-
* machine-local file is what makes the default state need no file, no key and no edit.
|
|
62
|
-
*
|
|
63
|
-
* Three states, and only three:
|
|
64
|
-
* - the file does not exist (essentially every machine), or exists without the key → the guard is
|
|
65
|
-
* OFF, and inert: no block, no log, no message. Every key in that file is optional, because it is
|
|
66
|
-
* MACHINE-GLOBAL and the repos on one machine pin different webpieces releases — a required key
|
|
67
|
-
* there is unsatisfiable (see home-config.ts).
|
|
68
|
-
* - the key is present → its boolean decides, and only `true` arms the guard.
|
|
69
|
-
* - the file exists and is unparseable, or a key it DOES define has the wrong type → HARD FAILURE
|
|
70
|
-
* naming the edit. That is a file somebody wrote wrongly, not one written for another release.
|
|
71
|
-
* Editing that file is an unconditional PASS in the guards, so the block is always self-curable.
|
|
56
|
+
* for. The fault was the REQUIRED KEY: the failure was at config LOAD, before any command was judged.
|
|
57
|
+
* A guard with no key at all cannot fail that way.
|
|
72
58
|
*
|
|
73
59
|
* ─── ONE message, because the gate now always captures ─────────────────────────────────────────────
|
|
74
60
|
* There used to be two refusals here, chosen by `experimental.buildGateLogCapture`: one naming the
|
|
@@ -100,9 +86,6 @@ class WholeRepoBuildGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
100
86
|
this.affectedBuildCommand = affectedBuildCommand;
|
|
101
87
|
}
|
|
102
88
|
scanner = new hook_runtime_4.CommandScanner();
|
|
103
|
-
homeConfig = new rules_config_1.HomeConfigService();
|
|
104
|
-
/** Set by check() when the home config is unreadable, so the fix hint names the same repair. */
|
|
105
|
-
homeConfigError = '';
|
|
106
89
|
description = 'Block a whole-monorepo build (build-all, an unnarrowed nx run-many, nx affected with no ' +
|
|
107
90
|
'--base, a bare vitest run) and name the affected-scoped command to run instead.';
|
|
108
91
|
/**
|
|
@@ -113,32 +96,13 @@ class WholeRepoBuildGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
113
96
|
*/
|
|
114
97
|
resolvedCommand = '';
|
|
115
98
|
get fixHint() {
|
|
116
|
-
if (this.homeConfigError !== '') {
|
|
117
|
-
return new hook_runtime_3.FixHint('~/.webpieces/config.json exists but cannot be read.', 'Edit ~/.webpieces/config.json (editing it is always permitted, including right now), or ' +
|
|
118
|
-
'delete it outright — with no such file every webpieces command behaves exactly as it ' +
|
|
119
|
-
'does by default.');
|
|
120
|
-
}
|
|
121
99
|
const command = this.resolvedCommand !== '' ? this.resolvedCommand : this.buildCommandTemplate();
|
|
122
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' +
|
|
123
|
-
` 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` +
|
|
124
102
|
' pnpm nx run <project>:ci # one project\n' +
|
|
125
|
-
' pnpm exec vitest run <path> # one suite
|
|
126
|
-
'This guard is OFF unless a machine opts in with "experimental": ' +
|
|
127
|
-
'{ "whole-repo-build-guard": true } in ~/.webpieces/config.json — remove that line to turn ' +
|
|
128
|
-
'it off again (there is no webpieces.config.json entry for it).');
|
|
103
|
+
' pnpm exec vitest run <path> # one suite');
|
|
129
104
|
}
|
|
130
105
|
check(ctx) {
|
|
131
|
-
const home = this.loadHome();
|
|
132
|
-
// A file someone deliberately created must be correct — see the class docstring. Reported for
|
|
133
|
-
// whatever command happens to be running, because a broken opt-in file is not a build question.
|
|
134
|
-
if (home instanceof Error)
|
|
135
|
-
return this.blockOnBrokenHomeConfig(ctx, home);
|
|
136
|
-
// THE OPT-IN. False for every machine that has not said `true` out loud, including every machine
|
|
137
|
-
// with no `~/.webpieces/config.json` at all. Being off is silent on purpose: no block, no log, no
|
|
138
|
-
// file touched — the default must be indistinguishable from "this guard does not exist".
|
|
139
|
-
this.homeConfigError = '';
|
|
140
|
-
if (!home.wholeRepoBuildGuard)
|
|
141
|
-
return [];
|
|
142
106
|
// Blocklist-shaped, so match on commandCode: stripping heredocs and quoted prose can only ever
|
|
143
107
|
// block LESS, and this repo's own commit messages are full of the command names above.
|
|
144
108
|
const hit = new whole_repo_build_scan_1.WholeRepoBuildScan(this.scanner, ctx.effectiveCwd === ctx.workspaceRoot)
|
|
@@ -149,34 +113,6 @@ class WholeRepoBuildGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
149
113
|
this.resolvedCommand = this.resolvedBuildCommand(ctx.workspaceRoot);
|
|
150
114
|
return this.block(ctx, hit, this.message());
|
|
151
115
|
}
|
|
152
|
-
/**
|
|
153
|
-
* The home config, or the Error explaining why it is unusable. NOT a boolean: "absent" is already
|
|
154
|
-
* folded into the returned HomeConfig (each key's default — for this guard, OFF), so the only thing
|
|
155
|
-
* left to distinguish is "present and wrong", which must be reported rather than swallowed.
|
|
156
|
-
*/
|
|
157
|
-
loadHome() {
|
|
158
|
-
// webpieces-disable no-unmanaged-exceptions -- chokepoint: a rejected home config is converted
|
|
159
|
-
// into this guard's own block, which carries the loader's fix instruction verbatim
|
|
160
|
-
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
161
|
-
try {
|
|
162
|
-
return this.homeConfig.load();
|
|
163
|
-
}
|
|
164
|
-
catch (err) {
|
|
165
|
-
const error = (0, to_error_1.toError)(err);
|
|
166
|
-
return error;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
blockOnBrokenHomeConfig(ctx, error) {
|
|
170
|
-
this.homeConfigError = error.message;
|
|
171
|
-
this.logDecision(ctx, 'BLOCK_AI_CURE', 'home-config-invalid');
|
|
172
|
-
return [new hook_runtime_1.Violation(1, this.truncate(ctx.command), this.brokenHomeConfigMessage(error))];
|
|
173
|
-
}
|
|
174
|
-
brokenHomeConfigMessage(error) {
|
|
175
|
-
const detail = error instanceof tooling_common_1.InformAiError
|
|
176
|
-
? error.message
|
|
177
|
-
: `~/.webpieces/config.json could not be read: ${error.message}`;
|
|
178
|
-
return `Blocked: ~/.webpieces/config.json is present but unusable.\n\n${detail}`;
|
|
179
|
-
}
|
|
180
116
|
// The whole refusal. Short on purpose: it is read mid-task by an agent that needs the ONE command
|
|
181
117
|
// to run next, and a guard message long enough to skim is a guard message that gets skimmed.
|
|
182
118
|
//
|
|
@@ -193,7 +129,7 @@ class WholeRepoBuildGuardRule extends hook_runtime_2.BashRuleBase {
|
|
|
193
129
|
// no cure at all.
|
|
194
130
|
message() {
|
|
195
131
|
return 'Blocked: that builds the WHOLE monorepo. Build only what your change affects:\n\n'
|
|
196
|
-
+ ` pnpm wp-build # runs: ${this.resolvedCommand}\n`
|
|
132
|
+
+ ` pnpm wp-build <tracker> <number> # runs: ${this.resolvedCommand}\n`
|
|
197
133
|
+ ' (its full output goes to a FILE — it prints "FullLog : <path>"; grep THAT instead of\n'
|
|
198
134
|
+ ' rebuilding. Never re-run a build to read a different slice of it.)\n\n'
|
|
199
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":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA+F;AAC/F,8DAA0D;AAG1D,0DAAyD;AACzD,0DAAwE;AACxE,0DAAkD;AAClD,iEAA6D;AAC7D,0DAAwD;AACxD,kDAA8F;AAC9F,0DAAyD;AACzD,mEAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AACH,MAAa,uBAAwB,SAAQ,2BAA6B;IAMzC;IAL7B;;;;OAIG;IACH,YAA6B,oBAA4B;QACrD,2EAA2E;QAC3E,6FAA6F;QAC7F,sFAAsF;QACtF,+EAA+E;QAC/E,KAAK,CAAC,IAAI,8BAAe,EAAE,EAAE,wBAAwB,EAAE,wBAAwB,CAAC,CAAC;QALxD,yBAAoB,GAApB,oBAAoB,CAA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nimport { DEFAULT_BUILD_COMMAND, HomeConfig, HomeConfigService } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\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 * ─── EXPERIMENTAL, OFF by default, with ONE machine-local opt-in ───────────────────────────────────\n * `experimental.whole-repo-build-guard` in `~/.webpieces/config.json` is this guard's only switch, and\n * it is an OPT-IN: ON requires the explicit boolean `true`. Absent key, absent `experimental` section,\n * absent file, and an explicit `false` are ONE state, and that state is OFF.\n *\n * That direction is a standing policy, not a per-flag judgement: EVERY `experimental.*` flag in this\n * codebase ships OFF and stays OFF for two years. A flag that defaults ON is not an experiment — it is\n * a shipped behaviour that skipped its soak period, and it changes what every agent on every machine\n * can do the moment they upgrade. If few machines opt in, that is information about the experiment; it\n * is not a reason to force it on everybody.\n *\n * There is also 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 * and the cure was \"edit a file to get your shell back\". Keeping the switch in an OPTIONAL\n * machine-local file is what makes the default state need no file, no key and no edit.\n *\n * Three states, and only three:\n * - the file does not exist (essentially every machine), or exists without the key → the guard is\n * OFF, and inert: no block, no log, no message. Every key in that file is optional, because it is\n * MACHINE-GLOBAL and the repos on one machine pin different webpieces releases — a required key\n * there is unsatisfiable (see home-config.ts).\n * - the key is present → its boolean decides, and only `true` arms the guard.\n * - the file exists and is unparseable, or a key it DOES define has the wrong type → HARD FAILURE\n * naming the edit. That is a file somebody wrote wrongly, not one written for another release.\n * Editing that file is an unconditional PASS in the guards, so the block is always self-curable.\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 private readonly homeConfig = new HomeConfigService();\n\n /** Set by check() when the home config is unreadable, so the fix hint names the same repair. */\n private homeConfigError = '';\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 if (this.homeConfigError !== '') {\n return new FixHint(\n '~/.webpieces/config.json exists but cannot be read.',\n 'Edit ~/.webpieces/config.json (editing it is always permitted, including right now), or ' +\n 'delete it outright — with no such file every webpieces command behaves exactly as it ' +\n 'does by default.',\n );\n }\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 'This guard is OFF unless a machine opts in with \"experimental\": ' +\n '{ \"whole-repo-build-guard\": true } in ~/.webpieces/config.json — remove that line to turn ' +\n 'it off again (there is no webpieces.config.json entry for it).',\n );\n }\n\n check(ctx: BashContext): readonly Violation[] {\n const home = this.loadHome();\n // A file someone deliberately created must be correct — see the class docstring. Reported for\n // whatever command happens to be running, because a broken opt-in file is not a build question.\n if (home instanceof Error) return this.blockOnBrokenHomeConfig(ctx, home);\n\n // THE OPT-IN. False for every machine that has not said `true` out loud, including every machine\n // with no `~/.webpieces/config.json` at all. Being off is silent on purpose: no block, no log, no\n // file touched — the default must be indistinguishable from \"this guard does not exist\".\n this.homeConfigError = '';\n if (!home.wholeRepoBuildGuard) return [];\n\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 /**\n * The home config, or the Error explaining why it is unusable. NOT a boolean: \"absent\" is already\n * folded into the returned HomeConfig (each key's default — for this guard, OFF), so the only thing\n * left to distinguish is \"present and wrong\", which must be reported rather than swallowed.\n */\n private loadHome(): HomeConfig | Error {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a rejected home config is converted\n // into this guard's own block, which carries the loader's fix instruction verbatim\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return this.homeConfig.load();\n } catch (err: unknown) {\n const error = toError(err);\n return error;\n }\n }\n\n private blockOnBrokenHomeConfig(ctx: BashContext, error: Error): readonly Violation[] {\n this.homeConfigError = error.message;\n this.logDecision(ctx, 'BLOCK_AI_CURE', 'home-config-invalid');\n return [new V(1, this.truncate(ctx.command), this.brokenHomeConfigMessage(error))];\n }\n\n private brokenHomeConfigMessage(error: Error): string {\n const detail = error instanceof InformAiError\n ? error.message\n : `~/.webpieces/config.json could not be read: ${error.message}`;\n return `Blocked: ~/.webpieces/config.json is present but unusable.\\n\\n${detail}`;\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,0DAAwD;AACxD,kDAA8F;AAC9F,0DAAyD;AACzD,mEAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,MAAa,uBAAwB,SAAQ,2BAA6B;IAMzC;IAL7B;;;;OAIG;IACH,YAA6B,oBAA4B;QACrD,2EAA2E;QAC3E,6FAA6F;QAC7F,sFAAsF;QACtF,+EAA+E;QAC/E,KAAK,CAAC,IAAI,8BAAe,EAAE,EAAE,wBAAwB,EAAE,wBAAwB,CAAC,CAAC;QALxD,yBAAoB,GAApB,oBAAoB,CAAQ;IAMzD,CAAC;IAEgB,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC;IAEvC,WAAW,GAChB,0FAA0F;QAC1F,iFAAiF,CAAC;IAEtF;;;;;OAKG;IACK,eAAe,GAAG,EAAE,CAAC;IAE7B,IAAI,OAAO;QACP,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACjG,OAAO,IAAI,sBAAO,CACd,8EAA8E,EAC9E,wFAAwF;YACxF,sEAAsE,OAAO,IAAI;YACjF,8CAA8C;YAC9C,6CAA6C,CAChD,CAAC;IACN,CAAC;IAED,KAAK,CAAC,GAAgB;QAClB,+FAA+F;QAC/F,uFAAuF;QACvF,MAAM,GAAG,GAAG,IAAI,0CAAkB,CAAC,IAAI,CAAC,OA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AC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;IACvD,CAAC;IAEO,WAAW,CAAC,GAAgB,EAAE,OAAgB,EAAE,MAAc;QAClE,IAAA,+BAAgB,EACZ,GAAG,CAAC,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 <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/runner.js
CHANGED
|
@@ -384,9 +384,8 @@ function misplacedCdBlock(command, tree) {
|
|
|
384
384
|
* The KEYLESS bash guards, deliberately kept OUT of the config-driven rule set. They have no
|
|
385
385
|
* webpieces.config.json entry at all, so passing them through checkConfigSync would make every
|
|
386
386
|
* consumer's next Bash call a fault-Y block ("this rule has no entry") for a feature nobody opted into
|
|
387
|
-
* — which is exactly what whole-repo-build-guard did on its first release.
|
|
388
|
-
*
|
|
389
|
-
* (absent means OFF); commit-message-substitution-guard and build-output-pipe-guard act unconditionally.
|
|
387
|
+
* — which is exactly what whole-repo-build-guard did on its first release. All of them act
|
|
388
|
+
* unconditionally (whole-repo-build-guard's machine-local opt-in was ended by a human on issue #1494).
|
|
390
389
|
* They still honour excludePaths, and they do not run in `rules` mode (code-style-only hook).
|
|
391
390
|
*/
|
|
392
391
|
// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape
|