@webpieces/ai-hook-rules 0.4.816 → 0.4.818

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/ai-hook-rules",
3
- "version": "0.4.816",
3
+ "version": "0.4.818",
4
4
  "description": "Pluggable write-time validation framework for AI coding agents (@webpieces/ai-hook-rules). Claude Code PreToolUse + openclaw before_tool_call adapters share one rule engine.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -25,7 +25,7 @@
25
25
  "directory": "packages/tooling/ai-hook-rules"
26
26
  },
27
27
  "dependencies": {
28
- "@webpieces/rules-config": "0.4.816",
28
+ "@webpieces/rules-config": "0.4.818",
29
29
  "inversify": "7.10.4",
30
30
  "reflect-metadata": "0.2.2"
31
31
  },
@@ -85,7 +85,7 @@ with the verdict JSON on stdin (a heredoc is simplest), or \`--file <path>\` nam
85
85
  it, writes the verdict file, and records that YOU wrote it. A verdict file written any other way —
86
86
  by you, or by the coordinating agent on your behalf — is rejected by the gate, so there is no other route.
87
87
 
88
- You NEVER edit code, config, docs, or any other file in the repo. You never write \`review.json\` or an
88
+ You NEVER edit code, config, docs, or any other file in the repo. You never write \`summary.json\` or an
89
89
  \`override-<id>.json\`. If a finding needs a human's decision, say so in \`output\`; the coordinating
90
90
  agent is the one with the human.
91
91
  `;
