@webpieces/ai-hook-rules 0.4.837 → 0.4.838
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 +6 -4
- package/src/adapters/codex-subagent-guard.js +5 -3
- package/src/adapters/codex-subagent-guard.js.map +1 -1
- package/src/adapters/review-identity-stamper.d.ts +1 -1
- package/src/adapters/review-identity-stamper.js +3 -3
- package/src/adapters/review-identity-stamper.js.map +1 -1
- package/src/bin/shim-audit-log.js +4 -4
- package/src/bin/shim-audit-log.js.map +1 -1
- package/src/core/decision-log.js +7 -5
- package/src/core/decision-log.js.map +1 -1
- package/src/core/effective-tree.js +5 -4
- package/src/core/effective-tree.js.map +1 -1
- package/src/core/l0-tooling-doc.js +5 -4
- package/src/core/l0-tooling-doc.js.map +1 -1
- package/src/core/main-sync-log.js +3 -3
- package/src/core/main-sync-log.js.map +1 -1
- package/src/core/main-sync-timeout.js +4 -3
- package/src/core/main-sync-timeout.js.map +1 -1
- package/src/core/rejection-log.js +2 -1
- package/src/core/rejection-log.js.map +1 -1
- package/src/core/rules/branch-creation-guard.js +5 -4
- package/src/core/rules/branch-creation-guard.js.map +1 -1
- package/src/core/rules/feature-branch-guard.js +4 -3
- package/src/core/rules/feature-branch-guard.js.map +1 -1
- package/src/core/rules/main-freshness.d.ts +1 -1
- package/src/core/rules/main-freshness.js.map +1 -1
- package/src/core/rules/merge-in-progress-guard.js +2 -1
- package/src/core/rules/merge-in-progress-guard.js.map +1 -1
- package/src/core/rules/merged-branch-bash-guard.js +3 -2
- package/src/core/rules/merged-branch-bash-guard.js.map +1 -1
- package/src/core/rules/read-stale-guard.js +4 -3
- package/src/core/rules/read-stale-guard.js.map +1 -1
- package/src/core/rules/stale-main-bash-guard.js +3 -2
- package/src/core/rules/stale-main-bash-guard.js.map +1 -1
- package/src/core/rules/tree-recovery.js +2 -1
- package/src/core/rules/tree-recovery.js.map +1 -1
- package/src/core/rules/wait-spin-guard.js +2 -2
- package/src/core/rules/wait-spin-guard.js.map +1 -1
- package/src/core/rules/whole-repo-build-guard.js +2 -1
- package/src/core/rules/whole-repo-build-guard.js.map +1 -1
- package/src/core/session-call-history.js +2 -2
- package/src/core/session-call-history.js.map +1 -1
- package/src/core/sync-main.js +9 -8
- package/src/core/sync-main.js.map +1 -1
- package/src/core/types.d.ts +2 -1
- package/src/core/types.js +3 -2
- package/src/core/types.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wait-spin-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/wait-spin-guard.ts"],"names":[],"mappings":";;;AAAA,0DAAuD;AAGvD,oCAA0C;AAC1C,4CAA6D;AAC7D,0CAAsC;AACtC,sDAAkD;AAClD,kDAA8F;AAC9F,kDAAiD;AACjD,kEAA6D;AAC7D,6DAAwD;AACxD,qDAAwE;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AACH,MAAa,iBAAkB,SAAQ,wBAA6B;IAChE;QACI,8FAA8F;QAC9F,wBAAwB;QACxB,KAAK,CAAC,IAAI,2BAAe,EAAE,EAAE,iBAAiB,EAAE,iBAAiB,CAAC,CAAC;IACvE,CAAC;IAEgB,IAAI,GAAG,IAAI,6BAAY,CAAC,IAAI,6BAAc,EAAE,EAAE,IAAI,qCAAgB,EAAE,CAAC,CAAC;IACtE,OAAO,GAAG,IAAI,yCAAkB,EAAE,CAAC;IAE3C,WAAW,GAChB,gGAAgG;QAChG,8FAA8F;QAC9F,0FAA0F;QAC1F,gGAAgG;QAChG,kGAAkG;QAClG,8BAA8B,CAAC;IAEnC,IAAI,OAAO;QACP,OAAO,IAAI,kBAAO,CACd,+FAA+F;cAC7F,qDAAqD,EACvD,sFAAsF;cACpF,2DAA2D,EAC7D,EAAE,CACL,CAAC;IACN,CAAC;IAED,KAAK,CAAC,GAAgB;QAClB,gGAAgG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;CACJ;AA5GD,8CA4GC;AAED;;;GAGG;AACU,QAAA,sBAAsB,GAAG,CAAC,CAAC;AAExC;;;;;;GAMG;AACU,QAAA,aAAa,GACtB,4FAA4F;MAC1F,wBAAwB;MACxB,qEAAqE;MACrE,iEAAiE;MACjE,qGAAqG;MACrG,iGAAiG;MACjG,kGAAkG;MAClG,yEAAyE;MACzE,oGAAoG;MACpG,qGAAqG;MACrG,gBAAgB;MAChB,oGAAoG;MACpG,oGAAoG;MACpG,oDAAoD,CAAC;AAE3D;;;;;GAKG;AACU,QAAA,eAAe,GACxB,oGAAoG;MAClG,gGAAgG;MAChG,kGAAkG;MAClG,2BAA2B,CAAC","sourcesContent":["import { dotWebpieces } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase, EmptyRuleConfig } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2_UNROWED } from '../decision-log';\nimport { CommandScanner } from '../command-scan';\nimport { SessionCallHistory } from '../session-call-history';\nimport { ShellSegmentScan } from './shell-segment-scan';\nimport { WaitSpinScan, WaitSpinHit, SPIN_POLL } from './wait-spin-scan';\n\n/**\n * Blocks the two shapes an agent uses to WAIT when it has nothing left to do — a bare `echo .` /\n * `true` / `date` keep-alive, and the same `gh pr checks <n>` asked for the third time — and hands back\n * the ONE blocking command that its kind of agent can actually use instead.\n *\n * ─── The incident, measured (issue #874) ───────────────────────────────────────────────────────────\n * In the 24 hours to 2026-09-07, ten agent runs across four repos spun this way: 920M tokens, 18.3% of\n * every token the fleet spent, ~$1,389. Excluding the single worst run entirely it is still 9.0%. The\n * arithmetic is not subtle — every turn resends the whole conversation, measured at ~557,000 tokens per\n * turn, so a three-second `echo .` costs more than most of the work around it.\n *\n * ─── WHY agents do it, and TWO corrections to the cure (issues #878, then #900) ────────────────────\n * The first cut of this guard told a subagent it could not end its turn at all. #878 measured that and\n * found it false — 2,605 subagent turns ended with `stop_reason: end_turn`, 588 were followed by MORE\n * turns, and 449 of those resumptions arrived as a `[SYSTEM NOTIFICATION] … background-task event`\n * (288 of them while waiting on spawned reviewers). So the cure was rewritten to lead with ENDING THE\n * TURN and to offer a blocking command second.\n *\n * **#900 measured the other half of that claim, and it does not hold.** Those 449 resumptions say a\n * wake-up CAN happen; they never established that it RELIABLY happens for the case this cure creates —\n * a worktree-isolated subagent whose only pending work is one `run_in_background` wait. Measured\n * directly: three stalls across two subagents in a single session, each of which HAD launched its wait\n * with `run_in_background: true` exactly as instructed. Every task-notification read\n * \"stops with no live background children of its own\", and each run made ZERO further progress until a\n * human poked it. On a 19-minute CI job that is 19 minutes of dead time per wait plus a parent\n * round-trip to notice it.\n *\n * So the SUBAGENT cure no longer asks the agent to end its turn and be re-invoked. It names the\n * FOREGROUND blocking wait — the same shape Codex already gets, which returns under its harness ceiling\n * and is re-run — because a wait that re-invokes on its own is only cheaper than a foreground call when\n * the re-invocation actually fires, and here it does not. The honest cost, stated so nobody has to\n * rediscover it: a stop costs ~650 tokens, while foregrounding re-enters the agent roughly every nine\n * minutes and resends its context each time. That is more expensive per wait and still right, because\n * the alternative is a run that does not finish.\n *\n * **REVERT TO THE END-YOUR-TURN CURE IF THE HARNESS BEHAVIOUR IS FIXED.** The root cause is Claude\n * Code's, was reported to Anthropic separately, and is not webpieces' to repair; this guard only\n * mitigates it. When background re-invocation is observed to fire reliably for a subagent with a\n * backgrounded Bash and nothing else pending, the free wait is the better cure again.\n *\n * What both corrections leave untouched: `Monitor` still does not block (its own result text says\n * \"Keep working — do not poll or sleep\"), and a `Monitor` carrying a real polling loop is still refused\n * by the HARNESS — 178 of 553 subagent Monitor calls — because a `while`/`until` with a redirect cannot\n * be statically proven to stay inside the worktree. That refusal is Claude Code's, not webpieces'; it\n * is not ours to relax and this guard does not try. A blocking Bash call remains the only wait a\n * subagent can actually express, and that is what `pnpm wp-await-reviews` and `pnpm wp-await-checks`\n * are for. They are the FIRST answer now.\n *\n * ─── THE CURE STILL DIFFERS BY AGENT KIND ──────────────────────────────────────────────────────────\n * A main agent has `Monitor` and `run_in_background` genuinely available and its own cure names them;\n * #900's evidence is entirely about worktree-isolated subagents, so MAIN_AGENT_CURE is unchanged. The\n * kind is read the same way the decision log stamps it: `dotWebpieces.worktreeName(root)`, git's own\n * worktree name, empty for the primary clone. Same call, so a `tree=` column and this verdict cannot\n * disagree.\n *\n * ─── WHY THE SUBAGENT CURE NAMES A COMMAND AND NOT THE AGENT'S PENDING WORK ────────────────────────\n * The cure would ideally say \"you have 4 reviewers running, they will wake you\". It cannot, and the\n * reason is structural rather than an omission: this hook is registered on `Write|Edit|MultiEdit|Bash|\n * Read`, so an Agent spawn NEVER reaches it and no count of live children exists to read. A\n * backgrounded Bash is no better — `run_in_background` is not carried on the normalized payload, and\n * even if it were, a background command's EXIT is unobservable from a PreToolUse hook, so a remembered\n * spawn could not be distinguished from one that finished an hour ago. That header note is now the\n * measured story of #900 rather than a caveat: the guard cannot see the wake-up, and the wake-up cannot\n * be relied on, so the cure names the one move that works from where the agent is standing.\n *\n * ─── It acts UNCONDITIONALLY, and has NO config key ────────────────────────────────────────────────\n * Like `commit-message-substitution-guard` and `build-output-pipe-guard`, and on the same two tests. A\n * NEW key under `hookGuards` is a key every consumer must ADD or have every Bash call blocked on\n * upgrade (fault Y) — that shipped once, with `whole-repo-build-guard`. And there is nothing for a\n * switch to rescue: the cure is available for every input, is strictly better than what was blocked,\n * and can never itself match this guard.\n */\nexport class WaitSpinGuardRule extends BashRuleBase<EmptyRuleConfig> {\n constructor() {\n // configKey === name and is DELIBERATELY not a real webpieces.config.json key — see the class\n // docstring on fault Y.\n super(new EmptyRuleConfig(), 'wait-spin-guard', 'wait-spin-guard');\n }\n\n private readonly scan = new WaitSpinScan(new CommandScanner(), new ShellSegmentScan());\n private readonly history = new SessionCallHistory();\n\n readonly description =\n 'Block a Bash call whose whole purpose is to stay alive — a bare echo/true/date keep-alive, or ' +\n 'the same gh pr checks/view asked a third time (a trailing | head/tail/cat/wc -l included) — ' +\n 'and name the wait its kind of agent can actually use: a worktree subagent blocks in the ' +\n 'FOREGROUND with pnpm wp-await-reviews / pnpm wp-await-checks and re-runs it while it is still ' +\n 'waiting, a main agent starts a Monitor or backgrounds the command. gh pr checks --watch already ' +\n 'blocks and is never refused.';\n\n get fixHint(): FixHint {\n return new FixHint(\n 'This command does nothing except keep your turn alive, and a turn costs your whole context — '\n + '~557,000 tokens measured, whatever the command was.',\n 'Stop waiting by taking turns. The lines above name what the agent you are should do '\n + 'instead, cheapest first; they are the only moves to make.',\n [],\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 docs and commit messages are full of these command names.\n const hit = this.scan.classify(ctx.commandCode);\n if (hit === null) return this.allow(ctx, 'not-a-wait-spin');\n if (hit.shape === SPIN_POLL) return this.judgePoll(ctx, hit);\n return this.block(ctx, hit);\n }\n\n /**\n * ONE `gh pr checks 874` is a snapshot somebody acts on and must stay allowed — the difference\n * between asking a question and refusing to stop asking it is the number of times, and nothing else.\n * So the third identical call is the one refused, and the count comes from this session's own call\n * log (which holds calls 1..N-1 by the time this runs) and fails OPEN when it cannot be read.\n */\n private judgePoll(ctx: BashContext, hit: WaitSpinHit): readonly Violation[] {\n const prior = this.history.priorBashCalls(ctx.workspaceRoot, ctx.command);\n if (prior < REPEATS_BEFORE_REFUSAL) return this.allow(ctx, `poll-${String(prior)}-prior`);\n return this.block(ctx, hit);\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: WaitSpinHit): readonly Violation[] {\n // BLOCK_AI_CURE: the cure is a command the agent runs itself, right now, in place of this one.\n this.logDecision(ctx, 'BLOCK_AI_CURE', `${hit.shape}-${hit.program}`);\n return [new V(1, this.truncate(ctx.command), this.message(ctx, hit))];\n }\n\n // Short on purpose: it is read mid-wait by an agent that needs the ONE next move.\n private message(ctx: BashContext, hit: WaitSpinHit): string {\n return `Blocked: \\`${hit.program}\\` ${this.what(hit)}. `\n + 'Every turn resends your whole conversation — ~557,000 tokens measured — so waiting by '\n + 'taking turns is the most expensive thing you can do, and it was 18.3% of all fleet '\n + 'tokens in one measured day.\\n\\n'\n + this.cure(ctx);\n }\n\n private what(hit: WaitSpinHit): string {\n return hit.shape === SPIN_POLL\n ? 'has already been run twice in this session with the identical arguments, and the answer '\n + 'has not changed because you have not done anything between the calls'\n : 'does nothing at all — it exists only to keep your turn alive';\n }\n\n /**\n * The ONE cure for the agent that is actually calling, and never both. See the class docstring: a\n * main agent told to block wastes ten minutes it did not have to spend, and a subagent told to end\n * its turn stalls until a human notices (issue #900).\n */\n private cure(ctx: BashContext): string {\n return this.isWorktreeIsolated(ctx) ? SUBAGENT_CURE : MAIN_AGENT_CURE;\n }\n\n /**\n * A linked worktree means a worktree-isolated subagent — git's own answer, via the same call the\n * decision log's `tree=` column makes. Fails to `false` (the main-agent cure) only when git says\n * this is the primary clone, which is what the primary clone is.\n */\n private isWorktreeIsolated(ctx: BashContext): boolean {\n return dotWebpieces.worktreeName(ctx.workspaceRoot) !== '';\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(\n 'wait-spin-guard', 'Bash', ctx.command, '-', verdict, reason,\n '-', L0_FAULT_NONE, MATRIX_L2_UNROWED,\n ),\n );\n }\n}\n\n/**\n * How many identical prior calls make the next one a spin. TWO, so the THIRD is refused: one call is a\n * snapshot, two is a re-check after doing something, three in a row with nothing in between is a loop.\n */\nexport const REPEATS_BEFORE_REFUSAL = 2;\n\n/**\n * The subagent cure: BLOCK IN THE FOREGROUND. An earlier cut led with ending the turn, on the strength\n * of 449 measured re-invocations — and #900 measured that the re-invocation does not fire for the case\n * that cure creates (three stalls, two subagents, one session, every one of them backgrounded exactly\n * as told). A wait that never wakes is not a cheap wait; it is a run that does not finish. See the\n * class docstring, including the condition under which this reverts to the free wait.\n */\nexport const SUBAGENT_CURE =\n 'BLOCK IN ONE FOREGROUND CALL. Run whichever of these you are waiting on, and do NOT pass\\n'\n + 'run_in_background:\\n\\n'\n + ' pnpm wp-await-reviews # waiting on reviewer verdicts\\n'\n + ' pnpm wp-await-checks --pr <n> # waiting on CI for a PR\\n\\n'\n + 'Either one heartbeats throughout and RETURNS on its own at 540s — under the 600s ceiling at which\\n'\n + 'the harness demotes a foreground call to the background and the result is lost. When it comes\\n'\n + 'back saying it is still waiting, run the IDENTICAL command again; that is the wait continuing,\\n'\n + 'not a failure. A 100-minute wait costs about eleven calls this way.\\n\\n'\n + 'Same contract if you are waiting on something these two do not cover and you have the full-cycle\\n'\n + \"skill's wp-await.sh: run it in the FOREGROUND with --timeout 545 and re-run the identical command\\n\"\n + 'on exit 2.\\n\\n'\n + 'Do NOT end your turn expecting a backgrounded wait to re-invoke you. Measured three times in one\\n'\n + 'session (issue #900): the notification read \"no live background children of its own\" and the run\\n'\n + 'made zero further progress until a human poked it.';\n\n/**\n * The main-agent cure. A main agent has `Monitor` and `run_in_background` genuinely available, so the\n * efficient wait is named and the wasteful poll is refused — and nothing further is said. Telling it to\n * sit inside a blocking command instead would be worse advice than the spin it just wrote; telling it\n * when to end its turn would be webpieces ruling on a judgement it cannot see (issue #902).\n */\nexport const MAIN_AGENT_CURE =\n 'You are the main agent, so the efficient wait is available to you: start a `Monitor`, or run the\\n'\n + 'command you are waiting on with run_in_background. Be efficient with tokens — a backgrounded\\n'\n + 'command costs nothing while it runs, where a status check every few seconds costs a whole turn\\n'\n + '(~557k tokens) each time.';\n"]}
|
|
1
|
+
{"version":3,"file":"wait-spin-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/wait-spin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AgG;MAChG,kGAAkG;MAClG,2BAA2B,CAAC","sourcesContent":["import { dotWebpieces } from '@webpieces/tooling-common';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase, EmptyRuleConfig } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2_UNROWED } from '../decision-log';\nimport { CommandScanner } from '../command-scan';\nimport { SessionCallHistory } from '../session-call-history';\nimport { ShellSegmentScan } from './shell-segment-scan';\nimport { WaitSpinScan, WaitSpinHit, SPIN_POLL } from './wait-spin-scan';\n\n/**\n * Blocks the two shapes an agent uses to WAIT when it has nothing left to do — a bare `echo .` /\n * `true` / `date` keep-alive, and the same `gh pr checks <n>` asked for the third time — and hands back\n * the ONE blocking command that its kind of agent can actually use instead.\n *\n * ─── The incident, measured (issue #874) ───────────────────────────────────────────────────────────\n * In the 24 hours to 2026-09-07, ten agent runs across four repos spun this way: 920M tokens, 18.3% of\n * every token the fleet spent, ~$1,389. Excluding the single worst run entirely it is still 9.0%. The\n * arithmetic is not subtle — every turn resends the whole conversation, measured at ~557,000 tokens per\n * turn, so a three-second `echo .` costs more than most of the work around it.\n *\n * ─── WHY agents do it, and TWO corrections to the cure (issues #878, then #900) ────────────────────\n * The first cut of this guard told a subagent it could not end its turn at all. #878 measured that and\n * found it false — 2,605 subagent turns ended with `stop_reason: end_turn`, 588 were followed by MORE\n * turns, and 449 of those resumptions arrived as a `[SYSTEM NOTIFICATION] … background-task event`\n * (288 of them while waiting on spawned reviewers). So the cure was rewritten to lead with ENDING THE\n * TURN and to offer a blocking command second.\n *\n * **#900 measured the other half of that claim, and it does not hold.** Those 449 resumptions say a\n * wake-up CAN happen; they never established that it RELIABLY happens for the case this cure creates —\n * a worktree-isolated subagent whose only pending work is one `run_in_background` wait. Measured\n * directly: three stalls across two subagents in a single session, each of which HAD launched its wait\n * with `run_in_background: true` exactly as instructed. Every task-notification read\n * \"stops with no live background children of its own\", and each run made ZERO further progress until a\n * human poked it. On a 19-minute CI job that is 19 minutes of dead time per wait plus a parent\n * round-trip to notice it.\n *\n * So the SUBAGENT cure no longer asks the agent to end its turn and be re-invoked. It names the\n * FOREGROUND blocking wait — the same shape Codex already gets, which returns under its harness ceiling\n * and is re-run — because a wait that re-invokes on its own is only cheaper than a foreground call when\n * the re-invocation actually fires, and here it does not. The honest cost, stated so nobody has to\n * rediscover it: a stop costs ~650 tokens, while foregrounding re-enters the agent roughly every nine\n * minutes and resends its context each time. That is more expensive per wait and still right, because\n * the alternative is a run that does not finish.\n *\n * **REVERT TO THE END-YOUR-TURN CURE IF THE HARNESS BEHAVIOUR IS FIXED.** The root cause is Claude\n * Code's, was reported to Anthropic separately, and is not webpieces' to repair; this guard only\n * mitigates it. When background re-invocation is observed to fire reliably for a subagent with a\n * backgrounded Bash and nothing else pending, the free wait is the better cure again.\n *\n * What both corrections leave untouched: `Monitor` still does not block (its own result text says\n * \"Keep working — do not poll or sleep\"), and a `Monitor` carrying a real polling loop is still refused\n * by the HARNESS — 178 of 553 subagent Monitor calls — because a `while`/`until` with a redirect cannot\n * be statically proven to stay inside the worktree. That refusal is Claude Code's, not webpieces'; it\n * is not ours to relax and this guard does not try. A blocking Bash call remains the only wait a\n * subagent can actually express, and that is what `pnpm wp-await-reviews` and `pnpm wp-await-checks`\n * are for. They are the FIRST answer now.\n *\n * ─── THE CURE STILL DIFFERS BY AGENT KIND ──────────────────────────────────────────────────────────\n * A main agent has `Monitor` and `run_in_background` genuinely available and its own cure names them;\n * #900's evidence is entirely about worktree-isolated subagents, so MAIN_AGENT_CURE is unchanged. The\n * kind is read the same way the decision log stamps it: `dotWebpieces.worktreeName(root)`, git's own\n * worktree name, empty for the primary clone. Same call, so a `tree=` column and this verdict cannot\n * disagree.\n *\n * ─── WHY THE SUBAGENT CURE NAMES A COMMAND AND NOT THE AGENT'S PENDING WORK ────────────────────────\n * The cure would ideally say \"you have 4 reviewers running, they will wake you\". It cannot, and the\n * reason is structural rather than an omission: this hook is registered on `Write|Edit|MultiEdit|Bash|\n * Read`, so an Agent spawn NEVER reaches it and no count of live children exists to read. A\n * backgrounded Bash is no better — `run_in_background` is not carried on the normalized payload, and\n * even if it were, a background command's EXIT is unobservable from a PreToolUse hook, so a remembered\n * spawn could not be distinguished from one that finished an hour ago. That header note is now the\n * measured story of #900 rather than a caveat: the guard cannot see the wake-up, and the wake-up cannot\n * be relied on, so the cure names the one move that works from where the agent is standing.\n *\n * ─── It acts UNCONDITIONALLY, and has NO config key ────────────────────────────────────────────────\n * Like `commit-message-substitution-guard` and `build-output-pipe-guard`, and on the same two tests. A\n * NEW key under `hookGuards` is a key every consumer must ADD or have every Bash call blocked on\n * upgrade (fault Y) — that shipped once, with `whole-repo-build-guard`. And there is nothing for a\n * switch to rescue: the cure is available for every input, is strictly better than what was blocked,\n * and can never itself match this guard.\n */\nexport class WaitSpinGuardRule extends BashRuleBase<EmptyRuleConfig> {\n constructor() {\n // configKey === name and is DELIBERATELY not a real webpieces.config.json key — see the class\n // docstring on fault Y.\n super(new EmptyRuleConfig(), 'wait-spin-guard', 'wait-spin-guard');\n }\n\n private readonly scan = new WaitSpinScan(new CommandScanner(), new ShellSegmentScan());\n private readonly history = new SessionCallHistory();\n\n readonly description =\n 'Block a Bash call whose whole purpose is to stay alive — a bare echo/true/date keep-alive, or ' +\n 'the same gh pr checks/view asked a third time (a trailing | head/tail/cat/wc -l included) — ' +\n 'and name the wait its kind of agent can actually use: a worktree subagent blocks in the ' +\n 'FOREGROUND with pnpm wp-await-reviews / pnpm wp-await-checks and re-runs it while it is still ' +\n 'waiting, a main agent starts a Monitor or backgrounds the command. gh pr checks --watch already ' +\n 'blocks and is never refused.';\n\n get fixHint(): FixHint {\n return new FixHint(\n 'This command does nothing except keep your turn alive, and a turn costs your whole context — '\n + '~557,000 tokens measured, whatever the command was.',\n 'Stop waiting by taking turns. The lines above name what the agent you are should do '\n + 'instead, cheapest first; they are the only moves to make.',\n [],\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 docs and commit messages are full of these command names.\n const hit = this.scan.classify(ctx.commandCode);\n if (hit === null) return this.allow(ctx, 'not-a-wait-spin');\n if (hit.shape === SPIN_POLL) return this.judgePoll(ctx, hit);\n return this.block(ctx, hit);\n }\n\n /**\n * ONE `gh pr checks 874` is a snapshot somebody acts on and must stay allowed — the difference\n * between asking a question and refusing to stop asking it is the number of times, and nothing else.\n * So the third identical call is the one refused, and the count comes from this session's own call\n * log (which holds calls 1..N-1 by the time this runs) and fails OPEN when it cannot be read.\n */\n private judgePoll(ctx: BashContext, hit: WaitSpinHit): readonly Violation[] {\n const prior = this.history.priorBashCalls(ctx.workspaceRoot, ctx.command);\n if (prior < REPEATS_BEFORE_REFUSAL) return this.allow(ctx, `poll-${String(prior)}-prior`);\n return this.block(ctx, hit);\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: WaitSpinHit): readonly Violation[] {\n // BLOCK_AI_CURE: the cure is a command the agent runs itself, right now, in place of this one.\n this.logDecision(ctx, 'BLOCK_AI_CURE', `${hit.shape}-${hit.program}`);\n return [new V(1, this.truncate(ctx.command), this.message(ctx, hit))];\n }\n\n // Short on purpose: it is read mid-wait by an agent that needs the ONE next move.\n private message(ctx: BashContext, hit: WaitSpinHit): string {\n return `Blocked: \\`${hit.program}\\` ${this.what(hit)}. `\n + 'Every turn resends your whole conversation — ~557,000 tokens measured — so waiting by '\n + 'taking turns is the most expensive thing you can do, and it was 18.3% of all fleet '\n + 'tokens in one measured day.\\n\\n'\n + this.cure(ctx);\n }\n\n private what(hit: WaitSpinHit): string {\n return hit.shape === SPIN_POLL\n ? 'has already been run twice in this session with the identical arguments, and the answer '\n + 'has not changed because you have not done anything between the calls'\n : 'does nothing at all — it exists only to keep your turn alive';\n }\n\n /**\n * The ONE cure for the agent that is actually calling, and never both. See the class docstring: a\n * main agent told to block wastes ten minutes it did not have to spend, and a subagent told to end\n * its turn stalls until a human notices (issue #900).\n */\n private cure(ctx: BashContext): string {\n return this.isWorktreeIsolated(ctx) ? SUBAGENT_CURE : MAIN_AGENT_CURE;\n }\n\n /**\n * A linked worktree means a worktree-isolated subagent — git's own answer, via the same call the\n * decision log's `tree=` column makes. Fails to `false` (the main-agent cure) only when git says\n * this is the primary clone, which is what the primary clone is.\n */\n private isWorktreeIsolated(ctx: BashContext): boolean {\n return dotWebpieces.worktreeName(ctx.workspaceRoot) !== '';\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(\n 'wait-spin-guard', 'Bash', ctx.command, '-', verdict, reason,\n '-', L0_FAULT_NONE, MATRIX_L2_UNROWED,\n ),\n );\n }\n}\n\n/**\n * How many identical prior calls make the next one a spin. TWO, so the THIRD is refused: one call is a\n * snapshot, two is a re-check after doing something, three in a row with nothing in between is a loop.\n */\nexport const REPEATS_BEFORE_REFUSAL = 2;\n\n/**\n * The subagent cure: BLOCK IN THE FOREGROUND. An earlier cut led with ending the turn, on the strength\n * of 449 measured re-invocations — and #900 measured that the re-invocation does not fire for the case\n * that cure creates (three stalls, two subagents, one session, every one of them backgrounded exactly\n * as told). A wait that never wakes is not a cheap wait; it is a run that does not finish. See the\n * class docstring, including the condition under which this reverts to the free wait.\n */\nexport const SUBAGENT_CURE =\n 'BLOCK IN ONE FOREGROUND CALL. Run whichever of these you are waiting on, and do NOT pass\\n'\n + 'run_in_background:\\n\\n'\n + ' pnpm wp-await-reviews # waiting on reviewer verdicts\\n'\n + ' pnpm wp-await-checks --pr <n> # waiting on CI for a PR\\n\\n'\n + 'Either one heartbeats throughout and RETURNS on its own at 540s — under the 600s ceiling at which\\n'\n + 'the harness demotes a foreground call to the background and the result is lost. When it comes\\n'\n + 'back saying it is still waiting, run the IDENTICAL command again; that is the wait continuing,\\n'\n + 'not a failure. A 100-minute wait costs about eleven calls this way.\\n\\n'\n + 'Same contract if you are waiting on something these two do not cover and you have the full-cycle\\n'\n + \"skill's wp-await.sh: run it in the FOREGROUND with --timeout 545 and re-run the identical command\\n\"\n + 'on exit 2.\\n\\n'\n + 'Do NOT end your turn expecting a backgrounded wait to re-invoke you. Measured three times in one\\n'\n + 'session (issue #900): the notification read \"no live background children of its own\" and the run\\n'\n + 'made zero further progress until a human poked it.';\n\n/**\n * The main-agent cure. A main agent has `Monitor` and `run_in_background` genuinely available, so the\n * efficient wait is named and the wasteful poll is refused — and nothing further is said. Telling it to\n * sit inside a blocking command instead would be worse advice than the spin it just wrote; telling it\n * when to end its turn would be webpieces ruling on a judgement it cannot see (issue #902).\n */\nexport const MAIN_AGENT_CURE =\n 'You are the main agent, so the efficient wait is available to you: start a `Monitor`, or run the\\n'\n + 'command you are waiting on with run_in_background. Be efficient with tokens — a backgrounded\\n'\n + 'command costs nothing while it runs, where a status check every few seconds costs a whole turn\\n'\n + '(~557k tokens) each time.';\n"]}
|
|
@@ -3,6 +3,7 @@ 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");
|
|
6
7
|
const types_1 = require("../types");
|
|
7
8
|
const rule_base_1 = require("../rule-base");
|
|
8
9
|
const fix_hint_1 = require("../fix-hint");
|
|
@@ -171,7 +172,7 @@ class WholeRepoBuildGuardRule extends rule_base_1.BashRuleBase {
|
|
|
171
172
|
return [new types_1.Violation(1, this.truncate(ctx.command), this.brokenHomeConfigMessage(error))];
|
|
172
173
|
}
|
|
173
174
|
brokenHomeConfigMessage(error) {
|
|
174
|
-
const detail = error instanceof
|
|
175
|
+
const detail = error instanceof tooling_common_1.InformAiError
|
|
175
176
|
? error.message
|
|
176
177
|
: `~/.webpieces/config.json could not be read: ${error.message}`;
|
|
177
178
|
return `Blocked: ~/.webpieces/config.json is present but unusable.\n\n${detail}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"whole-repo-build-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/whole-repo-build-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA8G;AAG9G,oCAA0C;AAC1C,4CAA6D;AAC7D,0CAAsC;AACtC,0CAAsC;AACtC,sDAAkD;AAClD,kDAA8F;AAC9F,kDAAiD;AACjD,mEAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AACH,MAAa,uBAAwB,SAAQ,wBAA6B;IAMzC;IAL7B;;;;OAIG;IACH,YAA6B,oBAA4B;QACrD,2EAA2E;QAC3E,6FAA6F;QAC7F,sFAAsF;QACtF,+EAA+E;QAC/E,KAAK,CAAC,IAAI,2BAAe,EAAE,EAAE,wBAAwB,EAAE,wBAAwB,CAAC,CAAC;QALxD,yBAAoB,GAApB,oBAAoB,CAAQ;IAMzD,CAAC;IAEgB,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC;IAC/B,UAAU,GAAG,IAAI,gCAAiB,EAAE,CAAC;IAEtD,gGAAgG;IACxF,eAAe,GAAG,EAAE,CAAC;IAEpB,WAAW,GAChB,0FAA0F;QAC1F,iFAAiF,CAAC;IAEtF;;;;;OAKG;IACK,eAAe,GAAG,EAAE,CAAC;IAE7B,IAAI,OAAO;QACP,IAAI,IAAI,CAAC,eAAe,KAAK,EAAE,EAAE,CAAC;YAC9B,OAAO,IAAI,kBAAO,CACd,qDAAqD,EACrD,0FAA0F;gBAC1F,uFAAuF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K,CAAC,GAAgB,EAAE,GAAsB,EAAE,OAAe;QACnE,yFAAyF;QACzF,0CAA0C;QAC1C,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;QAClD,OAAO,CAAC,IAAI,iBAAC,CAAC,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3D,CAAC;IAEO,QAAQ,CAAC,CAAS;QACtB,MAAM,GAAG,GAAG,GAAG,CAAC;QAChB,OAAO,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;IACvD,CAAC;IAEO,WAAW,CAAC,GAAgB,EAAE,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,8BAAa,EAAE,gCAAiB,CAAC,CAChI,CAAC;IACN,CAAC;CACJ;AA9LD,0DA8LC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { DEFAULT_BUILD_COMMAND, HomeConfig, HomeConfigService, InformAiError } from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase, EmptyRuleConfig } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2_UNROWED } from '../decision-log';\nimport { CommandScanner } from '../command-scan';\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/ai-hook-rules/src/core/rules/whole-repo-build-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA+F;AAC/F,8DAA0D;AAG1D,oCAA0C;AAC1C,4CAA6D;AAC7D,0CAAsC;AACtC,0CAAsC;AACtC,sDAAkD;AAClD,kDAA8F;AAC9F,kDAAiD;AACjD,mEAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AACH,MAAa,uBAAwB,SAAQ,w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ACjB,IAAI,4BAAa,CAAC,wBAAwB,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,8BAAa,EAAE,gCAAiB,CAAC,CAChI,CAAC;IACN,CAAC;CACJ;AA9LD,0DA8LC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { DEFAULT_BUILD_COMMAND, HomeConfig, HomeConfigService } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase, EmptyRuleConfig } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { logGuardDecision, GuardDecision, Verdict, MATRIX_L2_UNROWED } from '../decision-log';\nimport { CommandScanner } from '../command-scan';\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"]}
|
|
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.SessionCallHistory = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
|
-
const
|
|
6
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
7
7
|
const log_streams_1 = require("./log-streams");
|
|
8
8
|
const log_stream_1 = require("./log-stream");
|
|
9
9
|
const log_target_1 = require("./log-target");
|
|
@@ -63,7 +63,7 @@ class SessionCallHistory {
|
|
|
63
63
|
// is the fail-open answer; a logging failure must never become a refusal
|
|
64
64
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
65
65
|
try {
|
|
66
|
-
const file =
|
|
66
|
+
const file = tooling_common_1.dotWebpieces.logsFile(root, log_streams_1.CALLS_STREAM, log_stream_1.logStream.writerFile('.log'));
|
|
67
67
|
if (!fs.existsSync(file))
|
|
68
68
|
return [];
|
|
69
69
|
return fs.readFileSync(file, 'utf8').split('\n');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-call-history.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/session-call-history.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AAEzB,
|
|
1
|
+
{"version":3,"file":"session-call-history.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/session-call-history.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AAEzB,8DAAyD;AAEzD,+CAA6C;AAC7C,6CAAyC;AACzC,6CAAyC;AACzC,yCAAqC;AAErC;;;;;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;CACJ;AArCD,gDAqCC","sourcesContent":["import * as fs from 'fs';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\n\nimport { CALLS_STREAM } from './log-streams';\nimport { logStream } from './log-stream';\nimport { logTarget } from './log-target';\nimport { toError } from './to-error';\n\n/**\n * HOW MANY TIMES has this session already run this exact Bash command?\n *\n * ─── Why a guard is allowed to ask a question about HISTORY at all ─────────────────────────────────\n * Every other guard here answers from the command TEXT plus the tree's git state, and `managed-env.ts`\n * states that preference out loud: same command, same verdict, every time. That rule exists so a\n * verdict cannot depend on where an unrelated earlier command left the shell — an accident.\n *\n * A SPIN is not an accident, and it is not visible in one command. `gh pr checks 874` asked once is a\n * snapshot somebody acts on; asked for the ninetieth time in four minutes it is the wait loop this\n * whole feature exists to delete, and the two are byte-identical. Repetition IS the defect, so\n * repetition is the only thing that can be measured. Nothing else about the call differs.\n *\n * ─── Where the count comes from ────────────────────────────────────────────────────────────────────\n * `InvocationLog` already writes ONE tab-separated line per guards-hook call to\n * `<state>/logs/calls/<sessionId>-<agentId|coordinator>-<hook>.log`, and `logStream` has already been\n * identified with this session and agent by the time a rule's `check()` runs. So the file IS the\n * session, for free — no new state, no new writer, and a worktree-isolated subagent gets its own\n * because the path is resolved from the tree it acts on.\n *\n * Each tool call is its own process and flushes that line at its terminal boundary, so on call N the\n * file holds calls 1..N-1. The count this returns is therefore PRIOR calls, never including the one\n * being judged.\n *\n * ─── It fails OPEN, always ─────────────────────────────────────────────────────────────────────────\n * A missing file (the first call of a session), a rotated one, an unreadable one — all of them mean\n * \"no evidence\", which is 0, which blocks nothing. A logging failure may never become a refusal.\n */\nexport class SessionCallHistory {\n /**\n * How many times `command` already appears as a Bash target in THIS session's call log.\n *\n * The comparison is against the same one-line normalization `InvocationLog` writes, so a command\n * spanning two lines in the payload and the same command on one line count as the same command.\n */\n priorBashCalls(root: string, command: string): number {\n const wanted = logTarget.oneLine(command);\n if (wanted === '') return 0;\n return this.lines(root).filter((line: string): boolean => this.isBashCallOf(line, wanted)).length;\n }\n\n /**\n * One logged call is `[<iso>]\\tBash\\t<target>\\tbranch=…` — so field 1 is the tool and field 2 the\n * command. Split rather than `includes`, because a command that MENTIONS another command in its\n * text would otherwise count as that command.\n */\n private isBashCallOf(line: string, wanted: string): boolean {\n const fields = line.split('\\t');\n return fields.length > 2 && fields[1] === 'Bash' && fields[2] === wanted;\n }\n\n private lines(root: string): readonly string[] {\n // webpieces-disable no-unmanaged-exceptions -- a log that cannot be read is NO EVIDENCE, which\n // is the fail-open answer; a logging failure must never become a refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const file = dotWebpieces.logsFile(root, CALLS_STREAM, logStream.writerFile('.log'));\n if (!fs.existsSync(file)) return [];\n return fs.readFileSync(file, 'utf8').split('\\n');\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n}\n"]}
|
package/src/core/sync-main.js
CHANGED
|
@@ -4,6 +4,7 @@ exports.main = main;
|
|
|
4
4
|
exports.hangTimeoutFromArgv = hangTimeoutFromArgv;
|
|
5
5
|
exports.spawnerIdentity = spawnerIdentity;
|
|
6
6
|
exports.refreshMainSync = refreshMainSync;
|
|
7
|
+
const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
|
|
7
8
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
8
9
|
const to_error_1 = require("./to-error");
|
|
9
10
|
const main_sync_log_1 = require("./main-sync-log");
|
|
@@ -44,9 +45,9 @@ function main() {
|
|
|
44
45
|
// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape
|
|
45
46
|
function hangTimeoutFromArgv(raw) {
|
|
46
47
|
if (raw === undefined || raw.trim() === '')
|
|
47
|
-
return
|
|
48
|
+
return repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
|
|
48
49
|
const parsed = Number(raw);
|
|
49
|
-
return Number.isFinite(parsed) ? parsed :
|
|
50
|
+
return Number.isFinite(parsed) ? parsed : repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
|
|
50
51
|
}
|
|
51
52
|
/**
|
|
52
53
|
* The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is
|
|
@@ -74,7 +75,7 @@ function refreshMainSync(repoRoot, hangTimeoutMinutes, argvDetail = '') {
|
|
|
74
75
|
try {
|
|
75
76
|
// ONE atomic acquire — not a check followed by a write. The old check-then-write pair had a
|
|
76
77
|
// gap in which two detached children could both pass the check and then both run `git fetch`.
|
|
77
|
-
const lock = (0,
|
|
78
|
+
const lock = (0, repo_workflow_core_1.tryAcquireMainSyncLock)(repoRoot, hangTimeoutMinutes);
|
|
78
79
|
if (!lock) {
|
|
79
80
|
(0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', 'another refresh is in progress'));
|
|
80
81
|
return;
|
|
@@ -85,12 +86,12 @@ function refreshMainSync(repoRoot, hangTimeoutMinutes, argvDetail = '') {
|
|
|
85
86
|
// to describe only the branch of whichever tree won this lock, so every other worktree's
|
|
86
87
|
// guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all
|
|
87
88
|
// of them; the map is rebuilt from the live worktree set, so dead branches drop out.
|
|
88
|
-
const file = (0,
|
|
89
|
-
(0,
|
|
89
|
+
const file = (0, repo_workflow_core_1.computeAllMainSyncStatuses)(repoRoot);
|
|
90
|
+
(0, repo_workflow_core_1.writeMainSyncStatusFile)(repoRoot, file);
|
|
90
91
|
// Second slow signal, same lock, same detached run: which local branches are dead. One bulk
|
|
91
92
|
// `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its
|
|
92
93
|
// cap without ever touching the network itself. Deliberately allowed to go stale.
|
|
93
|
-
const mergedBranches = new
|
|
94
|
+
const mergedBranches = new repo_workflow_core_1.MergedBranchesService();
|
|
94
95
|
// `false`: the background refresher NEVER ignores a standing agent lock. That flag is
|
|
95
96
|
// wp-cleanup's, and it means "a human asked for this run" — nothing an unattended
|
|
96
97
|
// refresher can claim on somebody's behalf.
|
|
@@ -108,7 +109,7 @@ function refreshMainSync(repoRoot, hangTimeoutMinutes, argvDetail = '') {
|
|
|
108
109
|
finally {
|
|
109
110
|
// Always flip the lock off so a compute failure can't wedge the guard until the
|
|
110
111
|
// staleness reclaim kicks in.
|
|
111
|
-
(0,
|
|
112
|
+
(0, repo_workflow_core_1.writeMainSyncLock)(repoRoot, (0, repo_workflow_core_1.finishedLock)(lock.started));
|
|
112
113
|
}
|
|
113
114
|
}
|
|
114
115
|
catch (err) {
|
|
@@ -156,7 +157,7 @@ function autoReap(repoRoot, cache) {
|
|
|
156
157
|
// that basis would be deleting on a preference nobody expressed.
|
|
157
158
|
if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true)
|
|
158
159
|
return 0;
|
|
159
|
-
const result = new
|
|
160
|
+
const result = new repo_workflow_core_1.BranchReaper().reap(repoRoot, 'auto-reap', cache);
|
|
160
161
|
for (const failure of result.failed) {
|
|
161
162
|
(0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));
|
|
162
163
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/sync-main.ts"],"names":[],"mappings":";;AAwCA,oBAOC;AAWD,kDAIC;AAWD,0CAEC;AAOD,0CA0DC;AA5ID,0DAaiC;AAEjC,yCAAqC;AACrC,mDAA6D;AAC7D,6CAAyD;AAEzD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAgB,IAAI;IAChB,sBAAS,CAAC,QAAQ,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IAClD,eAAe,CACX,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,EAChC,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAA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/F,2FAA2F;QAC3F,2FAA2F;QAC3F,iEAAiE;QACjE,IAAI,MAAM,EAAE,IAAI,KAAK,KAAK,IAAI,MAAM,EAAE,sBAAsB,KAAK,IAAI;YAAE,OAAO,CAAC,CAAC;QAEhF,MAAM,MAAM,GAAe,IAAI,2BAAY,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC;QACjF,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAClC,IAAA,4BAAY,EAAC,QAAQ,EAAE,IAAI,4BAAY,CACnC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,gBAAgB,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAChF,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IAChC,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,IAAA,4BAAY,EAAC,QAAQ,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,aAAa,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAClG,OAAO,CAAC,CAAC;IACb,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["import {\n BranchReaper,\n DEFAULT_HANG_TIMEOUT_MINUTES,\n MainSyncStatusFile,\n MergedBranchesCache,\n MergedBranchesService,\n ReapResult,\n loadAndValidate,\n computeAllMainSyncStatuses,\n writeMainSyncStatusFile,\n writeMainSyncLock,\n tryAcquireMainSyncLock,\n finishedLock,\n} from '@webpieces/rules-config';\n\nimport { toError } from './to-error';\nimport { logSyncEvent, SyncLogEvent } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n/**\n * The detached, fire-and-forget refresher spawned (by file path, not a bin) from\n * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +\n * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it\n * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.\n *\n * Concurrency: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start\n * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds\n * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,\n * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.\n *\n * argv: [, , repoRoot, hangTimeoutMinutes, sessionId, agentId, hook]\n *\n * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason\n * they are passed. This process has its own fresh module-level `logStream`; left unidentified it\n * named every line `unknown-coordinator-hook.log` — one shared file that every\n * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),\n * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file\n * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv\n * (a hand-run of this file) leaves the default, which still prefixes.\n */\nexport function main(): void {\n logStream.identify(spawnerIdentity(process.argv));\n refreshMainSync(\n process.argv[2] ?? process.cwd(),\n hangTimeoutFromArgv(process.argv[3]),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * Parse the hang timeout off argv, WITHOUT `||`.\n *\n * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — \"never treat a lock as stale\" — into\n * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state\n * policy entry), so a value that survives the config only to be discarded at the process boundary is\n * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function hangTimeoutFromArgv(raw: string | undefined): number {\n if (raw === undefined || raw.trim() === '') return DEFAULT_HANG_TIMEOUT_MINUTES;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : DEFAULT_HANG_TIMEOUT_MINUTES;\n}\n\n/**\n * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is\n * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).\n *\n * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a\n * disagreement between two files about argv positions, and a test that only checks the reader would\n * have stayed green through it.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function spawnerIdentity(argv: string[]): StreamIdentity {\n return new StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');\n}\n\n/**\n * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a\n * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape\nexport function refreshMainSync(repoRoot: string, hangTimeoutMinutes: number, argvDetail: string = ''): void {\n const startedMs = Date.now();\n\n // First action: prove the detached child actually started. If the async-refresh stream has no START line\n // for a spawn, the child never launched (or died before this point).\n logSyncEvent(repoRoot, new SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // ONE atomic acquire — not a check followed by a write. The old check-then-write pair had a\n // gap in which two detached children could both pass the check and then both run `git fetch`.\n const lock = tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', 'another refresh is in progress'));\n return;\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used\n // to describe only the branch of whichever tree won this lock, so every other worktree's\n // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all\n // of them; the map is rebuilt from the live worktree set, so dead branches drop out.\n const file = computeAllMainSyncStatuses(repoRoot);\n writeMainSyncStatusFile(repoRoot, file);\n\n // Second slow signal, same lock, same detached run: which local branches are dead. One bulk\n // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its\n // cap without ever touching the network itself. Deliberately allowed to go stale.\n const mergedBranches = new MergedBranchesService();\n // `false`: the background refresher NEVER ignores a standing agent lock. That flag is\n // wp-cleanup's, and it means \"a human asked for this run\" — nothing an unattended\n // refresher can claim on somebody's behalf.\n const cache = mergedBranches.computeMergedBranches(repoRoot, false);\n mergedBranches.writeMergedBranches(repoRoot, cache);\n\n // Third step, same detached run: actually DELETE the dead branches. Reporting them was\n // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an\n // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has\n // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).\n const reaped = autoReap(repoRoot, cache);\n\n // FINISH after a successful write — START-without-FINISH means we were killed mid-run.\n const names = Object.keys(file.branches);\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'FINISH', process.pid, names.join(','),\n `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`,\n ));\n } finally {\n // Always flip the lock off so a compute failure can't wedge the guard until the\n // staleness reclaim kicks in.\n writeMainSyncLock(repoRoot, finishedLock(lock.started));\n }\n } catch (err: unknown) {\n const error = toError(err);\n // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call\n // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));\n }\n}\n\n/**\n * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log\n * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to\n * name every branch written, not just the tree the refresher happened to run in.\n */\n// webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape\nfunction summarize(file: MainSyncStatusFile): (branch: string) => string {\n return (branch: string): string => {\n const status = file.branches[branch];\n if (status === undefined) return `${branch}(?)`;\n return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;\n };\n}\n\n/**\n * Delete the branches the verdicts just declared dead. Returns how many actually went.\n *\n * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup\n * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded\n * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that\n * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on\n * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.\n *\n * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the\n * main-sync status this process exists to produce — but every failure is logged, because a silent\n * background deletion is exactly what nobody should have to trust.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction autoReap(repoRoot: string, cache: MergedBranchesCache): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const config = loadAndValidate(repoRoot).rulesConfig['branch-creation-guard'];\n // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,\n // so every validated config states an answer — which means \"absent\" here is not a consumer\n // who wants the default, it is a config that never passed validation. Deleting branches on\n // that basis would be deleting on a preference nobody expressed.\n if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true) return 0;\n\n const result: ReapResult = new BranchReaper().reap(repoRoot, 'auto-reap', cache);\n for (const failure of result.failed) {\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));\n }\n return result.reaped.length;\n } catch (err: unknown) {\n const error = toError(err);\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));\n return 0;\n }\n}\n\nif (require.main === module) {\n main();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/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,CAAC;QAClG,OAAO,CAAC,CAAC;IACb,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { BranchReaper, DEFAULT_HANG_TIMEOUT_MINUTES, MainSyncStatusFile, MergedBranchesCache, MergedBranchesService, ReapResult, computeAllMainSyncStatuses, writeMainSyncStatusFile, writeMainSyncLock, tryAcquireMainSyncLock, finishedLock } from '@webpieces/repo-workflow-core';\nimport { loadAndValidate } from '@webpieces/rules-config';\n\nimport { toError } from './to-error';\nimport { logSyncEvent, SyncLogEvent } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n/**\n * The detached, fire-and-forget refresher spawned (by file path, not a bin) from\n * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +\n * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it\n * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.\n *\n * Concurrency: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start\n * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds\n * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,\n * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.\n *\n * argv: [, , repoRoot, hangTimeoutMinutes, sessionId, agentId, hook]\n *\n * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason\n * they are passed. This process has its own fresh module-level `logStream`; left unidentified it\n * named every line `unknown-coordinator-hook.log` — one shared file that every\n * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),\n * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file\n * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv\n * (a hand-run of this file) leaves the default, which still prefixes.\n */\nexport function main(): void {\n logStream.identify(spawnerIdentity(process.argv));\n refreshMainSync(\n process.argv[2] ?? process.cwd(),\n hangTimeoutFromArgv(process.argv[3]),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * Parse the hang timeout off argv, WITHOUT `||`.\n *\n * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — \"never treat a lock as stale\" — into\n * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state\n * policy entry), so a value that survives the config only to be discarded at the process boundary is\n * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function hangTimeoutFromArgv(raw: string | undefined): number {\n if (raw === undefined || raw.trim() === '') return DEFAULT_HANG_TIMEOUT_MINUTES;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : DEFAULT_HANG_TIMEOUT_MINUTES;\n}\n\n/**\n * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is\n * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).\n *\n * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a\n * disagreement between two files about argv positions, and a test that only checks the reader would\n * have stayed green through it.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function spawnerIdentity(argv: string[]): StreamIdentity {\n return new StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');\n}\n\n/**\n * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a\n * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape\nexport function refreshMainSync(repoRoot: string, hangTimeoutMinutes: number, argvDetail: string = ''): void {\n const startedMs = Date.now();\n\n // First action: prove the detached child actually started. If the async-refresh stream has no START line\n // for a spawn, the child never launched (or died before this point).\n logSyncEvent(repoRoot, new SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // ONE atomic acquire — not a check followed by a write. The old check-then-write pair had a\n // gap in which two detached children could both pass the check and then both run `git fetch`.\n const lock = tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', 'another refresh is in progress'));\n return;\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used\n // to describe only the branch of whichever tree won this lock, so every other worktree's\n // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all\n // of them; the map is rebuilt from the live worktree set, so dead branches drop out.\n const file = computeAllMainSyncStatuses(repoRoot);\n writeMainSyncStatusFile(repoRoot, file);\n\n // Second slow signal, same lock, same detached run: which local branches are dead. One bulk\n // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its\n // cap without ever touching the network itself. Deliberately allowed to go stale.\n const mergedBranches = new MergedBranchesService();\n // `false`: the background refresher NEVER ignores a standing agent lock. That flag is\n // wp-cleanup's, and it means \"a human asked for this run\" — nothing an unattended\n // refresher can claim on somebody's behalf.\n const cache = mergedBranches.computeMergedBranches(repoRoot, false);\n mergedBranches.writeMergedBranches(repoRoot, cache);\n\n // Third step, same detached run: actually DELETE the dead branches. Reporting them was\n // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an\n // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has\n // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).\n const reaped = autoReap(repoRoot, cache);\n\n // FINISH after a successful write — START-without-FINISH means we were killed mid-run.\n const names = Object.keys(file.branches);\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'FINISH', process.pid, names.join(','),\n `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`,\n ));\n } finally {\n // Always flip the lock off so a compute failure can't wedge the guard until the\n // staleness reclaim kicks in.\n writeMainSyncLock(repoRoot, finishedLock(lock.started));\n }\n } catch (err: unknown) {\n const error = toError(err);\n // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call\n // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));\n }\n}\n\n/**\n * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log\n * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to\n * name every branch written, not just the tree the refresher happened to run in.\n */\n// webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape\nfunction summarize(file: MainSyncStatusFile): (branch: string) => string {\n return (branch: string): string => {\n const status = file.branches[branch];\n if (status === undefined) return `${branch}(?)`;\n return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;\n };\n}\n\n/**\n * Delete the branches the verdicts just declared dead. Returns how many actually went.\n *\n * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup\n * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded\n * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that\n * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on\n * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.\n *\n * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the\n * main-sync status this process exists to produce — but every failure is logged, because a silent\n * background deletion is exactly what nobody should have to trust.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction autoReap(repoRoot: string, cache: MergedBranchesCache): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const config = loadAndValidate(repoRoot).rulesConfig['branch-creation-guard'];\n // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,\n // so every validated config states an answer — which means \"absent\" here is not a consumer\n // who wants the default, it is a config that never passed validation. Deleting branches on\n // that basis would be deleting on a preference nobody expressed.\n if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true) return 0;\n\n const result: ReapResult = new BranchReaper().reap(repoRoot, 'auto-reap', cache);\n for (const failure of result.failed) {\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));\n }\n return result.reaped.length;\n } catch (err: unknown) {\n const error = toError(err);\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));\n return 0;\n }\n}\n\nif (require.main === module) {\n main();\n}\n"]}
|
package/src/core/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { RuleOptions } from '@webpieces/rules-config';
|
|
2
2
|
import { ToolKind } from '@webpieces/hook-runtime';
|
|
3
|
-
export { ResolvedConfig, ResolvedRuleConfig, RuleOptions,
|
|
3
|
+
export { ResolvedConfig, ResolvedRuleConfig, RuleOptions, RuleFailError } from '@webpieces/rules-config';
|
|
4
|
+
export { InformAiError } from '@webpieces/tooling-common';
|
|
4
5
|
export { HookMode, NormalizedBashInput, NormalizedEdit, NormalizedToolInput, ToolKind } from '@webpieces/hook-runtime';
|
|
5
6
|
import { FixHint } from './fix-hint';
|
|
6
7
|
export type RuleScope = 'edit' | 'file' | 'bash';
|
package/src/core/types.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.BlockedResult = exports.RuleGroup = exports.FileContext = exports.BashContext = exports.EditContext = exports.Violation = exports.NormalizedToolInput = exports.NormalizedEdit = exports.NormalizedBashInput = exports.
|
|
3
|
+
exports.BlockedResult = exports.RuleGroup = exports.FileContext = exports.BashContext = exports.EditContext = exports.Violation = exports.NormalizedToolInput = exports.NormalizedEdit = exports.NormalizedBashInput = exports.InformAiError = exports.RuleFailError = exports.ResolvedRuleConfig = exports.ResolvedConfig = void 0;
|
|
4
4
|
var rules_config_1 = require("@webpieces/rules-config");
|
|
5
5
|
Object.defineProperty(exports, "ResolvedConfig", { enumerable: true, get: function () { return rules_config_1.ResolvedConfig; } });
|
|
6
6
|
Object.defineProperty(exports, "ResolvedRuleConfig", { enumerable: true, get: function () { return rules_config_1.ResolvedRuleConfig; } });
|
|
7
|
-
Object.defineProperty(exports, "InformAiError", { enumerable: true, get: function () { return rules_config_1.InformAiError; } });
|
|
8
7
|
Object.defineProperty(exports, "RuleFailError", { enumerable: true, get: function () { return rules_config_1.RuleFailError; } });
|
|
8
|
+
var tooling_common_1 = require("@webpieces/tooling-common");
|
|
9
|
+
Object.defineProperty(exports, "InformAiError", { enumerable: true, get: function () { return tooling_common_1.InformAiError; } });
|
|
9
10
|
var hook_runtime_1 = require("@webpieces/hook-runtime");
|
|
10
11
|
Object.defineProperty(exports, "NormalizedBashInput", { enumerable: true, get: function () { return hook_runtime_1.NormalizedBashInput; } });
|
|
11
12
|
Object.defineProperty(exports, "NormalizedEdit", { enumerable: true, get: function () { return hook_runtime_1.NormalizedEdit; } });
|
package/src/core/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/types.ts"],"names":[],"mappings":";;;AAIA,wDAAwH;AAA/G,8GAAA,cAAc,OAAA;AAAE,kHAAA,kBAAkB,OAAA;AAAe,6GAAA,aAAa,OAAA;AAAE,6GAAA,aAAa,OAAA;AACtF,wDAAuH;AAApG,mHAAA,mBAAmB,OAAA;AAAE,8GAAA,cAAc,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAE3E,qDAAiD;AAmBjD,MAAa,SAAS;IACT,IAAI,CAAS;IACb,OAAO,CAAS;IACzB,yFAAyF;IACzF,yFAAyF;IACzF,iEAAiE;IACxD,OAAO,CAAqB;IACrC,SAAS,CAAqB;IAC9B,SAAS,CAAqB;IAE9B,YAAY,IAAY,EAAE,OAAe,EAAE,OAAgB;QACvD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AQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAjBD,8BAiBC;AAED,MAAa,aAAa;IACb,MAAM,CAAS;IACxB;;;;;;;;OAQG;IACM,KAAK,CAAS;IAEvB,YAAY,MAAc,EAAE,QAAgB,8BAAa;QACrD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAjBD,sCAiBC","sourcesContent":["// ResolvedConfig / ResolvedRuleConfig / RuleOptions now live in @webpieces/rules-config\n// so ai-hooks and the Nx validate-code executor share one loader and one config file.\nimport { RuleOptions } from '@webpieces/rules-config';\nimport { HookMode, NormalizedBashInput, NormalizedEdit, NormalizedToolInput, ToolKind } from '@webpieces/hook-runtime';\nexport { ResolvedConfig, ResolvedRuleConfig, RuleOptions, InformAiError, RuleFailError } from '@webpieces/rules-config';\nexport { HookMode, NormalizedBashInput, NormalizedEdit, NormalizedToolInput, ToolKind } from '@webpieces/hook-runtime';\nimport { FixHint } from './fix-hint';\nimport { L0_FAULT_NONE } from './l0-fault-codes';\n\n// 'Read' is a first-class member because read-stale-guard is a file-scoped guard that runs on the\n// Read fast path. It is deliberately NOT in HANDLED_FILE_TOOLS (adapters/claude-code-adapter.ts), so\n// ClaudeCodeAdapter.kindOf() maps it to the 'Read' routing kind and Read never enters the edit/file\n// rule pipeline — only the one guard that asks for it. Nothing switches exhaustively on this union;\n// it is carried for logging.\n//\n// 'Delete' arrives ONLY from a Codex `apply_patch` carrying a `*** Delete File:` directive — no Claude\n// Code tool produces it. Every existing rule DEFAULTS TO NOT FIRING on it (see DeleteScopedRules in\n// ./delete-scoped-rules.ts): a rule written to judge the bytes an edit ADDS has nothing to say about a file going\n// away, and inventing a verdict for it would be guessing. Rules for which a delete IS meaningful — a\n// barrel export disappearing, a doc that documents a deleted file — opt in there, deliberately.\nexport type RuleScope = 'edit' | 'file' | 'bash';\n// Which category of built-in rules a hook invocation runs: code-style 'rules', git/PR/branch\n// 'guards' (the hookGuards section), or 'all' (both categories — used by the openclaw plugin adapter,\n// which is a single before_tool_call hook rather than two split PreToolUse hooks).\nexport type IsLineDisabled = (lineNum: number, ruleName: string) => boolean;\n\nexport class Violation {\n readonly line: number;\n readonly snippet: string;\n // Optional per-occurrence override for the `→` line. When omitted, the report falls back\n // to the rule's `FixHint.violation`. Dynamic rules (param name, line count, marker path,\n // branch/PR) pass a specific message here; static rules omit it.\n readonly message: string | undefined;\n editIndex: number | undefined;\n editCount: number | undefined;\n\n constructor(line: number, snippet: string, message?: string) {\n this.line = line;\n this.snippet = snippet;\n this.message = message;\n this.editIndex = undefined;\n this.editCount = undefined;\n }\n}\n\nexport class EditContext {\n readonly tool: ToolKind;\n readonly editIndex: number;\n readonly editCount: number;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n readonly addedContent: string;\n readonly strippedContent: string;\n readonly lines: readonly string[];\n readonly strippedLines: readonly string[];\n readonly removedContent: string;\n readonly isLineDisabled: IsLineDisabled;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n editIndex: number,\n editCount: number,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n addedContent: string,\n strippedContent: string,\n lines: readonly string[],\n strippedLines: readonly string[],\n removedContent: string,\n isLineDisabled: IsLineDisabled,\n ) {\n this.tool = tool;\n this.editIndex = editIndex;\n this.editCount = editCount;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.addedContent = addedContent;\n this.strippedContent = strippedContent;\n this.lines = lines;\n this.strippedLines = strippedLines;\n this.removedContent = removedContent;\n this.isLineDisabled = isLineDisabled;\n this.options = {};\n }\n}\n\n// A heredoc and its body: `<<EOF` / `<<'EOF'` / `<<-EOF` through the terminator line.\nconst HEREDOC_BODY = /<<-?\\s*(['\"]?)(\\w+)\\1[\\s\\S]*?^\\t*\\2\\s*$/gm;\n\n// A single- or double-quoted span.\nconst QUOTED_SPAN = /'([^']*)'|\"([^\"]*)\"/g;\n\n// Shell syntax that a quoted span is explicitly NOT: separators, pipes, subshells, redirection,\n// expansion. Content carrying any of these is data (a jq filter, a regex, a glob), and unquoting it\n// would hand the segment scanner syntax the shell never sees. See stripProse.\nconst SHELL_METACHARACTER = /[|;&()<>$`]/;\n\nexport class BashContext {\n readonly tool: 'Bash';\n readonly command: string;\n /**\n * `command` with heredoc bodies and prose-in-quotes removed — what a guard should MATCH on, while\n * `command` stays raw for the violation message (a human needs to see what they actually typed).\n *\n * A commit message that merely MENTIONS a blocked command is not that command. This repo's whole\n * subject matter is the git workflow, so its commit messages, docs and the guards' own fix-hint\n * text are full of `git push` / `gh pr …` strings; matching raw text blocks writing about the\n * tooling. A guard that cries wolf is a guard someone eventually turns OFF, which costs far more\n * than the theoretical bypass this opens (`sh -c '<blocked command>'` stops matching). That trade\n * is deliberate: these guards exist to catch a FORGETFUL agent, not an adversarial one.\n *\n * ONLY for blocklist-shaped guards (\"if the command matches X, block\"), where stripping can only\n * ever block LESS. Never use it in an allowlist-shaped guard such as merged-branch-bash-guard,\n * where stripping could turn a permitted recovery command into a blocked one and deadlock the\n * session — there, match on the raw `command`.\n */\n readonly commandCode: string;\n /**\n * The tree this command is JUDGED against — the root of the worktree it actually acts on, which\n * is NOT the shell's cwd whenever the command carries a leading `cd <path> &&` (see\n * EffectiveTreeResolver). Guards read git state, the main-sync cache and the decision log from\n * here, so a command aimed at a linked worktree is judged on that worktree's branch, never the\n * primary clone's.\n */\n readonly workspaceRoot: string;\n /** The directory the command really runs in (post-`cd`). Relative paths resolve against THIS. */\n readonly effectiveCwd: string;\n /** The root owning webpieces.config.json. Equals workspaceRoot except in a linked worktree. */\n readonly governedRoot: string;\n options: RuleOptions;\n\n constructor(command: string, workspaceRoot: string, effectiveCwd?: string, governedRoot?: string) {\n this.tool = 'Bash';\n this.command = command;\n this.commandCode = this.stripProse(command);\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd ?? workspaceRoot;\n this.governedRoot = governedRoot ?? workspaceRoot;\n this.options = {};\n }\n\n /**\n * A quoted span WITHOUT whitespace is kept: `git checkout \"main\"` is a real command with a quoted\n * argument, not prose. One containing whitespace is a sentence, and becomes a single space.\n *\n * ONE exception, and it is a false positive that actually fired: a whitespace-free span carrying\n * SHELL METACHARACTERS is dropped too. Keeping the content strips only the quotes, so a jq filter —\n * `--jq '[.[]|select(.title|test(\"x\"))]|length'` — was handed to the guards as bare shell syntax.\n * Every guard then split it on its `|`, `(` and `;` and saw a segment reading exactly `test`, which\n * whole-repo-build-guard classified as the workspace-wide test script and BLOCKED. There was no\n * build anywhere in that command; it polled npm and GitHub.\n *\n * Quoting is precisely how a shell says \"this is DATA, not syntax\", so honouring the quotes is the\n * correct reading. And because commandCode only ever feeds blocklist-shaped guards, dropping more\n * can only ever block LESS — never turn an allowed command into a refused one.\n */\n private stripProse(command: string): string {\n const withoutHeredocs = command.replace(HEREDOC_BODY, ' ');\n return withoutHeredocs.replace(QUOTED_SPAN, (match: string, single?: string, double?: string): string => {\n const content = single ?? double ?? '';\n if (/\\s/.test(content)) return ' ';\n return SHELL_METACHARACTER.test(content) ? ' ' : content;\n });\n }\n}\n\nexport class FileContext {\n readonly tool: ToolKind;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n /** The git tree that owns filePath. workspaceRoot remains the root that owns policy/config. */\n readonly targetRoot: string;\n /** filePath relative to targetRoot, independent of its governed-root spelling. */\n readonly targetRelativePath: string;\n readonly currentFileLines: number;\n readonly linesAdded: number;\n readonly linesRemoved: number;\n readonly projectedFileLines: number;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n currentFileLines: number,\n linesAdded: number,\n linesRemoved: number,\n projectedFileLines: number,\n targetRoot: string = workspaceRoot,\n targetRelativePath: string = relativePath,\n ) {\n this.tool = tool;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.targetRoot = targetRoot;\n this.targetRelativePath = targetRelativePath;\n this.currentFileLines = currentFileLines;\n this.linesAdded = linesAdded;\n this.linesRemoved = linesRemoved;\n this.projectedFileLines = projectedFileLines;\n this.options = {};\n }\n}\n\n/**\n * The shape of a custom rule loaded from a `rulesDir` (a plain object returned by require()).\n * It carries only metadata + a `check` method — no on/off logic of its own.\n */\nexport interface PlainRule {\n readonly name: string;\n readonly description: string;\n readonly scope: RuleScope;\n readonly files: readonly string[];\n readonly defaultOptions: RuleOptions;\n readonly fixHint: FixHint;\n check(ctx: EditContext | FileContext | BashContext): readonly Violation[];\n}\n\n/**\n * The runtime contract the runner iterates. Both the built-in rule classes (which extend\n * EditRuleBase/FileRuleBase/BashRuleBase) and the custom-rule adapter satisfy this: they add\n * `shouldRun()` (mode + escape-hatch decision) on top of the PlainRule metadata.\n */\nexport interface Rule extends PlainRule {\n /**\n * The webpieces.config.json key whose entry configures this rule — NOT necessarily `name`.\n *\n * `name` is the operator identity (what a decision-log line and a deny report carry); `configKey`\n * is the switch. They differ wherever several classes implement one POLICY: all four branch-state\n * guards read `branch-state-guard`, all four PR-lifecycle guards read `pr-lifecycle-guard`. Every\n * consumer that asks \"which section does this live in?\" (filterByMode) or \"does this have an\n * entry?\" (the fault-Y config-sync check) must read THIS field, because asking for `name` there\n * demands entries under keys the validator rejects as retired.\n */\n readonly configKey: string;\n shouldRun(): boolean;\n}\n\nexport class RuleGroup {\n readonly ruleName: string;\n readonly ruleDescription: string;\n readonly fixHint: FixHint;\n readonly violations: readonly Violation[];\n\n constructor(\n ruleName: string,\n ruleDescription: string,\n fixHint: FixHint,\n violations: readonly Violation[],\n ) {\n this.ruleName = ruleName;\n this.ruleDescription = ruleDescription;\n this.fixHint = fixHint;\n this.violations = violations;\n }\n}\n\nexport class BlockedResult {\n readonly report: string;\n /**\n * The L0 fault this block IS, in the codebook's own letter (see core/l0-fault-codes.ts), or `-` for\n * an ordinary rule block.\n *\n * It rides on the result rather than being re-derived from the report text because the block is\n * decided deep in the runner (fault C in configMissingBlock, fault Y in checkConfigSync) and\n * STAMPED by the adapter at the terminal boundary, several frames up. Scraping the report for a\n * fault would be a second answer to a question the producer already knows.\n */\n readonly fault: string;\n\n constructor(report: string, fault: string = L0_FAULT_NONE) {\n this.report = report;\n this.fault = fault;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/types.ts"],"names":[],"mappings":";;;AAIA,wDAAyG;AAAhG,8GAAA,cAAc,OAAA;AAAE,kHAAA,kBAAkB,OAAA;AAAe,6GAAA,aAAa,OAAA;AACvE,4DAA0D;AAAjD,+GAAA,aAAa,OAAA;AACtB,wDAAuH;AAApG,mHAAA,mBAAmB,OAAA;AAAE,8GAAA,cAAc,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAE3E,qDAAiD;AAmBjD,MAAa,SAAS;IACT,IAAI,CAAS;IACb,OAAO,CAAS;IACzB,yFAAyF;IACzF,yFAAyF;IACzF,iEAAiE;IACxD,OAAO,CAAqB;IACrC,SAAS,CAAqB;IAC9B,SAAS,CAAqB;IAE9B,YAAY,IAAY,EAAE,OAAe,EAAE,OAAgB;QACvD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AAjBD,8BAiBC;AAED,MAAa,WAAW;IACX,IAAI,CAAW;IACf,SAAS,CAAS;IAClB,SAAS,CAAS;IAClB,QAAQ,CAAS;IACjB,YAAY,CAAS;IACrB,aAAa,CAA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AG,KAAK,CAAC;IACvB,CAAC;CACJ;AAjBD,sCAiBC","sourcesContent":["// ResolvedConfig / ResolvedRuleConfig / RuleOptions now live in @webpieces/rules-config\n// so ai-hooks and the Nx validate-code executor share one loader and one config file.\nimport { RuleOptions } from '@webpieces/rules-config';\nimport { HookMode, NormalizedBashInput, NormalizedEdit, NormalizedToolInput, ToolKind } from '@webpieces/hook-runtime';\nexport { ResolvedConfig, ResolvedRuleConfig, RuleOptions, RuleFailError } from '@webpieces/rules-config';\nexport { InformAiError } from '@webpieces/tooling-common';\nexport { HookMode, NormalizedBashInput, NormalizedEdit, NormalizedToolInput, ToolKind } from '@webpieces/hook-runtime';\nimport { FixHint } from './fix-hint';\nimport { L0_FAULT_NONE } from './l0-fault-codes';\n\n// 'Read' is a first-class member because read-stale-guard is a file-scoped guard that runs on the\n// Read fast path. It is deliberately NOT in HANDLED_FILE_TOOLS (adapters/claude-code-adapter.ts), so\n// ClaudeCodeAdapter.kindOf() maps it to the 'Read' routing kind and Read never enters the edit/file\n// rule pipeline — only the one guard that asks for it. Nothing switches exhaustively on this union;\n// it is carried for logging.\n//\n// 'Delete' arrives ONLY from a Codex `apply_patch` carrying a `*** Delete File:` directive — no Claude\n// Code tool produces it. Every existing rule DEFAULTS TO NOT FIRING on it (see DeleteScopedRules in\n// ./delete-scoped-rules.ts): a rule written to judge the bytes an edit ADDS has nothing to say about a file going\n// away, and inventing a verdict for it would be guessing. Rules for which a delete IS meaningful — a\n// barrel export disappearing, a doc that documents a deleted file — opt in there, deliberately.\nexport type RuleScope = 'edit' | 'file' | 'bash';\n// Which category of built-in rules a hook invocation runs: code-style 'rules', git/PR/branch\n// 'guards' (the hookGuards section), or 'all' (both categories — used by the openclaw plugin adapter,\n// which is a single before_tool_call hook rather than two split PreToolUse hooks).\nexport type IsLineDisabled = (lineNum: number, ruleName: string) => boolean;\n\nexport class Violation {\n readonly line: number;\n readonly snippet: string;\n // Optional per-occurrence override for the `→` line. When omitted, the report falls back\n // to the rule's `FixHint.violation`. Dynamic rules (param name, line count, marker path,\n // branch/PR) pass a specific message here; static rules omit it.\n readonly message: string | undefined;\n editIndex: number | undefined;\n editCount: number | undefined;\n\n constructor(line: number, snippet: string, message?: string) {\n this.line = line;\n this.snippet = snippet;\n this.message = message;\n this.editIndex = undefined;\n this.editCount = undefined;\n }\n}\n\nexport class EditContext {\n readonly tool: ToolKind;\n readonly editIndex: number;\n readonly editCount: number;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n readonly addedContent: string;\n readonly strippedContent: string;\n readonly lines: readonly string[];\n readonly strippedLines: readonly string[];\n readonly removedContent: string;\n readonly isLineDisabled: IsLineDisabled;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n editIndex: number,\n editCount: number,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n addedContent: string,\n strippedContent: string,\n lines: readonly string[],\n strippedLines: readonly string[],\n removedContent: string,\n isLineDisabled: IsLineDisabled,\n ) {\n this.tool = tool;\n this.editIndex = editIndex;\n this.editCount = editCount;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.addedContent = addedContent;\n this.strippedContent = strippedContent;\n this.lines = lines;\n this.strippedLines = strippedLines;\n this.removedContent = removedContent;\n this.isLineDisabled = isLineDisabled;\n this.options = {};\n }\n}\n\n// A heredoc and its body: `<<EOF` / `<<'EOF'` / `<<-EOF` through the terminator line.\nconst HEREDOC_BODY = /<<-?\\s*(['\"]?)(\\w+)\\1[\\s\\S]*?^\\t*\\2\\s*$/gm;\n\n// A single- or double-quoted span.\nconst QUOTED_SPAN = /'([^']*)'|\"([^\"]*)\"/g;\n\n// Shell syntax that a quoted span is explicitly NOT: separators, pipes, subshells, redirection,\n// expansion. Content carrying any of these is data (a jq filter, a regex, a glob), and unquoting it\n// would hand the segment scanner syntax the shell never sees. See stripProse.\nconst SHELL_METACHARACTER = /[|;&()<>$`]/;\n\nexport class BashContext {\n readonly tool: 'Bash';\n readonly command: string;\n /**\n * `command` with heredoc bodies and prose-in-quotes removed — what a guard should MATCH on, while\n * `command` stays raw for the violation message (a human needs to see what they actually typed).\n *\n * A commit message that merely MENTIONS a blocked command is not that command. This repo's whole\n * subject matter is the git workflow, so its commit messages, docs and the guards' own fix-hint\n * text are full of `git push` / `gh pr …` strings; matching raw text blocks writing about the\n * tooling. A guard that cries wolf is a guard someone eventually turns OFF, which costs far more\n * than the theoretical bypass this opens (`sh -c '<blocked command>'` stops matching). That trade\n * is deliberate: these guards exist to catch a FORGETFUL agent, not an adversarial one.\n *\n * ONLY for blocklist-shaped guards (\"if the command matches X, block\"), where stripping can only\n * ever block LESS. Never use it in an allowlist-shaped guard such as merged-branch-bash-guard,\n * where stripping could turn a permitted recovery command into a blocked one and deadlock the\n * session — there, match on the raw `command`.\n */\n readonly commandCode: string;\n /**\n * The tree this command is JUDGED against — the root of the worktree it actually acts on, which\n * is NOT the shell's cwd whenever the command carries a leading `cd <path> &&` (see\n * EffectiveTreeResolver). Guards read git state, the main-sync cache and the decision log from\n * here, so a command aimed at a linked worktree is judged on that worktree's branch, never the\n * primary clone's.\n */\n readonly workspaceRoot: string;\n /** The directory the command really runs in (post-`cd`). Relative paths resolve against THIS. */\n readonly effectiveCwd: string;\n /** The root owning webpieces.config.json. Equals workspaceRoot except in a linked worktree. */\n readonly governedRoot: string;\n options: RuleOptions;\n\n constructor(command: string, workspaceRoot: string, effectiveCwd?: string, governedRoot?: string) {\n this.tool = 'Bash';\n this.command = command;\n this.commandCode = this.stripProse(command);\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd ?? workspaceRoot;\n this.governedRoot = governedRoot ?? workspaceRoot;\n this.options = {};\n }\n\n /**\n * A quoted span WITHOUT whitespace is kept: `git checkout \"main\"` is a real command with a quoted\n * argument, not prose. One containing whitespace is a sentence, and becomes a single space.\n *\n * ONE exception, and it is a false positive that actually fired: a whitespace-free span carrying\n * SHELL METACHARACTERS is dropped too. Keeping the content strips only the quotes, so a jq filter —\n * `--jq '[.[]|select(.title|test(\"x\"))]|length'` — was handed to the guards as bare shell syntax.\n * Every guard then split it on its `|`, `(` and `;` and saw a segment reading exactly `test`, which\n * whole-repo-build-guard classified as the workspace-wide test script and BLOCKED. There was no\n * build anywhere in that command; it polled npm and GitHub.\n *\n * Quoting is precisely how a shell says \"this is DATA, not syntax\", so honouring the quotes is the\n * correct reading. And because commandCode only ever feeds blocklist-shaped guards, dropping more\n * can only ever block LESS — never turn an allowed command into a refused one.\n */\n private stripProse(command: string): string {\n const withoutHeredocs = command.replace(HEREDOC_BODY, ' ');\n return withoutHeredocs.replace(QUOTED_SPAN, (match: string, single?: string, double?: string): string => {\n const content = single ?? double ?? '';\n if (/\\s/.test(content)) return ' ';\n return SHELL_METACHARACTER.test(content) ? ' ' : content;\n });\n }\n}\n\nexport class FileContext {\n readonly tool: ToolKind;\n readonly filePath: string;\n readonly relativePath: string;\n readonly workspaceRoot: string;\n /** The git tree that owns filePath. workspaceRoot remains the root that owns policy/config. */\n readonly targetRoot: string;\n /** filePath relative to targetRoot, independent of its governed-root spelling. */\n readonly targetRelativePath: string;\n readonly currentFileLines: number;\n readonly linesAdded: number;\n readonly linesRemoved: number;\n readonly projectedFileLines: number;\n options: RuleOptions;\n\n constructor(\n tool: ToolKind,\n filePath: string,\n relativePath: string,\n workspaceRoot: string,\n currentFileLines: number,\n linesAdded: number,\n linesRemoved: number,\n projectedFileLines: number,\n targetRoot: string = workspaceRoot,\n targetRelativePath: string = relativePath,\n ) {\n this.tool = tool;\n this.filePath = filePath;\n this.relativePath = relativePath;\n this.workspaceRoot = workspaceRoot;\n this.targetRoot = targetRoot;\n this.targetRelativePath = targetRelativePath;\n this.currentFileLines = currentFileLines;\n this.linesAdded = linesAdded;\n this.linesRemoved = linesRemoved;\n this.projectedFileLines = projectedFileLines;\n this.options = {};\n }\n}\n\n/**\n * The shape of a custom rule loaded from a `rulesDir` (a plain object returned by require()).\n * It carries only metadata + a `check` method — no on/off logic of its own.\n */\nexport interface PlainRule {\n readonly name: string;\n readonly description: string;\n readonly scope: RuleScope;\n readonly files: readonly string[];\n readonly defaultOptions: RuleOptions;\n readonly fixHint: FixHint;\n check(ctx: EditContext | FileContext | BashContext): readonly Violation[];\n}\n\n/**\n * The runtime contract the runner iterates. Both the built-in rule classes (which extend\n * EditRuleBase/FileRuleBase/BashRuleBase) and the custom-rule adapter satisfy this: they add\n * `shouldRun()` (mode + escape-hatch decision) on top of the PlainRule metadata.\n */\nexport interface Rule extends PlainRule {\n /**\n * The webpieces.config.json key whose entry configures this rule — NOT necessarily `name`.\n *\n * `name` is the operator identity (what a decision-log line and a deny report carry); `configKey`\n * is the switch. They differ wherever several classes implement one POLICY: all four branch-state\n * guards read `branch-state-guard`, all four PR-lifecycle guards read `pr-lifecycle-guard`. Every\n * consumer that asks \"which section does this live in?\" (filterByMode) or \"does this have an\n * entry?\" (the fault-Y config-sync check) must read THIS field, because asking for `name` there\n * demands entries under keys the validator rejects as retired.\n */\n readonly configKey: string;\n shouldRun(): boolean;\n}\n\nexport class RuleGroup {\n readonly ruleName: string;\n readonly ruleDescription: string;\n readonly fixHint: FixHint;\n readonly violations: readonly Violation[];\n\n constructor(\n ruleName: string,\n ruleDescription: string,\n fixHint: FixHint,\n violations: readonly Violation[],\n ) {\n this.ruleName = ruleName;\n this.ruleDescription = ruleDescription;\n this.fixHint = fixHint;\n this.violations = violations;\n }\n}\n\nexport class BlockedResult {\n readonly report: string;\n /**\n * The L0 fault this block IS, in the codebook's own letter (see core/l0-fault-codes.ts), or `-` for\n * an ordinary rule block.\n *\n * It rides on the result rather than being re-derived from the report text because the block is\n * decided deep in the runner (fault C in configMissingBlock, fault Y in checkConfigSync) and\n * STAMPED by the adapter at the terminal boundary, several frames up. Scraping the report for a\n * fault would be a second answer to a question the producer already knows.\n */\n readonly fault: string;\n\n constructor(report: string, fault: string = L0_FAULT_NONE) {\n this.report = report;\n this.fault = fault;\n }\n}\n"]}
|