@@ -1 +1 @@
1
- {"version":3,"file":"reviewer-agent.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/reviewer-agent.ts"],"names":[],"mappings":";;;AAqCA,8CAEC;AAGD,kDAgDC;AAQD,gDAKC;AAOD,gDAOC;;AArHD,+CAAyB;AACzB,mDAA6B;AAE7B,iCAAkC;AAElC,8EAA8E;AAC9E,yGAAyG;AACzG,gBAAgB;AAChB,EAAE;AACF,yGAAyG;AACzG,sGAAsG;AACtG,wGAAwG;AACxG,wGAAwG;AACxG,qJAAqJ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AAO,GAAG,mBAAmB,EAAE,CAAC;IACtC,IAAI,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACvF,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACxD,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,OAAO,IAAI,CAAC;AAChB,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { shimPath } from './shim';\n\n// ---------------------------------------------------------------------------\n// THE GENERIC REVIEWER AGENT — `.claude/agents/webpieces-reviewer.md`, a webpieces-owned, committed file\n// (issue #938).\n//\n// Every PR-gate checklist used to name its OWN agent type, one `.claude/agents/<name>-reviewer.md` each.\n// Those files added almost nothing over the checklist doc — a tool restriction and a paragraph saying\n// \"read your instructions file\" — were annoying to author per checklist, and drifted (#863: Codex never\n// read them at all). They also forced one subagent per checklist. So a repo now names ONE agent type in\n// `commands.pr-gate` (`webpieces-reviewer` unless `overrideReviewerAgent` is true), and this is the one webpieces ships: checklist-agnostic, because\n// everything checklist-specific is in the per-run instructions files `wp-review-upsert-pr` generates.\n//\n// It is a MANAGED SURFACE, exactly like `.claude/webpieces/ai-hook.sh`: GENERATED from\n// renderReviewerAgent(), byte-STABLE across releases (no version stamp, so it changes only when its own\n// words do), written by `wp-install-ai-hooks` and `wp-upgrade-shim`, and checked by managedSurfaceDrift()\n// so a missing, stale or hand-edited copy is flagged with `pnpm wp-upgrade-shim` as the cure. A repo\n// that wants different words sets `\"overrideReviewerAgent\": true` and `reviewerAgentName` to an agent of its\n// own instead of editing this.\n//\n// fs + path + ./shim only, like the rest of this directory: the cure must run on a tree too broken to\n// load the rule engine.\n// ---------------------------------------------------------------------------\n\n/** The agent type this file registers — the reviewer every repo gets unless it sets `overrideReviewerAgent`. */\nexport const REVIEWER_AGENT_NAME = 'webpieces-reviewer';\n\n/** The committed file, repo-relative — also the name the drift check reports it under. */\nexport const REVIEWER_AGENT_MARKER = `.claude/agents/${REVIEWER_AGENT_NAME}.md`;\n\n/** The copy that ships in the package, byte-identical to renderReviewerAgent() (locked by a unit test). */\nexport const REVIEWER_AGENT_TEMPLATE = `${REVIEWER_AGENT_NAME}.md`;\n\n// webpieces-disable no-function-outside-class -- pure fs+path helper beside shimPath, in the dependency-free bin module\nexport function reviewerAgentPath(projectRoot: string): string {\n return path.join(projectRoot, ...REVIEWER_AGENT_MARKER.split('/'));\n}\n\n// webpieces-disable no-function-outside-class -- pure renderer beside renderShim, in the dependency-free bin module\nexport function renderReviewerAgent(): string {\n return `---\nname: ${REVIEWER_AGENT_NAME}\ndescription: Generic PR-gate reviewer. Reviews a diff against one or more checklist docs, each over its own in-scope files, and submits exactly one verdict per checklist through pnpm wp-write-review. Spawned by \\`pnpm wp-review-upsert-pr\\`, which names the instructions files to read. Never edits code.\ntools: Read, Grep, Glob, Bash, Write\n---\n\n<!-- Generated by webpieces (@webpieces/ai-hook-rules) — do not edit; regenerate with pnpm wp-upgrade-shim.\n To change how reviews are done, set commands.pr-gate \"overrideReviewerAgent\": true and \"reviewerAgentName\" to an agent of your own. -->\n\nYou are a PR-gate reviewer. You did not write this change, and your job is to judge it against the\nchecklist(s) you are handed — nothing else.\n\n## What you are given\n\nYour caller names ONE OR MORE instructions files by absolute path, one per checklist\n(\\`<checklist-id>.instructions.md\\`). Read every one of them FIRST. Each is regenerated on every run and\nholds, for its checklist:\n\n- the checklist doc to review against — the substance of that review;\n- the files in scope, each with its extracted diff and the absolute path of the full source;\n- the diff manifest, the diff basis, and any pre-resolved context for this repo;\n- the exact verdict format, and the exact command that submits it.\n\nWork only from those files. Nothing about any checklist is restated here, so nothing here can drift.\n\n## How to review\n\n1. Handle each checklist SEPARATELY. Read its doc, then its in-scope diffs, then the full source of every\n in-scope file — a hunk shows what changed, only the whole file shows what it changed into.\n2. Judge each checklist ONLY against its own in-scope files. A finding that belongs to another checklist\n is not a finding for this one; a matched file that turns out to be irrelevant gets one sentence.\n3. Read other files for context when a judgement needs it, but do not go hunting: no searches through\n \\`node_modules\\`, no re-deriving the dependency graph. If something you need is missing, say so in\n \\`output\\` and judge what you could see.\n\n## What you submit\n\nExactly ONE verdict per checklist you were handed — and nothing for a checklist you were not handed —\nin the format its instructions file gives, submitted through \\`pnpm wp-write-review --checklist <id>\\`\nwith the verdict JSON on stdin (a heredoc is simplest), or \\`--file <path>\\` naming a scratch file. It validates\nit, writes the verdict file, and records that YOU wrote it. A verdict file written any other way —\nby you, or by the coordinating agent on your behalf — is rejected by the gate, so there is no other route.\n\nYou NEVER edit code, config, docs, or any other file in the repo. You never write \\`review.json\\` or an\n\\`override-<id>.json\\`. If a finding needs a human's decision, say so in \\`output\\`; the coordinating\nagent is the one with the human.\n`;\n}\n\n/**\n * True when this tree is webpieces-hooked (its committed shim exists) and the reviewer agent is MISSING or\n * differs from renderReviewerAgent(). Gated on the shim for the same reason `committedShimStale` is gated\n * on its own file: a tree webpieces never installed into has no managed surface to police.\n */\n// webpieces-disable no-function-outside-class -- pure fs+path helper beside committedShimStale, in the dependency-free bin module\nexport function reviewerAgentStale(root: string | null): boolean {\n if (root === null || !fs.existsSync(shimPath(root))) return false;\n const target = reviewerAgentPath(root);\n if (!fs.existsSync(target)) return true;\n return fs.readFileSync(target, 'utf8') !== renderReviewerAgent();\n}\n\n/**\n * Write the reviewer agent under `root`, returning true when the file changed. Creates `.claude/agents/`\n * when it is absent — that directory is what a Claude Code session scans for agent types.\n */\n// webpieces-disable no-function-outside-class -- pure fs+path writer beside writeShim, in the dependency-free bin module\nexport function writeReviewerAgent(root: string): boolean {\n const target = reviewerAgentPath(root);\n const desired = renderReviewerAgent();\n if (fs.existsSync(target) && fs.readFileSync(target, 'utf8') === desired) return false;\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, desired);\n return true;\n}\n"]}
1
+ {"version":3,"file":"reviewer-agent.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/reviewer-agent.ts"],"names":[],"mappings":";;;AAqCA,8CAEC;AAGD,kDAgDC;AAQD,gDAKC;AAOD,gDAOC;;AArHD,+CAAyB;AACzB,mDAA6B;AAE7B,iCAAkC;AAElC,8EAA8E;AAC9E,yGAAyG;AACzG,gBAAgB;AAChB,EAAE;AACF,yGAAyG;AACzG,sGAAsG;AACtG,wGAAwG;AACxG,wGAAwG;AACxG,qJAAqJ;AACrJ,sGAAsG;AACtG,EAAE;AACF,uFAAuF;AACvF,wGAAwG;AACxG,0GAA0G;AAC1G,qGAAqG;AACrG,6GAA6G;AAC7G,+BAA+B;AAC/B,EAAE;AACF,sGAAsG;AACtG,wBAAwB;AACxB,8EAA8E;AAE9E,gHAAgH;AACnG,QAAA,mBAAmB,GAAG,oBAAoB,CAAC;AAExD,0FAA0F;AAC7E,QAAA,qBAAqB,GAAG,kBAAkB,2BAAmB,KAAK,CAAC;AAEhF,2GAA2G;AAC9F,QAAA,uBAAuB,GAAG,GAAG,2BAAmB,KAAK,CAAC;AAEnE,wHAAwH;AACxH,SAAgB,iBAAiB,CAAC,WAAmB;IACjD,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,6BAAqB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;AACvE,CAAC;AAED,oHAAoH;AACpH,SAAgB,mBAAmB;IAC/B,OAAO;QACH,2BAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6C1B,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,kIAAkI;AAClI,SAAgB,kBAAkB,CAAC,IAAmB;IAClD,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAA,eAAQ,EAAC,IAAI,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IAClE,MAAM,MAAM,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAC;IACxC,OAAO,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,mBAAmB,EAAE,CAAC;AACrE,CAAC;AAED;;;GAGG;AACH,yHAAyH;AACzH,SAAgB,kBAAkB,CAAC,IAAY;IAC3C,MAAM,MAAM,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvC,MAAM,OAAO,GAAG,mBAAmB,EAAE,CAAC;IACtC,IAAI,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACvF,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACxD,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,OAAO,IAAI,CAAC;AAChB,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { shimPath } from './shim';\n\n// ---------------------------------------------------------------------------\n// THE GENERIC REVIEWER AGENT — `.claude/agents/webpieces-reviewer.md`, a webpieces-owned, committed file\n// (issue #938).\n//\n// Every PR-gate checklist used to name its OWN agent type, one `.claude/agents/<name>-reviewer.md` each.\n// Those files added almost nothing over the checklist doc — a tool restriction and a paragraph saying\n// \"read your instructions file\" — were annoying to author per checklist, and drifted (#863: Codex never\n// read them at all). They also forced one subagent per checklist. So a repo now names ONE agent type in\n// `commands.pr-gate` (`webpieces-reviewer` unless `overrideReviewerAgent` is true), and this is the one webpieces ships: checklist-agnostic, because\n// everything checklist-specific is in the per-run instructions files `wp-review-upsert-pr` generates.\n//\n// It is a MANAGED SURFACE, exactly like `.claude/webpieces/ai-hook.sh`: GENERATED from\n// renderReviewerAgent(), byte-STABLE across releases (no version stamp, so it changes only when its own\n// words do), written by `wp-install-ai-hooks` and `wp-upgrade-shim`, and checked by managedSurfaceDrift()\n// so a missing, stale or hand-edited copy is flagged with `pnpm wp-upgrade-shim` as the cure. A repo\n// that wants different words sets `\"overrideReviewerAgent\": true` and `reviewerAgentName` to an agent of its\n// own instead of editing this.\n//\n// fs + path + ./shim only, like the rest of this directory: the cure must run on a tree too broken to\n// load the rule engine.\n// ---------------------------------------------------------------------------\n\n/** The agent type this file registers — the reviewer every repo gets unless it sets `overrideReviewerAgent`. */\nexport const REVIEWER_AGENT_NAME = 'webpieces-reviewer';\n\n/** The committed file, repo-relative — also the name the drift check reports it under. */\nexport const REVIEWER_AGENT_MARKER = `.claude/agents/${REVIEWER_AGENT_NAME}.md`;\n\n/** The copy that ships in the package, byte-identical to renderReviewerAgent() (locked by a unit test). */\nexport const REVIEWER_AGENT_TEMPLATE = `${REVIEWER_AGENT_NAME}.md`;\n\n// webpieces-disable no-function-outside-class -- pure fs+path helper beside shimPath, in the dependency-free bin module\nexport function reviewerAgentPath(projectRoot: string): string {\n return path.join(projectRoot, ...REVIEWER_AGENT_MARKER.split('/'));\n}\n\n// webpieces-disable no-function-outside-class -- pure renderer beside renderShim, in the dependency-free bin module\nexport function renderReviewerAgent(): string {\n return `---\nname: ${REVIEWER_AGENT_NAME}\ndescription: Generic PR-gate reviewer. Reviews a diff against one or more checklist docs, each over its own in-scope files, and submits exactly one verdict per checklist through pnpm wp-write-review. Spawned by \\`pnpm wp-review-upsert-pr\\`, which names the instructions files to read. Never edits code.\ntools: Read, Grep, Glob, Bash, Write\n---\n\n<!-- Generated by webpieces (@webpieces/ai-hook-rules) — do not edit; regenerate with pnpm wp-upgrade-shim.\n To change how reviews are done, set commands.pr-gate \"overrideReviewerAgent\": true and \"reviewerAgentName\" to an agent of your own. -->\n\nYou are a PR-gate reviewer. You did not write this change, and your job is to judge it against the\nchecklist(s) you are handed — nothing else.\n\n## What you are given\n\nYour caller names ONE OR MORE instructions files by absolute path, one per checklist\n(\\`<checklist-id>.instructions.md\\`). Read every one of them FIRST. Each is regenerated on every run and\nholds, for its checklist:\n\n- the checklist doc to review against — the substance of that review;\n- the files in scope, each with its extracted diff and the absolute path of the full source;\n- the diff manifest, the diff basis, and any pre-resolved context for this repo;\n- the exact verdict format, and the exact command that submits it.\n\nWork only from those files. Nothing about any checklist is restated here, so nothing here can drift.\n\n## How to review\n\n1. Handle each checklist SEPARATELY. Read its doc, then its in-scope diffs, then the full source of every\n in-scope file — a hunk shows what changed, only the whole file shows what it changed into.\n2. Judge each checklist ONLY against its own in-scope files. A finding that belongs to another checklist\n is not a finding for this one; a matched file that turns out to be irrelevant gets one sentence.\n3. Read other files for context when a judgement needs it, but do not go hunting: no searches through\n \\`node_modules\\`, no re-deriving the dependency graph. If something you need is missing, say so in\n \\`output\\` and judge what you could see.\n\n## What you submit\n\nExactly ONE verdict per checklist you were handed — and nothing for a checklist you were not handed —\nin the format its instructions file gives, submitted through \\`pnpm wp-write-review --checklist <id>\\`\nwith the verdict JSON on stdin (a heredoc is simplest), or \\`--file <path>\\` naming a scratch file. It validates\nit, writes the verdict file, and records that YOU wrote it. A verdict file written any other way —\nby you, or by the coordinating agent on your behalf — is rejected by the gate, so there is no other route.\n\nYou NEVER edit code, config, docs, or any other file in the repo. You never write \\`summary.json\\` or an\n\\`override-<id>.json\\`. If a finding needs a human's decision, say so in \\`output\\`; the coordinating\nagent is the one with the human.\n`;\n}\n\n/**\n * True when this tree is webpieces-hooked (its committed shim exists) and the reviewer agent is MISSING or\n * differs from renderReviewerAgent(). Gated on the shim for the same reason `committedShimStale` is gated\n * on its own file: a tree webpieces never installed into has no managed surface to police.\n */\n// webpieces-disable no-function-outside-class -- pure fs+path helper beside committedShimStale, in the dependency-free bin module\nexport function reviewerAgentStale(root: string | null): boolean {\n if (root === null || !fs.existsSync(shimPath(root))) return false;\n const target = reviewerAgentPath(root);\n if (!fs.existsSync(target)) return true;\n return fs.readFileSync(target, 'utf8') !== renderReviewerAgent();\n}\n\n/**\n * Write the reviewer agent under `root`, returning true when the file changed. Creates `.claude/agents/`\n * when it is absent — that directory is what a Claude Code session scans for agent types.\n */\n// webpieces-disable no-function-outside-class -- pure fs+path writer beside writeShim, in the dependency-free bin module\nexport function writeReviewerAgent(root: string): boolean {\n const target = reviewerAgentPath(root);\n const desired = renderReviewerAgent();\n if (fs.existsSync(target) && fs.readFileSync(target, 'utf8') === desired) return false;\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, desired);\n return true;\n}\n"]}
@@ -175,7 +175,7 @@ function renderFilterSection() {
175
175
  '<!-- webpieces-disable no-state-paths-in-templates -- this paragraph\'s subject IS the two spellings of the state dir; a computed path would print one of them and lose the contrast -->',
176
176
  'The skip is asked about the path relative to the tree that **OWNS** the file, not to the governed',
177
177
  'root, and the two differ in exactly one place: a linked worktree. `<primary>/.webpieces/…` was',
178
- 'exempt while `<primary>/.claude/worktrees/agent-<id>/.webpieces/pr-review/…/review.json` — the same',
178
+ 'exempt while `<primary>/.claude/worktrees/agent-<id>/.webpieces/pr-review/…/summary.json` — the same',
179
179
  'kind of file, in a worktree\'s own state dir — was not, because governed-root-relative it begins',
180
180
  '`.claude`. That is the file `wp-review-upsert-pr` REQUIRES before `wp-finish-upsert-pr` will open a',
181
181
  'PR, so the guard could forbid a file the gate demands (issue #851). `GovernedPath` carries both',
@@ -1 +1 @@
1
- {"version":3,"file":"l1-doc.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l1-doc.ts"],"names":[],"mappings":";;AA8CA,kCAQC;AAtDD,uCAAsF;AAEtF,8EAA8E;AAC9E,gDAAgD;AAChD,EAAE;AACF,sGAAsG;AACtG,uGAAuG;AACvG,2FAA2F;AAC3F,EAAE;AACF,mGAAmG;AACnG,uGAAuG;AACvG,uGAAuG;AACvG,oDAAoD;AACpD,8E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;QACvG,0EAA0E;QAC1E,EAAE;QACF,+CAA+C;QAC/C,eAAe;QACf,sEAAsE;QACtE,8FAA8F;QAC9F,mFAAmF;QACnF,EAAE;QACF,mGAAmG;QACnG,uGAAuG;QACvG,wGAAwG;QACxG,EAAE;QACF,mGAAmG;QACnG,4GAA4G;QAC5G,yGAAyG;QACzG,+CAA+C;QAC/C,EAAE;QACF,KAAK;QACL,EAAE;QACF,EAAE;QACF,iBAAiB;QACjB,EAAE;QACF,6BAA6B;QAC7B,eAAe;QACf,oGAAoG;QACpG,kGAAkG;QAClG,6HAA6H;QAC7H,4FAA4F;QAC5F,6GAA6G;QAC7G,uFAAuF;QACvF,oHAAoH;QACpH,8JAA8J;QAC9J,+FAA+F;QAC/F,EAAE;KACL,CAAC;AACN,CAAC","sourcesContent":["import { L1Row, L1UseCase, L1_ROWS, L1_PRESTAGE_ROW, allL1UseCases } from './l1-rows';\n\n// ---------------------------------------------------------------------------\n// guards/L1-location.md, rendered from L1_ROWS.\n//\n// Same arrangement as l0-matrix.renderGuardMatrixDoc(): one join('\\n') of literal markdown lines with\n// the ROW DATA interpolated from the array the guard consults. Everything that is not row data — every\n// prose section — is a literal line here, because that is the half a generator cannot own.\n//\n// A unit test (l1-matrix.spec.ts) locks guards/L1-location.md byte-identical to renderL1Doc(), and\n// `pnpm guards:generate` rewrites the file. So the table in the doc IS the array, not a description of\n// it. This module, like l1-rows.ts, has no runtime imports outside this pair so the generator can load\n// it without the package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\n/** A dimension cell: the wildcard renders bare, every value renders as code. */\n// webpieces-disable no-function-outside-class -- pure cell formatter for renderL1Doc below, in this render module\nfunction cell(value: string): string {\n return value === '-' ? '-' : `\\`${value}\\``;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module\nfunction tableRow(row: L1Row): string {\n const dims = [row.k, row.a, row.r, row.g, row.p].map(cell).join(' | ');\n // Row 6 has no `why` — an EMPTY cell is `| |`, not `| |`. Two spaces would render the same in a\n // browser and fail the byte-lock, which is the whole point of locking bytes rather than markdown.\n const why = row.why === '' ? ' ' : ` ${row.why} `;\n // The CURE column exists so a reader who arrived here from a `row=` in a log gets the remedy on the\n // same line as the verdict, the way L2's matrix does. Only blocking rows have one; a row that hands\n // down to L2 or exempts has nothing to cure, and says so rather than leaving the cell blank.\n const cure = row.cure === null ? 'n/a — not a block' : row.cure.summary;\n return `| ${row.num} | ${dims} | ${row.action.label} |${why}| ${cure} |`;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module\nfunction useCaseRow(useCase: L1UseCase): string {\n return `| ${useCase.num} | ${useCase.symptom} | ${useCase.state} | ${useCase.verdict} | ${useCase.fix} |`;\n}\n\n/**\n * Render guards/L1-location.md.\n *\n * Split into three consecutive halves purely to stay inside the method-line budget — the join order is\n * what makes them one file, so keep them adjacent and keep the byte-lock test as the arbiter.\n */\n// webpieces-disable no-function-outside-class -- pure string builder over L1_ROWS, beside the array it reads\nexport function renderL1Doc(): string {\n return [\n ...renderHead(),\n ...renderTable(),\n ...renderLogJoin(),\n ...renderUseCases(),\n ...renderTail(),\n ].join('\\n');\n}\n\n// How a `row=` in the L1 log joins back to the table above — the section this doc existed without for\n// 1,457 logged decisions across nine repos, none of which an agent could look up, because the DELIVERED\n// copy of this page did not exist either. L2's doc has carried the same section since its own delivery.\n// webpieces-disable no-function-outside-class -- prose section of renderL1Doc's string, beside it in this module\nfunction renderLogJoin(): string[] {\n return [\n '## How a log line joins to a row',\n '',\n 'Every L1 decision is written to `.webpieces/logs/L1-location/<writer>.log` with `layer=L1` and',\n '`row=<n>`, where `<n>` is a row number from the table above. So `row=6` means \"this call was judged',\n 'by row 6\" and you read the dimensions, the verdict, the reason and the cure straight off that line. Row `0` is',\n 'the pre-stage; it is in the table for exactly this reason.',\n '',\n '**The join is by DISPATCH, and that is the difference from L2.** L1 takes the FIRST matching row in',\n '`L1_ROWS` and switches on it, so a row and a behaviour are the same object — delete the row and you',\n 'delete the block. L2\\'s four guard classes each own their own ladder and join to their rows by REASON',\n 'instead (see `webpieces.branch-state-matrix.md`). A totality test walks all 80 classifications and',\n 'asserts each lands on exactly one row, so there is no verdict this page cannot explain.',\n '',\n 'Row numbers are IDENTITY and are never reused: row 3 is retired (coordinator-in-worktree) and row 8',\n 'was added in its place rather than renumbering 4-7, because every `row=` already written to a log',\n 'would otherwise re-point.',\n '',\n ];\n}\n\n\n// The three questions L1 answers, the preamble and the filter — all prose, none of it row data.\n// webpieces-disable no-function-outside-class -- first section of renderL1Doc's string, beside it in this module\nfunction renderHead(): string[] {\n return [\n '# L1 — location',\n '',\n '**Goal: is this call ours to judge, is this tree governed by the release it asks for, and is git being run from the root?**',\n '',\n '**Config key: none, and none is proposed.** Force-to-root and trinary-version-skew have **no config',\n 'key** and cannot be disabled; `excludePaths` is a top-level block, not a `hookGuards` entry. A',\n '`location-guard` key was once proposed here — it never existed, and `hookGuards` has just gone from',\n 'nine keys to three, so adding a tenth-turned-fourth for a layer nobody has asked to switch off would',\n 'run against the whole point. L0 has no key for the stronger version of the same reason: a layer that',\n 'decides whether the tooling can be trusted cannot be configured by the file it has not validated yet.',\n '',\n '',\n '**Code:** `packages/tooling/ai-hook-rules/src/core/effective-tree.ts` (`EffectiveTreeResolver`,',\n '`TreeKind`) · `packages/tooling/ai-hook-rules/src/core/target-tree.ts` (`TargetTreeResolver`,',\n '`GovernedPath` — the same question asked about a FILE) ·',\n '`packages/tooling/ai-hook-rules/src/core/runner.ts` (`l1LocationBlock`, the `foreign` check) ·',\n '`packages/tooling/ai-hook-rules/src/core/excluded-paths.ts` (`filterByExcludedPaths`) ·',\n '`.../force-to-root.ts` (`ForceToRootGuard`) ·',\n '`packages/tooling/ai-hook-rules/src/core/missing-directory.ts` (`MissingDirectoryGuard`) ·',\n '`packages/tooling/ai-hook-rules/src/core/version-sync.ts` (`VersionSyncGuard`,',\n '`WebpiecesVersions`).',\n '',\n 'L1 answers four questions, and they are genuinely separate:',\n '',\n '1. **Do we govern this at all?** — the escape hatches, for other repos and non-governed paths.',\n ' Answered by asking GIT (`--git-common-dir`), never by path math: see the legend under **K**.',\n '2. **Does the directory still EXIST?** — row 7. A worktree reaped out from under a live shell leaves',\n ' a cwd that names nothing, and that state needs its own name and its own message, because the',\n ' remedy for \"you are in a subdirectory\" is a `cd` back into the very directory that is gone.',\n '3. **Is this tree governed by a release it did not ask for?** — row 8. A worktree MAY have its own',\n ' `node_modules` (nx, vitest and the eslint plugin all execute there and load from it), and when it',\n ' has none the shim\\'s upward walk runs the main tree\\'s binary. Either way the rule is the same and',\n ' holds whichever registration form — absolute or relative — is live in the consumer: the two trees',\n ' must PIN the same `@webpieces`, or the worktree is linted, validated and built by a release its',\n ' own manifest does not ask for. Asked of the PATH acted on, never of who is asking —',\n ' agent identity was measured untrustworthy for tree detection (a worktree-isolated agent whose tree',\n ' is auto-reaped at a turn boundary silently resumes on the primary clone).',\n '4. **Is the agent stranded away from the root?** — force-to-root, git/gh only. Agents forget where',\n ' they are constantly, and `cd` gives them two different ways to be wrong: a `cd` that stays INSIDE',\n ' the workspace PERSISTS to later calls (so the shell can be parked in a subdirectory left by an',\n ' unrelated command turns earlier), while a `cd` that LEAVES it is reset by the harness, which says',\n ' so — `Shell cwd was reset to <root>`. Neither can be assumed, which is why every remedy names the',\n ' root explicitly instead of telling the agent to `cd` first.',\n '',\n '## Preamble — resolve the target first (Bash only)',\n '',\n '`EffectiveTreeResolver.resolve()` computes `effectiveCwd`: the directory the command actually runs in,',\n 'which is the shell\\'s cwd unless the command leads with `cd <dir> &&`. **K is classified from',\n '`effectiveCwd`, not from the shell\\'s cwd** — so \"a foreign repo that `cd`s into ours\" is not a cell,',\n 'it is simply `pw` after resolution.',\n '',\n 'That holds because K is resolved by ASKING GIT about `effectiveCwd`, not by testing whether the path',\n 'is lexically under the governed root. It has to be said that way round: the resolver used to do the',\n 'path test, and a linked worktree under `.claude/worktrees/**` therefore resolved `f` — every bash',\n 'guard exempt in the one sandbox agents are told to work in. A sentence in this file asserted the',\n 'opposite as fact for several releases, which is how it went unnoticed.',\n '',\n 'Only a LEADING run of `cd`/`pushd` counts. A *trailing* `… && cd <exempt-tree>` must never',\n 'retroactively pull a command out of scope — that would smuggle a root-level `git push` past the',\n 'guards. Quoting is handled by `ShellSegmentScan`, so `echo \"cd sub && git push\"` is one opaque',\n 'segment and its quoted `cd` is never picked up.',\n '',\n ...renderFilterSection(),\n ];\n}\n\n// `excludePaths` — a FILTER over the rule list, not a dimension of the table. Its own function because\n// renderHead is at the 70-line method cap, and because this section is one self-contained argument.\n// webpieces-disable no-function-outside-class -- prose section of renderL1Doc's string, beside it in this module\nfunction renderFilterSection(): string[] {\n return [\n '## Filter — not a dimension (all tools)',\n '',\n '`filterByExcludedPaths` drops every rule excluded for this path: the **target path** for',\n 'Read/Write/Edit, `effectiveCwd` for Bash. An empty rule list means allow. This is a filter, not a row:',\n '\"exempt\" is what emerges when the list empties.',\n '',\n 'ONE path is filtered out BEFORE the list is consulted and cannot be put back: **`.webpieces/`**,',\n 'the tooling\\'s own state dir (`isWebpiecesStateDir`). It is gitignored in every consumer, so nothing',\n 'under it can reach a branch, be reviewed or be reverted — every reason L2 prints for protecting',\n '`main` is vacuous there. It was config-only once, which made the exemption optional on exactly the',\n 'directory webpieces itself writes to: `wp-review-upsert-pr` hands a reviewer subagent a',\n '`<primary>/.webpieces/worktrees/agent-<id>/pr-review/…` path, that write resolves to the PRIMARY',\n 'clone, and L2 judged the primary\\'s live branch — so the reviewer was denied \"You should not be',\n 'working on main\" whenever an unrelated session had left the primary there. There is deliberately',\n 'NO companion `\".webpieces/**\"` glob seeded into `excludePaths`: a config entry that changes',\n 'nothing is a second and WEAKER spelling — the matcher below misses the bare directory that the',\n 'predicate matches — and it invites a consumer to delete it and believe the exemption went too.',\n '',\n // The SUBJECT of this paragraph is which SPELLING of the state dir is exempt, so the two\n // spellings have to appear literally — computing them from a resolver would print one path and\n // destroy the contrast that is the whole point. This is exactly the case the rule's own escape\n // is for, and it is scoped to the three lines below rather than the file.\n '<!-- webpieces-disable no-state-paths-in-templates -- this paragraph\\'s subject IS the two spellings of the state dir; a computed path would print one of them and lose the contrast -->',\n 'The skip is asked about the path relative to the tree that **OWNS** the file, not to the governed',\n 'root, and the two differ in exactly one place: a linked worktree. `<primary>/.webpieces/…` was',\n 'exempt while `<primary>/.claude/worktrees/agent-<id>/.webpieces/pr-review/…/review.json` — the same',\n 'kind of file, in a worktree\\'s own state dir — was not, because governed-root-relative it begins',\n '`.claude`. That is the file `wp-review-upsert-pr` REQUIRES before `wp-finish-upsert-pr` will open a',\n 'PR, so the guard could forbid a file the gate demands (issue #851). `GovernedPath` carries both',\n 'spellings together so a caller cannot reach for the wrong one.',\n '',\n '`excludePaths` is **ONE glob list** (canonical: `\"excludePaths\": [\"repositories/**\"]`). The',\n '`{ rules: [...], guards: [...] }` object is **retired and rejected**, with the union it must become',\n 'named in the error. `wp-install-ai-hooks` migrates it in place.',\n '',\n 'This used to be a tolerated fallback, justified here by \"rejecting it would block every Bash/Edit',\n 'including the edit that would fix it.\" **That was never true**, and the fallback it licensed is why',\n 'consumer configs — this repo\\'s own included — sat on the dead shape for releases. A Write/Edit whose',\n 'target is `webpieces.config.json` is an unconditional **PASS** (see the L0 table above), and',\n '`pnpm install` has an installer bypass, so an invalid config can always be repaired from inside the',\n 'block. Config rejection is self-recoverable by construction; see `retired-config-keys.ts` for the',\n 'policy and the reasoning.',\n '',\n ];\n}\n\n// The legend, the table itself (ROW DATA), and the note on the two structural blocks.\n// webpieces-disable no-function-outside-class -- second section of renderL1Doc's string, beside it in this module\nfunction renderTable(): string[] {\n return [\n '## Legend',\n '',\n '| col | dimension | values |',\n '|---|---|---|',\n '| **K** | tree kind of the resolved target, from git\\'s own dirs | `f` foreign repo (a DIFFERENT `--git-common-dir`) · `m` the directory does not exist · `o` outside any repo · `w` a LINKED worktree of ours (`--git-dir` ≠ `--git-common-dir`), wherever it sits on disk · `pw` ours (primary **or** worktree) |',\n '| **V** | do the `@webpieces` versions agree between this worktree and the MAIN tree | `n` skewed · `y` in sync |',\n '| **R** | command is provably read-only inspection | `n` · `y` |',\n '| **G** | command invokes git/gh | `n` · `y` |',\n '| **P** | position of the resolved target | `root` · `sub` |',\n '',\n 'All of them are **Bash only**. Read/Write/Edit resolve their own target (`input.filePath`) and have no',\n 'dimensions — the filter is all that applies to them. **The Read tool is never blocked by L1.**',\n '',\n 'A linked worktree is deliberately **not** foreign: it is the same project, so the guards run against',\n 'THAT tree\\'s branch and cache. Every rule-scoped guard treats `p` and `w` alike, hence `pw`; row 8 below',\n 'is the ONE place they separate, and it turns on **V** — the versions, read off the tree itself.',\n '',\n 'PLACEMENT IS NOT IDENTITY. A worktree checked out INSIDE the repo — `<repo>/.claude/worktrees/agent-XXXX`,',\n 'which is where Claude Code puts every agent worktree — is `w` exactly like a sibling `../feature-dir` one.',\n 'K comes from git\\'s own dirs (`--git-common-dir` is identical for every checkout of one repo,',\n '`--git-dir` differs only in a linked worktree), never from whether the path sits under the governed root.',\n 'It used to short-circuit on that path test, so an in-repo worktree read as `f` — every bash guard exempt,',\n 'and row 8 unreachable, for the only layout the harness actually produces. A nested clone under',\n '`repositories/**` still reads `f`, because its shared git dir is its own.',\n '',\n '`V` comes from reading manifests off disk — the MAIN tree\\'s `pnpm-workspace.yaml` catalog pin, its',\n 'installed `node_modules` version, this worktree\\'s pin, and this worktree\\'s own installed version when',\n 'it has one (which it does the moment anyone runs `pnpm add` there). Three always, a fourth when',\n 'present. Anything unreadable is NO OPINION, never skew: a guard that cannot measure must not block.',\n 'It is deliberately NOT read from `agent_id`/`agent_type` — the dimension this replaced was, and a',\n 'worktree-isolated agent was measured resuming on the primary clone after its tree was reaped, so who',\n 'is asking cannot be trusted to say which tree is being acted on.',\n '',\n '`R` is `ReadOnlyInspectionScan` — the same paranoid \"provably inert\" test the unloadable-config escape',\n 'hatch uses (allowlisted viewers/searchers only, no redirects, no `sed -i`).',\n '',\n '## Table',\n '',\n '| # | K | V | R | G | P | act | why | cure |',\n '|---|---|---|---|---|---|---|---|---|',\n // Row 0 is the PRE-STAGE (`misplacedCdBlock`). It decides from command TEXT before a tree is\n // resolved, so it cannot be classified over the five dimensions rows 1-6 share — but it IS an\n // L1 block, and an L1 block the table did not describe is exactly the drift this table exists\n // to prevent. It is numbered 0, not 7, because it does not sit in the first-match scan; and it\n // is PRINTED because `row=0` in the L1 log has to join to something.\n `| ${L1_PRESTAGE_ROW} | – | – | – | – | – | 4 block | a \\`cd\\` that is not leading + literal, judged before any tree is resolved | \\`cd <literal abs path> && <the rest>\\` — ONE leading \\`cd\\`, or drop it |`,\n ...L1_ROWS.map(tableRow),\n '',\n 'Rows 3, 5 and 7 are the structural blocks, and they run as ONE step (`l1LocationBlock` in `runner.ts`)',\n 'so they can never be reordered by accident — row 7 (the directory is gone) first, then row 8, then',\n 'force-to-root. Row 7 is printed LAST above only because row numbers are stable across releases and',\n 'renumbering 1-6 would invalidate every `row=` in the logs; `m` matches no other row, so its position',\n 'in the scan is immaterial. All three sit after the L0',\n 'allowlist, after the `f` check, and after the `excludePaths` filter and the config-sync check. So a',\n 'cure (`cd <worktree> && pnpm install`) still reaches any tree: that is L0\\'s invariant, and row 8 does',\n 'not weaken it.',\n '',\n ];\n}\n\n// The use-case table (ROW DATA, in the doc's own numbering) and the two notes that follow it.\n// webpieces-disable no-function-outside-class -- third section of renderL1Doc's string, beside it in this module\nfunction renderUseCases(): string[] {\n return [\n '## L1 use cases',\n '',\n 'Same row shape as L0: the **Fix** is literal or it is not a fix. `<root>` is the absolute workspace',\n 'root — the messages name it explicitly rather than telling you to `cd` first, for the reason in the',\n 'section head (neither the shell\\'s cwd nor a `cd`\\'s persistence can be assumed).',\n '',\n '| # | what you SEE (exact symptom) | state | verdict | Fix |',\n '|---|---|---|---|---|',\n ...allL1UseCases().map(useCaseRow),\n '',\n 'Row 8 is the one that changed. It used to be ALLOWED, because the predicate was',\n '`shellAtRoot || cdsToRoot` — two variables OR\\'d, so the same destination got opposite verdicts',\n 'depending on where the shell happened to start. It is now one variable, `effectiveCwd === root`.',\n '',\n 'Row 12 is the incident that produced table row 8, and it is a VERSION SKEW incident — which is why',\n 'the row that replaced it measures versions rather than agent identity. The coordinator ran',\n '`git worktree add`, `cd`\\'d in,',\n 'and worked there. An L0 version-drift fault then fired against the PRIMARY (pin `0.4.545` vs',\n '`node_modules` `0.4.526`) and prescribed `pnpm install` — which ran in the WORKTREE, internally',\n 'consistent at `0.4.526`/`0.4.526`, so it succeeded, changed nothing in the measured tree, and the guard',\n 're-denied. Five identical installs later the agent had invented a theory about the harness stripping',\n 'its `cd` and handed the problem to the human. Note what row 15 says: the fix is NOT to deny that',\n 'install. It is to make the split state unreachable, so the wrong-tree install is never plausible.',\n '',\n ];\n}\n\n// The known gap and the code anchors — prose, and the one section that must never be summarised away:\n// three code comments point at it.\n// webpieces-disable no-function-outside-class -- last section of renderL1Doc's string, beside it in this module\nfunction renderTail(): string[] {\n return [\n '## Not done — `o` is not exempt yet',\n '',\n 'Row 2 hands `\\'outside\\'` down to L2 rather than exempting it. `\\'outside\\'` is produced at',\n '`effective-tree.ts` (git has no answer for the directory) carrying `governedRoot`, and **no code branches on it**, so a',\n 'command in no git repo is judged against the governed repo\\'s branch and staleness state. That is a',\n 'wrong verdict, and `exempt` is the right action.',\n '',\n '**It must not ship alone.** Jurisdiction comes from the shell cwd, not from what the command touches,',\n 'so exempting `o` opens a bypass an agent reaches by typing `cd /tmp &&`:',\n '',\n '| command | today | with `o → exempt` alone |',\n '|---|---|---|',\n '| `cd /tmp && ls` | judged against the repo | exempt — **correct** |',\n '| `cd /tmp && git -C $REPO commit` | L2 guards fire | exempt — **every L2 guard bypassed** |',\n '| `cd /tmp && rm -rf $REPO/packages/http/src` | judged | exempt — **unguarded** |',\n '',\n 'The two cases only separate once jurisdiction is judged on **what the command touches** (explicit',\n '`git -C` / `--work-tree`, then path arguments, then the `cd`, then the shell cwd), with the fail-safe',\n 'rule that **any** resolved target inside `governedRoot` means `pw`. Ship the two together, or neither.',\n '',\n 'Tracked in `backlog/bug-bash-guards-judge-the-shell-cwd-not-the-paths-the-command-touches.md` and',\n '`backlog/bug-outside-tree-kind-is-never-consumed-so-a-non-git-dir-is-judged-against-the-governed-repo.md`.',\n 'That resolver has three consumers — L1\\'s K, L2\\'s scope dimension, and `excludePaths` on the Bash path',\n '— which is why the backlog says **fix once**.',\n '',\n '---',\n '',\n '',\n '## Code anchors',\n '',\n '| section | file | symbol |',\n '|---|---|---|',\n '| resolver, K | `ai-hook-rules/src/core/effective-tree.ts` | `EffectiveTreeResolver`, `TreeKind` |',\n '| the two structural blocks, in order | `ai-hook-rules/src/core/runner.ts` | `l1LocationBlock` |',\n '| trinary-version-skew (row 8), V, R | `ai-hook-rules/src/core/version-sync.ts` | `VersionSyncGuard`, `WebpiecesVersions` |',\n '| force-to-root (row 5) | `ai-hook-rules/src/core/force-to-root.ts` | `ForceToRootGuard` |',\n '| the directory is gone (row 7) | `ai-hook-rules/src/core/missing-directory.ts` | `MissingDirectoryGuard` |',\n '| the filter | `ai-hook-rules/src/core/excluded-paths.ts` | `filterByExcludedPaths` |',\n '| which tree owns a TARGET PATH | `ai-hook-rules/src/core/target-tree.ts` | `TargetTreeResolver`, `GovernedPath` |',\n '| `excludePaths` shape | `rules-config/src/exclude-hook-paths.ts`, `validate-config.ts`, `retired-config-keys.ts` | `ExcludePaths`, `validateExcludePaths` |',\n '| the `.webpieces/` skip | `rules-config/src/exclude-hook-paths.ts` | `isWebpiecesStateDir` |',\n '',\n ];\n}\n"]}
1
+ {"version":3,"file":"l1-doc.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l1-doc.ts"],"names":[],"mappings":";;AA8CA,kCAQC;AAtDD,uCAAsF;AAEtF,8EAA8E;AAC9E,gDAAgD;AAChD,EAAE;AACF,sGAAsG;AACtG,uGAAuG;AACvG,2FAA2F;AAC3F,EAAE;AACF,mGAAmG;AACnG,uGAAuG;AACvG,uGA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kD;QAClD,EAAE;QACF,uGAAuG;QACvG,0EAA0E;QAC1E,EAAE;QACF,+CAA+C;QAC/C,eAAe;QACf,sEAAsE;QACtE,8FAA8F;QAC9F,mFAAmF;QACnF,EAAE;QACF,mGAAmG;QACnG,uGAAuG;QACvG,wGAAwG;QACxG,EAAE;QACF,mGAAmG;QACnG,4GAA4G;QAC5G,yGAAyG;QACzG,+CAA+C;QAC/C,EAAE;QACF,KAAK;QACL,EAAE;QACF,EAAE;QACF,iBAAiB;QACjB,EAAE;QACF,6BAA6B;QAC7B,eAAe;QACf,oGAAoG;QACpG,kGAAkG;QAClG,6HAA6H;QAC7H,4FAA4F;QAC5F,6GAA6G;QAC7G,uFAAuF;QACvF,oHAAoH;QACpH,8JAA8J;QAC9J,+FAA+F;QAC/F,EAAE;KACL,CAAC;AACN,CAAC","sourcesContent":["import { L1Row, L1UseCase, L1_ROWS, L1_PRESTAGE_ROW, allL1UseCases } from './l1-rows';\n\n// ---------------------------------------------------------------------------\n// guards/L1-location.md, rendered from L1_ROWS.\n//\n// Same arrangement as l0-matrix.renderGuardMatrixDoc(): one join('\\n') of literal markdown lines with\n// the ROW DATA interpolated from the array the guard consults. Everything that is not row data — every\n// prose section — is a literal line here, because that is the half a generator cannot own.\n//\n// A unit test (l1-matrix.spec.ts) locks guards/L1-location.md byte-identical to renderL1Doc(), and\n// `pnpm guards:generate` rewrites the file. So the table in the doc IS the array, not a description of\n// it. This module, like l1-rows.ts, has no runtime imports outside this pair so the generator can load\n// it without the package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\n/** A dimension cell: the wildcard renders bare, every value renders as code. */\n// webpieces-disable no-function-outside-class -- pure cell formatter for renderL1Doc below, in this render module\nfunction cell(value: string): string {\n return value === '-' ? '-' : `\\`${value}\\``;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module\nfunction tableRow(row: L1Row): string {\n const dims = [row.k, row.a, row.r, row.g, row.p].map(cell).join(' | ');\n // Row 6 has no `why` — an EMPTY cell is `| |`, not `| |`. Two spaces would render the same in a\n // browser and fail the byte-lock, which is the whole point of locking bytes rather than markdown.\n const why = row.why === '' ? ' ' : ` ${row.why} `;\n // The CURE column exists so a reader who arrived here from a `row=` in a log gets the remedy on the\n // same line as the verdict, the way L2's matrix does. Only blocking rows have one; a row that hands\n // down to L2 or exempts has nothing to cure, and says so rather than leaving the cell blank.\n const cure = row.cure === null ? 'n/a — not a block' : row.cure.summary;\n return `| ${row.num} | ${dims} | ${row.action.label} |${why}| ${cure} |`;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module\nfunction useCaseRow(useCase: L1UseCase): string {\n return `| ${useCase.num} | ${useCase.symptom} | ${useCase.state} | ${useCase.verdict} | ${useCase.fix} |`;\n}\n\n/**\n * Render guards/L1-location.md.\n *\n * Split into three consecutive halves purely to stay inside the method-line budget — the join order is\n * what makes them one file, so keep them adjacent and keep the byte-lock test as the arbiter.\n */\n// webpieces-disable no-function-outside-class -- pure string builder over L1_ROWS, beside the array it reads\nexport function renderL1Doc(): string {\n return [\n ...renderHead(),\n ...renderTable(),\n ...renderLogJoin(),\n ...renderUseCases(),\n ...renderTail(),\n ].join('\\n');\n}\n\n// How a `row=` in the L1 log joins back to the table above — the section this doc existed without for\n// 1,457 logged decisions across nine repos, none of which an agent could look up, because the DELIVERED\n// copy of this page did not exist either. L2's doc has carried the same section since its own delivery.\n// webpieces-disable no-function-outside-class -- prose section of renderL1Doc's string, beside it in this module\nfunction renderLogJoin(): string[] {\n return [\n '## How a log line joins to a row',\n '',\n 'Every L1 decision is written to `.webpieces/logs/L1-location/<writer>.log` with `layer=L1` and',\n '`row=<n>`, where `<n>` is a row number from the table above. So `row=6` means \"this call was judged',\n 'by row 6\" and you read the dimensions, the verdict, the reason and the cure straight off that line. Row `0` is',\n 'the pre-stage; it is in the table for exactly this reason.',\n '',\n '**The join is by DISPATCH, and that is the difference from L2.** L1 takes the FIRST matching row in',\n '`L1_ROWS` and switches on it, so a row and a behaviour are the same object — delete the row and you',\n 'delete the block. L2\\'s four guard classes each own their own ladder and join to their rows by REASON',\n 'instead (see `webpieces.branch-state-matrix.md`). A totality test walks all 80 classifications and',\n 'asserts each lands on exactly one row, so there is no verdict this page cannot explain.',\n '',\n 'Row numbers are IDENTITY and are never reused: row 3 is retired (coordinator-in-worktree) and row 8',\n 'was added in its place rather than renumbering 4-7, because every `row=` already written to a log',\n 'would otherwise re-point.',\n '',\n ];\n}\n\n\n// The three questions L1 answers, the preamble and the filter — all prose, none of it row data.\n// webpieces-disable no-function-outside-class -- first section of renderL1Doc's string, beside it in this module\nfunction renderHead(): string[] {\n return [\n '# L1 — location',\n '',\n '**Goal: is this call ours to judge, is this tree governed by the release it asks for, and is git being run from the root?**',\n '',\n '**Config key: none, and none is proposed.** Force-to-root and trinary-version-skew have **no config',\n 'key** and cannot be disabled; `excludePaths` is a top-level block, not a `hookGuards` entry. A',\n '`location-guard` key was once proposed here — it never existed, and `hookGuards` has just gone from',\n 'nine keys to three, so adding a tenth-turned-fourth for a layer nobody has asked to switch off would',\n 'run against the whole point. L0 has no key for the stronger version of the same reason: a layer that',\n 'decides whether the tooling can be trusted cannot be configured by the file it has not validated yet.',\n '',\n '',\n '**Code:** `packages/tooling/ai-hook-rules/src/core/effective-tree.ts` (`EffectiveTreeResolver`,',\n '`TreeKind`) · `packages/tooling/ai-hook-rules/src/core/target-tree.ts` (`TargetTreeResolver`,',\n '`GovernedPath` — the same question asked about a FILE) ·',\n '`packages/tooling/ai-hook-rules/src/core/runner.ts` (`l1LocationBlock`, the `foreign` check) ·',\n '`packages/tooling/ai-hook-rules/src/core/excluded-paths.ts` (`filterByExcludedPaths`) ·',\n '`.../force-to-root.ts` (`ForceToRootGuard`) ·',\n '`packages/tooling/ai-hook-rules/src/core/missing-directory.ts` (`MissingDirectoryGuard`) ·',\n '`packages/tooling/ai-hook-rules/src/core/version-sync.ts` (`VersionSyncGuard`,',\n '`WebpiecesVersions`).',\n '',\n 'L1 answers four questions, and they are genuinely separate:',\n '',\n '1. **Do we govern this at all?** — the escape hatches, for other repos and non-governed paths.',\n ' Answered by asking GIT (`--git-common-dir`), never by path math: see the legend under **K**.',\n '2. **Does the directory still EXIST?** — row 7. A worktree reaped out from under a live shell leaves',\n ' a cwd that names nothing, and that state needs its own name and its own message, because the',\n ' remedy for \"you are in a subdirectory\" is a `cd` back into the very directory that is gone.',\n '3. **Is this tree governed by a release it did not ask for?** — row 8. A worktree MAY have its own',\n ' `node_modules` (nx, vitest and the eslint plugin all execute there and load from it), and when it',\n ' has none the shim\\'s upward walk runs the main tree\\'s binary. Either way the rule is the same and',\n ' holds whichever registration form — absolute or relative — is live in the consumer: the two trees',\n ' must PIN the same `@webpieces`, or the worktree is linted, validated and built by a release its',\n ' own manifest does not ask for. Asked of the PATH acted on, never of who is asking —',\n ' agent identity was measured untrustworthy for tree detection (a worktree-isolated agent whose tree',\n ' is auto-reaped at a turn boundary silently resumes on the primary clone).',\n '4. **Is the agent stranded away from the root?** — force-to-root, git/gh only. Agents forget where',\n ' they are constantly, and `cd` gives them two different ways to be wrong: a `cd` that stays INSIDE',\n ' the workspace PERSISTS to later calls (so the shell can be parked in a subdirectory left by an',\n ' unrelated command turns earlier), while a `cd` that LEAVES it is reset by the harness, which says',\n ' so — `Shell cwd was reset to <root>`. Neither can be assumed, which is why every remedy names the',\n ' root explicitly instead of telling the agent to `cd` first.',\n '',\n '## Preamble — resolve the target first (Bash only)',\n '',\n '`EffectiveTreeResolver.resolve()` computes `effectiveCwd`: the directory the command actually runs in,',\n 'which is the shell\\'s cwd unless the command leads with `cd <dir> &&`. **K is classified from',\n '`effectiveCwd`, not from the shell\\'s cwd** — so \"a foreign repo that `cd`s into ours\" is not a cell,',\n 'it is simply `pw` after resolution.',\n '',\n 'That holds because K is resolved by ASKING GIT about `effectiveCwd`, not by testing whether the path',\n 'is lexically under the governed root. It has to be said that way round: the resolver used to do the',\n 'path test, and a linked worktree under `.claude/worktrees/**` therefore resolved `f` — every bash',\n 'guard exempt in the one sandbox agents are told to work in. A sentence in this file asserted the',\n 'opposite as fact for several releases, which is how it went unnoticed.',\n '',\n 'Only a LEADING run of `cd`/`pushd` counts. A *trailing* `… && cd <exempt-tree>` must never',\n 'retroactively pull a command out of scope — that would smuggle a root-level `git push` past the',\n 'guards. Quoting is handled by `ShellSegmentScan`, so `echo \"cd sub && git push\"` is one opaque',\n 'segment and its quoted `cd` is never picked up.',\n '',\n ...renderFilterSection(),\n ];\n}\n\n// `excludePaths` — a FILTER over the rule list, not a dimension of the table. Its own function because\n// renderHead is at the 70-line method cap, and because this section is one self-contained argument.\n// webpieces-disable no-function-outside-class -- prose section of renderL1Doc's string, beside it in this module\nfunction renderFilterSection(): string[] {\n return [\n '## Filter — not a dimension (all tools)',\n '',\n '`filterByExcludedPaths` drops every rule excluded for this path: the **target path** for',\n 'Read/Write/Edit, `effectiveCwd` for Bash. An empty rule list means allow. This is a filter, not a row:',\n '\"exempt\" is what emerges when the list empties.',\n '',\n 'ONE path is filtered out BEFORE the list is consulted and cannot be put back: **`.webpieces/`**,',\n 'the tooling\\'s own state dir (`isWebpiecesStateDir`). It is gitignored in every consumer, so nothing',\n 'under it can reach a branch, be reviewed or be reverted — every reason L2 prints for protecting',\n '`main` is vacuous there. It was config-only once, which made the exemption optional on exactly the',\n 'directory webpieces itself writes to: `wp-review-upsert-pr` hands a reviewer subagent a',\n '`<primary>/.webpieces/worktrees/agent-<id>/pr-review/…` path, that write resolves to the PRIMARY',\n 'clone, and L2 judged the primary\\'s live branch — so the reviewer was denied \"You should not be',\n 'working on main\" whenever an unrelated session had left the primary there. There is deliberately',\n 'NO companion `\".webpieces/**\"` glob seeded into `excludePaths`: a config entry that changes',\n 'nothing is a second and WEAKER spelling — the matcher below misses the bare directory that the',\n 'predicate matches — and it invites a consumer to delete it and believe the exemption went too.',\n '',\n // The SUBJECT of this paragraph is which SPELLING of the state dir is exempt, so the two\n // spellings have to appear literally — computing them from a resolver would print one path and\n // destroy the contrast that is the whole point. This is exactly the case the rule's own escape\n // is for, and it is scoped to the three lines below rather than the file.\n '<!-- webpieces-disable no-state-paths-in-templates -- this paragraph\\'s subject IS the two spellings of the state dir; a computed path would print one of them and lose the contrast -->',\n 'The skip is asked about the path relative to the tree that **OWNS** the file, not to the governed',\n 'root, and the two differ in exactly one place: a linked worktree. `<primary>/.webpieces/…` was',\n 'exempt while `<primary>/.claude/worktrees/agent-<id>/.webpieces/pr-review/…/summary.json` — the same',\n 'kind of file, in a worktree\\'s own state dir — was not, because governed-root-relative it begins',\n '`.claude`. That is the file `wp-review-upsert-pr` REQUIRES before `wp-finish-upsert-pr` will open a',\n 'PR, so the guard could forbid a file the gate demands (issue #851). `GovernedPath` carries both',\n 'spellings together so a caller cannot reach for the wrong one.',\n '',\n '`excludePaths` is **ONE glob list** (canonical: `\"excludePaths\": [\"repositories/**\"]`). The',\n '`{ rules: [...], guards: [...] }` object is **retired and rejected**, with the union it must become',\n 'named in the error. `wp-install-ai-hooks` migrates it in place.',\n '',\n 'This used to be a tolerated fallback, justified here by \"rejecting it would block every Bash/Edit',\n 'including the edit that would fix it.\" **That was never true**, and the fallback it licensed is why',\n 'consumer configs — this repo\\'s own included — sat on the dead shape for releases. A Write/Edit whose',\n 'target is `webpieces.config.json` is an unconditional **PASS** (see the L0 table above), and',\n '`pnpm install` has an installer bypass, so an invalid config can always be repaired from inside the',\n 'block. Config rejection is self-recoverable by construction; see `retired-config-keys.ts` for the',\n 'policy and the reasoning.',\n '',\n ];\n}\n\n// The legend, the table itself (ROW DATA), and the note on the two structural blocks.\n// webpieces-disable no-function-outside-class -- second section of renderL1Doc's string, beside it in this module\nfunction renderTable(): string[] {\n return [\n '## Legend',\n '',\n '| col | dimension | values |',\n '|---|---|---|',\n '| **K** | tree kind of the resolved target, from git\\'s own dirs | `f` foreign repo (a DIFFERENT `--git-common-dir`) · `m` the directory does not exist · `o` outside any repo · `w` a LINKED worktree of ours (`--git-dir` ≠ `--git-common-dir`), wherever it sits on disk · `pw` ours (primary **or** worktree) |',\n '| **V** | do the `@webpieces` versions agree between this worktree and the MAIN tree | `n` skewed · `y` in sync |',\n '| **R** | command is provably read-only inspection | `n` · `y` |',\n '| **G** | command invokes git/gh | `n` · `y` |',\n '| **P** | position of the resolved target | `root` · `sub` |',\n '',\n 'All of them are **Bash only**. Read/Write/Edit resolve their own target (`input.filePath`) and have no',\n 'dimensions — the filter is all that applies to them. **The Read tool is never blocked by L1.**',\n '',\n 'A linked worktree is deliberately **not** foreign: it is the same project, so the guards run against',\n 'THAT tree\\'s branch and cache. Every rule-scoped guard treats `p` and `w` alike, hence `pw`; row 8 below',\n 'is the ONE place they separate, and it turns on **V** — the versions, read off the tree itself.',\n '',\n 'PLACEMENT IS NOT IDENTITY. A worktree checked out INSIDE the repo — `<repo>/.claude/worktrees/agent-XXXX`,',\n 'which is where Claude Code puts every agent worktree — is `w` exactly like a sibling `../feature-dir` one.',\n 'K comes from git\\'s own dirs (`--git-common-dir` is identical for every checkout of one repo,',\n '`--git-dir` differs only in a linked worktree), never from whether the path sits under the governed root.',\n 'It used to short-circuit on that path test, so an in-repo worktree read as `f` — every bash guard exempt,',\n 'and row 8 unreachable, for the only layout the harness actually produces. A nested clone under',\n '`repositories/**` still reads `f`, because its shared git dir is its own.',\n '',\n '`V` comes from reading manifests off disk — the MAIN tree\\'s `pnpm-workspace.yaml` catalog pin, its',\n 'installed `node_modules` version, this worktree\\'s pin, and this worktree\\'s own installed version when',\n 'it has one (which it does the moment anyone runs `pnpm add` there). Three always, a fourth when',\n 'present. Anything unreadable is NO OPINION, never skew: a guard that cannot measure must not block.',\n 'It is deliberately NOT read from `agent_id`/`agent_type` — the dimension this replaced was, and a',\n 'worktree-isolated agent was measured resuming on the primary clone after its tree was reaped, so who',\n 'is asking cannot be trusted to say which tree is being acted on.',\n '',\n '`R` is `ReadOnlyInspectionScan` — the same paranoid \"provably inert\" test the unloadable-config escape',\n 'hatch uses (allowlisted viewers/searchers only, no redirects, no `sed -i`).',\n '',\n '## Table',\n '',\n '| # | K | V | R | G | P | act | why | cure |',\n '|---|---|---|---|---|---|---|---|---|',\n // Row 0 is the PRE-STAGE (`misplacedCdBlock`). It decides from command TEXT before a tree is\n // resolved, so it cannot be classified over the five dimensions rows 1-6 share — but it IS an\n // L1 block, and an L1 block the table did not describe is exactly the drift this table exists\n // to prevent. It is numbered 0, not 7, because it does not sit in the first-match scan; and it\n // is PRINTED because `row=0` in the L1 log has to join to something.\n `| ${L1_PRESTAGE_ROW} | – | – | – | – | – | 4 block | a \\`cd\\` that is not leading + literal, judged before any tree is resolved | \\`cd <literal abs path> && <the rest>\\` — ONE leading \\`cd\\`, or drop it |`,\n ...L1_ROWS.map(tableRow),\n '',\n 'Rows 3, 5 and 7 are the structural blocks, and they run as ONE step (`l1LocationBlock` in `runner.ts`)',\n 'so they can never be reordered by accident — row 7 (the directory is gone) first, then row 8, then',\n 'force-to-root. Row 7 is printed LAST above only because row numbers are stable across releases and',\n 'renumbering 1-6 would invalidate every `row=` in the logs; `m` matches no other row, so its position',\n 'in the scan is immaterial. All three sit after the L0',\n 'allowlist, after the `f` check, and after the `excludePaths` filter and the config-sync check. So a',\n 'cure (`cd <worktree> && pnpm install`) still reaches any tree: that is L0\\'s invariant, and row 8 does',\n 'not weaken it.',\n '',\n ];\n}\n\n// The use-case table (ROW DATA, in the doc's own numbering) and the two notes that follow it.\n// webpieces-disable no-function-outside-class -- third section of renderL1Doc's string, beside it in this module\nfunction renderUseCases(): string[] {\n return [\n '## L1 use cases',\n '',\n 'Same row shape as L0: the **Fix** is literal or it is not a fix. `<root>` is the absolute workspace',\n 'root — the messages name it explicitly rather than telling you to `cd` first, for the reason in the',\n 'section head (neither the shell\\'s cwd nor a `cd`\\'s persistence can be assumed).',\n '',\n '| # | what you SEE (exact symptom) | state | verdict | Fix |',\n '|---|---|---|---|---|',\n ...allL1UseCases().map(useCaseRow),\n '',\n 'Row 8 is the one that changed. It used to be ALLOWED, because the predicate was',\n '`shellAtRoot || cdsToRoot` — two variables OR\\'d, so the same destination got opposite verdicts',\n 'depending on where the shell happened to start. It is now one variable, `effectiveCwd === root`.',\n '',\n 'Row 12 is the incident that produced table row 8, and it is a VERSION SKEW incident — which is why',\n 'the row that replaced it measures versions rather than agent identity. The coordinator ran',\n '`git worktree add`, `cd`\\'d in,',\n 'and worked there. An L0 version-drift fault then fired against the PRIMARY (pin `0.4.545` vs',\n '`node_modules` `0.4.526`) and prescribed `pnpm install` — which ran in the WORKTREE, internally',\n 'consistent at `0.4.526`/`0.4.526`, so it succeeded, changed nothing in the measured tree, and the guard',\n 're-denied. Five identical installs later the agent had invented a theory about the harness stripping',\n 'its `cd` and handed the problem to the human. Note what row 15 says: the fix is NOT to deny that',\n 'install. It is to make the split state unreachable, so the wrong-tree install is never plausible.',\n '',\n ];\n}\n\n// The known gap and the code anchors — prose, and the one section that must never be summarised away:\n// three code comments point at it.\n// webpieces-disable no-function-outside-class -- last section of renderL1Doc's string, beside it in this module\nfunction renderTail(): string[] {\n return [\n '## Not done — `o` is not exempt yet',\n '',\n 'Row 2 hands `\\'outside\\'` down to L2 rather than exempting it. `\\'outside\\'` is produced at',\n '`effective-tree.ts` (git has no answer for the directory) carrying `governedRoot`, and **no code branches on it**, so a',\n 'command in no git repo is judged against the governed repo\\'s branch and staleness state. That is a',\n 'wrong verdict, and `exempt` is the right action.',\n '',\n '**It must not ship alone.** Jurisdiction comes from the shell cwd, not from what the command touches,',\n 'so exempting `o` opens a bypass an agent reaches by typing `cd /tmp &&`:',\n '',\n '| command | today | with `o → exempt` alone |',\n '|---|---|---|',\n '| `cd /tmp && ls` | judged against the repo | exempt — **correct** |',\n '| `cd /tmp && git -C $REPO commit` | L2 guards fire | exempt — **every L2 guard bypassed** |',\n '| `cd /tmp && rm -rf $REPO/packages/http/src` | judged | exempt — **unguarded** |',\n '',\n 'The two cases only separate once jurisdiction is judged on **what the command touches** (explicit',\n '`git -C` / `--work-tree`, then path arguments, then the `cd`, then the shell cwd), with the fail-safe',\n 'rule that **any** resolved target inside `governedRoot` means `pw`. Ship the two together, or neither.',\n '',\n 'Tracked in `backlog/bug-bash-guards-judge-the-shell-cwd-not-the-paths-the-command-touches.md` and',\n '`backlog/bug-outside-tree-kind-is-never-consumed-so-a-non-git-dir-is-judged-against-the-governed-repo.md`.',\n 'That resolver has three consumers — L1\\'s K, L2\\'s scope dimension, and `excludePaths` on the Bash path',\n '— which is why the backlog says **fix once**.',\n '',\n '---',\n '',\n '',\n '## Code anchors',\n '',\n '| section | file | symbol |',\n '|---|---|---|',\n '| resolver, K | `ai-hook-rules/src/core/effective-tree.ts` | `EffectiveTreeResolver`, `TreeKind` |',\n '| the two structural blocks, in order | `ai-hook-rules/src/core/runner.ts` | `l1LocationBlock` |',\n '| trinary-version-skew (row 8), V, R | `ai-hook-rules/src/core/version-sync.ts` | `VersionSyncGuard`, `WebpiecesVersions` |',\n '| force-to-root (row 5) | `ai-hook-rules/src/core/force-to-root.ts` | `ForceToRootGuard` |',\n '| the directory is gone (row 7) | `ai-hook-rules/src/core/missing-directory.ts` | `MissingDirectoryGuard` |',\n '| the filter | `ai-hook-rules/src/core/excluded-paths.ts` | `filterByExcludedPaths` |',\n '| which tree owns a TARGET PATH | `ai-hook-rules/src/core/target-tree.ts` | `TargetTreeResolver`, `GovernedPath` |',\n '| `excludePaths` shape | `rules-config/src/exclude-hook-paths.ts`, `validate-config.ts`, `retired-config-keys.ts` | `ExcludePaths`, `validateExcludePaths` |',\n '| the `.webpieces/` skip | `rules-config/src/exclude-hook-paths.ts` | `isWebpiecesStateDir` |',\n '',\n ];\n}\n"]}
@@ -48,7 +48,7 @@ import { FixHint } from '../fix-hint';
48
48
  * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's
49
49
  * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was
50
50
  * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the
51
- * lookup key was. Four tool calls were refused, including the `review.json` that `wp-review-upsert-pr`
51
+ * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`
52
52
  * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the
53
53
  * sanctioned flow rather than merely annoying somebody.
54
54
  *
@@ -62,7 +62,7 @@ const tree_recovery_1 = require("./tree-recovery");
62
62
  * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's
63
63
  * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was
64
64
  * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the
65
- * lookup key was. Four tool calls were refused, including the `review.json` that `wp-review-upsert-pr`
65
+ * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`
66
66
  * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the
67
67
  * sanctioned flow rather than merely annoying somebody.
68
68
  *
@@ -1 +1 @@
1
- {"version":3,"file":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA0M;AAG1M,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,0CAAsC;AACtC,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,sDAAkD;AAClD,gDAAoD;AACpD,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAa,sBAAuB,SAAQ,wBAAoC;IAC5E,wFAAwF;IACxF,mGAAmG;IACnG,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,sBAAsB,EAAE,qCAAsB,CAAC,CAAC,CAAC,CAAC;IAErG,WAAW,GAAG,kHAAkH,CAAC;IACxH,KAAK,GAAG,CAAC,MAAM,CAAC,CAAC;IACjB,cAAc,GAAG;QAC/B,sBAAsB,EAAE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E;QAC1E,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YAChB,OAAO,MAAM;iBACR,MAAM,CAAC;gBACJ,gBAAgB,MAAM,iEAAiE;gBACvF,gEAAgE;gBAChE,EAAE;aACL,CAAC;iBACD,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;iBACzB,MAAM,CAAC,CAAC,EAAE,EAAE,GAAG,QAAQ,CAAC,gBAAgB,EAAE,CAAC,CAAC;iBAC5C,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;iBAClB,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,MAAM;aACR,MAAM,CAAC;YACJ,yFAAyF;YACzF,kEAAkE;YAClE,EAAE;SACL,CAAC;aACD,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;aACxB,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;aAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IAEO,kBAAkB,CAAC,MAAkB;QACzC,OAAO;YACH,MAAM,CAAC,MAAM,EAAE;YACf,qFAAqF;YACrF,sFAAsF;YACtF,EAAE;YACF,GAAG,IAAA,kCAAmB,EAAC,MAAM,CAAC,MAAM,CAAC;YACrC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;SAC5D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACJ;AA1QD,wDA0QC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus, SyncFlowGuidance, Option } from '@webpieces/rules-config';\n\nimport type { FileContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { FileRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { TargetTreeResolver } from '../target-tree';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * States 2–4 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `review.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval, or the trail cannot tell a policy\n // that is protecting something from one that is quietly standing down.\n // Reached only when the branch is NOT merged, HAS a fork point and does NOT conflict. The\n // last two are pure git; only the first depends on the forge, which is why an unreachable\n // forge downgrades this to an abstention rather than leaving it a clean approval.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n private block(ctx: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n 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 /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
1
+ {"version":3,"file":"feature-branch-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/feature-branch-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA0M;AAG1M,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,0CAAsC;AACtC,4DAA8D;AAC9D,4DAAqD;AACrD,kDAAwF;AACxF,oDAAuF;AACvF,sDAAkD;AAClD,gDAAoD;AACpD,mEAA8D;AAC9D,+CAA2C;AAC3C,mDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAa,sBAAuB,SAAQ,wBAAoC;IAC5E,wFAAwF;IACxF,mGAAmG;IACnG,YAAY,MAA8B,IAAI,KAAK,CAAC,MAAM,EAAE,sBAAsB,EAAE,qCAAsB,CAAC,CAAC,CAAC,CAAC;IAErG,WAAW,GAAG,kHAAkH,CAAC;IACxH,KAAK,GAAG,CAAC,MAAM,CAAC,CAAC;IACjB,cAAc,GAAG;QAC/B,sBAAsB,EAAE,wBAAwB;QAChD,kBAAkB,EAAE,2CAA4B;KACnD,CAAC;IACO,OAAO,GAAG,IAAI,kBAAO,CAC1B,oDAAoD,EACpD,2EAA2E,EAC3E;QACI,IAAI,qBAAM,CAAC,4EAA4E,EAAE,IAAI,CAAC;QAC9F,IAAI,qBAAM,CAAC,mWAAmW,CAAC;QAC/W,IAAI,qBAAM,CAAC,kLAAkL,CAAC;KACjM,CACJ,CAAC;IAEF,KAAK,CAAC,GAAgB;QAClB,2FAA2F;QAC3F,IAAI,GAAG,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC;YAAE,OAAO,EAAE,CAAC;QAEjD,6FAA6F;QAC7F,yFAAyF;QACzF,qEAAqE;QACrE,MAAM,M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;SACL,CAAC;aACD,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;aACxB,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;aAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IAEO,kBAAkB,CAAC,MAAkB;QACzC,OAAO;YACH,MAAM,CAAC,MAAM,EAAE;YACf,qFAAqF;YACrF,sFAAsF;YACtF,EAAE;YACF,GAAG,IAAA,kCAAmB,EAAC,MAAM,CAAC,MAAM,CAAC;YACrC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;SAC5D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACJ;AA1QD,wDA0QC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchStateGuardConfig, BRANCH_STATE_GUARD_KEY, DEFAULT_HANG_TIMEOUT_MINUTES, readMainSyncStatus, squashRecoverySteps, MainSyncStatus, SyncFlowGuidance, Option } from '@webpieces/rules-config';\n\nimport type { FileContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { FileRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { toError } from '../to-error';\nimport { triggerMainSyncRefresh } from '../main-sync-refresh';\nimport { hangTimeoutOf } from '../main-sync-timeout';\nimport { logGuardDecision, GuardDecision, Verdict, matrixL2Row } from '../decision-log';\nimport { writeBranchStateMatrixDoc, branchStateMatrixPointer } from '../l2-matrix-doc';\nimport { L0_FAULT_NONE } from '../l0-fault-codes';\nimport { TargetTreeResolver } from '../target-tree';\nimport { MergedBranchMessage } from './merged-branch-message';\nimport { JudgedTree } from './judged-tree';\nimport { TreeRecovery } from './tree-recovery';\n\n/**\n * Comprehensive \"are you on a proper feature branch?\" guard — the single rule that blocks edits when\n * the branch isn't a healthy place to work. Four states, in priority order:\n * 1. On main (checked SYNCHRONOUSLY here) → block: create a feature branch.\n * 2. Branch already merged into main (merged PR) → block: your work is in main, branch off fresh.\n * 3. No fork point with origin/main → block: squash onto a new branch.\n * 4. origin/main moved & touches your files → block: merge main first.\n * States 2–4 are PRECOMPUTED into `.webpieces/main-sync-status.json` by the detached refresher, so\n * this check does NO network git (only a fast local `git rev-parse` for state 1). On every call it\n * fire-and-forget spawns the refresher so the NEXT call is fresh. Runs in the GUARDS hook (it's a\n * hookGuard); file-scoped, so only Write/Edit/MultiEdit are guarded — Bash passes through so the AI\n * can still run `pnpm wp-start-upsert-pr` and the rest of the recovery flow.\n *\n * ── STATE 1 IS UNCONDITIONAL, AND `B` NO LONGER TRACKS `E` HERE ──────────────────────────────────\n *\n * Earlier docblocks in this family argued that the Bash half of \"on `main`\" should match this one\n * exactly — one `git rev-parse`, no cache, so it fires on the first call of a session. That argument\n * has been split, deliberately, and the two halves now differ:\n *\n * `E` (here) blocks on ANY `main`, current or stale.\n * `B` (stale-main-bash-guard) blocks only once local `main` is KNOWN BEHIND `origin/main`.\n *\n * The hazards are not the same hazard. A WRITE on `main` puts work where it cannot be reviewed, cannot\n * be reverted as a unit, and is one `git checkout` from being lost — none of which depends on how\n * current `main` is, so nothing about freshness could make this block right or wrong. A READ or a\n * BUILD on a CURRENT `main` harms nothing at all, and denying it strands the agent immediately after\n * `pnpm wp-sync-main` — the very command this repo prescribes — put it there.\n *\n * So do NOT \"restore the symmetry\" by gating this on the cache. That would make writes on `main`\n * permitted for the whole first call of every session (the cache is populated for the NEXT call), and\n * permanently in a multi-worktree repo where another tree can hold the refresh lock. That ordering is\n * the most load-bearing thing in the L2 table, which is why row 5 sits ABOVE the cache divider.\n *\n * ── WHICH TREE IS JUDGED: THE ONE THAT OWNS THE FILE, NEVER THE ONE THE SESSION SITS IN ─────────────\n *\n * Every state above is a property of A BRANCH IN A CHECKOUT, so the first question this guard answers is\n * WHICH checkout — and the answer comes from the TARGET PATH, through TargetTreeResolver, which is\n * EffectiveTreeResolver asked about a file instead of a cwd. It is emphatically NOT `ctx.workspaceRoot`:\n * that is the walk-up from the session's cwd to the governing `webpieces.config.json`, and for a\n * main-session edit into an agent worktree it names the PRIMARY clone.\n *\n * Issue #851 is the incident. Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, so a containment test answers \"primary\" for a path that is\n * plainly the worktree's. This guard then read the branch-keyed main-sync cache under the PRIMARY's\n * branch and enforced that verdict on a file belonging to a clean branch in another tree. The cache was\n * not stale and was not wrong — the correct entry sat in the same JSON file, one key over. Only the\n * lookup key was. Four tool calls were refused, including the `summary.json` that `wp-review-upsert-pr`\n * requires before `wp-finish-upsert-pr` will open a PR, which is the shape where this wedges the\n * sanctioned flow rather than merely annoying somebody.\n *\n * Two consequences worth stating out loud, because both were argued the other way at some point:\n *\n * - The DENY NAMES THE TREE (JudgedTree.header) and, when the judged tree is not the session's, the\n * `pnpm --dir=<tree>` form of the cure. A resolution nobody can see is a resolution nobody can\n * contradict, and the printed cure was measurably a no-op for the tree it was aimed at.\n * - DETACHED HEAD in the target tree fails OPEN, logged. There is no branch name, so there is no map\n * key and nothing to judge — matrix row 14. It used to reach here as the literal branch `HEAD`, miss\n * in the cache and fail open as `no-sync-cache`, which is the right verdict recorded under a reason\n * that says something else happened.\n */\nexport class FeatureBranchGuardRule extends FileRuleBase<BranchStateGuardConfig> {\n // NAME is this class's operator identity (every `rule=` in the log, every deny header);\n // CONFIG KEY is the one branch-state policy entry all four of these guards read. See AbstractRule.\n constructor(config: BranchStateGuardConfig) { super(config, 'feature-branch-guard', BRANCH_STATE_GUARD_KEY); }\n\n readonly description = 'Block edits unless you are on a proper feature branch (not main, not already-merged, forked, in sync with main).';\n override readonly files = ['**/*'];\n override readonly defaultOptions = {\n branchNamingConvention: '{whoami}/{featurename}',\n hangTimeoutMinutes: DEFAULT_HANG_TIMEOUT_MINUTES,\n };\n readonly fixHint = new FixHint(\n 'You are not on a clean, up-to-date feature branch.',\n 'You must be on a clean, up-to-date feature branch to edit code. Pick one:',\n [\n new Option('On main → create a feature branch. Already merged → branch off fresh main.', true),\n new Option('main moved/conflicts, NO PR yet → `pnpm wp-start-update` (merge), `/wp-merge` (resolve), `pnpm wp-finish-update`. An OPEN PR? then you MUST use `pnpm wp-start-upsert-pr` → `/wp-merge` → `pnpm wp-finish-upsert-pr` (the merge rewrites the branch, so the PR must be re-pointed in the same run). Never mix a start from one pair with a finish from the other.'),\n new Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),\n ],\n );\n\n check(ctx: FileContext): readonly Violation[] {\n // Only files inside the workspace root — guard has no jurisdiction, nothing worth logging.\n if (ctx.relativePath.startsWith('..')) return [];\n\n // WHICH CHECKOUT owns this file? Git's answer, via the resolver the bash half already uses —\n // never a path-containment test, which is exactly what answered \"primary\" for a worktree\n // checked out INSIDE the repo (issue #851, and this class's header).\n const target = new TargetTreeResolver().resolve(ctx.filePath, ctx.workspaceRoot);\n // A NESTED CLONE under `repositories/**` is somebody else's repo. The bash path calls this\n // ALLOW_EXEMPT; here it is an abstention, because the state was not established, not waived.\n if (target.kind === 'foreign') return this.failOpen(ctx, null, 'target-tree-foreign');\n\n const judgedRoot = target.root;\n const branch = this.currentBranch(judgedRoot);\n // Can't determine branch (e.g. not a git repo) → don't block. Fail-open.\n if (branch === null) return this.failOpen(ctx, branch, 'branch-undeterminable', this.treeSummary(judgedRoot));\n // Mid-rebase / mid-bisect: `--abbrev-ref HEAD` prints the literal `HEAD`, there is no branch\n // name, and therefore no key into the branch-keyed cache. Matrix row 14 — abstain, out loud.\n if (branch === 'HEAD') return this.failOpen(ctx, branch, 'detached-head', this.treeSummary(judgedRoot));\n\n const judged = new JudgedTree(target, branch, target.governedRoot);\n\n // State 1: on main — synchronous, no cache needed.\n if (branch === 'main') {\n return this.block(ctx, branch, 'on-main', this.onMainMessage(judged), this.treeSummary(judgedRoot));\n }\n\n // Keep the cache warm for the next call. Detached; never blocks this edit. Rooted at the JUDGED\n // tree, so the refresher recomputes the entry this guard is about to read rather than a sibling's.\n triggerMainSyncRefresh(judgedRoot, hangTimeoutOf(this.config));\n\n const status = readMainSyncStatus(judgedRoot, branch);\n // No cache yet (first edit of the session) → allow; the refresh we just spawned populates it\n // for the next call. Fail-open: never block on missing data.\n if (status === null) return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');\n\n const cache = `${this.treeSummary(judgedRoot)} ${this.cacheSummary(status)}`;\n // BELT-AND-BRACES since the cache became branch-keyed: we looked this entry up BY `branch`, so\n // a mismatch now means the map's key and the entry's own `branch` field disagree — a shape bug,\n // not a normal state. Kept (rather than deleted) so such a bug degrades to an allow instead of\n // blocking on another branch's signals. Unreachable in normal operation.\n if (status.branch !== branch) return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);\n\n // State 2: this feature branch was already merged into main.\n if (status.branchAlreadyMerged) {\n const pr = status.mergedPr !== '' ? status.mergedPr : '?';\n const merged = this.alreadyMergedMessage(judged, status.mergedPr);\n return this.block(ctx, branch, `already-merged PR#${pr}`, merged, cache);\n }\n // State 3: no fork point — main was merged into the branch.\n if (!status.hasForkPoint) {\n return this.block(ctx, branch, 'no-fork-point', this.noForkPointMessage(judged), cache);\n }\n // State 4: origin/main moved and touches files you changed.\n if (status.conflict) {\n return this.block(ctx, branch, 'main-moved-conflict', this.conflictMessage(judged, status.conflictFiles, status.openPr), cache);\n }\n // NOT-MERGED, or NOT-ASKED? `branchAlreadyMerged: false` is produced both by \"this branch has\n // no merged PR\" and by \"the forge could not be reached\" (`gh` missing, unauthenticated,\n // rate-limited, offline). Same allow either way — never block on data you could not establish\n // — but the LOG must not call the second one an approval, or the trail cannot tell a policy\n // that is protecting something from one that is quietly standing down.\n // Reached only when the branch is NOT merged, HAS a fork point and does NOT conflict. The\n // last two are pure git; only the first depends on the forge, which is why an unreachable\n // forge downgrades this to an abstention rather than leaving it a clean approval.\n if (!status.forgeReachable) return this.failOpen(ctx, branch, 'no-forge', cache);\n return this.allow(ctx, branch, 'clean-feature-branch', cache);\n }\n\n /**\n * WHICH TREE this decision was judged against, for the log.\n *\n * The trail already carried a `tree=` field, but it is stamped from the root the decision is LOGGED\n * to (the session's), so during issue #851 every misfired block recorded `tree=primary` for a path\n * under `.claude/worktrees/` and read as perfectly ordinary. This one is the root the verdict was\n * actually computed from, so the two disagreeing is the defect, visible in one grep.\n */\n private treeSummary(judgedRoot: string): string {\n return `judged=${judgedRoot}`;\n }\n\n // One-line summary of the async-written cache that drove this decision, for the SYNC log — so a\n // wrong allow/block is traceable to the exact (possibly stale) main-sync-status.json read.\n private cacheSummary(status: MainSyncStatus): string {\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `cache=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n }\n\n // Log + return for the allow path. Centralizes the decision-log call so every exit of check()\n // is recorded with its reason + the async cache it read (this is the audit trail for \"why didn't\n // the guard fire?\"). `cache` is the summary of the main-sync-status.json that drove the decision.\n /**\n * The guard could not ESTABLISH the state it judges on, so it judged nothing.\n *\n * A sibling of allow() rather than a reason string passed to it, because the difference has to\n * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`\n * suffix on the free-text reason, which meant an abstention and a real approval were the same\n * verdict and the abstentions could not be counted — so nobody could tell whether these guards\n * were protecting anything or quietly standing down. Never block on data you could not\n * establish; but say out loud, in a field, that you did not establish it.\n */\n private failOpen(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);\n return [];\n }\n\n private allow(ctx: FileContext, branch: string | null, reason: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'ALLOW', reason, cache);\n return [];\n }\n\n private block(ctx: FileContext, branch: string, reason: string, message: string, cache: string = '-'): readonly Violation[] {\n this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);\n // Deliver the matrix and name the row — see stale-main-bash-guard.block for why it is lazy.\n const pointer = branchStateMatrixPointer(writeBranchStateMatrixDoc(ctx.workspaceRoot), matrixL2Row(reason).row);\n return [new V(1, ctx.relativePath, message + pointer)];\n }\n\n private logDecision(ctx: FileContext, branch: string | null, verdict: Verdict, reason: string, cache: string): void {\n logGuardDecision(\n ctx.workspaceRoot,\n new GuardDecision('feature-branch-guard', ctx.tool, ctx.relativePath, branch ?? 'unknown', verdict, reason, cache, L0_FAULT_NONE, matrixL2Row(reason)),\n );\n }\n\n private currentBranch(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n 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 /**\n * The Write/Edit half of row 5. Same three points as stale-main-bash-guard's deny, told for THIS\n * surface: reading main while you plan is legitimate and is not what got blocked; the feature\n * branch is the unit of work; and a `main` that is behind makes the reads wrong too, so getting\n * current is not an extra step, it is what makes the plan you are about to write against correct.\n *\n * Per-surface, deliberately: this guard sees only Write/Edit, so it says the WRITE was blocked.\n * (read-stale-guard is the one that can close Read, and only once `main` falls behind.)\n *\n * ONE CURE, and it is the dirty-safe one. This half used to print `git pull origin main` and then\n * \"create a feature branch\" — but this guard fires on a WRITE, so uncommitted work is the LIKELY\n * state, and a pull is exactly the form that is not a clean fast-forward there. Its two siblings\n * (stale-main-bash-guard's rows-6/7 deny, StaleMainMessage.forReads) both prescribe\n * `git fetch origin main && git checkout -b <new> origin/main`, which fetches AND carries the\n * uncommitted work onto the new branch. Three halves of one row printing one cure is the point:\n * a fragile cure is a defect here even when it often happens to work.\n */\n private onMainMessage(judged: JudgedTree): string {\n const convention = this.config.branchNamingConvention ?? '{whoami}/{featurename}';\n return [\n judged.header(),\n 'Blocked: this is a WRITE on main. Reading main to PLAN is fine — writing here is not, because the feature branch is the unit of work: reviewable, revertable, and not one `git checkout` from being lost.',\n 'And if local main is BEHIND origin/main, what you read here was out of date too — so the fetch below is not an extra step, it is what makes your reads true.',\n 'Branch off origin/main (it fetches first, and uncommitted work comes with you):',\n ' git fetch origin main && git checkout -b <new-branch> origin/main',\n `Name <new-branch> by the convention (from webpieces.config.json): ${convention}`,\n 'Example: git fetch origin main && git checkout -b ' + convention.replace(/<[^>]+>/g, 'value') + ' origin/main',\n judged.redirectNote([judged.cdCure('git fetch origin main && git checkout -b <new-branch> origin/main')]),\n ].join('\\n');\n }\n\n // Shared with read-stale-guard, which blocks READS in this same state — see MergedBranchMessage.\n // The tree kind picks the flavour of the cure: a dead LINKED WORKTREE is told to open a new\n // worktree off origin/main and reap this one; the primary clone is told to branch off origin/main.\n // Every one of those questions is asked of the JUDGED tree, not the session's: the branch that is\n // merged, the checkout to recover, and the directory the cure has to run in are all properties of\n // the tree that owns the file (issue #851).\n private alreadyMergedMessage(judged: JudgedTree, mergedPr: string): string {\n const body = new MergedBranchMessage(judged.root).forEdits(\n judged.branch, mergedPr, new TreeRecovery().kindOf(judged.root), judged.root,\n );\n // NO redirect note here, deliberately. MergedBranchMessage was built with the JUDGED root and\n // already aims every command it prints through `atRoot` — and it picks the WORKTREE flavour of\n // the cure (open a NEW worktree off origin/main and reap this dead one) when that is what the\n // tree is. Appending a generic `checkout -b` would contradict the paragraph directly above it,\n // in exactly the redirected-and-a-worktree case where the worktree flavour is the right advice.\n return [judged.header(), body].join('\\n');\n }\n\n private conflictMessage(judged: JudgedTree, conflictFiles: readonly string[], openPr: string): string {\n const files = conflictFiles.length > 0\n ? conflictFiles.map((f: string): string => ` - ${f}`).join('\\n')\n : ' (see git diff)';\n // NAME THE BRANCH AND THE TREE. Without them this read \"files you also changed\", listing files\n // the edit had never touched on a branch it was not on, and there was nothing in the text to\n // contradict — see JudgedTree.\n const header = [\n judged.header(),\n `origin/main moved and touched files that \\`${judged.branch}\\` also changed since its fork point:`,\n files,\n '',\n ];\n const redirect = judged.redirectNote([\n judged.pnpmCure('wp-start-update'),\n `${judged.pnpmCure('wp-start-upsert-pr')} (instead, when a PR is open)`,\n ]);\n // Steer EARLY: if a PR already tracks this branch, the update-only flow would just fail-fast\n // (a 3-point update strands the PR on the old branch generation), so recommend ONLY the PR\n // flow and don't waste the AI's tokens on wp-start-update.\n const guidance = new SyncFlowGuidance();\n // An OPEN PR removes the choice, so print ONLY the PR flow here — showing the update-only flow\n // as if it were an option just burns tokens on a command that fail-fasts.\n if (openPr !== '') {\n return header\n .concat([\n `An OPEN PR (#${openPr}) already tracks this branch, so the PR flow is the ONLY option`,\n 'here — it re-merges main AND re-points the PR in the same run:',\n '',\n ])\n .concat(guidance.prFlow())\n .concat(['', ...guidance.whyPrForcesFlowB()])\n .concat([redirect])\n .join('\\n');\n }\n return header\n .concat([\n 'You must merge main in before editing further. No PR is open for this branch, so flow A',\n 'below is the one to use — but use flow B the moment a PR exists:',\n '',\n ])\n .concat(guidance.flows())\n .concat([redirect])\n .join('\\n');\n }\n\n private noForkPointMessage(judged: JudgedTree): string {\n return [\n judged.header(),\n 'No fork point with origin/main — main appears to have been merged into this branch,',\n 'so a clean squash-merge is impossible. A human must redo the work on a fresh branch:',\n '',\n ...squashRecoverySteps(judged.branch),\n judged.redirectNote([judged.pnpmCure('wp-start-update')]),\n ].join('\\n');\n }\n}\n"]}
@@ -22,7 +22,7 @@ function fixHintFor(upsertPrCommand) {
22
22
  + 'LANDING ON MAIN (a PR, prod-quality, reviewed):\n'
23
23
  + ` ${upsertPrCommand}\n`
24
24
  + ' It updates the branch from main (3-point merge) and runs the real build (nx affected), then\n'
25
- + ' instructs you to write review.json and run `pnpm wp-finish-upsert-pr`, which assembles the\n'
25
+ + ' instructs you to write summary.json and run `pnpm wp-finish-upsert-pr`, which assembles the\n'
26
26
  + ' dashboard and creates/updates the PR — and pushes for you. A failing build = no push, no PR.\n\n'
27
27
  + 'JUST WANT IT ON THE SHARED DEV SERVER (no PR, not landing on main):\n'
28
28
  + ` ${rules_config_1.WP_PUSH_DEV}\n`
@@ -32,7 +32,7 @@ function fixHintFor(upsertPrCommand) {
32
32
  + 'Both push internally as child processes this hook never sees, so the gated commands are\n'
33
33
  + 'unaffected by this guard. There is nothing to paste or attest to; the commands do the work.\n'
34
34
  + 'If a HUMAN genuinely needs an out-of-band push (neither destination above), do NOT do it\n'
35
- + 'yourself — ask them to run the push, since a manual push bypasses the build gate, review.json,\n'
35
+ + 'yourself — ask them to run the push, since a manual push bypasses the build gate, summary.json,\n'
36
36
  + 'and dashboard.\n'
37
37
  + 'Full branch → update → PR flow: READ the instruct-ai git-workflow doc at the absolute path on the violation line above.\n'
38
38
  + 'Add this to your memory so you don\'t forget next time and waste tokens.');
@@ -1 +1 @@
1
- {"version":3,"file":"pr-creation-or-push-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/pr-creation-or-push-guard.ts"],"names":[],"mappings":";;;AAAA,0DASiC;AAGjC,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AAEtC,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAElD;;;;;;;;;GASG;AACH,SAAS,UAAU,CAAC,eAAuB;IACvC,OAAO,IAAI,kBAAO,CACd,8DAA8D,EAC9D,oGAAoG;UAClG,4BAA4B;UAC5B,mDAAmD;UACnD,KAAK,eAAe,IAAI;UACxB,iGAAiG;UACjG,gGAAgG;UAChG,oGAAoG;UACpG,uEAAuE;UACvE,KAAK,0BAAW,IAAI;UACpB,mGAAmG;UACnG,kGAAkG;UAClG,iGAAiG;UACjG,2FAA2F;UAC3F,+FAA+F;UAC/F,4FAA4F;UAC5F,kGAAkG;UAClG,kBAAkB;UAClB,2HAA2H;UAC3H,0EAA0E,CAC/E,CAAC;AACN,CAAC;AAED,kGAAkG;AAClG,mGAAmG;AACnG,mGAAmG;AACnG,yBAAyB;AACzB,SAAS,iBAAiB,CAAC,GAAW;IAClC,yFAAyF;IACzF,I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,CAAC,eAAe,mDAAmD,OAAO,GAAG,CAAC,CAAC,CAAC;QACzH,CAAC;QACD,OAAO,CAAC,IAAI,iBAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAClC,4DAA4D,IAAI,CAAC,eAAe,sBAAsB,OAAO,GAAG,CAAC,CAAC,CAAC;IAC3H,CAAC;IAED;;;;;;OAMG;IACK,qBAAqB,CAAC,GAAgB;QAC1C,MAAM,SAAS,GAAG,IAAA,8BAAe,EAAC,GAAG,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC;QACrE,OAAO,qBAAqB,CACxB,GAAG,CAAC,WAAW,EACf,SAAS,CAAC,eAAe,KAAK,EAAE,CAAC,CAAC,CAAC,2CAA4B,CAAC,CAAC,CAAC,SAAS,CAAC,eAAe,EAC3F,SAAS,CAAC,SAAS,KAAK,EAAE,CAAC,CAAC,CAAC,iCAAkB,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC/E,CAAC;CACJ;AAjDD,8DAiDC","sourcesContent":["import {\n DEFAULT_DEV_BRANCH,\n DEFAULT_DEV_BRANCH_NAMESPACE,\n PrLifecycleGuardConfig,\n PR_LIFECYCLE_GUARD_KEY,\n RepoRootFinder,\n WP_PUSH_DEV,\n loadAndValidate,\n writeTemplate,\n} from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\n\n/**\n * The hint BRANCHES ON INTENT, and that is not polish.\n *\n * There are now two legitimate destinations for a blocked push — land it on `main`, or get it onto the\n * shared dev server — and the block alone cannot tell them apart. The old flat hint said \"everything goes\n * through `wp-start-upsert-pr`\", so an AI told \"put my branch on dev\" would try `git push`, get blocked,\n * read this, and open a PR to main: the exact opposite of what it was asked to do, and the destructive\n * direction of the two. Naming both destinations is what makes the dev flow discoverable at all — nothing\n * else the AI can see mentions it.\n */\nfunction fixHintFor(upsertPrCommand: string): FixHint {\n return new FixHint(\n 'Direct PR creation/update AND manual `git push` are blocked.',\n 'Never push or open/update a PR by hand. There are TWO gated destinations — pick by what you were\\n'\n + 'actually trying to do:\\n\\n'\n + 'LANDING ON MAIN (a PR, prod-quality, reviewed):\\n'\n + ` ${upsertPrCommand}\\n`\n + ' It updates the branch from main (3-point merge) and runs the real build (nx affected), then\\n'\n + ' instructs you to write review.json and run `pnpm wp-finish-upsert-pr`, which assembles the\\n'\n + ' dashboard and creates/updates the PR — and pushes for you. A failing build = no push, no PR.\\n\\n'\n + 'JUST WANT IT ON THE SHARED DEV SERVER (no PR, not landing on main):\\n'\n + ` ${WP_PUSH_DEV}\\n`\n + ' It publishes a DISPOSABLE copy of your branch that the dev environment composes and rebuilds.\\n'\n + ' Your feature branch is never moved and never acquires another developer\\'s commits, which is\\n'\n + ' the whole reason the copy exists. Do NOT open a PR to main just to test something in dev.\\n\\n'\n + 'Both push internally as child processes this hook never sees, so the gated commands are\\n'\n + 'unaffected by this guard. There is nothing to paste or attest to; the commands do the work.\\n'\n + 'If a HUMAN genuinely needs an out-of-band push (neither destination above), do NOT do it\\n'\n + 'yourself — ask them to run the push, since a manual push bypasses the build gate, review.json,\\n'\n + 'and dashboard.\\n'\n + 'Full branch → update → PR flow: READ the instruct-ai git-workflow doc at the absolute path on the violation line above.\\n'\n + 'Add this to your memory so you don\\'t forget next time and waste tokens.',\n );\n}\n\n// Detect every way an agent could push or open/update a PR directly, so the ONLY path left is the\n// gated flow (wp-start-upsert-pr → wp-finish-upsert-pr, whose internal `git push` / `gh pr create`\n// run as child processes the hook never sees). Read-only `gh pr list` / `gh api .../pulls` GET are\n// intentionally allowed.\nfunction isBlockedPrOrPush(cmd: string): boolean {\n // A manual push is always blocked — the gated flow pushes for you behind the build gate.\n if (/\\bgit\\s+push\\b/.test(cmd)) return true;\n\n if (/\\bgh\\s+pr\\s+(create|edit)\\b/.test(cmd)) return true;\n\n const ghApiPulls = /\\bgh\\s+api\\b[^\\n]*\\/pulls\\b/.test(cmd);\n if (ghApiPulls && (/--method\\s+POST/i.test(cmd) || /-X\\s+POST/i.test(cmd) || /\\s-f\\b/.test(cmd) || /\\s-F\\b/.test(cmd) || /--field\\b/.test(cmd))) {\n return true;\n }\n\n const curlPulls = /\\bcurl\\b[^\\n]*api\\.github\\.com[^\\n]*\\/pulls\\b/.test(cmd);\n if (curlPulls && (/-X\\s*POST/i.test(cmd) || /--request\\s+POST/i.test(cmd) || /(\\s-d\\b|--data\\b)/.test(cmd))) {\n return true;\n }\n return false;\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\n/**\n * Does this blocked push AIM at the shared dev environment?\n *\n * The refspec is the one place the AI already stated its intent unambiguously, so reading it is strictly\n * better than making the AI choose between two hints it has no way to disambiguate. A push whose\n * destination is the dev namespace or the dev branch itself gets the `wp-push-dev` remedy on the `→`\n * line; everything else keeps the PR-flow remedy it has always had.\n */\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction targetsDevEnvironment(cmd: string, namespace: string, devBranch: string): boolean {\n if (cmd.includes(`${namespace}/`)) return true;\n const push = /\\bgit\\s+push\\b([^\\n;&|]*)/.exec(cmd);\n if (push === null) return false;\n // Split on whitespace AND `:` so both halves of a `HEAD:<dest>` refspec are examined. Matching whole\n // tokens (never a substring) keeps a branch merely NAMED `develop` from reading as the dev branch.\n return push[1].split(/[\\s:]+/).some(\n (token: string): boolean => token === devBranch || token === `refs/heads/${devBranch}`);\n}\n\nexport class PrCreationOrPushGuardRule extends BashRuleBase<PrLifecycleGuardConfig> {\n /**\n * The gated command this guard names, handed in by the LOADER from `commands.guardHints\n * .prCreationOrPush` (already defaulted there). It is a constructor parameter, not a config field:\n * the field `pr-creation-or-push-guard.upsertPrCommand` was a SECOND SPELLING that beat the\n * commands section at the point of use, and the loader's name-keyed injection that fed it could\n * miss a rename without failing the build. One spelling, wired at compile time.\n */\n private readonly upsertPrCommand: string;\n\n constructor(config: PrLifecycleGuardConfig, upsertPrCommand: string) {\n super(config, 'pr-creation-or-push-guard', PR_LIFECYCLE_GUARD_KEY);\n this.upsertPrCommand = upsertPrCommand;\n }\n\n readonly description = 'Block manual `git push` and direct PR creation/edit (gh pr / gh api / curl) so pushes and PRs go only through the gated upsert-pr command.';\n get fixHint(): FixHint { return fixHintFor(this.upsertPrCommand); }\n\n check(ctx: BashContext): readonly Violation[] {\n if (!isBlockedPrOrPush(ctx.commandCode)) return [];\n // Materialize the doc we are about to send the AI to. Pointing at a path that does not exist\n // (nothing has run a `wp-*` command in this tree yet) costs the AI a turn to discover; a STALE\n // copy from an older @webpieces is just as bad, so overwrite rather than write-if-missing.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n if (this.aimedAtDevEnvironment(ctx)) {\n return [new V(1, truncate(ctx.command),\n 'Manual push is blocked — but this one is aimed at the shared DEV environment, which has its own\\n'\n + `gated command. Use \\`${WP_PUSH_DEV}\\` (publishes a disposable copy; never moves your branch, never\\n`\n + `opens a PR). Do NOT use ${this.upsertPrCommand} for this — that lands on main. Full flow: READ ${docPath}.`)];\n }\n return [new V(1, truncate(ctx.command),\n `Manual push / direct PR is blocked — use the gated flow (${this.upsertPrCommand}). Full flow: READ ${docPath}.`)];\n }\n\n /**\n * Read the configured dev refs, falling back to the defaults when this repo has no `pr-gate` section\n * at all (a consumer that has not adopted the gate still gets a correct hint for the default names).\n *\n * Calling the loader here is safe by construction: an INVALID config blocks every Bash call long\n * before a rule runs, so reaching this line already means the config loaded.\n */\n private aimedAtDevEnvironment(ctx: BashContext): boolean {\n const devDeploy = loadAndValidate(ctx.governedRoot).prGate.devDeploy;\n return targetsDevEnvironment(\n ctx.commandCode,\n devDeploy.branchNamespace === '' ? DEFAULT_DEV_BRANCH_NAMESPACE : devDeploy.branchNamespace,\n devDeploy.devBranch === '' ? DEFAULT_DEV_BRANCH : devDeploy.devBranch);\n }\n}\n"]}
1
+ {"version":3,"file":"pr-creation-or-push-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/pr-creation-or-push-guard.ts"],"names":[],"mappings":";;;AAAA,0DASiC;AAGjC,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AAEtC,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAElD;;;;;;;;;GASG;AACH,SAAS,UAAU,CAAC,eAAuB;IACvC,OAAO,IAAI,kBAAO,CACd,8DAA8D,EAC9D,oGAAoG;UAClG,4BAA4B;UAC5B,mDAAmD;UACnD,KAAK,eAAe,IAAI;UACxB,iGAAiG;UACjG,iGAAiG;UACjG,oGAAoG;UACpG,uEAAuE;UACvE,KAAK,0BAAW,IAAI;UACpB,mGAAmG;UACnG,kGAAkG;UAClG,iGAAiG;UACjG,2FAA2F;UAC3F,+FAA+F;UAC/F,4FAA4F;UAC5F,mGAAmG;UACnG,kBAAkB;UAClB,2HAA2H;UAC3H,0EAA0E,CAC/E,CAAC;AACN,CAAC;AAED,kGAAkG;AAClG,mGAAmG;AACnG,mGAAmG;AACnG,yBAAyB;AACzB,SAAS,iBAAiB,CAAC,GAAW;IAClC,yFAAyF;IACzF,IAAI,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IAE5C,IAAI,6BAA6B,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IAEzD,MAAM,UAAU,GAAG,6BAA6B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3D,IAAI,UAAU,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,QAAQ,CA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AO,qBAAqB,CACxB,GAAG,CAAC,WAAW,EACf,SAAS,CAAC,eAAe,KAAK,EAAE,CAAC,CAAC,CAAC,2CAA4B,CAAC,CAAC,CAAC,SAAS,CAAC,eAAe,EAC3F,SAAS,CAAC,SAAS,KAAK,EAAE,CAAC,CAAC,CAAC,iCAAkB,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC/E,CAAC;CACJ;AAjDD,8DAiDC","sourcesContent":["import {\n DEFAULT_DEV_BRANCH,\n DEFAULT_DEV_BRANCH_NAMESPACE,\n PrLifecycleGuardConfig,\n PR_LIFECYCLE_GUARD_KEY,\n RepoRootFinder,\n WP_PUSH_DEV,\n loadAndValidate,\n writeTemplate,\n} from '@webpieces/rules-config';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\n\n/**\n * The hint BRANCHES ON INTENT, and that is not polish.\n *\n * There are now two legitimate destinations for a blocked push — land it on `main`, or get it onto the\n * shared dev server — and the block alone cannot tell them apart. The old flat hint said \"everything goes\n * through `wp-start-upsert-pr`\", so an AI told \"put my branch on dev\" would try `git push`, get blocked,\n * read this, and open a PR to main: the exact opposite of what it was asked to do, and the destructive\n * direction of the two. Naming both destinations is what makes the dev flow discoverable at all — nothing\n * else the AI can see mentions it.\n */\nfunction fixHintFor(upsertPrCommand: string): FixHint {\n return new FixHint(\n 'Direct PR creation/update AND manual `git push` are blocked.',\n 'Never push or open/update a PR by hand. There are TWO gated destinations — pick by what you were\\n'\n + 'actually trying to do:\\n\\n'\n + 'LANDING ON MAIN (a PR, prod-quality, reviewed):\\n'\n + ` ${upsertPrCommand}\\n`\n + ' It updates the branch from main (3-point merge) and runs the real build (nx affected), then\\n'\n + ' instructs you to write summary.json and run `pnpm wp-finish-upsert-pr`, which assembles the\\n'\n + ' dashboard and creates/updates the PR — and pushes for you. A failing build = no push, no PR.\\n\\n'\n + 'JUST WANT IT ON THE SHARED DEV SERVER (no PR, not landing on main):\\n'\n + ` ${WP_PUSH_DEV}\\n`\n + ' It publishes a DISPOSABLE copy of your branch that the dev environment composes and rebuilds.\\n'\n + ' Your feature branch is never moved and never acquires another developer\\'s commits, which is\\n'\n + ' the whole reason the copy exists. Do NOT open a PR to main just to test something in dev.\\n\\n'\n + 'Both push internally as child processes this hook never sees, so the gated commands are\\n'\n + 'unaffected by this guard. There is nothing to paste or attest to; the commands do the work.\\n'\n + 'If a HUMAN genuinely needs an out-of-band push (neither destination above), do NOT do it\\n'\n + 'yourself — ask them to run the push, since a manual push bypasses the build gate, summary.json,\\n'\n + 'and dashboard.\\n'\n + 'Full branch → update → PR flow: READ the instruct-ai git-workflow doc at the absolute path on the violation line above.\\n'\n + 'Add this to your memory so you don\\'t forget next time and waste tokens.',\n );\n}\n\n// Detect every way an agent could push or open/update a PR directly, so the ONLY path left is the\n// gated flow (wp-start-upsert-pr → wp-finish-upsert-pr, whose internal `git push` / `gh pr create`\n// run as child processes the hook never sees). Read-only `gh pr list` / `gh api .../pulls` GET are\n// intentionally allowed.\nfunction isBlockedPrOrPush(cmd: string): boolean {\n // A manual push is always blocked — the gated flow pushes for you behind the build gate.\n if (/\\bgit\\s+push\\b/.test(cmd)) return true;\n\n if (/\\bgh\\s+pr\\s+(create|edit)\\b/.test(cmd)) return true;\n\n const ghApiPulls = /\\bgh\\s+api\\b[^\\n]*\\/pulls\\b/.test(cmd);\n if (ghApiPulls && (/--method\\s+POST/i.test(cmd) || /-X\\s+POST/i.test(cmd) || /\\s-f\\b/.test(cmd) || /\\s-F\\b/.test(cmd) || /--field\\b/.test(cmd))) {\n return true;\n }\n\n const curlPulls = /\\bcurl\\b[^\\n]*api\\.github\\.com[^\\n]*\\/pulls\\b/.test(cmd);\n if (curlPulls && (/-X\\s*POST/i.test(cmd) || /--request\\s+POST/i.test(cmd) || /(\\s-d\\b|--data\\b)/.test(cmd))) {\n return true;\n }\n return false;\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\n/**\n * Does this blocked push AIM at the shared dev environment?\n *\n * The refspec is the one place the AI already stated its intent unambiguously, so reading it is strictly\n * better than making the AI choose between two hints it has no way to disambiguate. A push whose\n * destination is the dev namespace or the dev branch itself gets the `wp-push-dev` remedy on the `→`\n * line; everything else keeps the PR-flow remedy it has always had.\n */\n// webpieces-disable no-function-outside-class -- module-level guard helper, matches the rest of this file\nfunction targetsDevEnvironment(cmd: string, namespace: string, devBranch: string): boolean {\n if (cmd.includes(`${namespace}/`)) return true;\n const push = /\\bgit\\s+push\\b([^\\n;&|]*)/.exec(cmd);\n if (push === null) return false;\n // Split on whitespace AND `:` so both halves of a `HEAD:<dest>` refspec are examined. Matching whole\n // tokens (never a substring) keeps a branch merely NAMED `develop` from reading as the dev branch.\n return push[1].split(/[\\s:]+/).some(\n (token: string): boolean => token === devBranch || token === `refs/heads/${devBranch}`);\n}\n\nexport class PrCreationOrPushGuardRule extends BashRuleBase<PrLifecycleGuardConfig> {\n /**\n * The gated command this guard names, handed in by the LOADER from `commands.guardHints\n * .prCreationOrPush` (already defaulted there). It is a constructor parameter, not a config field:\n * the field `pr-creation-or-push-guard.upsertPrCommand` was a SECOND SPELLING that beat the\n * commands section at the point of use, and the loader's name-keyed injection that fed it could\n * miss a rename without failing the build. One spelling, wired at compile time.\n */\n private readonly upsertPrCommand: string;\n\n constructor(config: PrLifecycleGuardConfig, upsertPrCommand: string) {\n super(config, 'pr-creation-or-push-guard', PR_LIFECYCLE_GUARD_KEY);\n this.upsertPrCommand = upsertPrCommand;\n }\n\n readonly description = 'Block manual `git push` and direct PR creation/edit (gh pr / gh api / curl) so pushes and PRs go only through the gated upsert-pr command.';\n get fixHint(): FixHint { return fixHintFor(this.upsertPrCommand); }\n\n check(ctx: BashContext): readonly Violation[] {\n if (!isBlockedPrOrPush(ctx.commandCode)) return [];\n // Materialize the doc we are about to send the AI to. Pointing at a path that does not exist\n // (nothing has run a `wp-*` command in this tree yet) costs the AI a turn to discover; a STALE\n // copy from an older @webpieces is just as bad, so overwrite rather than write-if-missing.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n if (this.aimedAtDevEnvironment(ctx)) {\n return [new V(1, truncate(ctx.command),\n 'Manual push is blocked — but this one is aimed at the shared DEV environment, which has its own\\n'\n + `gated command. Use \\`${WP_PUSH_DEV}\\` (publishes a disposable copy; never moves your branch, never\\n`\n + `opens a PR). Do NOT use ${this.upsertPrCommand} for this — that lands on main. Full flow: READ ${docPath}.`)];\n }\n return [new V(1, truncate(ctx.command),\n `Manual push / direct PR is blocked — use the gated flow (${this.upsertPrCommand}). Full flow: READ ${docPath}.`)];\n }\n\n /**\n * Read the configured dev refs, falling back to the defaults when this repo has no `pr-gate` section\n * at all (a consumer that has not adopted the gate still gets a correct hint for the default names).\n *\n * Calling the loader here is safe by construction: an INVALID config blocks every Bash call long\n * before a rule runs, so reaching this line already means the config loaded.\n */\n private aimedAtDevEnvironment(ctx: BashContext): boolean {\n const devDeploy = loadAndValidate(ctx.governedRoot).prGate.devDeploy;\n return targetsDevEnvironment(\n ctx.commandCode,\n devDeploy.branchNamespace === '' ? DEFAULT_DEV_BRANCH_NAMESPACE : devDeploy.branchNamespace,\n devDeploy.devBranch === '' ? DEFAULT_DEV_BRANCH : devDeploy.devBranch);\n }\n}\n"]}
@@ -66,7 +66,7 @@ export declare class TargetTreeResolver {
66
66
  * `treeRelativePath` — relative to the tree that OWNS the file. What `isWebpiecesStateDir` must be
67
67
  * asked about, because `.webpieces/` is the tooling's state dir *of a tree*, and
68
68
  * a worktree has its own. Governed-root-relative, a reviewer subagent's
69
- * `<primary>/.claude/worktrees/agent-X/.webpieces/pr-review/<branch>/review.json`
69
+ * `<primary>/.claude/worktrees/agent-X/.webpieces/pr-review/<branch>/summary.json`
70
70
  * reads as `.claude/...` and was NOT exempt — while
71
71
  * `<primary>/.webpieces/worktrees/agent-X/pr-review/.../review-1.json`, the same
72
72
  * kind of file one directory over, was. `wp-review-upsert-pr` REQUIRES that file
@@ -124,7 +124,7 @@ exports.TargetTreeResolver = TargetTreeResolver;
124
124
  * `treeRelativePath` — relative to the tree that OWNS the file. What `isWebpiecesStateDir` must be
125
125
  * asked about, because `.webpieces/` is the tooling's state dir *of a tree*, and
126
126
  * a worktree has its own. Governed-root-relative, a reviewer subagent's
127
- * `<primary>/.claude/worktrees/agent-X/.webpieces/pr-review/<branch>/review.json`
127
+ * `<primary>/.claude/worktrees/agent-X/.webpieces/pr-review/<branch>/summary.json`
128
128
  * reads as `.claude/...` and was NOT exempt — while
129
129
  * `<primary>/.webpieces/worktrees/agent-X/pr-review/.../review-1.json`, the same
130
130
  * kind of file one directory over, was. `wp-review-upsert-pr` REQUIRES that file
@@ -1 +1 @@
1
- {"version":3,"file":"target-tree.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/target-tree.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAE7B,qDAAwE;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,kBAAkB;IACE;IAA7B,YAA6B,QAA+B,IAAI,sCAAqB,EAAE;QAA1D,UAAK,GAAL,KAAK,CAAqD;IAAG,CAAC;IAE3F;;;;;;OAMG;IACH,OAAO,CAAC,UAAkB,EAAE,YAAoB;QAC5C,+FAA+F;QAC/F,+FAA+F;QAC/F,+FAA+F;QAC/F,gGAAgG;QAChG,6FAA6F;QAC7F,6FAA6F;QAC7F,2FAA2F;QAC3F,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC5C,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,IAAI,CAAC,kBAAkB,CAAC,UAAU,EAAE,QAAQ,CAA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AS,CAAC;YACN,IAAI,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC;gBAAE,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC;YACxE,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,MAAM,KAAK,GAAG;gBAAE,OAAO,QAAQ,CAAC;YACpC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;YACjC,GAAG,GAAG,MAAM,CAAC;QACjB,CAAC;IACL,CAAC;IAED,8EAA8E;IACtE,OAAO,CAAC,GAAW;QACvB,OAAO,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACzE,CAAC;CACJ;AA/ED,gDA+EC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,YAAY;IACZ,YAAY,CAAS;IACrB,gBAAgB,CAAS;IAClC,2GAA2G;IAClG,QAAQ,CAAS;IAE1B,YAAY,YAAoB,EAAE,gBAAwB,EAAE,QAAgB;QACxE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AAXD,oCAWC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { EffectiveTree, EffectiveTreeResolver } from './effective-tree';\n\n/**\n * WHICH TREE owns the FILE a Write/Edit/Read is aimed at? The file-path counterpart to\n * EffectiveTreeResolver, which answers the same question for a Bash command's effective cwd.\n *\n * WHY IT HAS TO EXIST (issue #851). The bash half of this question has been answered by git since\n * effective-tree.ts was written — `isLinkedWorktree` is `--git-dir !== --git-common-dir`, and its header\n * states the principle in capitals: *PLACEMENT IS NOT IDENTITY*. The FILE half never consumed that\n * answer. Every file-scoped guard judged `ctx.workspaceRoot`, which is the walk-up from the SESSION's\n * cwd to whichever `webpieces.config.json` governs it — the PRIMARY clone, for a main-session edit into\n * an agent worktree. Because Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, that walk-up answers \"primary\" for a path that is manifestly\n * not the primary's, and nothing downstream re-examined it.\n *\n * Measured live on 2026-09-03: an Edit of one import line inside a worktree on a CLEAN branch was\n * refused, citing `pnpm-lock.yaml` and `pnpm-workspace.yaml` — the PRIMARY clone's branch's conflict\n * files. The main-sync cache is already keyed by branch and already held the correct, non-conflicting\n * entry for the worktree's branch, one key over. Only the lookup key was wrong. So this class exists to\n * make the lookup ask the same authority the bash half asks, rather than to introduce a second one.\n *\n * IT ASKS EffectiveTreeResolver, and adds NOTHING of its own beyond finding a directory to ask about.\n * That is deliberate and it is the whole design: two resolvers WILL disagree about which tree a path is\n * in, and this module exists precisely because two layers already did. There is no `.claude/worktrees`\n * string match here and there must never be one — matching on placement is the bug, not the fix.\n *\n * The only thing worth naming is the walk-up: a Write legitimately names a file, and directories, that\n * do not exist yet, and git cannot be asked about a directory that is not there. So we climb to the\n * nearest EXISTING ancestor and ask about that. A parent directory is in the same worktree as the child\n * it is about to contain — that is a property of the filesystem, not a guess.\n */\nexport class TargetTreeResolver {\n constructor(private readonly trees: EffectiveTreeResolver = new EffectiveTreeResolver()) {}\n\n /**\n * The tree that owns `targetPath`, classified exactly as a Bash command's cwd would be.\n *\n * `governedRoot` is the fallback for every case with no better answer — an empty path, a path with\n * no existing ancestor at all — and is also what `EffectiveTree.governedRoot` keeps meaning: whose\n * config and excludePaths apply. It is NOT the tree to judge; `EffectiveTree.root` is.\n */\n resolve(targetPath: string, governedRoot: string): EffectiveTree {\n // REAL paths on BOTH sides, or git's answers cannot be compared with each other. Identity here\n // is `commonDir(target) === commonDir(governed)`, and git prints an ABSOLUTE, symlink-resolved\n // path from a linked worktree while printing a bare relative `.git` from the primary clone. So\n // on any repo reached through a symlink — `/var/folders/...` on macOS, which is `/private/var`,\n // and every `os.tmpdir()` path under it — the two strings differ for the same `.git` and the\n // repo's OWN worktree classifies as `foreign`, i.e. every guard silently off. Resolving both\n // sides first is what makes the comparison an answer about git rather than about spelling.\n const governed = this.realDir(governedRoot);\n return this.trees.resolve('', this.nearestExistingDir(targetPath, governed), governed);\n }\n\n /**\n * The two relative spellings of one target path, resolved together so a caller cannot accidentally\n * use the wrong one. See GovernedPath for why there are two.\n */\n governedPath(targetPath: string, governedRoot: string): GovernedPath {\n const absolute = this.realAbsolute(targetPath);\n const tree = this.resolve(targetPath, governedRoot);\n // `tree.root` and `tree.governedRoot` are already resolved by resolve() above, so both\n // subtractions are real-against-real. Mixing one resolved side with one unresolved one produces\n // a `../../../..` climb out of the filesystem — which reads as \"outside the workspace\" and\n // would quietly hand every path the wrong verdict on a symlinked checkout.\n return new GovernedPath(\n path.relative(tree.governedRoot, absolute),\n path.relative(tree.root, absolute),\n tree.root,\n );\n }\n\n // The nearest ancestor directory of `targetPath` that EXISTS — the deepest directory git can be\n // asked about — with symlinks resolved. Bounded by the filesystem root (path.dirname is its own\n // fixed point at `/`), so the loop terminates without a counter.\n private nearestExistingDir(targetPath: string, governedRoot: string): string {\n if (targetPath === '') return governedRoot;\n let dir = path.dirname(path.resolve(targetPath));\n for (;;) {\n if (fs.existsSync(dir)) return fs.realpathSync(dir);\n const parent = path.dirname(dir);\n if (parent === dir) return governedRoot;\n dir = parent;\n }\n }\n\n /**\n * `targetPath` made absolute AND symlink-resolved, including when it does not exist yet.\n *\n * `fs.realpathSync` throws on a missing path, and a Write's target is missing by definition, so the\n * resolvable HEAD of the path (its nearest existing ancestor) is resolved and the not-yet-existing\n * TAIL is re-appended verbatim. That keeps it comparable with `tree.root`, which is git's answer and\n * always real.\n */\n private realAbsolute(targetPath: string): string {\n const absolute = path.resolve(targetPath);\n const tail: string[] = [];\n let dir = absolute;\n for (;;) {\n if (fs.existsSync(dir)) return path.join(fs.realpathSync(dir), ...tail);\n const parent = path.dirname(dir);\n if (parent === dir) return absolute;\n tail.unshift(path.basename(dir));\n dir = parent;\n }\n }\n\n // A directory made real when it is there, and merely absolute when it is not.\n private realDir(dir: string): string {\n return fs.existsSync(dir) ? fs.realpathSync(dir) : path.resolve(dir);\n }\n}\n\n/**\n * One target path, in the TWO relative spellings the hook path needs — data-only, per CLAUDE.md.\n *\n * They are different questions and conflating them is issue #851's secondary defect:\n *\n * `relativePath` — relative to the GOVERNED root. What `excludePaths`' globs are written against,\n * and what the violation report prints.\n * `treeRelativePath` — relative to the tree that OWNS the file. What `isWebpiecesStateDir` must be\n * asked about, because `.webpieces/` is the tooling's state dir *of a tree*, and\n * a worktree has its own. Governed-root-relative, a reviewer subagent's\n * `<primary>/.claude/worktrees/agent-X/.webpieces/pr-review/<branch>/review.json`\n * reads as `.claude/...` and was NOT exempt — while\n * `<primary>/.webpieces/worktrees/agent-X/pr-review/.../review-1.json`, the same\n * kind of file one directory over, was. `wp-review-upsert-pr` REQUIRES that file\n * before `wp-finish-upsert-pr` will open a PR, so the guard could forbid a file\n * the gate demands.\n *\n * In the primary clone the two strings are identical, which is why the gap was invisible for so long.\n */\nexport class GovernedPath {\n readonly relativePath: string;\n readonly treeRelativePath: string;\n /** The git tree that owns the target path; policy still belongs to the separately loaded governed root. */\n readonly treeRoot: string;\n\n constructor(relativePath: string, treeRelativePath: string, treeRoot: string) {\n this.relativePath = relativePath;\n this.treeRelativePath = treeRelativePath;\n this.treeRoot = treeRoot;\n }\n}\n"]}
1
+ {"version":3,"file":"target-tree.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/target-tree.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAE7B,qDAAwE;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,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B,EAAE,gBAAwB,EAAE,QAAgB;QACxE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AAXD,oCAWC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { EffectiveTree, EffectiveTreeResolver } from './effective-tree';\n\n/**\n * WHICH TREE owns the FILE a Write/Edit/Read is aimed at? The file-path counterpart to\n * EffectiveTreeResolver, which answers the same question for a Bash command's effective cwd.\n *\n * WHY IT HAS TO EXIST (issue #851). The bash half of this question has been answered by git since\n * effective-tree.ts was written — `isLinkedWorktree` is `--git-dir !== --git-common-dir`, and its header\n * states the principle in capitals: *PLACEMENT IS NOT IDENTITY*. The FILE half never consumed that\n * answer. Every file-scoped guard judged `ctx.workspaceRoot`, which is the walk-up from the SESSION's\n * cwd to whichever `webpieces.config.json` governs it — the PRIMARY clone, for a main-session edit into\n * an agent worktree. Because Claude Code checks a worktree out INSIDE the repo at\n * `<repo>/.claude/worktrees/agent-XXXX`, that walk-up answers \"primary\" for a path that is manifestly\n * not the primary's, and nothing downstream re-examined it.\n *\n * Measured live on 2026-09-03: an Edit of one import line inside a worktree on a CLEAN branch was\n * refused, citing `pnpm-lock.yaml` and `pnpm-workspace.yaml` — the PRIMARY clone's branch's conflict\n * files. The main-sync cache is already keyed by branch and already held the correct, non-conflicting\n * entry for the worktree's branch, one key over. Only the lookup key was wrong. So this class exists to\n * make the lookup ask the same authority the bash half asks, rather than to introduce a second one.\n *\n * IT ASKS EffectiveTreeResolver, and adds NOTHING of its own beyond finding a directory to ask about.\n * That is deliberate and it is the whole design: two resolvers WILL disagree about which tree a path is\n * in, and this module exists precisely because two layers already did. There is no `.claude/worktrees`\n * string match here and there must never be one — matching on placement is the bug, not the fix.\n *\n * The only thing worth naming is the walk-up: a Write legitimately names a file, and directories, that\n * do not exist yet, and git cannot be asked about a directory that is not there. So we climb to the\n * nearest EXISTING ancestor and ask about that. A parent directory is in the same worktree as the child\n * it is about to contain — that is a property of the filesystem, not a guess.\n */\nexport class TargetTreeResolver {\n constructor(private readonly trees: EffectiveTreeResolver = new EffectiveTreeResolver()) {}\n\n /**\n * The tree that owns `targetPath`, classified exactly as a Bash command's cwd would be.\n *\n * `governedRoot` is the fallback for every case with no better answer — an empty path, a path with\n * no existing ancestor at all — and is also what `EffectiveTree.governedRoot` keeps meaning: whose\n * config and excludePaths apply. It is NOT the tree to judge; `EffectiveTree.root` is.\n */\n resolve(targetPath: string, governedRoot: string): EffectiveTree {\n // REAL paths on BOTH sides, or git's answers cannot be compared with each other. Identity here\n // is `commonDir(target) === commonDir(governed)`, and git prints an ABSOLUTE, symlink-resolved\n // path from a linked worktree while printing a bare relative `.git` from the primary clone. So\n // on any repo reached through a symlink — `/var/folders/...` on macOS, which is `/private/var`,\n // and every `os.tmpdir()` path under it — the two strings differ for the same `.git` and the\n // repo's OWN worktree classifies as `foreign`, i.e. every guard silently off. Resolving both\n // sides first is what makes the comparison an answer about git rather than about spelling.\n const governed = this.realDir(governedRoot);\n return this.trees.resolve('', this.nearestExistingDir(targetPath, governed), governed);\n }\n\n /**\n * The two relative spellings of one target path, resolved together so a caller cannot accidentally\n * use the wrong one. See GovernedPath for why there are two.\n */\n governedPath(targetPath: string, governedRoot: string): GovernedPath {\n const absolute = this.realAbsolute(targetPath);\n const tree = this.resolve(targetPath, governedRoot);\n // `tree.root` and `tree.governedRoot` are already resolved by resolve() above, so both\n // subtractions are real-against-real. Mixing one resolved side with one unresolved one produces\n // a `../../../..` climb out of the filesystem — which reads as \"outside the workspace\" and\n // would quietly hand every path the wrong verdict on a symlinked checkout.\n return new GovernedPath(\n path.relative(tree.governedRoot, absolute),\n path.relative(tree.root, absolute),\n tree.root,\n );\n }\n\n // The nearest ancestor directory of `targetPath` that EXISTS — the deepest directory git can be\n // asked about — with symlinks resolved. Bounded by the filesystem root (path.dirname is its own\n // fixed point at `/`), so the loop terminates without a counter.\n private nearestExistingDir(targetPath: string, governedRoot: string): string {\n if (targetPath === '') return governedRoot;\n let dir = path.dirname(path.resolve(targetPath));\n for (;;) {\n if (fs.existsSync(dir)) return fs.realpathSync(dir);\n const parent = path.dirname(dir);\n if (parent === dir) return governedRoot;\n dir = parent;\n }\n }\n\n /**\n * `targetPath` made absolute AND symlink-resolved, including when it does not exist yet.\n *\n * `fs.realpathSync` throws on a missing path, and a Write's target is missing by definition, so the\n * resolvable HEAD of the path (its nearest existing ancestor) is resolved and the not-yet-existing\n * TAIL is re-appended verbatim. That keeps it comparable with `tree.root`, which is git's answer and\n * always real.\n */\n private realAbsolute(targetPath: string): string {\n const absolute = path.resolve(targetPath);\n const tail: string[] = [];\n let dir = absolute;\n for (;;) {\n if (fs.existsSync(dir)) return path.join(fs.realpathSync(dir), ...tail);\n const parent = path.dirname(dir);\n if (parent === dir) return absolute;\n tail.unshift(path.basename(dir));\n dir = parent;\n }\n }\n\n // A directory made real when it is there, and merely absolute when it is not.\n private realDir(dir: string): string {\n return fs.existsSync(dir) ? fs.realpathSync(dir) : path.resolve(dir);\n }\n}\n\n/**\n * One target path, in the TWO relative spellings the hook path needs — data-only, per CLAUDE.md.\n *\n * They are different questions and conflating them is issue #851's secondary defect:\n *\n * `relativePath` — relative to the GOVERNED root. What `excludePaths`' globs are written against,\n * and what the violation report prints.\n * `treeRelativePath` — relative to the tree that OWNS the file. What `isWebpiecesStateDir` must be\n * asked about, because `.webpieces/` is the tooling's state dir *of a tree*, and\n * a worktree has its own. Governed-root-relative, a reviewer subagent's\n * `<primary>/.claude/worktrees/agent-X/.webpieces/pr-review/<branch>/summary.json`\n * reads as `.claude/...` and was NOT exempt — while\n * `<primary>/.webpieces/worktrees/agent-X/pr-review/.../review-1.json`, the same\n * kind of file one directory over, was. `wp-review-upsert-pr` REQUIRES that file\n * before `wp-finish-upsert-pr` will open a PR, so the guard could forbid a file\n * the gate demands.\n *\n * In the primary clone the two strings are identical, which is why the gap was invisible for so long.\n */\nexport class GovernedPath {\n readonly relativePath: string;\n readonly treeRelativePath: string;\n /** The git tree that owns the target path; policy still belongs to the separately loaded governed root. */\n readonly treeRoot: string;\n\n constructor(relativePath: string, treeRelativePath: string, treeRoot: string) {\n this.relativePath = relativePath;\n this.treeRelativePath = treeRelativePath;\n this.treeRoot = treeRoot;\n }\n}\n"]}
@@ -41,6 +41,6 @@ with the verdict JSON on stdin (a heredoc is simplest), or `--file <path>` namin
41
41
  it, writes the verdict file, and records that YOU wrote it. A verdict file written any other way —
42
42
  by you, or by the coordinating agent on your behalf — is rejected by the gate, so there is no other route.
43
43
 
44
- You NEVER edit code, config, docs, or any other file in the repo. You never write `review.json` or an
44
+ You NEVER edit code, config, docs, or any other file in the repo. You never write `summary.json` or an
45
45
  `override-<id>.json`. If a finding needs a human's decision, say so in `output`; the coordinating
46
46
  agent is the one with the human.