@webpieces/rules-config 0.4.823 → 0.4.824

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/rules-config",
3
- "version": "0.4.823",
3
+ "version": "0.4.824",
4
4
  "description": "Shared webpieces.config.json loader. Single source of truth for validation rule configuration consumed by @webpieces/ai-hook-rules, @webpieces/code-rules, and @webpieces/nx-webpieces-rules.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -118,10 +118,10 @@ export declare class PrGateConfig {
118
118
  maxReviewerRounds: number;
119
119
  checklistComments: boolean;
120
120
  /**
121
- * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes
122
- * `HMAC(gateSalt, HEAD_sha)` as a hidden marker into the PR body (and REFUSES to mint it unless
123
- * every BLOCK checklist passed), so a valid token IS proof the local gate ran and passed. A CI
124
- * check (`wp-check-pr` + the scaffolded workflow) recomputes it from the PR head sha and this salt.
121
+ * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes it after
122
+ * the automated gate passes; `wp-human-post-pr` writes the same token after explicit human attestation
123
+ * and visibly labels review as skipped plus whether its optional local build ran. A CI check
124
+ * recomputes it from the PR head + salt.
125
125
  *
126
126
  * Optional, defaults to '' — empty means "no token minted, no CI enforcement" (byte-identical to
127
127
  * before this field existed). This is COMMITTED, obscurity-grade: it stops unhooked teammates who
@@ -185,10 +185,10 @@ class PrGateConfig {
185
185
  // (idempotently updated on every push). Defaults to true. Set false to keep the PR body-only.
186
186
  checklistComments;
187
187
  /**
188
- * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes
189
- * `HMAC(gateSalt, HEAD_sha)` as a hidden marker into the PR body (and REFUSES to mint it unless
190
- * every BLOCK checklist passed), so a valid token IS proof the local gate ran and passed. A CI
191
- * check (`wp-check-pr` + the scaffolded workflow) recomputes it from the PR head sha and this salt.
188
+ * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes it after
189
+ * the automated gate passes; `wp-human-post-pr` writes the same token after explicit human attestation
190
+ * and visibly labels review as skipped plus whether its optional local build ran. A CI check
191
+ * recomputes it from the PR head + salt.
192
192
  *
193
193
  * Optional, defaults to '' — empty means "no token minted, no CI enforcement" (byte-identical to
194
194
  * before this field existed). This is COMMITTED, obscurity-grade: it stops unhooked teammates who
@@ -311,8 +311,12 @@ function buildPrGateConfig(section) {
311
311
  built.maxReviewerRounds = raw.maxReviewerRounds;
312
312
  // Review-context knobs. All optional and all defaulted, so a config that omits every one of them (which
313
313
  // is every consumer's config today) behaves exactly as it did before they existed.
314
- built.reviewDiffExclude = Array.isArray(raw.reviewDiffExclude) ? raw.reviewDiffExclude : defaults.reviewDiffExclude;
315
- built.reviewContextPackages = Array.isArray(raw.reviewContextPackages) ? raw.reviewContextPackages : defaults.reviewContextPackages;
314
+ built.reviewDiffExclude = Array.isArray(raw.reviewDiffExclude)
315
+ ? raw.reviewDiffExclude
316
+ : defaults.reviewDiffExclude;
317
+ built.reviewContextPackages = Array.isArray(raw.reviewContextPackages)
318
+ ? raw.reviewContextPackages
319
+ : defaults.reviewContextPackages;
316
320
  built.reviewContext = Array.isArray(raw.reviewContext)
317
321
  ? raw.reviewContext.map((e) => new ReviewContextEntry(e.label ?? '', e.path ?? ''))
318
322
  : defaults.reviewContext;
@@ -331,9 +335,11 @@ function buildDevDeployConfig(raw) {
331
335
  if (raw === undefined || raw === null || typeof raw !== 'object')
332
336
  return defaults;
333
337
  const namespace = typeof raw.branchNamespace === 'string' && raw.branchNamespace.trim() !== ''
334
- ? raw.branchNamespace.trim() : defaults.branchNamespace;
338
+ ? raw.branchNamespace.trim()
339
+ : defaults.branchNamespace;
335
340
  const devBranch = typeof raw.devBranch === 'string' && raw.devBranch.trim() !== ''
336
- ? raw.devBranch.trim() : defaults.devBranch;
341
+ ? raw.devBranch.trim()
342
+ : defaults.devBranch;
337
343
  return new DevDeployConfig(namespace, devBranch);
338
344
  }
339
345
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"pr-gate-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/pr-gate-config.ts"],"names":[],"mappings":";;;AAqFA,kDAEC;AA6CD,wDAEC;AAgID,oCAOC;AAED,kDAGC;AAuDD,8CA6CC;AAQD,oDAQC;AAQD,8CAMC;AApZD,uDAAoF;AACpF,yDAE4B;AAE5B,2FAA2F;AAC3F,2FAA2F;AAC3F,iFAAiF;AACjF,iGAAiG;AAEjG;;;;;;;;;;;GAWG;AACU,QAAA,qBAAqB,GAAG,wEAAwE,CAAC;AAE9G,MAAa,cAAc;IACvB,IAAI,CAAS;IACb,QAAQ,CAAW;IACnB,iGAAiG;IACjG,8FAA8F;IAC9F,+FAA+F;IAC/F,gGAAgG;IAChG,YAAY,CAAS,CAAC,mBAAmB;IACzC,2FAA2F;IAC3F,yFAAyF;IACzF,QAAQ,CAAU;IAElB,YAAY,IAAY,EAAE,QAAkB,EAAE,YAAoB,EAAE,QAAQ,GAAG,KAAK;QAChF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AAlBD,wCAkBC;AAED,qGAAqG;AACrG,mGAAmG;AACnG,sGAAsG;AACtG,sGAAsG;AACtG,sGAAsG;AACzF,QAAA,eAAe,GAAG,MAAM,CAAC;AACzB,QAAA,eAAe,GAAG,MAAM,CAAC;AACzB,QAAA,WAAW,GAAG,CAAC,uBAAe,EAAE,uBAAe,CAAC,CAAC;AAE9D;;;;;;GAMG;AACH;;;GAGG;AACH,MAAa,kBAAkB;IAC3B,KAAK,CAAS;IACd,IAAI,CAAS,CAAC,uFAAuF;IAErG,YAAY,KAAa,EAAE,SAAiB;QACxC,IAAI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;IAClF,MAAM,SAAS,GAAG,OAAO,GAAG,CAAC,eAAe,KAAK,QAAQ,IAAI,GAAG,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,EAAE;QAC1F,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,eAAe,CAAC;IAC5D,MAAM,SAAS,GAAG,OAAO,GAAG,CAAC,SAAS,KAAK,QAAQ,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE;QAC9E,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC;IAChD,OAAO,IAAI,eAAe,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACrD,CAAC;AAED;;;;GAIG;AACH,gHAAgH;AAChH,SAAgB,iBAAiB,CAAC,GAA0B;IACxD,MAAM,QAAQ,GAAG,mBAAmB,EAAE,CAAC;IACvC,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAClF,MAAM,SAAS,GAAG,GAAG,CAAC,eAAe,CAAC;IACtC,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,mCAAiB,CAAC,QAAQ,CAAC,SAAS,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC7F,OAAO,IAAI,YAAY,CAAC,SAAS,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { BRANCH_RETENTION_ARCHIVE_TAG, BRANCH_RETENTIONS } from './branch-archiver';\nimport {\n ChecklistDefinition, DEFAULT_REVIEWER_AGENT_NAME, RawChecklistItem, REVIEWER_AGENTS_PLACEHOLDER, ReviewerAgentPolicy, toChecklist,\n} from './checklist-config';\n\n// PrGateConfig is the \"special section\" for the pr-gate dashboard. It does NOT live in the\n// validated `rules` map (the FieldDef schema can't express nested object arrays), but as a\n// top-level `pr-gate` key in webpieces.config.json. It is built and validated by\n// loadAndValidate (load-config.ts); this module holds only the data classes + defaults + toGate.\n\n/**\n * The build the pr-gate runs when a repo configures no `commands.pr-gate.buildCommand` — and the ONE\n * definition of it, because two things now need it: the gate that RUNS it (pr-gate's BuildAffected)\n * and the guard that REFUSES a whole-monorepo build and prints it instead (ai-hook-rules'\n * whole-repo-build-guard). A second copy in either package is a message that can teach a command the\n * gate does not run.\n *\n * `--base=$(git merge-base origin/main HEAD)` — the FORK POINT, not `origin/main`: basing on\n * origin/main marks projects touched by other people's already-merged PRs as affected. The `$(…)`\n * resolves because the gate spawns with `shell: true`; the guard resolves it itself before printing,\n * so the AI is never handed a template it might paste somewhere without a shell.\n */\nexport const DEFAULT_BUILD_COMMAND = 'pnpm nx affected --target=ci --base=$(git merge-base origin/main HEAD)';\n\nexport class GateDefinition {\n name: string;\n patterns: string[];\n // The warning color shown on the dashboard WHEN this gate's patterns match a changed file. Green\n // is implicit (shown when nothing matched), so it is never configured. warningColor is purely\n // visual — even 'red' never fails/blocks the PR (only the build gate can). 'yellow' = caution,\n // 'red' = louder \"look here\" flag (e.g. DB schema / migration changes). REQUIRED on every gate.\n warningColor: string; // 'yellow' | 'red'\n // Example/inactive gate: parsed and kept in the file (JSON has no comments) but skipped at\n // compute/render time. Other projects flip this to false and tune patterns/warningColor.\n disabled: boolean;\n\n constructor(name: string, patterns: string[], warningColor: string, disabled = false) {\n this.name = name;\n this.patterns = patterns;\n this.warningColor = warningColor;\n this.disabled = disabled;\n }\n}\n\n// How wp-finish-upsert-pr should try to LAND the PR once it has posted it. GitHub's auto-merge queue\n// is a REPO-level setting (`allow_auto_merge`) that many orgs turn OFF as a policy control, and it\n// CANNOT be forced from the client: `gh pr merge --auto` calls the enablePullRequestAutoMerge GraphQL\n// mutation, which hard-errors with \"Auto merge is not allowed for this repository\" when the repo says\n// no. So the only lever a config knob has is WHICH PATHS WE ATTEMPT — never whether the queue exists.\nexport const MERGE_MODE_AUTO = 'AUTO';\nexport const MERGE_MODE_NONE = 'NONE';\nexport const MERGE_MODES = [MERGE_MODE_AUTO, MERGE_MODE_NONE];\n\n/**\n * `pr-gate.landPr` — what happens to the LOCAL branch once its PR has landed.\n *\n * A rich object rather than a bare string (the `commands.pr-gate` precedent) so the next knob about\n * landing has a home, and so the rationale can sit beside the setting as a `*Why` sibling: JSON has no\n * comments, and `<key>Why` is how this repo documents non-obvious config.\n */\n/**\n * One `pr-gate.reviewContext` entry: a human label and a repo-relative path a reviewer is handed instead of\n * having to find it. Data-only (per CLAUDE.md).\n */\nexport class ReviewContextEntry {\n label: string;\n path: string; // repo-relative in config; resolved to absolute when written into an instructions file\n\n constructor(label: string, entryPath: string) {\n this.label = label;\n this.path = entryPath;\n }\n}\n\nexport class LandPrConfig {\n // One of BRANCH_RETENTIONS. Defaults to 'archive-tag' — see BranchArchiver for why a tag beats\n // keeping the branch, storing a patch, or trusting the reflog.\n branchRetention: string;\n\n constructor(branchRetention: string = BRANCH_RETENTION_ARCHIVE_TAG) {\n this.branchRetention = branchRetention;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultLandPrConfig(): LandPrConfig {\n return new LandPrConfig(BRANCH_RETENTION_ARCHIVE_TAG);\n}\n\n// The two literal ref names the dev-deploy flow derives everything else from. Defaults, not policy —\n// `pr-gate.devDeploy` overrides both, because a consumer whose shared environment is called `staging`\n// must not be forced onto webpieces' vocabulary.\nexport const DEFAULT_DEV_BRANCH_NAMESPACE = 'dev-include';\nexport const DEFAULT_DEV_BRANCH = 'dev';\n\n/**\n * `pr-gate.devDeploy` — where `wp-push-dev` publishes the throwaway copy of a feature branch, and which\n * ref is the shared dev branch itself.\n *\n * WHY A NAMESPACE AT ALL, i.e. why the copy is not just the feature branch: the feature branch is the PR\n * head, and landing that PR ships whatever is on it. The moment a conflict between two devs has to be\n * resolved SOMEWHERE for the shared environment to build, that resolution needs a home that is not the PR\n * branch — otherwise \"test it in dev\" silently ships another dev's unreviewed work to production. The\n * `<branchNamespace>/<feature>` copy is that home, and it is disposable by construction.\n *\n * `devBranch` is REFUSED as a source branch (you never push the composed branch back into itself); it is\n * written by the consumer's CI only, which recomputes it from `origin/main` on every run.\n */\nexport class DevDeployConfig {\n // Literal prefix on the feature branch name: `dev-include/dean/ONE-2275`. Git refs allow slashes, and\n // nobody ever types this — the command derives it.\n branchNamespace: string;\n // The composed, CI-owned branch that actually deploys. Never a source, never pushed to by this flow.\n devBranch: string;\n\n constructor(branchNamespace: string = DEFAULT_DEV_BRANCH_NAMESPACE, devBranch: string = DEFAULT_DEV_BRANCH) {\n this.branchNamespace = branchNamespace;\n this.devBranch = devBranch;\n }\n\n /** `<branchNamespace>/<branch>` — the remote ref holding the disposable copy of `branch`. */\n copyRefFor(branch: string): string {\n return `${this.branchNamespace}/${branch}`;\n }\n\n /** The `git ls-remote --heads origin <pattern>` pattern matching every live copy. */\n copyRefGlob(): string {\n return `${this.branchNamespace}/*`;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultDevDeployConfig(): DevDeployConfig {\n return new DevDeployConfig(DEFAULT_DEV_BRANCH_NAMESPACE, DEFAULT_DEV_BRANCH);\n}\n\nexport class PrGateConfig {\n mode: string;\n /**\n * The nx-affected build gate command, shared by the two commands that can run it.\n *\n * It is NOT finish-only any more, and the change is the point. It used to run once, in\n * wp-finish-upsert-pr, which meant reviewers were spawned against a branch nobody had built — they could\n * spend a full review on code that does not compile, or on an unresolved 3-point merge.\n *\n * Now `wp-review-upsert-pr` finalizes the merge and runs this gate BEFORE briefing any reviewer, and\n * records the passing HEAD sha in the stage receipt. `wp-finish-upsert-pr` re-runs it only when HEAD has\n * moved since — so the flow gained a gate where it mattered without paying for two full builds.\n *\n * Empty string => BuildAffected falls back to DEFAULT_BUILD_COMMAND.\n */\n buildCommand: string;\n gates: GateDefinition[];\n /**\n * REQUIRED — every repo must state its policy; there is deliberately no default, because the two\n * answers are a real policy decision and guessing it either merges when a team did not want that,\n * or silently stops landing PRs on a team that relied on it.\n *\n * AUTO — wp-finish-upsert-pr LANDS the PR: squash-merge it right away when it is mergeable, else\n * enable GitHub auto-merge so it lands when the checks pass. Both carry an explicit --subject /\n * --body-file, which is the ONLY way main's history gets the PR title plus the compact\n * risk/flags body — no repo setting can produce that. Requires allow_auto_merge on the repo.\n * NONE — wp-finish-upsert-pr only opens/updates the PR and stops; a human merges. NOTE the cost:\n * a UI merge cannot use the compact body, so main's commit falls back to the repo's\n * squash_merge_commit_title/message settings. Set squash_merge_commit_title=PR_TITLE there, or\n * commits land as the internal \"Squash merge of <branch>\" subject.\n */\n mergeMode: string;\n // This repo's review checklists, straight from the `pr-gate.checklists` ARRAY in webpieces.config.json —\n // the ONLY accepted shape (`patterns` is a path-glob dispatch table and `id` the checklist's name, so both\n // are config). Every def carries {@link reviewer}. [] = no checklists. The removed `{ doc }` manifest\n // form is a hard config error; see validateChecklistsSection.\n checklists: ChecklistDefinition[];\n /**\n * The ONE agent type every checklist is reviewed by — `webpieces-reviewer` unless\n * `overrideReviewerAgent` is true, in which case `reviewerAgentName` — and `reviewerAgents`, the most such\n * subagents a round may use. The same instance is bound into every {@link checklists} entry, so a caller\n * holding only a checklist still knows what to spawn. Field-with-default because the constructor is at\n * max-params; the agent name defaults to the webpieces reviewer, exactly what a config that says nothing\n * gets, while the CAP is a required field, so the placeholder here is only ever overwritten by the real\n * number buildPrGateConfig reads.\n */\n reviewer: ReviewerAgentPolicy = new ReviewerAgentPolicy(DEFAULT_REVIEWER_AGENT_NAME, REVIEWER_AGENTS_PLACEHOLDER);\n /**\n * REQUIRED positive integer: the maximum number of complete global reviewer rounds a PR review state\n * may start. This is deliberately repository policy rather than a machine-local preference.\n */\n maxReviewerRounds!: number;\n // Whether wp-finish-upsert-pr publishes each reviewer's full `output` as ONE combined PR comment\n // (idempotently updated on every push). Defaults to true. Set false to keep the PR body-only.\n checklistComments: boolean;\n /**\n * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes\n * `HMAC(gateSalt, HEAD_sha)` as a hidden marker into the PR body (and REFUSES to mint it unless\n * every BLOCK checklist passed), so a valid token IS proof the local gate ran and passed. A CI\n * check (`wp-check-pr` + the scaffolded workflow) recomputes it from the PR head sha and this salt.\n *\n * Optional, defaults to '' — empty means \"no token minted, no CI enforcement\" (byte-identical to\n * before this field existed). This is COMMITTED, obscurity-grade: it stops unhooked teammates who\n * push + open a PR in the web UI, but is readable in-repo and therefore forgeable by a determined\n * reader. It is deliberately NOT cryptographically sound; nothing local can stop a filesystem-reading\n * agent. See RESPONSE-pr-gate-ci-enforcement / the design memo for the full tradeoff.\n */\n gateSalt: string;\n /**\n * What `wp-land-pr` (and `wp-cleanup`, which reaps the same branches) does with the LOCAL branch\n * once its PR is in main. Field-with-default rather than another positional constructor param —\n * this constructor is already at the max-params limit, and every existing `new PrGateConfig(...)`\n * call site correctly wants the default.\n */\n landPr: LandPrConfig = defaultLandPrConfig();\n /**\n * Globs whose diffs are NOT extracted into `.webpieces/pr-review/<feature>/diff/` — regenerated noise a\n * reviewer should not spend context reading (lockfiles, generated graphs). Default [].\n *\n * They are still MATCHED against checklists and still listed in the manifest, with a stub naming the\n * command that gets the real diff. Removing them from the changed-file set would read as \"this file did\n * not change\", which is a different and false claim.\n *\n * Fields-with-defaults rather than constructor params: that constructor is already at max-params, and\n * every existing `new PrGateConfig(...)` correctly wants the defaults.\n */\n reviewDiffExclude: string[] = [];\n /**\n * Repo-specific places a reviewer would otherwise hunt for, as `{label, path}` — e.g.\n * `{\"label\":\"Cloud Tasks queue names\",\"path\":\"terraform/services/\"}`. Resolved to absolute paths in each\n * generated instructions file; a configured-but-missing path is printed as missing, never dropped.\n */\n reviewContext: ReviewContextEntry[] = [];\n /**\n * Installed packages to resolve and hand reviewers by absolute directory. This is the knob aimed at a\n * measured failure: one reviewer burned three separate greps into `node_modules/@webpieces` looking for\n * a scanner the tooling could have pointed at directly.\n */\n reviewContextPackages: string[] = [];\n /**\n * Promote \"this reviewer wrote a verdict without ever opening the diff\" from a warning to a refusal.\n * Default false, and it should stay false until a repo has watched the warning for a while: the signal\n * is derived from undocumented Claude Code transcript internals, so a format change would otherwise\n * wedge every PR in the repo with no self-service way out.\n */\n requireDiffEvidence = false;\n /**\n * Where `wp-push-dev` publishes the disposable copy. Omitted ⇒ `dev-include` / `dev`, which is what\n * makes the whole flow work with NO config edit at all.\n */\n devDeploy: DevDeployConfig = defaultDevDeployConfig();\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(mode: string, buildCommand: string, gates: GateDefinition[], mergeMode: string, checklists: ChecklistDefinition[] = [], gateSalt = '', checklistComments = true) {\n this.mode = mode;\n this.buildCommand = buildCommand;\n this.gates = gates;\n this.mergeMode = mergeMode;\n this.checklists = checklists;\n this.gateSalt = gateSalt;\n this.checklistComments = checklistComments;\n }\n}\n\n// Default infra gates — path-pattern based, tuned for this monorepo. Clients override the\n// whole list via the `pr-gate.gates` array in webpieces.config.json.\nexport function defaultGates(): GateDefinition[] {\n return [\n new GateDefinition('API Changed', ['libraries/apis/**', '**/*Api.ts'], 'yellow'),\n new GateDefinition('Config Files Changed', ['**/package.json', '**/tsconfig*.json', 'nx.json', '**/*.config.*'], 'yellow'),\n new GateDefinition('Dependency Graph Changed', ['architecture/dependencies.json'], 'yellow'),\n new GateDefinition('Claude / Rules Changed', ['**/CLAUDE.md', '**/claude.*.md', '.claude/**', 'webpieces.config.json'], 'yellow'),\n ];\n}\n\nexport function defaultPrGateConfig(): PrGateConfig {\n // No default checklists — the extension point is opt-in; the default monorepo ships none.\n return new PrGateConfig('ON', '', defaultGates(), MERGE_MODE_AUTO, []);\n}\n\ninterface RawGate {\n name?: string;\n patterns?: string[];\n warningColor?: string;\n disabled?: boolean;\n}\n\ninterface RawPrGateSection {\n mode?: string;\n buildCommand?: string;\n gates?: RawGate[];\n mergeMode?: string;\n // An ARRAY, always. validateChecklistsSection rejects every other shape (including the removed { doc }).\n checklists?: RawChecklistItem[];\n overrideReviewerAgent?: boolean;\n reviewerAgentName?: string;\n reviewerAgents?: number;\n maxReviewerRounds?: number;\n gateSalt?: string;\n checklistComments?: boolean;\n landPr?: RawLandPr;\n reviewDiffExclude?: string[];\n reviewContext?: RawReviewContext[];\n reviewContextPackages?: string[];\n requireDiffEvidence?: boolean;\n devDeploy?: RawDevDeploy;\n}\n\ninterface RawDevDeploy {\n branchNamespace?: string;\n devBranch?: string;\n}\n\ninterface RawLandPr {\n branchRetention?: string;\n}\n\ninterface RawReviewContext {\n label?: string;\n path?: string;\n}\n\nfunction toGate(raw: RawGate): GateDefinition {\n return new GateDefinition(raw.name ?? '', raw.patterns ?? [], raw.warningColor ?? 'yellow', raw.disabled ?? false);\n}\n\n/**\n * Build a PrGateConfig from the already-parsed top-level `pr-gate` section, falling back to defaults\n * for any field the consumer omits. Pure transform — the file read + structural validation happen in\n * loadAndValidate (load-config.ts) so every consumer goes through one validated path. Pass undefined\n * (no `pr-gate` key / no config file) to get full defaults.\n */\n// webpieces-disable no-any-unknown -- `section` is opaque consumer JSON until narrowed here\nexport function buildPrGateConfig(section: unknown): PrGateConfig {\n const defaults = defaultPrGateConfig();\n if (section === undefined || section === null || typeof section !== 'object') return defaults;\n\n const raw = section as RawPrGateSection;\n const mode = raw.mode ?? defaults.mode;\n const buildCommand = raw.buildCommand ?? defaults.buildCommand;\n const gates = raw.gates !== undefined ? raw.gates.map(toGate) : defaults.gates;\n // REQUIRED — validatePrGateSection rejects an omitted/unknown value, so this fallback only ever\n // applies to the no-config-file path that defaultPrGateConfig() serves.\n const mergeMode = raw.mergeMode ?? defaults.mergeMode;\n // Optional extension point — omitted ⇒ [] ⇒ no checklists computed anywhere downstream. A non-array here\n // cannot reach us: validateChecklistsSection has already failed the load.\n // The webpieces reviewer unless `overrideReviewerAgent` is true, in which case `reviewerAgentName` names the\n // agent (validatePrGateSection rejects a name without the override, and the override without a name).\n // Required nonnegative integer: 0 disables reviewer-agent reviews; positive values cap the round.\n const agentName = raw.overrideReviewerAgent === true\n ? (raw.reviewerAgentName ?? '').trim()\n : DEFAULT_REVIEWER_AGENT_NAME;\n // `reviewerAgents` is REQUIRED and validated as a nonnegative integer before this runs, so the fallback is\n // unreachable in a loaded config and exists only to keep this total for a structure-only caller.\n const reviewer = new ReviewerAgentPolicy(\n agentName,\n typeof raw.reviewerAgents === 'number' ? raw.reviewerAgents : REVIEWER_AGENTS_PLACEHOLDER);\n const checklists = Array.isArray(raw.checklists)\n ? raw.checklists.map((item: RawChecklistItem): ChecklistDefinition => toChecklist(item, reviewer))\n : defaults.checklists;\n // Optional — omitted ⇒ '' ⇒ no gate token minted and CI enforcement is a no-op (back-compat).\n const gateSalt = raw.gateSalt ?? defaults.gateSalt;\n // Optional — omitted ⇒ true ⇒ reviewer output published as a PR comment.\n const checklistComments = raw.checklistComments ?? defaults.checklistComments;\n const built = new PrGateConfig(mode, buildCommand, gates, mergeMode, checklists, gateSalt, checklistComments);\n built.landPr = buildLandPrConfig(raw.landPr);\n built.reviewer = reviewer;\n built.maxReviewerRounds = raw.maxReviewerRounds as number;\n // Review-context knobs. All optional and all defaulted, so a config that omits every one of them (which\n // is every consumer's config today) behaves exactly as it did before they existed.\n built.reviewDiffExclude = Array.isArray(raw.reviewDiffExclude) ? raw.reviewDiffExclude : defaults.reviewDiffExclude;\n built.reviewContextPackages = Array.isArray(raw.reviewContextPackages) ? raw.reviewContextPackages : defaults.reviewContextPackages;\n built.reviewContext = Array.isArray(raw.reviewContext)\n ? raw.reviewContext.map((e: RawReviewContext): ReviewContextEntry => new ReviewContextEntry(e.label ?? '', e.path ?? ''))\n : defaults.reviewContext;\n built.requireDiffEvidence = raw.requireDiffEvidence ?? defaults.requireDiffEvidence;\n built.devDeploy = buildDevDeployConfig(raw.devDeploy);\n return built;\n}\n\n/**\n * Build the `pr-gate.devDeploy` block. Omitted (the state of every consumer config today) ⇒ the\n * `dev-include` / `dev` defaults. An invalid value cannot reach here — validateDevDeploySection has\n * already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildDevDeployConfig(raw: RawDevDeploy | undefined): DevDeployConfig {\n const defaults = defaultDevDeployConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const namespace = typeof raw.branchNamespace === 'string' && raw.branchNamespace.trim() !== ''\n ? raw.branchNamespace.trim() : defaults.branchNamespace;\n const devBranch = typeof raw.devBranch === 'string' && raw.devBranch.trim() !== ''\n ? raw.devBranch.trim() : defaults.devBranch;\n return new DevDeployConfig(namespace, devBranch);\n}\n\n/**\n * Build the `pr-gate.landPr` block. Omitted (the current state of every consumer's config) ⇒ the\n * 'archive-tag' default, which is what makes this feature work with NO config edit at all. An invalid\n * value cannot reach here — validatePrGateSection has already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildLandPrConfig(raw: RawLandPr | undefined): LandPrConfig {\n const defaults = defaultLandPrConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const retention = raw.branchRetention;\n if (typeof retention !== 'string' || !BRANCH_RETENTIONS.includes(retention)) return defaults;\n return new LandPrConfig(retention);\n}\n"]}
1
+ {"version":3,"file":"pr-gate-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/pr-gate-config.ts"],"names":[],"mappings":";;;AA2FA,kDAEC;AAgDD,wDAEC;AAwID,oCAmBC;AAED,kDAGC;AA4DD,8CAgEC;AAQD,oDAYC;AAQD,8CAMC;AA7cD,uDAAoF;AACpF,yDAO4B;AAE5B,2FAA2F;AAC3F,2FAA2F;AAC3F,iFAAiF;AACjF,iGAAiG;AAEjG;;;;;;;;;;;GAWG;AACU,QAAA,qBAAqB,GAC9B,wEAAwE,CAAC;AAE7E,MAAa,cAAc;IACvB,IAAI,CAAS;IACb,QAAQ,CAAW;IACnB,iGAAiG;IACjG,8FAA8F;IAC9F,+FAA+F;IAC/F,gGAAgG;IAChG,YAAY,C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GAA0B;IACxD,MAAM,QAAQ,GAAG,mBAAmB,EAAE,CAAC;IACvC,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAClF,MAAM,SAAS,GAAG,GAAG,CAAC,eAAe,CAAC;IACtC,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,mCAAiB,CAAC,QAAQ,CAAC,SAAS,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC7F,OAAO,IAAI,YAAY,CAAC,SAAS,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { BRANCH_RETENTION_ARCHIVE_TAG, BRANCH_RETENTIONS } from './branch-archiver';\nimport {\n ChecklistDefinition,\n DEFAULT_REVIEWER_AGENT_NAME,\n RawChecklistItem,\n REVIEWER_AGENTS_PLACEHOLDER,\n ReviewerAgentPolicy,\n toChecklist,\n} from './checklist-config';\n\n// PrGateConfig is the \"special section\" for the pr-gate dashboard. It does NOT live in the\n// validated `rules` map (the FieldDef schema can't express nested object arrays), but as a\n// top-level `pr-gate` key in webpieces.config.json. It is built and validated by\n// loadAndValidate (load-config.ts); this module holds only the data classes + defaults + toGate.\n\n/**\n * The build the pr-gate runs when a repo configures no `commands.pr-gate.buildCommand` — and the ONE\n * definition of it, because two things now need it: the gate that RUNS it (pr-gate's BuildAffected)\n * and the guard that REFUSES a whole-monorepo build and prints it instead (ai-hook-rules'\n * whole-repo-build-guard). A second copy in either package is a message that can teach a command the\n * gate does not run.\n *\n * `--base=$(git merge-base origin/main HEAD)` — the FORK POINT, not `origin/main`: basing on\n * origin/main marks projects touched by other people's already-merged PRs as affected. The `$(…)`\n * resolves because the gate spawns with `shell: true`; the guard resolves it itself before printing,\n * so the AI is never handed a template it might paste somewhere without a shell.\n */\nexport const DEFAULT_BUILD_COMMAND =\n 'pnpm nx affected --target=ci --base=$(git merge-base origin/main HEAD)';\n\nexport class GateDefinition {\n name: string;\n patterns: string[];\n // The warning color shown on the dashboard WHEN this gate's patterns match a changed file. Green\n // is implicit (shown when nothing matched), so it is never configured. warningColor is purely\n // visual — even 'red' never fails/blocks the PR (only the build gate can). 'yellow' = caution,\n // 'red' = louder \"look here\" flag (e.g. DB schema / migration changes). REQUIRED on every gate.\n warningColor: string; // 'yellow' | 'red'\n // Example/inactive gate: parsed and kept in the file (JSON has no comments) but skipped at\n // compute/render time. Other projects flip this to false and tune patterns/warningColor.\n disabled: boolean;\n\n constructor(name: string, patterns: string[], warningColor: string, disabled = false) {\n this.name = name;\n this.patterns = patterns;\n this.warningColor = warningColor;\n this.disabled = disabled;\n }\n}\n\n// How wp-finish-upsert-pr should try to LAND the PR once it has posted it. GitHub's auto-merge queue\n// is a REPO-level setting (`allow_auto_merge`) that many orgs turn OFF as a policy control, and it\n// CANNOT be forced from the client: `gh pr merge --auto` calls the enablePullRequestAutoMerge GraphQL\n// mutation, which hard-errors with \"Auto merge is not allowed for this repository\" when the repo says\n// no. So the only lever a config knob has is WHICH PATHS WE ATTEMPT — never whether the queue exists.\nexport const MERGE_MODE_AUTO = 'AUTO';\nexport const MERGE_MODE_NONE = 'NONE';\nexport const MERGE_MODES = [MERGE_MODE_AUTO, MERGE_MODE_NONE];\n\n/**\n * `pr-gate.landPr` — what happens to the LOCAL branch once its PR has landed.\n *\n * A rich object rather than a bare string (the `commands.pr-gate` precedent) so the next knob about\n * landing has a home, and so the rationale can sit beside the setting as a `*Why` sibling: JSON has no\n * comments, and `<key>Why` is how this repo documents non-obvious config.\n */\n/**\n * One `pr-gate.reviewContext` entry: a human label and a repo-relative path a reviewer is handed instead of\n * having to find it. Data-only (per CLAUDE.md).\n */\nexport class ReviewContextEntry {\n label: string;\n path: string; // repo-relative in config; resolved to absolute when written into an instructions file\n\n constructor(label: string, entryPath: string) {\n this.label = label;\n this.path = entryPath;\n }\n}\n\nexport class LandPrConfig {\n // One of BRANCH_RETENTIONS. Defaults to 'archive-tag' — see BranchArchiver for why a tag beats\n // keeping the branch, storing a patch, or trusting the reflog.\n branchRetention: string;\n\n constructor(branchRetention: string = BRANCH_RETENTION_ARCHIVE_TAG) {\n this.branchRetention = branchRetention;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultLandPrConfig(): LandPrConfig {\n return new LandPrConfig(BRANCH_RETENTION_ARCHIVE_TAG);\n}\n\n// The two literal ref names the dev-deploy flow derives everything else from. Defaults, not policy —\n// `pr-gate.devDeploy` overrides both, because a consumer whose shared environment is called `staging`\n// must not be forced onto webpieces' vocabulary.\nexport const DEFAULT_DEV_BRANCH_NAMESPACE = 'dev-include';\nexport const DEFAULT_DEV_BRANCH = 'dev';\n\n/**\n * `pr-gate.devDeploy` — where `wp-push-dev` publishes the throwaway copy of a feature branch, and which\n * ref is the shared dev branch itself.\n *\n * WHY A NAMESPACE AT ALL, i.e. why the copy is not just the feature branch: the feature branch is the PR\n * head, and landing that PR ships whatever is on it. The moment a conflict between two devs has to be\n * resolved SOMEWHERE for the shared environment to build, that resolution needs a home that is not the PR\n * branch — otherwise \"test it in dev\" silently ships another dev's unreviewed work to production. The\n * `<branchNamespace>/<feature>` copy is that home, and it is disposable by construction.\n *\n * `devBranch` is REFUSED as a source branch (you never push the composed branch back into itself); it is\n * written by the consumer's CI only, which recomputes it from `origin/main` on every run.\n */\nexport class DevDeployConfig {\n // Literal prefix on the feature branch name: `dev-include/dean/ONE-2275`. Git refs allow slashes, and\n // nobody ever types this — the command derives it.\n branchNamespace: string;\n // The composed, CI-owned branch that actually deploys. Never a source, never pushed to by this flow.\n devBranch: string;\n\n constructor(\n branchNamespace: string = DEFAULT_DEV_BRANCH_NAMESPACE,\n devBranch: string = DEFAULT_DEV_BRANCH,\n ) {\n this.branchNamespace = branchNamespace;\n this.devBranch = devBranch;\n }\n\n /** `<branchNamespace>/<branch>` — the remote ref holding the disposable copy of `branch`. */\n copyRefFor(branch: string): string {\n return `${this.branchNamespace}/${branch}`;\n }\n\n /** The `git ls-remote --heads origin <pattern>` pattern matching every live copy. */\n copyRefGlob(): string {\n return `${this.branchNamespace}/*`;\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-level config default, matches defaultGates/defaultPrGateConfig in this file\nexport function defaultDevDeployConfig(): DevDeployConfig {\n return new DevDeployConfig(DEFAULT_DEV_BRANCH_NAMESPACE, DEFAULT_DEV_BRANCH);\n}\n\nexport class PrGateConfig {\n mode: string;\n /**\n * The nx-affected build gate command, shared by the two commands that can run it.\n *\n * It is NOT finish-only any more, and the change is the point. It used to run once, in\n * wp-finish-upsert-pr, which meant reviewers were spawned against a branch nobody had built — they could\n * spend a full review on code that does not compile, or on an unresolved 3-point merge.\n *\n * Now `wp-review-upsert-pr` finalizes the merge and runs this gate BEFORE briefing any reviewer, and\n * records the passing HEAD sha in the stage receipt. `wp-finish-upsert-pr` re-runs it only when HEAD has\n * moved since — so the flow gained a gate where it mattered without paying for two full builds.\n *\n * Empty string => BuildAffected falls back to DEFAULT_BUILD_COMMAND.\n */\n buildCommand: string;\n gates: GateDefinition[];\n /**\n * REQUIRED — every repo must state its policy; there is deliberately no default, because the two\n * answers are a real policy decision and guessing it either merges when a team did not want that,\n * or silently stops landing PRs on a team that relied on it.\n *\n * AUTO — wp-finish-upsert-pr LANDS the PR: squash-merge it right away when it is mergeable, else\n * enable GitHub auto-merge so it lands when the checks pass. Both carry an explicit --subject /\n * --body-file, which is the ONLY way main's history gets the PR title plus the compact\n * risk/flags body — no repo setting can produce that. Requires allow_auto_merge on the repo.\n * NONE — wp-finish-upsert-pr only opens/updates the PR and stops; a human merges. NOTE the cost:\n * a UI merge cannot use the compact body, so main's commit falls back to the repo's\n * squash_merge_commit_title/message settings. Set squash_merge_commit_title=PR_TITLE there, or\n * commits land as the internal \"Squash merge of <branch>\" subject.\n */\n mergeMode: string;\n // This repo's review checklists, straight from the `pr-gate.checklists` ARRAY in webpieces.config.json —\n // the ONLY accepted shape (`patterns` is a path-glob dispatch table and `id` the checklist's name, so both\n // are config). Every def carries {@link reviewer}. [] = no checklists. The removed `{ doc }` manifest\n // form is a hard config error; see validateChecklistsSection.\n checklists: ChecklistDefinition[];\n /**\n * The ONE agent type every checklist is reviewed by — `webpieces-reviewer` unless\n * `overrideReviewerAgent` is true, in which case `reviewerAgentName` — and `reviewerAgents`, the most such\n * subagents a round may use. The same instance is bound into every {@link checklists} entry, so a caller\n * holding only a checklist still knows what to spawn. Field-with-default because the constructor is at\n * max-params; the agent name defaults to the webpieces reviewer, exactly what a config that says nothing\n * gets, while the CAP is a required field, so the placeholder here is only ever overwritten by the real\n * number buildPrGateConfig reads.\n */\n reviewer: ReviewerAgentPolicy = new ReviewerAgentPolicy(DEFAULT_REVIEWER_AGENT_NAME, REVIEWER_AGENTS_PLACEHOLDER);\n /**\n * REQUIRED positive integer: the maximum number of complete global reviewer rounds a PR review state\n * may start. This is deliberately repository policy rather than a machine-local preference.\n */\n maxReviewerRounds!: number;\n // Whether wp-finish-upsert-pr publishes each reviewer's full `output` as ONE combined PR comment\n // (idempotently updated on every push). Defaults to true. Set false to keep the PR body-only.\n checklistComments: boolean;\n /**\n * Shared secret used to mint the server-verifiable gate token. `wp-finish-upsert-pr` writes it after\n * the automated gate passes; `wp-human-post-pr` writes the same token after explicit human attestation\n * and visibly labels review as skipped plus whether its optional local build ran. A CI check\n * recomputes it from the PR head + salt.\n *\n * Optional, defaults to '' — empty means \"no token minted, no CI enforcement\" (byte-identical to\n * before this field existed). This is COMMITTED, obscurity-grade: it stops unhooked teammates who\n * push + open a PR in the web UI, but is readable in-repo and therefore forgeable by a determined\n * reader. It is deliberately NOT cryptographically sound; nothing local can stop a filesystem-reading\n * agent. See RESPONSE-pr-gate-ci-enforcement / the design memo for the full tradeoff.\n */\n gateSalt: string;\n /**\n * What `wp-land-pr` (and `wp-cleanup`, which reaps the same branches) does with the LOCAL branch\n * once its PR is in main. Field-with-default rather than another positional constructor param —\n * this constructor is already at the max-params limit, and every existing `new PrGateConfig(...)`\n * call site correctly wants the default.\n */\n landPr: LandPrConfig = defaultLandPrConfig();\n /**\n * Globs whose diffs are NOT extracted into `.webpieces/pr-review/<feature>/diff/` — regenerated noise a\n * reviewer should not spend context reading (lockfiles, generated graphs). Default [].\n *\n * They are still MATCHED against checklists and still listed in the manifest, with a stub naming the\n * command that gets the real diff. Removing them from the changed-file set would read as \"this file did\n * not change\", which is a different and false claim.\n *\n * Fields-with-defaults rather than constructor params: that constructor is already at max-params, and\n * every existing `new PrGateConfig(...)` correctly wants the defaults.\n */\n reviewDiffExclude: string[] = [];\n /**\n * Repo-specific places a reviewer would otherwise hunt for, as `{label, path}` — e.g.\n * `{\"label\":\"Cloud Tasks queue names\",\"path\":\"terraform/services/\"}`. Resolved to absolute paths in each\n * generated instructions file; a configured-but-missing path is printed as missing, never dropped.\n */\n reviewContext: ReviewContextEntry[] = [];\n /**\n * Installed packages to resolve and hand reviewers by absolute directory. This is the knob aimed at a\n * measured failure: one reviewer burned three separate greps into `node_modules/@webpieces` looking for\n * a scanner the tooling could have pointed at directly.\n */\n reviewContextPackages: string[] = [];\n /**\n * Promote \"this reviewer wrote a verdict without ever opening the diff\" from a warning to a refusal.\n * Default false, and it should stay false until a repo has watched the warning for a while: the signal\n * is derived from undocumented Claude Code transcript internals, so a format change would otherwise\n * wedge every PR in the repo with no self-service way out.\n */\n requireDiffEvidence = false;\n /**\n * Where `wp-push-dev` publishes the disposable copy. Omitted ⇒ `dev-include` / `dev`, which is what\n * makes the whole flow work with NO config edit at all.\n */\n devDeploy: DevDeployConfig = defaultDevDeployConfig();\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n mode: string,\n buildCommand: string,\n gates: GateDefinition[],\n mergeMode: string,\n checklists: ChecklistDefinition[] = [],\n gateSalt = '',\n checklistComments = true,\n ) {\n this.mode = mode;\n this.buildCommand = buildCommand;\n this.gates = gates;\n this.mergeMode = mergeMode;\n this.checklists = checklists;\n this.gateSalt = gateSalt;\n this.checklistComments = checklistComments;\n }\n}\n\n// Default infra gates — path-pattern based, tuned for this monorepo. Clients override the\n// whole list via the `pr-gate.gates` array in webpieces.config.json.\nexport function defaultGates(): GateDefinition[] {\n return [\n new GateDefinition('API Changed', ['libraries/apis/**', '**/*Api.ts'], 'yellow'),\n new GateDefinition(\n 'Config Files Changed',\n ['**/package.json', '**/tsconfig*.json', 'nx.json', '**/*.config.*'],\n 'yellow',\n ),\n new GateDefinition(\n 'Dependency Graph Changed',\n ['architecture/dependencies.json'],\n 'yellow',\n ),\n new GateDefinition(\n 'Claude / Rules Changed',\n ['**/CLAUDE.md', '**/claude.*.md', '.claude/**', 'webpieces.config.json'],\n 'yellow',\n ),\n ];\n}\n\nexport function defaultPrGateConfig(): PrGateConfig {\n // No default checklists — the extension point is opt-in; the default monorepo ships none.\n return new PrGateConfig('ON', '', defaultGates(), MERGE_MODE_AUTO, []);\n}\n\ninterface RawGate {\n name?: string;\n patterns?: string[];\n warningColor?: string;\n disabled?: boolean;\n}\n\ninterface RawPrGateSection {\n mode?: string;\n buildCommand?: string;\n gates?: RawGate[];\n mergeMode?: string;\n // An ARRAY, always. validateChecklistsSection rejects every other shape (including the removed { doc }).\n checklists?: RawChecklistItem[];\n overrideReviewerAgent?: boolean;\n reviewerAgentName?: string;\n reviewerAgents?: number;\n maxReviewerRounds?: number;\n gateSalt?: string;\n checklistComments?: boolean;\n landPr?: RawLandPr;\n reviewDiffExclude?: string[];\n reviewContext?: RawReviewContext[];\n reviewContextPackages?: string[];\n requireDiffEvidence?: boolean;\n devDeploy?: RawDevDeploy;\n}\n\ninterface RawDevDeploy {\n branchNamespace?: string;\n devBranch?: string;\n}\n\ninterface RawLandPr {\n branchRetention?: string;\n}\n\ninterface RawReviewContext {\n label?: string;\n path?: string;\n}\n\nfunction toGate(raw: RawGate): GateDefinition {\n return new GateDefinition(\n raw.name ?? '',\n raw.patterns ?? [],\n raw.warningColor ?? 'yellow',\n raw.disabled ?? false,\n );\n}\n\n/**\n * Build a PrGateConfig from the already-parsed top-level `pr-gate` section, falling back to defaults\n * for any field the consumer omits. Pure transform — the file read + structural validation happen in\n * loadAndValidate (load-config.ts) so every consumer goes through one validated path. Pass undefined\n * (no `pr-gate` key / no config file) to get full defaults.\n */\n// webpieces-disable no-any-unknown -- `section` is opaque consumer JSON until narrowed here\nexport function buildPrGateConfig(section: unknown): PrGateConfig {\n const defaults = defaultPrGateConfig();\n if (section === undefined || section === null || typeof section !== 'object') return defaults;\n\n const raw = section as RawPrGateSection;\n const mode = raw.mode ?? defaults.mode;\n const buildCommand = raw.buildCommand ?? defaults.buildCommand;\n const gates = raw.gates !== undefined ? raw.gates.map(toGate) : defaults.gates;\n // REQUIRED — validatePrGateSection rejects an omitted/unknown value, so this fallback only ever\n // applies to the no-config-file path that defaultPrGateConfig() serves.\n const mergeMode = raw.mergeMode ?? defaults.mergeMode;\n // Optional extension point — omitted ⇒ [] ⇒ no checklists computed anywhere downstream. A non-array here\n // cannot reach us: validateChecklistsSection has already failed the load.\n // The webpieces reviewer unless `overrideReviewerAgent` is true, in which case `reviewerAgentName` names the\n // agent (validatePrGateSection rejects a name without the override, and the override without a name).\n // Required nonnegative integer: 0 disables reviewer-agent reviews; positive values cap the round.\n const agentName =\n raw.overrideReviewerAgent === true\n ? (raw.reviewerAgentName ?? '').trim()\n : DEFAULT_REVIEWER_AGENT_NAME;\n // `reviewerAgents` is REQUIRED and validated as a nonnegative integer before this runs, so the fallback is\n // unreachable in a loaded config and exists only to keep this total for a structure-only caller.\n const reviewer = new ReviewerAgentPolicy(\n agentName,\n typeof raw.reviewerAgents === 'number' ? raw.reviewerAgents : REVIEWER_AGENTS_PLACEHOLDER,\n );\n const checklists = Array.isArray(raw.checklists)\n ? raw.checklists.map(\n (item: RawChecklistItem): ChecklistDefinition => toChecklist(item, reviewer),\n )\n : defaults.checklists;\n // Optional — omitted ⇒ '' ⇒ no gate token minted and CI enforcement is a no-op (back-compat).\n const gateSalt = raw.gateSalt ?? defaults.gateSalt;\n // Optional — omitted ⇒ true ⇒ reviewer output published as a PR comment.\n const checklistComments = raw.checklistComments ?? defaults.checklistComments;\n const built = new PrGateConfig(\n mode,\n buildCommand,\n gates,\n mergeMode,\n checklists,\n gateSalt,\n checklistComments,\n );\n built.landPr = buildLandPrConfig(raw.landPr);\n built.reviewer = reviewer;\n built.maxReviewerRounds = raw.maxReviewerRounds as number;\n // Review-context knobs. All optional and all defaulted, so a config that omits every one of them (which\n // is every consumer's config today) behaves exactly as it did before they existed.\n built.reviewDiffExclude = Array.isArray(raw.reviewDiffExclude)\n ? raw.reviewDiffExclude\n : defaults.reviewDiffExclude;\n built.reviewContextPackages = Array.isArray(raw.reviewContextPackages)\n ? raw.reviewContextPackages\n : defaults.reviewContextPackages;\n built.reviewContext = Array.isArray(raw.reviewContext)\n ? raw.reviewContext.map(\n (e: RawReviewContext): ReviewContextEntry =>\n new ReviewContextEntry(e.label ?? '', e.path ?? ''),\n )\n : defaults.reviewContext;\n built.requireDiffEvidence = raw.requireDiffEvidence ?? defaults.requireDiffEvidence;\n built.devDeploy = buildDevDeployConfig(raw.devDeploy);\n return built;\n}\n\n/**\n * Build the `pr-gate.devDeploy` block. Omitted (the state of every consumer config today) ⇒ the\n * `dev-include` / `dev` defaults. An invalid value cannot reach here — validateDevDeploySection has\n * already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildDevDeployConfig(raw: RawDevDeploy | undefined): DevDeployConfig {\n const defaults = defaultDevDeployConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const namespace =\n typeof raw.branchNamespace === 'string' && raw.branchNamespace.trim() !== ''\n ? raw.branchNamespace.trim()\n : defaults.branchNamespace;\n const devBranch =\n typeof raw.devBranch === 'string' && raw.devBranch.trim() !== ''\n ? raw.devBranch.trim()\n : defaults.devBranch;\n return new DevDeployConfig(namespace, devBranch);\n}\n\n/**\n * Build the `pr-gate.landPr` block. Omitted (the current state of every consumer's config) ⇒ the\n * 'archive-tag' default, which is what makes this feature work with NO config edit at all. An invalid\n * value cannot reach here — validatePrGateSection has already failed the load.\n */\n// webpieces-disable no-function-outside-class -- module-level config transform, matches buildPrGateConfig above\nexport function buildLandPrConfig(raw: RawLandPr | undefined): LandPrConfig {\n const defaults = defaultLandPrConfig();\n if (raw === undefined || raw === null || typeof raw !== 'object') return defaults;\n const retention = raw.branchRetention;\n if (typeof retention !== 'string' || !BRANCH_RETENTIONS.includes(retention)) return defaults;\n return new LandPrConfig(retention);\n}\n"]}
@@ -125,9 +125,10 @@ class ChecklistReviewContext {
125
125
  }
126
126
  }
127
127
  exports.ChecklistReviewContext = ChecklistReviewContext;
128
- // The AI-authored PR summary (title, risk, summary). The AI writes summary.json itself between `wp-start-upsert-pr` (which
129
- // prints the schema) and `wp-finish-upsert-pr` (which reads it); reviewer subagents write the per-checklist
130
- // review-<id>.json files. Data-only (per CLAUDE.md).
128
+ // The AI-authored PR summary (title, risk, summary). Normally the AI writes summary.json between
129
+ // `wp-start-upsert-pr` (which prints the schema) and `wp-finish-upsert-pr` (which reads it), while reviewer
130
+ // subagents write review-<id>.json. The human-only `wp-human-post-pr` escape hatch also requires and reads
131
+ // this same summary shape, but deliberately skips reviewer verdicts. Data-only (per CLAUDE.md).
131
132
  class PrSummary {
132
133
  agent;
133
134
  model;
@@ -1 +1 @@
1
- {"version":3,"file":"review-json-data.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/review-json-data.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAKH,qGAAqG;AACrG,yGAAyG;AACzG,0GAA0G;AAC1G,4EAA4E;AAC/D,QAAA,aAAa,GAAG,OAAO,CAAC;AACxB,QAAA,cAAc,GAAG,QAAQ,CAAC;AAC1B,QAAA,WAAW,GAAG,KAAK,CAAC;AACpB,QAAA,gBAAgB,GAAG,CAAC,qBAAa,EAAE,sBAAc,EAAE,mBAAW,CAAU,CAAC;AAEtF,6GAA6G;AAC7G,sGAAsG;AACtG,gCAAgC;AAChC,gDAAgD;AACh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,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACnC,CAAC;CACJ;AAzCD,8BAyCC","sourcesContent":["/**\n * The DATA-ONLY classes and status constants of the PR review system — the verdict a reviewer writes, the\n * checklist that demanded it, the resolved outcome, and the diff context handed to reviewers.\n *\n * Split out of review-json.ts, which holds the SERVICE that reads and writes them. The split is purely by\n * kind (data vs behaviour): review-json.ts re-exports every name below, so `from './review-json'` and\n * `from '@webpieces/rules-config'` keep resolving exactly as before and no consumer changes.\n */\n\nimport { ReviewerAgentPolicy } from './checklist-config';\nimport { ChecklistOverride } from './checklist-override';\n\n// The three colors a reviewer subagent may report in `review-<id>.json`. A TRI-state, not a boolean,\n// because the boolean it replaced gave a reviewer no way to say \"this passes, but a human should look at\n// X\" — the only way to raise a concern was to FAIL the PR and then override your own failure, which reads\n// on the dashboard as a deliberately-accepted defect rather than as a note.\nexport const VERDICT_GREEN = 'green';\nexport const VERDICT_YELLOW = 'yellow';\nexport const VERDICT_RED = 'red';\nexport const VERDICT_STATUSES = [VERDICT_GREEN, VERDICT_YELLOW, VERDICT_RED] as const;\n\n// The verdict a reviewer SUBAGENT writes into `.webpieces/pr-review/<featureSlug>/review-<id>.json`, one per\n// matched checklist. One file per checklist so N concurrent reviewer subagents never clobber a shared\n// file. It records the OUTCOME:\n// status:'green' → PASS\n// status:'yellow' → WARN (passes; the concern is published on the PR, nothing is blocked)\n// status:'red' + an override-<id>.json → OVERRIDDEN (pass; the human's stated reason reaches the PR)\n// status:'red' + no override file → FAIL (refuse; `output` is printed verbatim)\n//\n// THE `override` FIELD IS GONE FROM THIS FILE, and there is no compatibility mode. The ship-anyway\n// justification used to live here as free text, which made the ONE participant who hears the human — the\n// coordinating agent — the one participant that could not record it, because editing a reviewer's verdict\n// file is (correctly) refused by the harness. It now lives in its own `override-<id>.json`; see\n// ChecklistOverride. A verdict file still carrying an `override` key is reported through `problem` with the\n// destination named, exactly as the removed `success` field is. Data-only (per CLAUDE.md).\nexport class ChecklistResult {\n agent: string;\n model: string;\n id: string;\n status: string; // one of VERDICT_STATUSES; anything else is reported via `problem`\n output: string; // what the reviewer found; printed verbatim when the checklist fails\n // The HUMAN's authorization loaded from `override-<id>.json` beside this verdict, or null when there is\n // none. Loaded alongside the verdict so `resolveVerdict` needs no second read of disk and every command\n // resolves the same outcome from the same bytes.\n override: ChecklistOverride | null;\n // '' = a well-formed verdict. Non-empty = the file exists and parses but its verdict cannot be READ\n // (most often: it still uses the removed `success` field, or the moved `override` field). Carried as\n // data rather than thrown so the complaint can be reported by BOTH wp-review-upsert-pr and\n // wp-finish-upsert-pr in identical words, and so a legacy file is never silently mistaken for a missing one.\n problem: string;\n /** Non-empty only when a valid SHA-bound author remediation resolves this red after the round cap. */\n remediation: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(agent: string, model: string, id: string, status: string, output: string, override: ChecklistOverride | null, problem = '') {\n this.agent = agent;\n this.model = model;\n this.id = id;\n this.status = status;\n this.output = output;\n this.override = override;\n this.problem = problem;\n this.remediation = '';\n }\n}\n\n/**\n * What the pr-gate command computed from the diff: a checklist this branch MATCHED (its patterns hit the\n * diff, so its reviewer subagent is in scope). Drives review-<id>.json enforcement, provenance, the schema\n * hint, and the dashboard. Data-only.\n *\n * NAME NOTE: \"Required\" here means MATCHED, not mandatory — it predates `required` by a long way and is\n * the shared shape across review-json, the detector, the briefing builder, provenance and the dashboard.\n * Whether the reviewer must actually run is the {@link RequiredChecklist.required} field below.\n */\nexport class RequiredChecklist {\n id: string; // the checklist's name; keys review-<id>.json and its instructions file\n reviewer: ReviewerAgentPolicy; // the agent type to spawn (agentType the harness stamps) + the round cap\n doc: string; // REPO-RELATIVE guidance doc the reviewer reads ('' → it just reads the diff)\n matchedFiles: string[]; // the changed files that matched it (for the dashboard + hint)\n // Which of the checklist's OWN globs actually fired. Printed so a reviewer can judge how coarse the\n // match was — a precise `db/migrations/**` hit means something different from a blanket `**` — and the\n // template tells reviewers that matching IS deliberately coarse. [] = no patterns (matches every PR).\n matchedPatterns: string[];\n // Straight from the checklist's config `required`. true = blocking; false = the human is offered it and\n // may decline. Carried on the MATCH rather than looked up from config downstream so the set that gates\n // and the set that is reported cannot disagree about which of the two a checklist is.\n required: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n id: string, reviewer: ReviewerAgentPolicy, doc: string, matchedFiles: string[], matchedPatterns: string[] = [],\n // Defaulted to the BLOCKING value so any construction that forgets it fails closed — a test or a\n // future call site that silently produced an optional checklist would be a hole in the gate.\n required = true,\n ) {\n this.id = id;\n this.reviewer = reviewer;\n this.doc = doc;\n this.matchedFiles = matchedFiles;\n this.matchedPatterns = matchedPatterns;\n this.required = required;\n }\n}\n\n/**\n * The per-PR facts every reviewer subagent needs GIVEN to it, alongside its own checklist: the exact base\n * sha the gate diffs against and the file holding the complete changed-file set. Both used to live only in\n * a doc the printed instruction told the AI to go read, one indirection away from the instruction to hand\n * them over — so the printed block could not stand on its own. Data-only; empty = omit those lines.\n */\nexport class ChecklistReviewContext {\n baseSha: string; // the 3-point merge-base sha\n prContextPath: string; // path of pr-context.json — the AUTHORITATIVE full changed-file set\n /**\n * The exact command that reproduces ONE file's diff, with a `-- <file>` tail — NOT assembled by the\n * caller. This used to be hardcoded as `git diff <baseSha> HEAD -- <file>`, which returns NOTHING on a\n * dirty tree because the changed-file set is computed base→working-tree. See DiffBasis, which derives\n * this string from the same range the file set came from.\n */\n fileDiffCommand: string;\n diffDir: string; // dir of the MATERIALIZED diff (diff/ALL.diff + diff/files/…); '' when not written\n dirty: boolean; // true ⇒ the range includes uncommitted + untracked work, and must be said out loud\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(baseSha = '', prContextPath = '', fileDiffCommand = '', diffDir = '', dirty = false) {\n this.baseSha = baseSha;\n this.prContextPath = prContextPath;\n this.fileDiffCommand = fileDiffCommand;\n this.diffDir = diffDir;\n this.dirty = dirty;\n }\n}\n\n// The AI-authored PR summary (title, risk, summary). The AI writes summary.json itself between `wp-start-upsert-pr` (which\n// prints the schema) and `wp-finish-upsert-pr` (which reads it); reviewer subagents write the per-checklist\n// review-<id>.json files. Data-only (per CLAUDE.md).\nexport class PrSummary {\n agent: string;\n model: string;\n title: string; // human PR title describing the change; used as the `gh pr` title (empty → caller falls back)\n riskScore: number; // 0–100, drives the risk bar\n riskLevel: string; // 'green' | 'yellow' | 'red'\n riskEmoji: string; // '🟢' | '🟡' | '🔴' — derived from riskLevel when omitted\n summary: string; // rendered in the dashboard Summary section\n violations: string[]; // pattern/architecture violations; length = the Pattern Violations count\n risks: string[];\n filesToReview: string[];\n results: ChecklistResult[]; // resolved per-checklist verdicts (from review-<id>.json); [] when none\n mainAgentInstructions: string; // non-empty only for the opt-in single-round experiment\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(agent: string, model: string,\n title: string,\n riskScore: number,\n riskLevel: string,\n riskEmoji: string,\n summary: string,\n violations: string[],\n risks: string[],\n filesToReview: string[],\n results: ChecklistResult[] = [],\n mainAgentInstructions = '',\n ) {\n this.agent = agent;\n this.model = model;\n this.title = title;\n this.riskScore = riskScore;\n this.riskLevel = riskLevel;\n this.riskEmoji = riskEmoji;\n this.summary = summary;\n this.violations = violations;\n this.risks = risks;\n this.filesToReview = filesToReview;\n this.results = results;\n this.mainAgentInstructions = mainAgentInstructions;\n }\n}\n\n// A checklist's resolved outcome, shared by summary.json enforcement and the dashboard so both agree.\n// PASS, WARN and OVERRIDDEN all ship; FAIL, MISSING and BAD_FORMAT all refuse the PR.\nexport const CK_PASS = 'pass'; // review-<id>.json status:'green'\nexport const CK_WARN = 'warn'; // review-<id>.json status:'yellow' → 🟡 passes WITH concerns\nexport const CK_OVERRIDDEN = 'overridden'; // status:'red' + a human's override-<id>.json → 🟠\nexport const CK_REMEDIATED = 'remediated'; // red + valid author remediation after reviewer round cap → 🟠\nexport const CK_FAIL = 'fail'; // review-<id>.json status:'red' + no override → refuse\nexport const CK_MISSING = 'missing'; // no review-<id>.json written → refuse\nexport const CK_BAD_FORMAT = 'bad-format'; // written, but its verdict is unreadable (e.g. legacy `success`)\n\nexport class ChecklistVerdict {\n id: string;\n status: string; // one of CK_PASS | CK_WARN | CK_OVERRIDDEN | CK_REMEDIATED | CK_FAIL | CK_MISSING | CK_BAD_FORMAT\n detail: string; // reviewer output / override justification / format complaint (dashboard + errors)\n\n constructor(id: string, status: string, detail: string) {\n this.id = id;\n this.status = status;\n this.detail = detail;\n }\n}\n\n// The PR's diff context, written by wp-start-upsert-pr into `.webpieces/pr-review/<featureSlug>/pr-context.json`\n// so a reviewer subagent knows the exact 3-point base the gate used and the full changed-file set — then\n// reads any file's actual diff with `git diff <base> HEAD -- <file>`. This is what lets a checklist match\n// coarsely by path (in the config) while the subagent makes the fine, content-level judgment. Data-only.\nexport class PrContext {\n base: string; // the 3-point merge-base sha the gate diffs against\n /**\n * The real HEAD sha. This was once the literal string 'HEAD', which is not a fact — it cannot be\n * compared later to detect that the tree moved under a review, and it reads as a range that was never\n * actually diffed. Its only reader (reviewContextFor) takes `base`, so recording the sha is free.\n */\n head: string;\n changedFiles: string[]; // every file changed in the range (NOT tsOnly — includes .sql/.gql/Dockerfile/…)\n dirty: boolean; // true ⇒ changedFiles includes uncommitted + untracked work\n dirtyFiles: string[]; // exactly which paths are uncommitted/untracked — why `dirty` is true\n diffCommand: string; // the command that reproduces the WHOLE diff (see DiffBasis; correct when dirty)\n diffDir: string; // dir holding the materialized per-file diffs + ALL.diff; '' when not materialized\n generatedAt: string; // ISO timestamp, so a stale context is detectable rather than silently trusted\n /**\n * Main's head as this clone last saw it — the THIRD hash point, matching the trio the 3-point merge\n * records in `merge-info/<branch>/updatemain-hashes.json`. `base`/`head` above are points A and B\n * under the review side's older names.\n *\n * The review side used to record only A and B, so nothing could answer \"did main move while this was\n * under review?\" — the question you most want answered when a review looks stale. '' when origin/main\n * is unresolvable. Purely informational; nothing gates on it.\n */\n hashMainHead: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n base: string, head: string, changedFiles: string[],\n dirty = false, dirtyFiles: string[] = [], diffCommand = '', diffDir = '', generatedAt = '',\n hashMainHead = '',\n ) {\n this.hashMainHead = hashMainHead;\n this.base = base;\n this.head = head;\n this.changedFiles = changedFiles;\n this.dirty = dirty;\n this.dirtyFiles = dirtyFiles;\n this.diffCommand = diffCommand;\n this.diffDir = diffDir;\n this.generatedAt = generatedAt;\n }\n}\n"]}
1
+ {"version":3,"file":"review-json-data.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/review-json-data.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAKH,qGAAqG;AACrG,yGAAyG;AACzG,0GAA0G;AAC1G,4EAA4E;AAC/D,QAAA,aAAa,GAAG,OAAO,CAAC;AACxB,QAAA,cAAc,GAAG,QAAQ,CAAC;AAC1B,QAAA,WAAW,GAAG,KAAK,CAAC;AACpB,QAAA,gBAAgB,GAAG,CAAC,qBAAa,EAAE,sBAAc,EAAE,mBAAW,CAAU,CAAC;AAEtF,6GAA6G;AAC7G,sGAAsG;AACtG,gCAAgC;AAChC,gDAAgD;AAChD,iHAAiH;AACjH,uGAAuG;AACvG,uFAAuF;AACvF,EAAE;AACF,mGAAmG;AACnG,yGAAyG;AACzG,0GAA0G;AAC1G,gGAAgG;AAChG,4GAA4G;AAC5G,2FAA2F;AAC3F,MAAa,eAAe;IACxB,KAAK,CAAS;IACd,KAAK,CAAS;IACd,EAAE,CAAS;IACX,MAAM,CAAS,CAAC,mEAAmE;IACnF,MAAM,CAAS,CAAC,qEAAqE;IACrF,wGAAwG;IACxG,wGAAwG;IACxG,iDAAiD;IACjD,QAAQ,CAA2B;IACnC,oGAAoG;IACpG,qGAAqG;IACrG,2FAA2F;IAC3F,6GAA6G;IAC7G,OAAO,CAAS;IAChB,sGAAsG;IACtG,WAAW,CAAS;IAEpB,yDAAyD;IACzD,YACI,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AClB,IAAI,CAAS,CAAC,oDAAoD;IAClE;;;;OAIG;IACH,IAAI,CAAS;IACb,YAAY,CAAW,CAAC,iFAAiF;IACzG,KAAK,CAAU,CAAC,4DAA4D;IAC5E,UAAU,CAAW,CAAC,sEAAsE;IAC5F,WAAW,CAAS,CAAC,iFAAiF;IACtG,OAAO,CAAS,CAAC,mFAAmF;IACpG,WAAW,CAAS,CAAC,+EAA+E;IACpG;;;;;;;;OAQG;IACH,YAAY,CAAS;IAErB,yDAAyD;IACzD,YACI,IAAY,EACZ,IAAY,EACZ,YAAsB,EACtB,KAAK,GAAG,KAAK,EACb,aAAuB,EAAE,EACzB,WAAW,GAAG,EAAE,EAChB,OAAO,GAAG,EAAE,EACZ,WAAW,GAAG,EAAE,EAChB,YAAY,GAAG,EAAE;QAEjB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACnC,CAAC;CACJ;AA/CD,8BA+CC","sourcesContent":["/**\n * The DATA-ONLY classes and status constants of the PR review system — the verdict a reviewer writes, the\n * checklist that demanded it, the resolved outcome, and the diff context handed to reviewers.\n *\n * Split out of review-json.ts, which holds the SERVICE that reads and writes them. The split is purely by\n * kind (data vs behaviour): review-json.ts re-exports every name below, so `from './review-json'` and\n * `from '@webpieces/rules-config'` keep resolving exactly as before and no consumer changes.\n */\n\nimport { ReviewerAgentPolicy } from './checklist-config';\nimport { ChecklistOverride } from './checklist-override';\n\n// The three colors a reviewer subagent may report in `review-<id>.json`. A TRI-state, not a boolean,\n// because the boolean it replaced gave a reviewer no way to say \"this passes, but a human should look at\n// X\" — the only way to raise a concern was to FAIL the PR and then override your own failure, which reads\n// on the dashboard as a deliberately-accepted defect rather than as a note.\nexport const VERDICT_GREEN = 'green';\nexport const VERDICT_YELLOW = 'yellow';\nexport const VERDICT_RED = 'red';\nexport const VERDICT_STATUSES = [VERDICT_GREEN, VERDICT_YELLOW, VERDICT_RED] as const;\n\n// The verdict a reviewer SUBAGENT writes into `.webpieces/pr-review/<featureSlug>/review-<id>.json`, one per\n// matched checklist. One file per checklist so N concurrent reviewer subagents never clobber a shared\n// file. It records the OUTCOME:\n// status:'green' → PASS\n// status:'yellow' → WARN (passes; the concern is published on the PR, nothing is blocked)\n// status:'red' + an override-<id>.json → OVERRIDDEN (pass; the human's stated reason reaches the PR)\n// status:'red' + no override file → FAIL (refuse; `output` is printed verbatim)\n//\n// THE `override` FIELD IS GONE FROM THIS FILE, and there is no compatibility mode. The ship-anyway\n// justification used to live here as free text, which made the ONE participant who hears the human — the\n// coordinating agent — the one participant that could not record it, because editing a reviewer's verdict\n// file is (correctly) refused by the harness. It now lives in its own `override-<id>.json`; see\n// ChecklistOverride. A verdict file still carrying an `override` key is reported through `problem` with the\n// destination named, exactly as the removed `success` field is. Data-only (per CLAUDE.md).\nexport class ChecklistResult {\n agent: string;\n model: string;\n id: string;\n status: string; // one of VERDICT_STATUSES; anything else is reported via `problem`\n output: string; // what the reviewer found; printed verbatim when the checklist fails\n // The HUMAN's authorization loaded from `override-<id>.json` beside this verdict, or null when there is\n // none. Loaded alongside the verdict so `resolveVerdict` needs no second read of disk and every command\n // resolves the same outcome from the same bytes.\n override: ChecklistOverride | null;\n // '' = a well-formed verdict. Non-empty = the file exists and parses but its verdict cannot be READ\n // (most often: it still uses the removed `success` field, or the moved `override` field). Carried as\n // data rather than thrown so the complaint can be reported by BOTH wp-review-upsert-pr and\n // wp-finish-upsert-pr in identical words, and so a legacy file is never silently mistaken for a missing one.\n problem: string;\n /** Non-empty only when a valid SHA-bound author remediation resolves this red after the round cap. */\n remediation: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n agent: string,\n model: string,\n id: string,\n status: string,\n output: string,\n override: ChecklistOverride | null,\n problem = '',\n ) {\n this.agent = agent;\n this.model = model;\n this.id = id;\n this.status = status;\n this.output = output;\n this.override = override;\n this.problem = problem;\n this.remediation = '';\n }\n}\n\n/**\n * What the pr-gate command computed from the diff: a checklist this branch MATCHED (its patterns hit the\n * diff, so its reviewer subagent is in scope). Drives review-<id>.json enforcement, provenance, the schema\n * hint, and the dashboard. Data-only.\n *\n * NAME NOTE: \"Required\" here means MATCHED, not mandatory — it predates `required` by a long way and is\n * the shared shape across review-json, the detector, the briefing builder, provenance and the dashboard.\n * Whether the reviewer must actually run is the {@link RequiredChecklist.required} field below.\n */\nexport class RequiredChecklist {\n id: string; // the checklist's name; keys review-<id>.json and its instructions file\n reviewer: ReviewerAgentPolicy; // the agent type to spawn (agentType the harness stamps) + the round cap\n doc: string; // REPO-RELATIVE guidance doc the reviewer reads ('' → it just reads the diff)\n matchedFiles: string[]; // the changed files that matched it (for the dashboard + hint)\n // Which of the checklist's OWN globs actually fired. Printed so a reviewer can judge how coarse the\n // match was — a precise `db/migrations/**` hit means something different from a blanket `**` — and the\n // template tells reviewers that matching IS deliberately coarse. [] = no patterns (matches every PR).\n matchedPatterns: string[];\n // Straight from the checklist's config `required`. true = blocking; false = the human is offered it and\n // may decline. Carried on the MATCH rather than looked up from config downstream so the set that gates\n // and the set that is reported cannot disagree about which of the two a checklist is.\n required: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n id: string,\n reviewer: ReviewerAgentPolicy,\n doc: string,\n matchedFiles: string[],\n matchedPatterns: string[] = [],\n // Defaulted to the BLOCKING value so any construction that forgets it fails closed — a test or a\n // future call site that silently produced an optional checklist would be a hole in the gate.\n required = true,\n ) {\n this.id = id;\n this.reviewer = reviewer;\n this.doc = doc;\n this.matchedFiles = matchedFiles;\n this.matchedPatterns = matchedPatterns;\n this.required = required;\n }\n}\n\n/**\n * The per-PR facts every reviewer subagent needs GIVEN to it, alongside its own checklist: the exact base\n * sha the gate diffs against and the file holding the complete changed-file set. Both used to live only in\n * a doc the printed instruction told the AI to go read, one indirection away from the instruction to hand\n * them over — so the printed block could not stand on its own. Data-only; empty = omit those lines.\n */\nexport class ChecklistReviewContext {\n baseSha: string; // the 3-point merge-base sha\n prContextPath: string; // path of pr-context.json — the AUTHORITATIVE full changed-file set\n /**\n * The exact command that reproduces ONE file's diff, with a `-- <file>` tail — NOT assembled by the\n * caller. This used to be hardcoded as `git diff <baseSha> HEAD -- <file>`, which returns NOTHING on a\n * dirty tree because the changed-file set is computed base→working-tree. See DiffBasis, which derives\n * this string from the same range the file set came from.\n */\n fileDiffCommand: string;\n diffDir: string; // dir of the MATERIALIZED diff (diff/ALL.diff + diff/files/…); '' when not written\n dirty: boolean; // true ⇒ the range includes uncommitted + untracked work, and must be said out loud\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n baseSha = '',\n prContextPath = '',\n fileDiffCommand = '',\n diffDir = '',\n dirty = false,\n ) {\n this.baseSha = baseSha;\n this.prContextPath = prContextPath;\n this.fileDiffCommand = fileDiffCommand;\n this.diffDir = diffDir;\n this.dirty = dirty;\n }\n}\n\n// The AI-authored PR summary (title, risk, summary). Normally the AI writes summary.json between\n// `wp-start-upsert-pr` (which prints the schema) and `wp-finish-upsert-pr` (which reads it), while reviewer\n// subagents write review-<id>.json. The human-only `wp-human-post-pr` escape hatch also requires and reads\n// this same summary shape, but deliberately skips reviewer verdicts. Data-only (per CLAUDE.md).\nexport class PrSummary {\n agent: string;\n model: string;\n title: string; // human PR title describing the change; used as the `gh pr` title (empty → caller falls back)\n riskScore: number; // 0–100, drives the risk bar\n riskLevel: string; // 'green' | 'yellow' | 'red'\n riskEmoji: string; // '🟢' | '🟡' | '🔴' — derived from riskLevel when omitted\n summary: string; // rendered in the dashboard Summary section\n violations: string[]; // pattern/architecture violations; length = the Pattern Violations count\n risks: string[];\n filesToReview: string[];\n results: ChecklistResult[]; // resolved per-checklist verdicts (from review-<id>.json); [] when none\n mainAgentInstructions: string; // non-empty only for the opt-in single-round experiment\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n agent: string,\n model: string,\n title: string,\n riskScore: number,\n riskLevel: string,\n riskEmoji: string,\n summary: string,\n violations: string[],\n risks: string[],\n filesToReview: string[],\n results: ChecklistResult[] = [],\n mainAgentInstructions = '',\n ) {\n this.agent = agent;\n this.model = model;\n this.title = title;\n this.riskScore = riskScore;\n this.riskLevel = riskLevel;\n this.riskEmoji = riskEmoji;\n this.summary = summary;\n this.violations = violations;\n this.risks = risks;\n this.filesToReview = filesToReview;\n this.results = results;\n this.mainAgentInstructions = mainAgentInstructions;\n }\n}\n\n// A checklist's resolved outcome, shared by summary.json enforcement and the dashboard so both agree.\n// PASS, WARN and OVERRIDDEN all ship; FAIL, MISSING and BAD_FORMAT all refuse the PR.\nexport const CK_PASS = 'pass'; // review-<id>.json status:'green'\nexport const CK_WARN = 'warn'; // review-<id>.json status:'yellow' → 🟡 passes WITH concerns\nexport const CK_OVERRIDDEN = 'overridden'; // status:'red' + a human's override-<id>.json → 🟠\nexport const CK_REMEDIATED = 'remediated'; // red + valid author remediation after reviewer round cap → 🟠\nexport const CK_FAIL = 'fail'; // review-<id>.json status:'red' + no override → refuse\nexport const CK_MISSING = 'missing'; // no review-<id>.json written → refuse\nexport const CK_BAD_FORMAT = 'bad-format'; // written, but its verdict is unreadable (e.g. legacy `success`)\n\nexport class ChecklistVerdict {\n id: string;\n status: string; // one of CK_PASS | CK_WARN | CK_OVERRIDDEN | CK_REMEDIATED | CK_FAIL | CK_MISSING | CK_BAD_FORMAT\n detail: string; // reviewer output / override justification / format complaint (dashboard + errors)\n\n constructor(id: string, status: string, detail: string) {\n this.id = id;\n this.status = status;\n this.detail = detail;\n }\n}\n\n// The PR's diff context, written by wp-start-upsert-pr into `.webpieces/pr-review/<featureSlug>/pr-context.json`\n// so a reviewer subagent knows the exact 3-point base the gate used and the full changed-file set — then\n// reads any file's actual diff with `git diff <base> HEAD -- <file>`. This is what lets a checklist match\n// coarsely by path (in the config) while the subagent makes the fine, content-level judgment. Data-only.\nexport class PrContext {\n base: string; // the 3-point merge-base sha the gate diffs against\n /**\n * The real HEAD sha. This was once the literal string 'HEAD', which is not a fact — it cannot be\n * compared later to detect that the tree moved under a review, and it reads as a range that was never\n * actually diffed. Its only reader (reviewContextFor) takes `base`, so recording the sha is free.\n */\n head: string;\n changedFiles: string[]; // every file changed in the range (NOT tsOnly — includes .sql/.gql/Dockerfile/…)\n dirty: boolean; // true ⇒ changedFiles includes uncommitted + untracked work\n dirtyFiles: string[]; // exactly which paths are uncommitted/untracked — why `dirty` is true\n diffCommand: string; // the command that reproduces the WHOLE diff (see DiffBasis; correct when dirty)\n diffDir: string; // dir holding the materialized per-file diffs + ALL.diff; '' when not materialized\n generatedAt: string; // ISO timestamp, so a stale context is detectable rather than silently trusted\n /**\n * Main's head as this clone last saw it — the THIRD hash point, matching the trio the 3-point merge\n * records in `merge-info/<branch>/updatemain-hashes.json`. `base`/`head` above are points A and B\n * under the review side's older names.\n *\n * The review side used to record only A and B, so nothing could answer \"did main move while this was\n * under review?\" — the question you most want answered when a review looks stale. '' when origin/main\n * is unresolvable. Purely informational; nothing gates on it.\n */\n hashMainHead: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n base: string,\n head: string,\n changedFiles: string[],\n dirty = false,\n dirtyFiles: string[] = [],\n diffCommand = '',\n diffDir = '',\n generatedAt = '',\n hashMainHead = '',\n ) {\n this.hashMainHead = hashMainHead;\n this.base = base;\n this.head = head;\n this.changedFiles = changedFiles;\n this.dirty = dirty;\n this.dirtyFiles = dirtyFiles;\n this.diffCommand = diffCommand;\n this.diffDir = diffDir;\n this.generatedAt = generatedAt;\n }\n}\n"]}
@@ -102,7 +102,10 @@ export declare class ReviewJsonService {
102
102
  * must have a well-formed, passing (or overridden) review-<id>.json or a validation error is raised
103
103
  * alongside the usual ones so the AI gets ONE message.
104
104
  */
105
- loadSummaryJson(filePath: string, required?: readonly RequiredChecklist[], expectedMainAgentInstructions?: string, remediations?: Record<string, string>): PrSummary;
105
+ loadSummaryJson(filePath: string, required?: readonly RequiredChecklist[], expectedMainAgentInstructions?: string, remediations?: Record<string, string>, retryCommand?: string): PrSummary;
106
+ private assertValidSummary;
107
+ /** Load the raw object and render every parse/shape error for the command that called us. */
108
+ private readSummaryObject;
106
109
  private validateMainAgentInstructions;
107
110
  /**
108
111
  * The checklists that still OWE a verdict: no review-<id>.json at all, a malformed one, or one whose
@@ -46,7 +46,7 @@ const ARCHIVE_NOTE_KEY = '_ARCHIVED_AUDIT_ONLY';
46
46
  const ARCHIVE_NOTE = 'ARCHIVE — this is the PR summary from the PREVIOUS wp-finish-upsert-pr run on this branch, kept for audit ' +
47
47
  'purposes only. It is NOT the summary for a new round: it describes the code as of the last PR ' +
48
48
  'update, which has since moved. If you are updating the PR again, write a FRESH summary.json at the path ' +
49
- 'pnpm wp-review-upsert-pr prints; do not copy this file\'s title, summary or risk level forward without ' +
49
+ "pnpm wp-review-upsert-pr prints; do not copy this file's title, summary or risk level forward without " +
50
50
  're-deciding each one. Overwritten by every finish, so only the most recent summary is ever here.';
51
51
  // The same stamp, for a retired per-checklist verdict. Verdict files get their OWN wording because the two
52
52
  // archives answer different questions: old-summary.json holds a description of the code, this holds a
@@ -213,12 +213,11 @@ let ReviewJsonService = class ReviewJsonService {
213
213
  * turns a bare "not found" — which reads as data loss, and invites hunting for the file — into the fact:
214
214
  * the last finish consumed it, and the archive is audit material, not a summary to reuse.
215
215
  */
216
- archivedSummaryHint(filePath) {
216
+ archivedSummaryHint(filePath, retryCommand) {
217
217
  const archive = this.oldSummaryJsonPath(filePath);
218
218
  if (!fs.existsSync(archive))
219
219
  return '';
220
- return `\nA PREVIOUS PR summary was archived to ${archive} when the last pnpm wp-finish-upsert-pr consumed it.\n` +
221
- `That file is for AUDIT ONLY — it describes code this branch has since moved past. Write a fresh one:`;
220
+ return `\nA PREVIOUS PR summary was archived to ${archive} when the last ${retryCommand} consumed it.\n` + `That file is for AUDIT ONLY — it describes code this branch has since moved past. Write a fresh one:`;
222
221
  }
223
222
  // Names summary.json when the author wrote its OLD name (review.json until #1033 — refused by Claude
224
223
  // auto-mode as Self-Approval beside the review-<id>.json verdicts). HARD CUT: the stale file is never read.
@@ -226,8 +225,7 @@ let ReviewJsonService = class ReviewJsonService {
226
225
  const stale = path.join(path.dirname(filePath), 'review.json');
227
226
  if (!fs.existsSync(stale))
228
227
  return '';
229
- return `\n${stale} is IGNORED — the author's file was renamed to summary.json. ` +
230
- `Write the same JSON to ${filePath} instead.`;
228
+ return `\n${stale} is IGNORED — the author's file was renamed to summary.json. ` + `Write the same JSON to ${filePath} instead.`;
231
229
  }
232
230
  // The per-checklist review file path that sits beside summary.json: review-<id>.json.
233
231
  checklistResultPath(summaryJsonFilePath, checklistId) {
@@ -277,16 +275,8 @@ let ReviewJsonService = class ReviewJsonService {
277
275
  * alongside the usual ones so the AI gets ONE message.
278
276
  */
279
277
  // webpieces-disable max-lines-new-methods -- one cohesive load+validate pass over the review fields
280
- loadSummaryJson(filePath, required = [], expectedMainAgentInstructions = '', remediations = {}) {
281
- if (!fs.existsSync(filePath)) {
282
- throw new inform_ai_error_1.InformAiError(`Required summary.json not found.${this.renamedFileHint(filePath)}${this.archivedSummaryHint(filePath)}\n\n` +
283
- `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\n\n` +
284
- `Then re-run: pnpm wp-finish-upsert-pr`);
285
- }
286
- const raw = this.parseSummaryJson(fs.readFileSync(filePath, 'utf8'), filePath, expectedMainAgentInstructions);
287
- if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
288
- throw new inform_ai_error_1.InformAiError(`summary.json must be a JSON object.\n\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}`);
289
- }
278
+ loadSummaryJson(filePath, required = [], expectedMainAgentInstructions = '', remediations = {}, retryCommand = 'pnpm wp-finish-upsert-pr') {
279
+ const raw = this.readSummaryObject(filePath, expectedMainAgentInstructions, retryCommand);
290
280
  const errors = [];
291
281
  for (const field of ['agent', 'model']) {
292
282
  if (typeof raw[field] !== 'string' || raw[field].trim() === '') {
@@ -311,22 +301,32 @@ let ReviewJsonService = class ReviewJsonService {
311
301
  result.remediation = remediations[result.id] ?? '';
312
302
  for (const err of this.requiredChecklistErrors(required, results, filePath))
313
303
  errors.push(err);
314
- if (errors.length > 0) {
315
- throw new inform_ai_error_1.InformAiError(`summary.json has ${errors.length} error(s) — fix ALL, then re-run pnpm wp-finish-upsert-pr:\n\n` +
316
- errors.map((e) => ` • ${e}`).join('\n') +
317
- `\n\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}`);
318
- }
304
+ this.assertValidSummary(errors, filePath, expectedMainAgentInstructions, retryCommand);
319
305
  const level = riskLevel;
320
- const emoji = typeof raw['riskEmoji'] === 'string' && raw['riskEmoji'] !== ''
321
- ? raw['riskEmoji']
322
- : (EMOJI_FOR_LEVEL[level] ?? '🟡');
306
+ const emoji = typeof raw['riskEmoji'] === 'string' && raw['riskEmoji'] !== '' ? raw['riskEmoji'] : (EMOJI_FOR_LEVEL[level] ?? '🟡');
323
307
  const summary = typeof raw['summary'] === 'string' ? raw['summary'] : '';
324
308
  return new review_json_data_1.PrSummary(raw['agent'].trim(), raw['model'].trim(), title, riskScore, level, emoji, summary, this.asStringArray(raw['violations']), this.asStringArray(raw['risks']), this.asStringArray(raw['filesToReview']), results, mainAgentInstructions);
325
309
  }
310
+ assertValidSummary(errors, filePath, expectedMainAgentInstructions, retryCommand) {
311
+ if (errors.length === 0)
312
+ return;
313
+ throw new inform_ai_error_1.InformAiError(`summary.json has ${errors.length} error(s) — fix ALL, then re-run ${retryCommand}:\n\n` + errors.map((e) => ` • ${e}`).join('\n') + `\n\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}`);
314
+ }
315
+ /** Load the raw object and render every parse/shape error for the command that called us. */
316
+ readSummaryObject(filePath, expectedMainAgentInstructions, retryCommand) {
317
+ if (!fs.existsSync(filePath)) {
318
+ throw new inform_ai_error_1.InformAiError(`Required summary.json not found.${this.renamedFileHint(filePath)}${this.archivedSummaryHint(filePath, retryCommand)}\n\n` + `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\n\n` + `Then re-run: ${retryCommand}`);
319
+ }
320
+ const raw = this.parseSummaryJson(fs.readFileSync(filePath, 'utf8'), filePath, expectedMainAgentInstructions, retryCommand);
321
+ if (typeof raw === 'object' && raw !== null && !Array.isArray(raw))
322
+ return raw;
323
+ throw new inform_ai_error_1.InformAiError(`summary.json must be a JSON object.\n\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}` + `\n\nThen re-run: ${retryCommand}`);
324
+ }
326
325
  // webpieces-disable no-any-unknown -- AI-authored JSON boundary is validated before use
327
- validateMainAgentInstructions(raw, expected, errors) {
328
- const actual = typeof raw['main_agent_instructions'] === 'string'
329
- ? raw['main_agent_instructions'].trim() : '';
326
+ validateMainAgentInstructions(
327
+ // webpieces-disable no-any-unknown -- opaque parsed JSON; only tested for key presence below
328
+ raw, expected, errors) {
329
+ const actual = typeof raw['main_agent_instructions'] === 'string' ? raw['main_agent_instructions'].trim() : '';
330
330
  if (expected !== '' && actual !== expected)
331
331
  errors.push('"main_agent_instructions" must exactly preserve the single-round instructions printed by stage ②.');
332
332
  return actual;
@@ -401,11 +401,11 @@ let ReviewJsonService = class ReviewJsonService {
401
401
  const head = `Checklist "${req.id}" FAILED review (status:"${review_json_data_1.VERDICT_RED}"). The reviewer (${req.reviewer.agentName}) wrote:\n ` + finding;
402
402
  const retired = archivedPath === ''
403
403
  ? ' Fix it, then re-run.\n'
404
- // Re-spawning is said only after the finding, because an instruction to spawn a subagent is the
405
- // one line an AI acts on first — see refusedChecklists for what that cost.
406
- : ` That verdict has been RETIRED to ${archivedPath} (audit only — it is not a live verdict).\n` +
407
- ` A FRESH ${this.checklistFileName(req.id)} is now required. Fix the finding first, then have the ` +
408
- `"${req.reviewer.agentName}" subagent review again and write a new verdict.\n`;
404
+ : // Re-spawning is said only after the finding, because an instruction to spawn a subagent is the
405
+ // one line an AI acts on first — see refusedChecklists for what that cost.
406
+ ` That verdict has been RETIRED to ${archivedPath} (audit only — it is not a live verdict).\n` +
407
+ ` A FRESH ${this.checklistFileName(req.id)} is now required. Fix the finding first, then have the ` +
408
+ `"${req.reviewer.agentName}" subagent review again and write a new verdict.\n`;
409
409
  return head + retired + this.overrideRoute(req, summaryJsonFilePath);
410
410
  }
411
411
  /**
@@ -416,11 +416,11 @@ let ReviewJsonService = class ReviewJsonService {
416
416
  * command that had since been deleted.
417
417
  */
418
418
  overrideRoute(req, summaryJsonFilePath) {
419
- return ` To SHIP ANYWAY a human must decide it, and the decision is recorded in its own file — `
420
- + `${this.overrides.overrideFileName(req.id)}, never inside the reviewer's verdict.\n`
421
- + ` ${this.overrides.writerRule()}\n`
422
- + ' Run exactly this, replacing only the "reason" with what the human actually said:\n\n'
423
- + `${this.overrides.writeCommand(summaryJsonFilePath, req.id)}\n`;
419
+ return (` To SHIP ANYWAY a human must decide it, and the decision is recorded in its own file — ` +
420
+ `${this.overrides.overrideFileName(req.id)}, never inside the reviewer's verdict.\n` +
421
+ ` ${this.overrides.writerRule()}\n` +
422
+ ' Run exactly this, replacing only the "reason" with what the human actually said:\n\n' +
423
+ `${this.overrides.writeCommand(summaryJsonFilePath, req.id)}\n`);
424
424
  }
425
425
  // Read the per-checklist verdict files `review-<id>.json` beside summary.json — one per matched checklist.
426
426
  // A missing file is simply absent from the result (→ counts as MISSING for that checklist); a malformed
@@ -508,8 +508,7 @@ let ReviewJsonService = class ReviewJsonService {
508
508
  if (!req.required)
509
509
  continue;
510
510
  const doc = req.doc.trim() !== '' ? ` Read: ${req.doc}.` : '';
511
- errors.push(`Checklist "${req.id}" MATCHED this diff but has no verdict. Spawn the "${req.reviewer.agentName}" subagent to review it; ` +
512
- `IT submits the verdict with ${this.submitCommand(req.id)} — nobody writes ${this.checklistFileName(req.id)} by hand.${doc}`);
511
+ errors.push(`Checklist "${req.id}" MATCHED this diff but has no verdict. Spawn the "${req.reviewer.agentName}" subagent to review it; ` + `IT submits the verdict with ${this.submitCommand(req.id)} — nobody writes ${this.checklistFileName(req.id)} by hand.${doc}`);
513
512
  }
514
513
  }
515
514
  return errors;
@@ -549,8 +548,7 @@ let ReviewJsonService = class ReviewJsonService {
549
548
  const status = typeof raw['status'] === 'string' ? raw['status'].trim().toLowerCase() : '';
550
549
  const agent = typeof raw['agent'] === 'string' ? raw['agent'].trim() : '';
551
550
  const model = typeof raw['model'] === 'string' ? raw['model'].trim() : '';
552
- const identityProblem = agent === '' || model === ''
553
- ? 'Both "agent" and "model" must be non-empty strings; use "unknown" when unavailable.' : '';
551
+ const identityProblem = agent === '' || model === '' ? 'Both "agent" and "model" must be non-empty strings; use "unknown" when unavailable.' : '';
554
552
  return new review_json_data_1.ChecklistResult(agent, model, id, status, output, override, this.verdictProblem(filePath, id, status, raw) || identityProblem);
555
553
  }
556
554
  catch (err) {
@@ -571,27 +569,26 @@ let ReviewJsonService = class ReviewJsonService {
571
569
  * The legacy-`success` case keeps its OWN message for the same reason: `success` was removed outright
572
570
  * (no compatibility mode), and a reviewer cannot tell a wrong value from a field that no longer exists.
573
571
  */
574
- // webpieces-disable no-any-unknown -- opaque parsed JSON; only tested for key presence here
575
- verdictProblem(filePath, id, status, raw) {
572
+ verdictProblem(filePath, id, status,
573
+ // webpieces-disable-next-line no-any-unknown -- opaque parsed JSON; only tested for key presence here
574
+ raw) {
576
575
  // The ONE renderer — see renderVerdictSchema. A second copy here is what let the old `success` shape
577
576
  // survive in print after it was removed from the parser.
578
577
  const shape = this.renderVerdictSchema(id);
579
578
  if ('override' in raw) {
580
- return `Checklist "${id}" wrote its verdict with the MOVED "override" field. A ship-anyway `
581
- + 'authorization is no longer part of a reviewer\'s verdict: it MOVED to its own file, '
582
- + `${this.overrides.overrideFileName(id)}, which only the coordinating agent writes and only on a `
583
- + 'human\'s in-session instruction. There is no compatibility mode — DELETE the "override" key from '
584
- + `${filePath} by resubmitting it:\n${shape}`;
579
+ return (`Checklist "${id}" wrote its verdict with the MOVED "override" field. A ship-anyway ` +
580
+ "authorization is no longer part of a reviewer's verdict: it MOVED to its own file, " +
581
+ `${this.overrides.overrideFileName(id)}, which only the coordinating agent writes and only on a ` +
582
+ 'human\'s in-session instruction. There is no compatibility mode — DELETE the "override" key from ' +
583
+ `${filePath} by resubmitting it:\n${shape}`);
585
584
  }
586
585
  // webpieces-disable no-any-unknown -- comparing against the readonly literal tuple of valid colors
587
586
  if (review_json_data_1.VERDICT_STATUSES.includes(status))
588
587
  return '';
589
588
  if ('success' in raw) {
590
- return `Checklist "${id}" wrote its verdict with the REMOVED "success" field. It is now a tri-state ` +
591
- `"status" — there is no compatibility mode. Resubmit it as:\n${shape}`;
589
+ return `Checklist "${id}" wrote its verdict with the REMOVED "success" field. It is now a tri-state ` + `"status" — there is no compatibility mode. Resubmit it as:\n${shape}`;
592
590
  }
593
- return `Checklist "${id}" wrote a verdict with no valid "status" (got ${JSON.stringify(status)}). ` +
594
- `It must be exactly one of ${review_json_data_1.VERDICT_STATUSES.join(', ')}:\n${shape}`;
591
+ return `Checklist "${id}" wrote a verdict with no valid "status" (got ${JSON.stringify(status)}). ` + `It must be exactly one of ${review_json_data_1.VERDICT_STATUSES.join(', ')}:\n${shape}`;
595
592
  }
596
593
  // webpieces-disable no-any-unknown -- opaque parsed JSON value, narrowed to string[] here
597
594
  asStringArray(value) {
@@ -602,7 +599,7 @@ let ReviewJsonService = class ReviewJsonService {
602
599
  }
603
600
  // Parse opaque AI-authored JSON, converting a SyntaxError into a readable InformAiError.
604
601
  // webpieces-disable no-any-unknown -- returns the opaque parsed object; loadSummaryJson narrows each field
605
- parseSummaryJson(raw, filePath, expectedMainAgentInstructions = '') {
602
+ parseSummaryJson(raw, filePath, expectedMainAgentInstructions = '', retryCommand = 'pnpm wp-finish-upsert-pr') {
606
603
  // webpieces-disable no-unmanaged-exceptions -- chokepoint: convert JSON.parse SyntaxError to an InformAiError for the AI
607
604
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
608
605
  try {
@@ -611,9 +608,7 @@ let ReviewJsonService = class ReviewJsonService {
611
608
  }
612
609
  catch (err) {
613
610
  const error = (0, to_error_1.toError)(err);
614
- throw new inform_ai_error_1.InformAiError(`summary.json is not valid JSON (${error.message}).\n\n` +
615
- `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\n\n` +
616
- `Then re-run: pnpm wp-finish-upsert-pr`);
611
+ throw new inform_ai_error_1.InformAiError(`summary.json is not valid JSON (${error.message}).\n\n` + `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\n\n` + `Then re-run: ${retryCommand}`);
617
612
  }
618
613
  }
619
614
  };
@@ -1 +1 @@
1
- {"version":3,"file":"review-json.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/review-json.ts"],"names":[],"mappings":";;;AAwqBA,4BAEC;AAGD,0CAEC;AAGD,sDAEC;;AAprBD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,2CAA4C;AAC5C,2CAAyD;AACzD,uDAAkD;AAClD,yCAAqC;AACrC,iFAA2E;AAC3E,uEAAkE;AAClE,6DAA6G;AAsBpG,kGAtBA,sCAAiB,OAsBA;AAAE,yGAtBA,6CAAwB,OAsBA;AAAE,yGAtBA,6CAAwB,OAsBA;AArB9E,yDAkB4B;AAKxB,8FAtBA,gCAAa,OAsBA;AACb,+FAtBA,iCAAc,OAsBA;AACd,4FAtBA,8BAAW,OAsBA;AACX,iGAtBA,mCAAgB,OAsBA;AAChB,gGAtBA,kCAAe,OAsBA;AACf,kGAtBA,oCAAiB,OAsBA;AACjB,uGAtBA,yCAAsB,OAsBA;AACtB,0FAtBA,4BAAS,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ify';\nimport { PR_REVIEW_DIR } from './constants';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\nimport { InformAiError } from './inform-ai-error';\nimport { toError } from './to-error';\nimport { SummaryJsonSchemaRenderer } from './summary-json-schema-renderer';\nimport { VerdictSchemaRenderer } from './verdict-schema-renderer';\nimport { ChecklistOverride, ChecklistOverrideService, checklistOverrideService } from './checklist-override';\nimport {\n VERDICT_GREEN,\n VERDICT_YELLOW,\n VERDICT_RED,\n VERDICT_STATUSES,\n ChecklistResult,\n RequiredChecklist,\n ChecklistReviewContext,\n PrSummary,\n CK_PASS,\n CK_WARN,\n CK_OVERRIDDEN,\n CK_REMEDIATED,\n CK_FAIL,\n CK_MISSING,\n CK_BAD_FORMAT,\n ChecklistVerdict,\n PrContext,\n} from './review-json-data';\n\n// Re-exported so review-json.ts stays the single import site for the review vocabulary.\nexport { ChecklistOverride, ChecklistOverrideService, checklistOverrideService };\nexport {\n VERDICT_GREEN,\n VERDICT_YELLOW,\n VERDICT_RED,\n VERDICT_STATUSES,\n ChecklistResult,\n RequiredChecklist,\n ChecklistReviewContext,\n PrSummary,\n CK_PASS,\n CK_WARN,\n CK_OVERRIDDEN,\n CK_REMEDIATED,\n CK_FAIL,\n CK_MISSING,\n CK_BAD_FORMAT,\n ChecklistVerdict,\n PrContext,\n};\n\nconst RISK_LEVELS = ['green', 'yellow', 'red'] as const;\nconst EMOJI_FOR_LEVEL: Record<string, string> = { green: '🟢', yellow: '🟡', red: '🔴' };\n\n// Where `wp-finish-upsert-pr` retires the summary.json it just consumed, and the note it stamps on the way.\n// The key sorts first in the written JSON because it is written first — an AI that opens the file to see\n// whether it can reuse the summary reads what the file IS before it reads a title it might be tempted to keep.\nconst OLD_SUMMARY_FILE = 'old-summary.json';\nconst ARCHIVE_NOTE_KEY = '_ARCHIVED_AUDIT_ONLY';\nconst ARCHIVE_NOTE =\n 'ARCHIVE — this is the PR summary from the PREVIOUS wp-finish-upsert-pr run on this branch, kept for audit ' +\n 'purposes only. It is NOT the summary for a new round: it describes the code as of the last PR ' +\n 'update, which has since moved. If you are updating the PR again, write a FRESH summary.json at the path ' +\n 'pnpm wp-review-upsert-pr prints; do not copy this file\\'s title, summary or risk level forward without ' +\n 're-deciding each one. Overwritten by every finish, so only the most recent summary is ever here.';\n\n// The same stamp, for a retired per-checklist verdict. Verdict files get their OWN wording because the two\n// archives answer different questions: old-summary.json holds a description of the code, this holds a\n// REVIEWER'S DECISION. The one thing that must not happen is a reader treating an archived red as the live\n// verdict — the whole reason the file was moved rather than copied — so the note says that outright.\nconst CHECKLIST_ARCHIVE_NOTE =\n 'ARCHIVE — this is a checklist verdict from a PREVIOUS reviewer run on this branch, kept for audit ' +\n 'purposes only. It is NOT a live verdict and must never be read back as one: it was RETIRED because it ' +\n 'refused the PR, and the gate moved it here so the only way forward is a FRESH review-<id>.json written ' +\n 'by a real reviewer run. Do not copy its status back onto the live path to get past the gate. ' +\n 'Overwritten by every retirement, so only the most recently retired verdict is ever here.';\n\n/** Locates + loads/validates the AI-authored summary.json. `@injectable(bindingScopeValues.Singleton)` so it's drawn in the design. */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewJsonService {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly overrides: ChecklistOverrideService = checklistOverrideService,\n ) {}\n\n // The per-feature PR working dir: `<worktree>/.webpieces/pr-review/<feature>`. AI-WRITABLE scope,\n // not local() — an agent AUTHORS summary.json here, and each reviewer subagent authors its own\n // review-<id>.json beside it. A worktree-isolated agent's Write is refused for any path under the\n // shared checkout, which is where local() puts this, so local() made both files unwritable by the\n // very agents the flow instructs to write them. See DotWebpieces.aiWritable() for the full account.\n prDirFor(repoRoot: string, featureName: string): string {\n return this.dotDir.aiWritableFile(repoRoot, PR_REVIEW_DIR, featureName);\n }\n\n // Absolute path of the summary.json for a feature — beside pr-body.md, keyed by branch name.\n summaryJsonPath(repoRoot: string, featureName: string): string {\n return path.join(this.prDirFor(repoRoot, featureName), 'summary.json');\n }\n\n // Absolute path of the pr-context.json for a feature (the diff base/head + changed files).\n prContextPath(repoRoot: string, featureName: string): string {\n return path.join(this.prDirFor(repoRoot, featureName), 'pr-context.json');\n }\n\n // Where a consumed summary.json is archived to, beside it. Always the SAME path — it holds the last\n // summary and only the last one, so it can never be mistaken for a series that means something.\n oldSummaryJsonPath(summaryJsonFilePath: string): string {\n return path.join(path.dirname(summaryJsonFilePath), OLD_SUMMARY_FILE);\n }\n\n /**\n * Retire the PR summary `wp-finish-upsert-pr` just used: move summary.json to old-summary.json, stamped\n * with a note saying what it is. Returns the archive path, or '' when there was nothing to archive.\n *\n * The point is the MOVE, not the copy. summary.json left in place after a PR is posted is a live-looking\n * file describing a PR update that already happened, and the next run of stage ② on this branch finds it\n * sitting there — so a reviewer subagent that judges the PR's stated intent (its title, summary or risk\n * level) can read the previous run's summary and return GREEN against a title that no longer exists.\n * Nothing in the verdict distinguishes that from a real pass. Moving it means the only way to reach\n * finish again is to write a fresh one, and {@link loadSummaryJson} points at the archive when it is\n * missing so the archive reads as an audit trail rather than as a lost file.\n *\n * Called only after the PR is actually up: a finish that failed before publishing must stay re-runnable.\n */\n archiveSummaryJson(summaryJsonFilePath: string): string {\n if (!fs.existsSync(summaryJsonFilePath)) return '';\n const archivePath = this.oldSummaryJsonPath(summaryJsonFilePath);\n const raw = fs.readFileSync(summaryJsonFilePath, 'utf8');\n fs.writeFileSync(archivePath, this.archivedBody(raw, ARCHIVE_NOTE));\n fs.rmSync(summaryJsonFilePath);\n return archivePath;\n }\n\n /**\n * The archived bytes: the original JSON with an AUDIT-ONLY note as its FIRST key, so anything that opens\n * the file — human or AI — reads what it is before it reads any of its content.\n *\n * `note` is a parameter rather than a constant because two different files are archived here (summary.json\n * and review-<id>.json) and they need to say different things, while the stamping MECHANICS — parse,\n * note first, original keys in order, fall back to raw — are identical. One implementation, two texts;\n * a second copy of this method would be the thing that drifts.\n *\n * Falls back to the raw bytes when they do not parse. For summary.json `loadSummaryJson` has already\n * accepted the file so that is close to impossible, but a verdict file is written by a subagent and may\n * be half-written or not an object at all — and preserving the original always beats losing it to a\n * stamping failure, since the archive exists precisely to be the record.\n */\n private archivedBody(raw: string, note: string): string {\n const parsed = this.tryParseObject(raw);\n if (parsed === null) return raw;\n // webpieces-disable no-any-unknown -- re-serializing opaque review fields verbatim; only the key ORDER is ours\n const stamped: Record<string, unknown> = {};\n stamped[ARCHIVE_NOTE_KEY] = note;\n for (const key of Object.keys(parsed)) stamped[key] = parsed[key];\n return JSON.stringify(stamped, null, 2) + '\\n';\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON; the caller only re-serializes it\n private tryParseObject(raw: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unparseable bytes are archived verbatim, never fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque; only its key order is used\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null;\n return parsed;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * Persist the PR's diff context so reviewer subagents can read the changed-file set + the exact base\n * sha. Returns the file path written.\n *\n * ALSO writes an immutable per-stage snapshot under `stages/<stage>.json` when `stage` is given.\n * `pr-context.json` is overwritten by each stage, so by the time anything goes wrong the earlier\n * states are gone — and \"what did the tooling think the diff was at stage ①, vs ②, vs ③?\" is exactly\n * the question you need answered when debugging a review that went sideways. The snapshots make the\n * review system auditable by an AI reviewing IT, which the single mutable file never could.\n */\n writePrContext(repoRoot: string, featureName: string, context: PrContext, stage = ''): string {\n const dir = this.prDirFor(repoRoot, featureName);\n fs.mkdirSync(dir, { recursive: true });\n const body = JSON.stringify(context, null, 2) + '\\n';\n const p = this.prContextPath(repoRoot, featureName);\n fs.writeFileSync(p, body);\n if (stage !== '') {\n const stagesDir = path.join(dir, 'stages');\n fs.mkdirSync(stagesDir, { recursive: true });\n fs.writeFileSync(path.join(stagesDir, `${stage}.json`), body);\n }\n return p;\n }\n\n /**\n * The review context for a feature, recovered from the pr-context.json wp-start-upsert-pr already wrote.\n * Lets wp-finish-upsert-pr's \"you still owe me review-<id>.json\" message inline the SAME self-sufficient\n * per-reviewer block start printed, instead of a checklist name and an indirection. Empty when the file\n * is absent or unreadable — the block then just omits those lines.\n */\n reviewContextFor(repoRoot: string, featureName: string): ChecklistReviewContext {\n const p = this.prContextPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return new ChecklistReviewContext();\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable context file degrades to fewer printed lines, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed on the next line\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n const base = typeof raw['base'] === 'string' ? (raw['base'] as string) : '';\n // Recover the REPRODUCE command rather than re-deriving it: a context written by an older\n // pr-gate has no diffCommand, and guessing `<base> HEAD` there would resurrect the exact\n // empty-on-a-dirty-tree bug this field exists to kill. Absent ⇒ omit the line entirely.\n const cmd = typeof raw['diffCommand'] === 'string' ? (raw['diffCommand'] as string) : '';\n const diffDir = typeof raw['diffDir'] === 'string' ? (raw['diffDir'] as string) : '';\n const dirty = raw['dirty'] === true;\n return new ChecklistReviewContext(base, p, cmd === '' ? '' : `${cmd} -- <file>`, diffDir, dirty);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return new ChecklistReviewContext('', p);\n }\n }\n\n // Copy-paste summary.json schema shared by every command that asks the coordinating AI to write it.\n summaryJsonSchemaHint(filePath: string, mainAgentInstructions = ''): string {\n return new SummaryJsonSchemaRenderer().render(filePath, mainAgentInstructions);\n }\n\n /**\n * The extra line the \"no summary.json\" complaint carries when a PREVIOUS summary was archived here. It\n * turns a bare \"not found\" — which reads as data loss, and invites hunting for the file — into the fact:\n * the last finish consumed it, and the archive is audit material, not a summary to reuse.\n */\n private archivedSummaryHint(filePath: string): string {\n const archive = this.oldSummaryJsonPath(filePath);\n if (!fs.existsSync(archive)) return '';\n return `\\nA PREVIOUS PR summary was archived to ${archive} when the last pnpm wp-finish-upsert-pr consumed it.\\n` +\n `That file is for AUDIT ONLY — it describes code this branch has since moved past. Write a fresh one:`;\n }\n\n // Names summary.json when the author wrote its OLD name (review.json until #1033 — refused by Claude\n // auto-mode as Self-Approval beside the review-<id>.json verdicts). HARD CUT: the stale file is never read.\n private renamedFileHint(filePath: string): string {\n const stale = path.join(path.dirname(filePath), 'review.json');\n if (!fs.existsSync(stale)) return '';\n return `\\n${stale} is IGNORED — the author's file was renamed to summary.json. ` +\n `Write the same JSON to ${filePath} instead.`;\n }\n\n // The per-checklist review file path that sits beside summary.json: review-<id>.json.\n checklistResultPath(summaryJsonFilePath: string, checklistId: string): string {\n return path.join(path.dirname(summaryJsonFilePath), `review-${checklistId}.json`);\n }\n\n /**\n * Where a RETIRED verdict for one checklist goes: `review-<id>.json.old`, beside the live path.\n *\n * Mirrors {@link oldSummaryJsonPath} deliberately, including its single-slot rule: ALWAYS the same path,\n * so it holds the last retired verdict and only the last one. A series (`.old.old`, `.old.1`) would read\n * as though the number of retirements meant something, and nothing downstream can interpret that — the\n * one fact worth keeping is \"this checklist refused before, here is what it said\".\n */\n oldChecklistResultPath(summaryJsonFilePath: string, checklistId: string): string {\n return `${this.checklistResultPath(summaryJsonFilePath, checklistId)}.old`;\n }\n\n /**\n * Retire one checklist's verdict: MOVE review-<id>.json to review-<id>.json.old, stamped with a note\n * saying what it is. Returns the archive path, or '' when there was nothing to archive.\n *\n * The point is the MOVE, exactly as in {@link archiveSummaryJson}. A red verdict left on the live path is\n * re-read by the next run and re-reported as the CURRENT state of the branch, so the branch keeps being\n * refused for a finding that may already be fixed — and the fix, when it comes, silently overwrites the\n * only record that the gate ever refused anything. Moving it makes the refusal durable and makes a fresh\n * reviewer run the only way forward, which is the honest requirement: the old verdict judged code that\n * has since changed.\n *\n * Safe by construction for RED verdicts specifically, which is why the caller only archives on CK_FAIL:\n * a red verdict is never reusable — it always blocks — so nothing is lost by moving it. Green and yellow\n * verdicts ARE deliberately reused across finish attempts, and retiring one would force a needless (and\n * expensive) subagent re-run.\n */\n archiveChecklistResult(summaryJsonFilePath: string, checklistId: string): string {\n const livePath = this.checklistResultPath(summaryJsonFilePath, checklistId);\n if (!fs.existsSync(livePath)) return '';\n const archivePath = this.oldChecklistResultPath(summaryJsonFilePath, checklistId);\n const raw = fs.readFileSync(livePath, 'utf8');\n fs.writeFileSync(archivePath, this.archivedBody(raw, CHECKLIST_ARCHIVE_NOTE));\n fs.rmSync(livePath);\n return archivePath;\n }\n\n /**\n * Load + validate the AI-authored summary.json. Throws InformAiError (with the schema) when missing,\n * unparseable, or structurally wrong. `required` is the set of checklists the diff matched: every one\n * must have a well-formed, passing (or overridden) review-<id>.json or a validation error is raised\n * alongside the usual ones so the AI gets ONE message.\n */\n // webpieces-disable max-lines-new-methods -- one cohesive load+validate pass over the review fields\n loadSummaryJson(\n filePath: string, required: readonly RequiredChecklist[] = [], expectedMainAgentInstructions = '',\n remediations: Record<string, string> = {},\n ): PrSummary {\n if (!fs.existsSync(filePath)) {\n throw new InformAiError(\n `Required summary.json not found.${this.renamedFileHint(filePath)}${this.archivedSummaryHint(filePath)}\\n\\n` +\n `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\\n\\n` +\n `Then re-run: pnpm wp-finish-upsert-pr`,\n );\n }\n const raw = this.parseSummaryJson(fs.readFileSync(filePath, 'utf8'), filePath, expectedMainAgentInstructions);\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new InformAiError(\n `summary.json must be a JSON object.\\n\\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}`);\n }\n const errors: string[] = [];\n for (const field of ['agent', 'model']) {\n if (typeof raw[field] !== 'string' || raw[field].trim() === '') {\n errors.push(`\"${field}\" must be a non-empty string; use \"unknown\" when unavailable.`);\n }\n }\n const riskScore = raw['riskScore'];\n if (typeof riskScore !== 'number' || !Number.isFinite(riskScore) || riskScore < 0 || riskScore > 100) {\n errors.push(`\"riskScore\" must be a number 0–100, got ${JSON.stringify(riskScore)}.`);\n }\n const riskLevel = raw['riskLevel'];\n if (typeof riskLevel !== 'string' || !RISK_LEVELS.includes(riskLevel as typeof RISK_LEVELS[number])) {\n errors.push(`\"riskLevel\" must be one of: ${RISK_LEVELS.join(', ')}.`);\n }\n const title = typeof raw['title'] === 'string' ? (raw['title'] as string).trim() : '';\n if (title === '') {\n errors.push('\"title\" must be a non-empty, imperative PR title describing the change (no branch names).');\n }\n const mainAgentInstructions = this.validateMainAgentInstructions(raw, expectedMainAgentInstructions, errors);\n\n const results = this.loadChecklistResults(filePath, required);\n for (const result of results) result.remediation = remediations[result.id] ?? '';\n for (const err of this.requiredChecklistErrors(required, results, filePath)) errors.push(err);\n\n if (errors.length > 0) {\n throw new InformAiError(\n `summary.json has ${errors.length} error(s) — fix ALL, then re-run pnpm wp-finish-upsert-pr:\\n\\n` +\n errors.map((e: string): string => ` • ${e}`).join('\\n') +\n `\\n\\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}`,\n );\n }\n\n const level = riskLevel as string;\n const emoji = typeof raw['riskEmoji'] === 'string' && raw['riskEmoji'] !== ''\n ? (raw['riskEmoji'] as string)\n : (EMOJI_FOR_LEVEL[level] ?? '🟡');\n const summary = typeof raw['summary'] === 'string' ? (raw['summary'] as string) : '';\n\n return new PrSummary((raw['agent'] as string).trim(), (raw['model'] as string).trim(),\n title,\n riskScore as number,\n level,\n emoji,\n summary,\n this.asStringArray(raw['violations']),\n this.asStringArray(raw['risks']),\n this.asStringArray(raw['filesToReview']),\n results,\n mainAgentInstructions,\n );\n }\n\n // webpieces-disable no-any-unknown -- AI-authored JSON boundary is validated before use\n private validateMainAgentInstructions(raw: Record<string, unknown>, expected: string, errors: string[]): string {\n const actual = typeof raw['main_agent_instructions'] === 'string'\n ? (raw['main_agent_instructions'] as string).trim() : '';\n if (expected !== '' && actual !== expected)\n errors.push('\"main_agent_instructions\" must exactly preserve the single-round instructions printed by stage ②.');\n return actual;\n }\n\n /**\n * The checklists that still OWE a verdict: no review-<id>.json at all, a malformed one, or one whose\n * verdict is an un-overridden FAIL. This is the set every message lists — a checklist already PASSed or\n * OVERRIDDEN on this branch is deliberately NOT re-listed, because re-instructing it invites a redundant\n * second run and reads as though the earlier verdict did not count.\n */\n pendingChecklists(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): RequiredChecklist[] {\n return required.filter((req: RequiredChecklist): boolean => {\n const status = this.resolveVerdict(req, results).status;\n // CK_WARN must be listed here beside PASS/OVERRIDDEN. A yellow verdict SHIPS — leaving it out\n // would mark the checklist owed forever, so `outstanding` never empties and the PR is refused\n // permanently no matter how many times the reviewer runs.\n return status !== CK_PASS && status !== CK_WARN && status !== CK_OVERRIDDEN && status !== CK_REMEDIATED;\n });\n }\n\n /**\n * The OPTIONAL checklists (`required: false`) that matched the diff but have no verdict file at all.\n *\n * This is the ONE set that separates \"nobody ran it\" from \"it failed\", and the distinction is the whole\n * feature: an optional checklist with no verdict was legitimately not run — declined by the human, or\n * skipped via `--no-optional` — so it must NOT block. An optional checklist with a RED verdict is not in\n * here (it resolves to CK_FAIL) and blocks exactly like a required one: choosing to run a reviewer and\n * then ignoring its answer would make the whole thing theater.\n *\n * A strict subset of {@link pendingChecklists}, computed here rather than at each call site so the\n * command that gates and the dashboard that reports cannot disagree about which checklists were skipped.\n */\n optionalWithoutVerdict(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): RequiredChecklist[] {\n return required.filter((req: RequiredChecklist): boolean =>\n !req.required && this.resolveVerdict(req, results).status === CK_MISSING);\n }\n\n /**\n * The checklists that REFUSED: a reviewer ran, judged the change, and said no (CK_FAIL — status red with\n * no override). A strict subset of {@link pendingChecklists}, split out because it demands a completely\n * different action from the reader.\n *\n * Public so every command agrees on the set. When \"refused\" was computed ad hoc, a refusal and a\n * never-ran reviewer landed in one bucket and produced one message — \"you MUST run these N reviewer\n * subagent(s)\" — handed to an AI, which obediently re-spawned a reviewer that had already answered. It\n * refused again for the same reason, and the loop cost a full subagent run per pass while the reviewer's\n * actual finding was never shown to anyone. A refusal is a RESULT, not a missing step.\n */\n refusedChecklists(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): RequiredChecklist[] {\n return required.filter((req: RequiredChecklist): boolean =>\n this.resolveVerdict(req, results).status === CK_FAIL);\n }\n\n /**\n * THE renderer for \"this reviewer refused\" — one wording, wherever the refusal surfaces. It exists as a\n * method because the text was previously inlined in {@link requiredChecklistErrors}, reachable only\n * through summary.json validation, while the command layer refused earlier with its own generic message.\n * Two messages for one event is how the useful one became unreachable; there is now exactly one.\n *\n * It always quotes the reviewer's own `output` verbatim: the finding is the whole point, and an error\n * that names a checklist without saying what it objected to gives the reader nothing to fix.\n *\n * IT NAMES THE WRITER, which is the half that was missing. The old text said WHAT to write (\"set a\n * non-empty override\") and WHERE, but never WHO MAY — so the only reachable move was an agent editing a\n * reviewer's verdict file in place, which the harness denies, which is how a human ended up hand-editing\n * JSON. The ship-anyway route is now a SEPARATE file the coordinating agent may write, and the command\n * that writes it is printed ready to run. See {@link ChecklistOverrideService.writerRule}.\n *\n * `archivedPath` non-empty ⇒ the verdict has just been RETIRED (moved) to that path, so the message says\n * where the record went — otherwise the move reads as data loss — and that a FRESH verdict is required.\n * The AUTHORIZATION is unaffected by that move: `override-<id>.json` is a different file, it survives the\n * retirement, and a human who already decided to accept this checklist is never asked again.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n refusalError(req: RequiredChecklist, verdict: ChecklistVerdict, summaryJsonFilePath: string, archivedPath = ''): string {\n const finding = `${verdict.detail.split('\\n').join('\\n ')}\\n`;\n const head = `Checklist \"${req.id}\" FAILED review (status:\"${VERDICT_RED}\"). The reviewer (${req.reviewer.agentName}) wrote:\\n ` + finding;\n const retired = archivedPath === ''\n ? ' Fix it, then re-run.\\n'\n // Re-spawning is said only after the finding, because an instruction to spawn a subagent is the\n // one line an AI acts on first — see refusedChecklists for what that cost.\n : ` That verdict has been RETIRED to ${archivedPath} (audit only — it is not a live verdict).\\n` +\n ` A FRESH ${this.checklistFileName(req.id)} is now required. Fix the finding first, then have the ` +\n `\"${req.reviewer.agentName}\" subagent review again and write a new verdict.\\n`;\n return head + retired + this.overrideRoute(req, summaryJsonFilePath);\n }\n\n /**\n * The ship-anyway paragraph: who may authorize, and the exact command that records it.\n *\n * Its own method because every refusal surface must say the identical thing about who may write an\n * override. A second copy of this paragraph is precisely how the previous one drifted into naming a\n * command that had since been deleted.\n */\n private overrideRoute(req: RequiredChecklist, summaryJsonFilePath: string): string {\n return ` To SHIP ANYWAY a human must decide it, and the decision is recorded in its own file — `\n + `${this.overrides.overrideFileName(req.id)}, never inside the reviewer's verdict.\\n`\n + ` ${this.overrides.writerRule()}\\n`\n + ' Run exactly this, replacing only the \"reason\" with what the human actually said:\\n\\n'\n + `${this.overrides.writeCommand(summaryJsonFilePath, req.id)}\\n`;\n }\n\n // Read the per-checklist verdict files `review-<id>.json` beside summary.json — one per matched checklist.\n // A missing file is simply absent from the result (→ counts as MISSING for that checklist); a malformed\n // one is skipped (a stale review-<id>.json never wedges the branch).\n //\n // It looks up the EXACT `review-<id>.json` name per required id — never a directory scan, never a prefix\n // match. That is what guarantees an archived `review-<id>.json.old` can never resolve as a live verdict:\n // the retired file sits right beside the live path, and a scan that swept the directory would hand a\n // RETIRED refusal (or worse, a retired pass) back as the current state, undoing the whole point of the\n // move in {@link archiveChecklistResult}.\n loadChecklistResults(summaryJsonFilePath: string, required: readonly RequiredChecklist[]): ChecklistResult[] {\n const results: ChecklistResult[] = [];\n for (const req of required) {\n const p = this.checklistResultPath(summaryJsonFilePath, req.id);\n if (!fs.existsSync(p)) continue;\n // The human's authorization is read from its OWN file beside the verdict, in the same pass, so\n // resolveVerdict never touches disk and every command resolves one outcome from one read.\n const parsed = this.parseChecklistResult(p, req.id, this.overrides.load(summaryJsonFilePath, req.id));\n if (parsed) results.push(parsed);\n }\n return results;\n }\n\n // Resolve ONE checklist's verdict from its review-<id>.json. Central so summary.json enforcement AND the\n // finish-command dashboard agree on the outcome. `problem` is checked FIRST: a file whose verdict cannot\n // be read must not fall through to any shipping outcome.\n resolveVerdict(req: RequiredChecklist, results: readonly ChecklistResult[]): ChecklistVerdict {\n const result = results.find((r: ChecklistResult): boolean => r.id === req.id);\n if (!result) return new ChecklistVerdict(req.id, CK_MISSING, '');\n if (result.problem !== '') return new ChecklistVerdict(req.id, CK_BAD_FORMAT, result.problem);\n if (result.status === VERDICT_GREEN) return new ChecklistVerdict(req.id, CK_PASS, result.output);\n if (result.status === VERDICT_YELLOW) return new ChecklistVerdict(req.id, CK_WARN, result.output);\n if (result.remediation !== '') return new ChecklistVerdict(req.id, CK_REMEDIATED, result.remediation);\n const override = result.override;\n // A malformed authorization is reported as a FORMAT problem, never treated as one: an override with\n // no stated reason authorizes nothing, and silently ignoring it would tell the reader their decision\n // was not recorded without ever saying why.\n if (override !== null && override.problem !== '') return new ChecklistVerdict(req.id, CK_BAD_FORMAT, override.problem);\n if (override !== null) return new ChecklistVerdict(req.id, CK_OVERRIDDEN, this.overrides.detail(override));\n return new ChecklistVerdict(req.id, CK_FAIL, result.output);\n }\n\n /**\n * One loud complaint per checklist whose verdict file EXISTS but cannot be read as a verdict — almost\n * always one still using the removed `success` field. Public and separate from\n * {@link requiredChecklistErrors} because `wp-finish-upsert-pr` refuses on missing reviewers BEFORE it\n * parses summary.json: without this, a legacy file would surface as the generic \"no verdict yet\" block\n * and the AI would re-run a reviewer that already ran instead of fixing four characters of JSON.\n */\n checklistFormatErrors(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): string[] {\n const errors: string[] = [];\n for (const req of required) {\n const verdict = this.resolveVerdict(req, results);\n if (verdict.status === CK_BAD_FORMAT) errors.push(verdict.detail);\n }\n return errors;\n }\n\n // Every matched checklist whose verdict is FAIL (reviewed, found a problem, no override) or MISSING (no\n // review-<id>.json written) → one error each, printing the reviewer's `output` verbatim.\n private requiredChecklistErrors(\n required: readonly RequiredChecklist[], results: readonly ChecklistResult[], filePath: string,\n ): string[] {\n // Format complaints come from the ONE renderer, so wp-review-upsert-pr and wp-finish word them identically.\n const errors: string[] = this.checklistFormatErrors(required, results);\n for (const req of required) {\n const verdict = this.resolveVerdict(req, results);\n // CK_WARN ('yellow' — passed with concerns) is deliberately absent from this chain: it SHIPS.\n // The concern still reaches the PR, published in the checklist comment. Do not \"fix\" this.\n if (verdict.status === CK_FAIL) {\n // Through the ONE renderer, so this path and the command layer's refusal say the same thing.\n // No archive path here: this is validation, not the act of retiring the verdict.\n errors.push(this.refusalError(req, verdict, filePath));\n } else if (verdict.status === CK_MISSING) {\n // An OPTIONAL checklist with no verdict was legitimately not run — the human was offered it\n // and declined (or `--no-optional` skipped the offer). Demanding it here would make\n // `required: false` mean nothing. Note the CK_FAIL branch above deliberately has no such\n // exemption: once an optional reviewer RUNS, its refusal counts.\n if (!req.required) continue;\n const doc = req.doc.trim() !== '' ? ` Read: ${req.doc}.` : '';\n errors.push(\n `Checklist \"${req.id}\" MATCHED this diff but has no verdict. Spawn the \"${req.reviewer.agentName}\" subagent to review it; ` +\n `IT submits the verdict with ${this.submitCommand(req.id)} — nobody writes ${this.checklistFileName(req.id)} by hand.${doc}`,\n );\n }\n }\n return errors;\n }\n\n private checklistFileName(checklistId: string): string {\n return `review-${checklistId}.json`;\n }\n\n /**\n * THE renderer for a reviewer's verdict schema — with the reviewer's own `id` already filled in.\n *\n * There is one because a verdict schema that lives anywhere a human maintains it goes stale, and a\n * reviewer follows the stale copy. That is not a hypothetical: when `success` was replaced by the\n * tri-state `status`, hand-written `.claude/agents/*.md` files kept documenting `success`, and a real\n * PR had to carry \"the verdict format in your own agent .md file is OUT OF DATE\" in the spawn prompt to\n * work around it. Every printed copy — the stage-② roster, the generated per-reviewer instructions\n * file, and the complaint raised against a malformed verdict — now comes from here. It ends with the\n * ONE way a verdict is submitted (`wp-write-review`, issue #863), never a file path to write.\n */\n renderVerdictSchema(id: string, indent = ' '): string {\n return new VerdictSchemaRenderer().render(id, indent);\n }\n\n /** THE command that submits one checklist's verdict (issue #863) — see VerdictSchemaRenderer. */\n submitCommand(id: string): string {\n return new VerdictSchemaRenderer().submitCommand(id);\n }\n\n // Unreadable objects retain their format complaint; absent/unparseable verdicts return null.\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field\n private parseChecklistResult(filePath: string, id: string, override: ChecklistOverride | null): ChecklistResult | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unparseable per-checklist file is skipped, not fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed below\n const raw = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null;\n const output = typeof raw['output'] === 'string' ? (raw['output'] as string) : '';\n const status = typeof raw['status'] === 'string' ? (raw['status'] as string).trim().toLowerCase() : '';\n const agent = typeof raw['agent'] === 'string' ? raw['agent'].trim() : '';\n const model = typeof raw['model'] === 'string' ? raw['model'].trim() : '';\n const identityProblem = agent === '' || model === ''\n ? 'Both \"agent\" and \"model\" must be non-empty strings; use \"unknown\" when unavailable.' : '';\n return new ChecklistResult(agent, model, id, status, output, override,\n this.verdictProblem(filePath, id, status, raw) || identityProblem);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * '' when the verdict can be READ. Otherwise the complaint to show the AI verbatim.\n *\n * The MOVED `override` field is checked FIRST, ahead of `status`, because it is the more specific fact: a\n * file carrying it was written against a schema that no longer exists, and a reader told only \"status\n * must be green|yellow|red\" would fix the wrong thing. It is rejected even when EMPTY — an accepted shape\n * is never migrated, and `\"override\": \"\"` sitting in a reviewer's file is the copy that teaches the next\n * reviewer the field still exists.\n *\n * The legacy-`success` case keeps its OWN message for the same reason: `success` was removed outright\n * (no compatibility mode), and a reviewer cannot tell a wrong value from a field that no longer exists.\n */\n // webpieces-disable no-any-unknown -- opaque parsed JSON; only tested for key presence here\n private verdictProblem(filePath: string, id: string, status: string, raw: Record<string, unknown>): string {\n // The ONE renderer — see renderVerdictSchema. A second copy here is what let the old `success` shape\n // survive in print after it was removed from the parser.\n const shape = this.renderVerdictSchema(id);\n if ('override' in raw) {\n return `Checklist \"${id}\" wrote its verdict with the MOVED \"override\" field. A ship-anyway `\n + 'authorization is no longer part of a reviewer\\'s verdict: it MOVED to its own file, '\n + `${this.overrides.overrideFileName(id)}, which only the coordinating agent writes and only on a `\n + 'human\\'s in-session instruction. There is no compatibility mode — DELETE the \"override\" key from '\n + `${filePath} by resubmitting it:\\n${shape}`;\n }\n // webpieces-disable no-any-unknown -- comparing against the readonly literal tuple of valid colors\n if ((VERDICT_STATUSES as readonly string[]).includes(status)) return '';\n if ('success' in raw) {\n return `Checklist \"${id}\" wrote its verdict with the REMOVED \"success\" field. It is now a tri-state ` +\n `\"status\" — there is no compatibility mode. Resubmit it as:\\n${shape}`;\n }\n return `Checklist \"${id}\" wrote a verdict with no valid \"status\" (got ${JSON.stringify(status)}). ` +\n `It must be exactly one of ${VERDICT_STATUSES.join(', ')}:\\n${shape}`;\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON value, narrowed to string[] here\n private asStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n // webpieces-disable no-any-unknown -- element of an opaque JSON array, narrowed by the type guard\n return value.filter((v: unknown): v is string => typeof v === 'string');\n }\n\n // Parse opaque AI-authored JSON, converting a SyntaxError into a readable InformAiError.\n // webpieces-disable no-any-unknown -- returns the opaque parsed object; loadSummaryJson narrows each field\n private parseSummaryJson(\n raw: string, filePath: string, expectedMainAgentInstructions = '',\n ): Record<string, unknown> {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: convert JSON.parse SyntaxError to an InformAiError for the AI\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(raw) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(\n `summary.json is not valid JSON (${error.message}).\\n\\n` +\n `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\\n\\n` +\n `Then re-run: pnpm wp-finish-upsert-pr`,\n );\n }\n }\n}\n\n// Temporary migration delegators to ReviewJsonService — removed once consumers inject it.\nconst reviewJsonSvc = new ReviewJsonService();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ReviewJsonService; removed once consumers inject it\nexport function prDirFor(repoRoot: string, featureName: string): string {\n return reviewJsonSvc.prDirFor(repoRoot, featureName);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ReviewJsonService; removed once consumers inject it\nexport function summaryJsonPath(repoRoot: string, featureName: string): string {\n return reviewJsonSvc.summaryJsonPath(repoRoot, featureName);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ReviewJsonService; removed once consumers inject it\nexport function summaryJsonSchemaHint(filePath: string, mainAgentInstructions = ''): string {\n return reviewJsonSvc.summaryJsonSchemaHint(filePath, mainAgentInstructions);\n}\n"]}
1
+ {"version":3,"file":"review-json.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/review-json.ts"],"names":[],"mappings":";;;AAypBA,4BAEC;AAGD,0CAEC;AAGD,sDAEC;;AArqBD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAC3D,2CAA4C;AAC5C,2CAAyD;AACzD,uDAAkD;AAClD,yCAAqC;AACrC,iFAA2E;AAC3E,uEAAkE;AAClE,6DAA6G;AAsBpG,kGAtBA,sCAAiB,OAsBA;AAAE,yGAtBA,6CAAwB,OAsBA;AAAE,yGAtBA,6CAAwB,OAsBA;AArB9E,yDAkB4B;AAKxB,8FAtBA,gCAAa,OAsBA;AACb,+FAtBA,iCAAc,OAsBA;AACd,4F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AiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGR,wBAAY;QACT,6CAAwB;GAH/C,iBAAiB,CAmkB7B;AAED,0FAA0F;AAC1F,MAAM,aAAa,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAE9C,wIAAwI;AACxI,SAAgB,QAAQ,CAAC,QAAgB,EAAE,WAAmB;IAC1D,OAAO,aAAa,CAAC,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;AACzD,CAAC;AAED,wIAAwI;AACxI,SAAgB,eAAe,CAAC,QAAgB,EAAE,WAAmB;IACjE,OAAO,aAAa,CAAC,eAAe,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;AAChE,CAAC;AAED,wIAAwI;AACxI,SAAgB,qBAAqB,CAAC,QAAgB,EAAE,qBAAqB,GAAG,EAAE;IAC9E,OAAO,aAAa,CAAC,qBAAqB,CAAC,QAAQ,EAAE,qBAAqB,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { PR_REVIEW_DIR } from './constants';\nimport { DotWebpieces, dotWebpieces } from './state-dir';\nimport { InformAiError } from './inform-ai-error';\nimport { toError } from './to-error';\nimport { SummaryJsonSchemaRenderer } from './summary-json-schema-renderer';\nimport { VerdictSchemaRenderer } from './verdict-schema-renderer';\nimport { ChecklistOverride, ChecklistOverrideService, checklistOverrideService } from './checklist-override';\nimport {\n VERDICT_GREEN,\n VERDICT_YELLOW,\n VERDICT_RED,\n VERDICT_STATUSES,\n ChecklistResult,\n RequiredChecklist,\n ChecklistReviewContext,\n PrSummary,\n CK_PASS,\n CK_WARN,\n CK_OVERRIDDEN,\n CK_REMEDIATED,\n CK_FAIL,\n CK_MISSING,\n CK_BAD_FORMAT,\n ChecklistVerdict,\n PrContext,\n} from './review-json-data';\n\n// Re-exported so review-json.ts stays the single import site for the review vocabulary.\nexport { ChecklistOverride, ChecklistOverrideService, checklistOverrideService };\nexport {\n VERDICT_GREEN,\n VERDICT_YELLOW,\n VERDICT_RED,\n VERDICT_STATUSES,\n ChecklistResult,\n RequiredChecklist,\n ChecklistReviewContext,\n PrSummary,\n CK_PASS,\n CK_WARN,\n CK_OVERRIDDEN,\n CK_REMEDIATED,\n CK_FAIL,\n CK_MISSING,\n CK_BAD_FORMAT,\n ChecklistVerdict,\n PrContext,\n};\n\nconst RISK_LEVELS = ['green', 'yellow', 'red'] as const;\nconst EMOJI_FOR_LEVEL: Record<string, string> = { green: '🟢', yellow: '🟡', red: '🔴' };\n\n// Where `wp-finish-upsert-pr` retires the summary.json it just consumed, and the note it stamps on the way.\n// The key sorts first in the written JSON because it is written first — an AI that opens the file to see\n// whether it can reuse the summary reads what the file IS before it reads a title it might be tempted to keep.\nconst OLD_SUMMARY_FILE = 'old-summary.json';\nconst ARCHIVE_NOTE_KEY = '_ARCHIVED_AUDIT_ONLY';\nconst ARCHIVE_NOTE =\n 'ARCHIVE — this is the PR summary from the PREVIOUS wp-finish-upsert-pr run on this branch, kept for audit ' +\n 'purposes only. It is NOT the summary for a new round: it describes the code as of the last PR ' +\n 'update, which has since moved. If you are updating the PR again, write a FRESH summary.json at the path ' +\n \"pnpm wp-review-upsert-pr prints; do not copy this file's title, summary or risk level forward without \" +\n 're-deciding each one. Overwritten by every finish, so only the most recent summary is ever here.';\n\n// The same stamp, for a retired per-checklist verdict. Verdict files get their OWN wording because the two\n// archives answer different questions: old-summary.json holds a description of the code, this holds a\n// REVIEWER'S DECISION. The one thing that must not happen is a reader treating an archived red as the live\n// verdict — the whole reason the file was moved rather than copied — so the note says that outright.\nconst CHECKLIST_ARCHIVE_NOTE =\n 'ARCHIVE — this is a checklist verdict from a PREVIOUS reviewer run on this branch, kept for audit ' +\n 'purposes only. It is NOT a live verdict and must never be read back as one: it was RETIRED because it ' +\n 'refused the PR, and the gate moved it here so the only way forward is a FRESH review-<id>.json written ' +\n 'by a real reviewer run. Do not copy its status back onto the live path to get past the gate. ' +\n 'Overwritten by every retirement, so only the most recently retired verdict is ever here.';\n\n/** Locates + loads/validates the AI-authored summary.json. `@injectable(bindingScopeValues.Singleton)` so it's drawn in the design. */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewJsonService {\n constructor(\n private readonly dotDir: DotWebpieces = dotWebpieces,\n private readonly overrides: ChecklistOverrideService = checklistOverrideService,\n ) {}\n\n // The per-feature PR working dir: `<worktree>/.webpieces/pr-review/<feature>`. AI-WRITABLE scope,\n // not local() — an agent AUTHORS summary.json here, and each reviewer subagent authors its own\n // review-<id>.json beside it. A worktree-isolated agent's Write is refused for any path under the\n // shared checkout, which is where local() puts this, so local() made both files unwritable by the\n // very agents the flow instructs to write them. See DotWebpieces.aiWritable() for the full account.\n prDirFor(repoRoot: string, featureName: string): string {\n return this.dotDir.aiWritableFile(repoRoot, PR_REVIEW_DIR, featureName);\n }\n\n // Absolute path of the summary.json for a feature — beside pr-body.md, keyed by branch name.\n summaryJsonPath(repoRoot: string, featureName: string): string {\n return path.join(this.prDirFor(repoRoot, featureName), 'summary.json');\n }\n\n // Absolute path of the pr-context.json for a feature (the diff base/head + changed files).\n prContextPath(repoRoot: string, featureName: string): string {\n return path.join(this.prDirFor(repoRoot, featureName), 'pr-context.json');\n }\n\n // Where a consumed summary.json is archived to, beside it. Always the SAME path — it holds the last\n // summary and only the last one, so it can never be mistaken for a series that means something.\n oldSummaryJsonPath(summaryJsonFilePath: string): string {\n return path.join(path.dirname(summaryJsonFilePath), OLD_SUMMARY_FILE);\n }\n\n /**\n * Retire the PR summary `wp-finish-upsert-pr` just used: move summary.json to old-summary.json, stamped\n * with a note saying what it is. Returns the archive path, or '' when there was nothing to archive.\n *\n * The point is the MOVE, not the copy. summary.json left in place after a PR is posted is a live-looking\n * file describing a PR update that already happened, and the next run of stage ② on this branch finds it\n * sitting there — so a reviewer subagent that judges the PR's stated intent (its title, summary or risk\n * level) can read the previous run's summary and return GREEN against a title that no longer exists.\n * Nothing in the verdict distinguishes that from a real pass. Moving it means the only way to reach\n * finish again is to write a fresh one, and {@link loadSummaryJson} points at the archive when it is\n * missing so the archive reads as an audit trail rather than as a lost file.\n *\n * Called only after the PR is actually up: a finish that failed before publishing must stay re-runnable.\n */\n archiveSummaryJson(summaryJsonFilePath: string): string {\n if (!fs.existsSync(summaryJsonFilePath)) return '';\n const archivePath = this.oldSummaryJsonPath(summaryJsonFilePath);\n const raw = fs.readFileSync(summaryJsonFilePath, 'utf8');\n fs.writeFileSync(archivePath, this.archivedBody(raw, ARCHIVE_NOTE));\n fs.rmSync(summaryJsonFilePath);\n return archivePath;\n }\n\n /**\n * The archived bytes: the original JSON with an AUDIT-ONLY note as its FIRST key, so anything that opens\n * the file — human or AI — reads what it is before it reads any of its content.\n *\n * `note` is a parameter rather than a constant because two different files are archived here (summary.json\n * and review-<id>.json) and they need to say different things, while the stamping MECHANICS — parse,\n * note first, original keys in order, fall back to raw — are identical. One implementation, two texts;\n * a second copy of this method would be the thing that drifts.\n *\n * Falls back to the raw bytes when they do not parse. For summary.json `loadSummaryJson` has already\n * accepted the file so that is close to impossible, but a verdict file is written by a subagent and may\n * be half-written or not an object at all — and preserving the original always beats losing it to a\n * stamping failure, since the archive exists precisely to be the record.\n */\n private archivedBody(raw: string, note: string): string {\n const parsed = this.tryParseObject(raw);\n if (parsed === null) return raw;\n // webpieces-disable no-any-unknown -- re-serializing opaque review fields verbatim; only the key ORDER is ours\n const stamped: Record<string, unknown> = {};\n stamped[ARCHIVE_NOTE_KEY] = note;\n for (const key of Object.keys(parsed)) stamped[key] = parsed[key];\n return JSON.stringify(stamped, null, 2) + '\\n';\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON; the caller only re-serializes it\n private tryParseObject(raw: string): Record<string, unknown> | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unparseable bytes are archived verbatim, never fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque; only its key order is used\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null;\n return parsed;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * Persist the PR's diff context so reviewer subagents can read the changed-file set + the exact base\n * sha. Returns the file path written.\n *\n * ALSO writes an immutable per-stage snapshot under `stages/<stage>.json` when `stage` is given.\n * `pr-context.json` is overwritten by each stage, so by the time anything goes wrong the earlier\n * states are gone — and \"what did the tooling think the diff was at stage ①, vs ②, vs ③?\" is exactly\n * the question you need answered when debugging a review that went sideways. The snapshots make the\n * review system auditable by an AI reviewing IT, which the single mutable file never could.\n */\n writePrContext(repoRoot: string, featureName: string, context: PrContext, stage = ''): string {\n const dir = this.prDirFor(repoRoot, featureName);\n fs.mkdirSync(dir, { recursive: true });\n const body = JSON.stringify(context, null, 2) + '\\n';\n const p = this.prContextPath(repoRoot, featureName);\n fs.writeFileSync(p, body);\n if (stage !== '') {\n const stagesDir = path.join(dir, 'stages');\n fs.mkdirSync(stagesDir, { recursive: true });\n fs.writeFileSync(path.join(stagesDir, `${stage}.json`), body);\n }\n return p;\n }\n\n /**\n * The review context for a feature, recovered from the pr-context.json wp-start-upsert-pr already wrote.\n * Lets wp-finish-upsert-pr's \"you still owe me review-<id>.json\" message inline the SAME self-sufficient\n * per-reviewer block start printed, instead of a checklist name and an indirection. Empty when the file\n * is absent or unreadable — the block then just omits those lines.\n */\n reviewContextFor(repoRoot: string, featureName: string): ChecklistReviewContext {\n const p = this.prContextPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return new ChecklistReviewContext();\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable context file degrades to fewer printed lines, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed on the next line\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n const base = typeof raw['base'] === 'string' ? (raw['base'] as string) : '';\n // Recover the REPRODUCE command rather than re-deriving it: a context written by an older\n // pr-gate has no diffCommand, and guessing `<base> HEAD` there would resurrect the exact\n // empty-on-a-dirty-tree bug this field exists to kill. Absent ⇒ omit the line entirely.\n const cmd = typeof raw['diffCommand'] === 'string' ? (raw['diffCommand'] as string) : '';\n const diffDir = typeof raw['diffDir'] === 'string' ? (raw['diffDir'] as string) : '';\n const dirty = raw['dirty'] === true;\n return new ChecklistReviewContext(base, p, cmd === '' ? '' : `${cmd} -- <file>`, diffDir, dirty);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return new ChecklistReviewContext('', p);\n }\n }\n\n // Copy-paste summary.json schema shared by every command that asks the coordinating AI to write it.\n summaryJsonSchemaHint(filePath: string, mainAgentInstructions = ''): string {\n return new SummaryJsonSchemaRenderer().render(filePath, mainAgentInstructions);\n }\n\n /**\n * The extra line the \"no summary.json\" complaint carries when a PREVIOUS summary was archived here. It\n * turns a bare \"not found\" — which reads as data loss, and invites hunting for the file — into the fact:\n * the last finish consumed it, and the archive is audit material, not a summary to reuse.\n */\n private archivedSummaryHint(filePath: string, retryCommand: string): string {\n const archive = this.oldSummaryJsonPath(filePath);\n if (!fs.existsSync(archive)) return '';\n return `\\nA PREVIOUS PR summary was archived to ${archive} when the last ${retryCommand} consumed it.\\n` + `That file is for AUDIT ONLY — it describes code this branch has since moved past. Write a fresh one:`;\n }\n\n // Names summary.json when the author wrote its OLD name (review.json until #1033 — refused by Claude\n // auto-mode as Self-Approval beside the review-<id>.json verdicts). HARD CUT: the stale file is never read.\n private renamedFileHint(filePath: string): string {\n const stale = path.join(path.dirname(filePath), 'review.json');\n if (!fs.existsSync(stale)) return '';\n return `\\n${stale} is IGNORED — the author's file was renamed to summary.json. ` + `Write the same JSON to ${filePath} instead.`;\n }\n\n // The per-checklist review file path that sits beside summary.json: review-<id>.json.\n checklistResultPath(summaryJsonFilePath: string, checklistId: string): string {\n return path.join(path.dirname(summaryJsonFilePath), `review-${checklistId}.json`);\n }\n\n /**\n * Where a RETIRED verdict for one checklist goes: `review-<id>.json.old`, beside the live path.\n *\n * Mirrors {@link oldSummaryJsonPath} deliberately, including its single-slot rule: ALWAYS the same path,\n * so it holds the last retired verdict and only the last one. A series (`.old.old`, `.old.1`) would read\n * as though the number of retirements meant something, and nothing downstream can interpret that — the\n * one fact worth keeping is \"this checklist refused before, here is what it said\".\n */\n oldChecklistResultPath(summaryJsonFilePath: string, checklistId: string): string {\n return `${this.checklistResultPath(summaryJsonFilePath, checklistId)}.old`;\n }\n\n /**\n * Retire one checklist's verdict: MOVE review-<id>.json to review-<id>.json.old, stamped with a note\n * saying what it is. Returns the archive path, or '' when there was nothing to archive.\n *\n * The point is the MOVE, exactly as in {@link archiveSummaryJson}. A red verdict left on the live path is\n * re-read by the next run and re-reported as the CURRENT state of the branch, so the branch keeps being\n * refused for a finding that may already be fixed — and the fix, when it comes, silently overwrites the\n * only record that the gate ever refused anything. Moving it makes the refusal durable and makes a fresh\n * reviewer run the only way forward, which is the honest requirement: the old verdict judged code that\n * has since changed.\n *\n * Safe by construction for RED verdicts specifically, which is why the caller only archives on CK_FAIL:\n * a red verdict is never reusable — it always blocks — so nothing is lost by moving it. Green and yellow\n * verdicts ARE deliberately reused across finish attempts, and retiring one would force a needless (and\n * expensive) subagent re-run.\n */\n archiveChecklistResult(summaryJsonFilePath: string, checklistId: string): string {\n const livePath = this.checklistResultPath(summaryJsonFilePath, checklistId);\n if (!fs.existsSync(livePath)) return '';\n const archivePath = this.oldChecklistResultPath(summaryJsonFilePath, checklistId);\n const raw = fs.readFileSync(livePath, 'utf8');\n fs.writeFileSync(archivePath, this.archivedBody(raw, CHECKLIST_ARCHIVE_NOTE));\n fs.rmSync(livePath);\n return archivePath;\n }\n\n /**\n * Load + validate the AI-authored summary.json. Throws InformAiError (with the schema) when missing,\n * unparseable, or structurally wrong. `required` is the set of checklists the diff matched: every one\n * must have a well-formed, passing (or overridden) review-<id>.json or a validation error is raised\n * alongside the usual ones so the AI gets ONE message.\n */\n // webpieces-disable max-lines-new-methods -- one cohesive load+validate pass over the review fields\n loadSummaryJson(\n filePath: string, required: readonly RequiredChecklist[] = [], expectedMainAgentInstructions = '',\n remediations: Record<string, string> = {},\n retryCommand = 'pnpm wp-finish-upsert-pr',\n ): PrSummary {\n const raw = this.readSummaryObject(filePath, expectedMainAgentInstructions, retryCommand);\n const errors: string[] = [];\n for (const field of ['agent', 'model']) {\n if (typeof raw[field] !== 'string' || raw[field].trim() === '') {\n errors.push(`\"${field}\" must be a non-empty string; use \"unknown\" when unavailable.`);\n }\n }\n const riskScore = raw['riskScore'];\n if (typeof riskScore !== 'number' || !Number.isFinite(riskScore) || riskScore < 0 || riskScore > 100) {\n errors.push(`\"riskScore\" must be a number 0–100, got ${JSON.stringify(riskScore)}.`);\n }\n const riskLevel = raw['riskLevel'];\n if (typeof riskLevel !== 'string' || !RISK_LEVELS.includes(riskLevel as (typeof RISK_LEVELS)[number])) {\n errors.push(`\"riskLevel\" must be one of: ${RISK_LEVELS.join(', ')}.`);\n }\n const title = typeof raw['title'] === 'string' ? (raw['title'] as string).trim() : '';\n if (title === '') {\n errors.push('\"title\" must be a non-empty, imperative PR title describing the change (no branch names).');\n }\n const mainAgentInstructions = this.validateMainAgentInstructions(raw, expectedMainAgentInstructions, errors);\n\n const results = this.loadChecklistResults(filePath, required);\n for (const result of results) result.remediation = remediations[result.id] ?? '';\n for (const err of this.requiredChecklistErrors(required, results, filePath)) errors.push(err);\n\n this.assertValidSummary(errors, filePath, expectedMainAgentInstructions, retryCommand);\n\n const level = riskLevel as string;\n const emoji = typeof raw['riskEmoji'] === 'string' && raw['riskEmoji'] !== '' ? (raw['riskEmoji'] as string) : (EMOJI_FOR_LEVEL[level] ?? '🟡');\n const summary = typeof raw['summary'] === 'string' ? (raw['summary'] as string) : '';\n\n return new PrSummary((raw['agent'] as string).trim(), (raw['model'] as string).trim(), title, riskScore as number, level, emoji, summary, this.asStringArray(raw['violations']), this.asStringArray(raw['risks']), this.asStringArray(raw['filesToReview']), results, mainAgentInstructions);\n }\n\n private assertValidSummary(errors: string[], filePath: string, expectedMainAgentInstructions: string, retryCommand: string): void {\n if (errors.length === 0) return;\n throw new InformAiError(`summary.json has ${errors.length} error(s) — fix ALL, then re-run ${retryCommand}:\\n\\n` + errors.map((e: string): string => ` • ${e}`).join('\\n') + `\\n\\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}`);\n }\n\n /** Load the raw object and render every parse/shape error for the command that called us. */\n private readSummaryObject(\n filePath: string,\n expectedMainAgentInstructions: string,\n retryCommand: string,\n // webpieces-disable-next-line no-any-unknown -- opaque JSON is narrowed field-by-field by loadSummaryJson\n ): Record<string, unknown> {\n if (!fs.existsSync(filePath)) {\n throw new InformAiError(`Required summary.json not found.${this.renamedFileHint(filePath)}${this.archivedSummaryHint(filePath, retryCommand)}\\n\\n` + `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\\n\\n` + `Then re-run: ${retryCommand}`);\n }\n const raw = this.parseSummaryJson(fs.readFileSync(filePath, 'utf8'), filePath, expectedMainAgentInstructions, retryCommand);\n if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) return raw;\n throw new InformAiError(`summary.json must be a JSON object.\\n\\n${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}` + `\\n\\nThen re-run: ${retryCommand}`);\n }\n\n // webpieces-disable no-any-unknown -- AI-authored JSON boundary is validated before use\n private validateMainAgentInstructions(\n // webpieces-disable no-any-unknown -- opaque parsed JSON; only tested for key presence below\n raw: Record<string, unknown>,\n expected: string,\n errors: string[],\n ): string {\n const actual = typeof raw['main_agent_instructions'] === 'string' ? (raw['main_agent_instructions'] as string).trim() : '';\n if (expected !== '' && actual !== expected) errors.push('\"main_agent_instructions\" must exactly preserve the single-round instructions printed by stage ②.');\n return actual;\n }\n\n /**\n * The checklists that still OWE a verdict: no review-<id>.json at all, a malformed one, or one whose\n * verdict is an un-overridden FAIL. This is the set every message lists — a checklist already PASSed or\n * OVERRIDDEN on this branch is deliberately NOT re-listed, because re-instructing it invites a redundant\n * second run and reads as though the earlier verdict did not count.\n */\n pendingChecklists(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): RequiredChecklist[] {\n return required.filter((req: RequiredChecklist): boolean => {\n const status = this.resolveVerdict(req, results).status;\n // CK_WARN must be listed here beside PASS/OVERRIDDEN. A yellow verdict SHIPS — leaving it out\n // would mark the checklist owed forever, so `outstanding` never empties and the PR is refused\n // permanently no matter how many times the reviewer runs.\n return status !== CK_PASS && status !== CK_WARN && status !== CK_OVERRIDDEN && status !== CK_REMEDIATED;\n });\n }\n\n /**\n * The OPTIONAL checklists (`required: false`) that matched the diff but have no verdict file at all.\n *\n * This is the ONE set that separates \"nobody ran it\" from \"it failed\", and the distinction is the whole\n * feature: an optional checklist with no verdict was legitimately not run — declined by the human, or\n * skipped via `--no-optional` — so it must NOT block. An optional checklist with a RED verdict is not in\n * here (it resolves to CK_FAIL) and blocks exactly like a required one: choosing to run a reviewer and\n * then ignoring its answer would make the whole thing theater.\n *\n * A strict subset of {@link pendingChecklists}, computed here rather than at each call site so the\n * command that gates and the dashboard that reports cannot disagree about which checklists were skipped.\n */\n optionalWithoutVerdict(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): RequiredChecklist[] {\n return required.filter((req: RequiredChecklist): boolean => !req.required && this.resolveVerdict(req, results).status === CK_MISSING);\n }\n\n /**\n * The checklists that REFUSED: a reviewer ran, judged the change, and said no (CK_FAIL — status red with\n * no override). A strict subset of {@link pendingChecklists}, split out because it demands a completely\n * different action from the reader.\n *\n * Public so every command agrees on the set. When \"refused\" was computed ad hoc, a refusal and a\n * never-ran reviewer landed in one bucket and produced one message — \"you MUST run these N reviewer\n * subagent(s)\" — handed to an AI, which obediently re-spawned a reviewer that had already answered. It\n * refused again for the same reason, and the loop cost a full subagent run per pass while the reviewer's\n * actual finding was never shown to anyone. A refusal is a RESULT, not a missing step.\n */\n refusedChecklists(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): RequiredChecklist[] {\n return required.filter((req: RequiredChecklist): boolean => this.resolveVerdict(req, results).status === CK_FAIL);\n }\n\n /**\n * THE renderer for \"this reviewer refused\" — one wording, wherever the refusal surfaces. It exists as a\n * method because the text was previously inlined in {@link requiredChecklistErrors}, reachable only\n * through summary.json validation, while the command layer refused earlier with its own generic message.\n * Two messages for one event is how the useful one became unreachable; there is now exactly one.\n *\n * It always quotes the reviewer's own `output` verbatim: the finding is the whole point, and an error\n * that names a checklist without saying what it objected to gives the reader nothing to fix.\n *\n * IT NAMES THE WRITER, which is the half that was missing. The old text said WHAT to write (\"set a\n * non-empty override\") and WHERE, but never WHO MAY — so the only reachable move was an agent editing a\n * reviewer's verdict file in place, which the harness denies, which is how a human ended up hand-editing\n * JSON. The ship-anyway route is now a SEPARATE file the coordinating agent may write, and the command\n * that writes it is printed ready to run. See {@link ChecklistOverrideService.writerRule}.\n *\n * `archivedPath` non-empty ⇒ the verdict has just been RETIRED (moved) to that path, so the message says\n * where the record went — otherwise the move reads as data loss — and that a FRESH verdict is required.\n * The AUTHORIZATION is unaffected by that move: `override-<id>.json` is a different file, it survives the\n * retirement, and a human who already decided to accept this checklist is never asked again.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n refusalError(req: RequiredChecklist, verdict: ChecklistVerdict, summaryJsonFilePath: string, archivedPath = ''): string {\n const finding = `${verdict.detail.split('\\n').join('\\n ')}\\n`;\n const head = `Checklist \"${req.id}\" FAILED review (status:\"${VERDICT_RED}\"). The reviewer (${req.reviewer.agentName}) wrote:\\n ` + finding;\n const retired =\n archivedPath === ''\n ? ' Fix it, then re-run.\\n'\n : // Re-spawning is said only after the finding, because an instruction to spawn a subagent is the\n // one line an AI acts on first — see refusedChecklists for what that cost.\n ` That verdict has been RETIRED to ${archivedPath} (audit only — it is not a live verdict).\\n` +\n ` A FRESH ${this.checklistFileName(req.id)} is now required. Fix the finding first, then have the ` +\n `\"${req.reviewer.agentName}\" subagent review again and write a new verdict.\\n`;\n return head + retired + this.overrideRoute(req, summaryJsonFilePath);\n }\n\n /**\n * The ship-anyway paragraph: who may authorize, and the exact command that records it.\n *\n * Its own method because every refusal surface must say the identical thing about who may write an\n * override. A second copy of this paragraph is precisely how the previous one drifted into naming a\n * command that had since been deleted.\n */\n private overrideRoute(req: RequiredChecklist, summaryJsonFilePath: string): string {\n return (\n ` To SHIP ANYWAY a human must decide it, and the decision is recorded in its own file — ` +\n `${this.overrides.overrideFileName(req.id)}, never inside the reviewer's verdict.\\n` +\n ` ${this.overrides.writerRule()}\\n` +\n ' Run exactly this, replacing only the \"reason\" with what the human actually said:\\n\\n' +\n `${this.overrides.writeCommand(summaryJsonFilePath, req.id)}\\n`\n );\n }\n\n // Read the per-checklist verdict files `review-<id>.json` beside summary.json — one per matched checklist.\n // A missing file is simply absent from the result (→ counts as MISSING for that checklist); a malformed\n // one is skipped (a stale review-<id>.json never wedges the branch).\n //\n // It looks up the EXACT `review-<id>.json` name per required id — never a directory scan, never a prefix\n // match. That is what guarantees an archived `review-<id>.json.old` can never resolve as a live verdict:\n // the retired file sits right beside the live path, and a scan that swept the directory would hand a\n // RETIRED refusal (or worse, a retired pass) back as the current state, undoing the whole point of the\n // move in {@link archiveChecklistResult}.\n loadChecklistResults(summaryJsonFilePath: string, required: readonly RequiredChecklist[]): ChecklistResult[] {\n const results: ChecklistResult[] = [];\n for (const req of required) {\n const p = this.checklistResultPath(summaryJsonFilePath, req.id);\n if (!fs.existsSync(p)) continue;\n // The human's authorization is read from its OWN file beside the verdict, in the same pass, so\n // resolveVerdict never touches disk and every command resolves one outcome from one read.\n const parsed = this.parseChecklistResult(p, req.id, this.overrides.load(summaryJsonFilePath, req.id));\n if (parsed) results.push(parsed);\n }\n return results;\n }\n\n // Resolve ONE checklist's verdict from its review-<id>.json. Central so summary.json enforcement AND the\n // finish-command dashboard agree on the outcome. `problem` is checked FIRST: a file whose verdict cannot\n // be read must not fall through to any shipping outcome.\n resolveVerdict(req: RequiredChecklist, results: readonly ChecklistResult[]): ChecklistVerdict {\n const result = results.find((r: ChecklistResult): boolean => r.id === req.id);\n if (!result) return new ChecklistVerdict(req.id, CK_MISSING, '');\n if (result.problem !== '') return new ChecklistVerdict(req.id, CK_BAD_FORMAT, result.problem);\n if (result.status === VERDICT_GREEN) return new ChecklistVerdict(req.id, CK_PASS, result.output);\n if (result.status === VERDICT_YELLOW) return new ChecklistVerdict(req.id, CK_WARN, result.output);\n if (result.remediation !== '') return new ChecklistVerdict(req.id, CK_REMEDIATED, result.remediation);\n const override = result.override;\n // A malformed authorization is reported as a FORMAT problem, never treated as one: an override with\n // no stated reason authorizes nothing, and silently ignoring it would tell the reader their decision\n // was not recorded without ever saying why.\n if (override !== null && override.problem !== '') return new ChecklistVerdict(req.id, CK_BAD_FORMAT, override.problem);\n if (override !== null) return new ChecklistVerdict(req.id, CK_OVERRIDDEN, this.overrides.detail(override));\n return new ChecklistVerdict(req.id, CK_FAIL, result.output);\n }\n\n /**\n * One loud complaint per checklist whose verdict file EXISTS but cannot be read as a verdict — almost\n * always one still using the removed `success` field. Public and separate from\n * {@link requiredChecklistErrors} because `wp-finish-upsert-pr` refuses on missing reviewers BEFORE it\n * parses summary.json: without this, a legacy file would surface as the generic \"no verdict yet\" block\n * and the AI would re-run a reviewer that already ran instead of fixing four characters of JSON.\n */\n checklistFormatErrors(required: readonly RequiredChecklist[], results: readonly ChecklistResult[]): string[] {\n const errors: string[] = [];\n for (const req of required) {\n const verdict = this.resolveVerdict(req, results);\n if (verdict.status === CK_BAD_FORMAT) errors.push(verdict.detail);\n }\n return errors;\n }\n\n // Every matched checklist whose verdict is FAIL (reviewed, found a problem, no override) or MISSING (no\n // review-<id>.json written) → one error each, printing the reviewer's `output` verbatim.\n private requiredChecklistErrors(required: readonly RequiredChecklist[], results: readonly ChecklistResult[], filePath: string): string[] {\n // Format complaints come from the ONE renderer, so wp-review-upsert-pr and wp-finish word them identically.\n const errors: string[] = this.checklistFormatErrors(required, results);\n for (const req of required) {\n const verdict = this.resolveVerdict(req, results);\n // CK_WARN ('yellow' — passed with concerns) is deliberately absent from this chain: it SHIPS.\n // The concern still reaches the PR, published in the checklist comment. Do not \"fix\" this.\n if (verdict.status === CK_FAIL) {\n // Through the ONE renderer, so this path and the command layer's refusal say the same thing.\n // No archive path here: this is validation, not the act of retiring the verdict.\n errors.push(this.refusalError(req, verdict, filePath));\n } else if (verdict.status === CK_MISSING) {\n // An OPTIONAL checklist with no verdict was legitimately not run — the human was offered it\n // and declined (or `--no-optional` skipped the offer). Demanding it here would make\n // `required: false` mean nothing. Note the CK_FAIL branch above deliberately has no such\n // exemption: once an optional reviewer RUNS, its refusal counts.\n if (!req.required) continue;\n const doc = req.doc.trim() !== '' ? ` Read: ${req.doc}.` : '';\n errors.push(`Checklist \"${req.id}\" MATCHED this diff but has no verdict. Spawn the \"${req.reviewer.agentName}\" subagent to review it; ` + `IT submits the verdict with ${this.submitCommand(req.id)} — nobody writes ${this.checklistFileName(req.id)} by hand.${doc}`);\n }\n }\n return errors;\n }\n\n private checklistFileName(checklistId: string): string {\n return `review-${checklistId}.json`;\n }\n\n /**\n * THE renderer for a reviewer's verdict schema — with the reviewer's own `id` already filled in.\n *\n * There is one because a verdict schema that lives anywhere a human maintains it goes stale, and a\n * reviewer follows the stale copy. That is not a hypothetical: when `success` was replaced by the\n * tri-state `status`, hand-written `.claude/agents/*.md` files kept documenting `success`, and a real\n * PR had to carry \"the verdict format in your own agent .md file is OUT OF DATE\" in the spawn prompt to\n * work around it. Every printed copy — the stage-② roster, the generated per-reviewer instructions\n * file, and the complaint raised against a malformed verdict — now comes from here. It ends with the\n * ONE way a verdict is submitted (`wp-write-review`, issue #863), never a file path to write.\n */\n renderVerdictSchema(id: string, indent = ' '): string {\n return new VerdictSchemaRenderer().render(id, indent);\n }\n\n /** THE command that submits one checklist's verdict (issue #863) — see VerdictSchemaRenderer. */\n submitCommand(id: string): string {\n return new VerdictSchemaRenderer().submitCommand(id);\n }\n\n // Unreadable objects retain their format complaint; absent/unparseable verdicts return null.\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field\n private parseChecklistResult(filePath: string, id: string, override: ChecklistOverride | null): ChecklistResult | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unparseable per-checklist file is skipped, not fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed below\n const raw = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, unknown>;\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null;\n const output = typeof raw['output'] === 'string' ? (raw['output'] as string) : '';\n const status = typeof raw['status'] === 'string' ? (raw['status'] as string).trim().toLowerCase() : '';\n const agent = typeof raw['agent'] === 'string' ? raw['agent'].trim() : '';\n const model = typeof raw['model'] === 'string' ? raw['model'].trim() : '';\n const identityProblem = agent === '' || model === '' ? 'Both \"agent\" and \"model\" must be non-empty strings; use \"unknown\" when unavailable.' : '';\n return new ChecklistResult(agent, model, id, status, output, override, this.verdictProblem(filePath, id, status, raw) || identityProblem);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * '' when the verdict can be READ. Otherwise the complaint to show the AI verbatim.\n *\n * The MOVED `override` field is checked FIRST, ahead of `status`, because it is the more specific fact: a\n * file carrying it was written against a schema that no longer exists, and a reader told only \"status\n * must be green|yellow|red\" would fix the wrong thing. It is rejected even when EMPTY — an accepted shape\n * is never migrated, and `\"override\": \"\"` sitting in a reviewer's file is the copy that teaches the next\n * reviewer the field still exists.\n *\n * The legacy-`success` case keeps its OWN message for the same reason: `success` was removed outright\n * (no compatibility mode), and a reviewer cannot tell a wrong value from a field that no longer exists.\n */\n private verdictProblem(\n filePath: string,\n id: string,\n status: string,\n // webpieces-disable-next-line no-any-unknown -- opaque parsed JSON; only tested for key presence here\n raw: Record<string, unknown>,\n ): string {\n // The ONE renderer — see renderVerdictSchema. A second copy here is what let the old `success` shape\n // survive in print after it was removed from the parser.\n const shape = this.renderVerdictSchema(id);\n if ('override' in raw) {\n return (\n `Checklist \"${id}\" wrote its verdict with the MOVED \"override\" field. A ship-anyway ` +\n \"authorization is no longer part of a reviewer's verdict: it MOVED to its own file, \" +\n `${this.overrides.overrideFileName(id)}, which only the coordinating agent writes and only on a ` +\n 'human\\'s in-session instruction. There is no compatibility mode — DELETE the \"override\" key from ' +\n `${filePath} by resubmitting it:\\n${shape}`\n );\n }\n // webpieces-disable no-any-unknown -- comparing against the readonly literal tuple of valid colors\n if ((VERDICT_STATUSES as readonly string[]).includes(status)) return '';\n if ('success' in raw) {\n return `Checklist \"${id}\" wrote its verdict with the REMOVED \"success\" field. It is now a tri-state ` + `\"status\" — there is no compatibility mode. Resubmit it as:\\n${shape}`;\n }\n return `Checklist \"${id}\" wrote a verdict with no valid \"status\" (got ${JSON.stringify(status)}). ` + `It must be exactly one of ${VERDICT_STATUSES.join(', ')}:\\n${shape}`;\n }\n\n // webpieces-disable no-any-unknown -- opaque parsed JSON value, narrowed to string[] here\n private asStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n // webpieces-disable no-any-unknown -- element of an opaque JSON array, narrowed by the type guard\n return value.filter((v: unknown): v is string => typeof v === 'string');\n }\n\n // Parse opaque AI-authored JSON, converting a SyntaxError into a readable InformAiError.\n // webpieces-disable no-any-unknown -- returns the opaque parsed object; loadSummaryJson narrows each field\n private parseSummaryJson(raw: string, filePath: string, expectedMainAgentInstructions = '', retryCommand = 'pnpm wp-finish-upsert-pr'): Record<string, unknown> {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: convert JSON.parse SyntaxError to an InformAiError for the AI\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed by the caller\n return JSON.parse(raw) as Record<string, unknown>;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`summary.json is not valid JSON (${error.message}).\\n\\n` + `${this.summaryJsonSchemaHint(filePath, expectedMainAgentInstructions)}\\n\\n` + `Then re-run: ${retryCommand}`);\n }\n }\n}\n\n// Temporary migration delegators to ReviewJsonService — removed once consumers inject it.\nconst reviewJsonSvc = new ReviewJsonService();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ReviewJsonService; removed once consumers inject it\nexport function prDirFor(repoRoot: string, featureName: string): string {\n return reviewJsonSvc.prDirFor(repoRoot, featureName);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ReviewJsonService; removed once consumers inject it\nexport function summaryJsonPath(repoRoot: string, featureName: string): string {\n return reviewJsonSvc.summaryJsonPath(repoRoot, featureName);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to ReviewJsonService; removed once consumers inject it\nexport function summaryJsonSchemaHint(filePath: string, mainAgentInstructions = ''): string {\n return reviewJsonSvc.summaryJsonSchemaHint(filePath, mainAgentInstructions);\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  # Webpieces PR gate — the SERVER-SIDE half of the gate.
2
2
  #
3
- # WHY: locally, pr-creation-or-push-guard blocks `gh pr create` / manual `git push`, so wp-finish-upsert-pr
4
- # is the sole PR opener FOR HOOKED developers. The gap is UNHOOKED teammates who push + open a PR in the
5
- # GitHub web UI — nothing local stops them. This required check closes that gap: wp-finish-upsert-pr writes
6
- # HMAC(prGate.gateSalt, HEAD_sha) into the PR body, and this job recomputes it from the committed salt and
7
- # the PR head sha. A PR opened outside the gated flow carries no valid token and fails here.
3
+ # WHY: locally, pr-creation-or-push-guard blocks `gh pr create` / manual `git push`. The automated
4
+ # wp-finish-upsert-pr flow and the interactive, human-only wp-human-post-pr escape hatch both write
5
+ # HMAC(prGate.gateSalt, HEAD_sha) into the PR body. This required check recomputes it from the committed
6
+ # salt and PR head sha. A PR opened outside either supported path carries no valid token and fails here;
7
+ # the visible PR body says whether automated review/build ran or a human explicitly bypassed it.
8
8
  #
9
9
  # TO ENABLE (client repo):
10
10
  # 1. Copy this file to .github/workflows/webpieces-pr-gate.yml and commit it.
@@ -30,33 +30,33 @@
30
30
 
31
31
  name: Webpieces PR Gate
32
32
  on:
33
- pull_request:
34
- # `synchronize` is the primary trigger and catches an unhooked teammate pushing over a gated PR. The
35
- # gated flow pushes exactly ONCE per cycle (from wp-finish-upsert-pr, after the PR body is written),
36
- # so the synchronize run always reads the correct token.
37
- #
38
- # `edited` is the BODY-TAMPER guard: the token lives in the PR body, so an edit that strips it must
39
- # re-run this check rather than leave a stale green. Keep it. Note it fires on wp-finish's body write,
40
- # a beat BEFORE that push — so its run can briefly resolve the OLD head sha and go red. Harmless: that
41
- # red is keyed to a sha that is no longer the PR head, and branch protection evaluates the current
42
- # head, where the synchronize run lands green.
43
- types: [opened, edited, synchronize, reopened]
33
+ pull_request:
34
+ # `synchronize` is the primary trigger and catches an unhooked teammate pushing over a gated PR. The
35
+ # gated flow pushes exactly ONCE per cycle (from wp-finish-upsert-pr, after the PR body is written),
36
+ # so the synchronize run always reads the correct token.
37
+ #
38
+ # `edited` is the BODY-TAMPER guard: the token lives in the PR body, so an edit that strips it must
39
+ # re-run this check rather than leave a stale green. Keep it. Note it fires on wp-finish's body write,
40
+ # a beat BEFORE that push — so its run can briefly resolve the OLD head sha and go red. Harmless: that
41
+ # red is keyed to a sha that is no longer the PR head, and branch protection evaluates the current
42
+ # head, where the synchronize run lands green.
43
+ types: [opened, edited, synchronize, reopened]
44
44
  permissions:
45
- contents: read
46
- pull-requests: read
45
+ contents: read
46
+ pull-requests: read
47
47
  jobs:
48
- webpieces-pr-gate:
49
- runs-on: ubuntu-latest
50
- steps:
51
- - uses: actions/checkout@v4
52
- - uses: pnpm/action-setup@v4
53
- - uses: actions/setup-node@v4
54
- with:
55
- node-version: 20
56
- cache: pnpm
57
- - run: pnpm install --frozen-lockfile
58
- - name: Verify webpieces gate token
59
- env:
60
- GH_TOKEN: ${{ github.token }}
61
- WP_PR_NUMBER: ${{ github.event.pull_request.number }}
62
- run: pnpm wp-check-pr
48
+ webpieces-pr-gate:
49
+ runs-on: ubuntu-latest
50
+ steps:
51
+ - uses: actions/checkout@v4
52
+ - uses: pnpm/action-setup@v4
53
+ - uses: actions/setup-node@v4
54
+ with:
55
+ node-version: 20
56
+ cache: pnpm
57
+ - run: pnpm install --frozen-lockfile
58
+ - name: Verify webpieces gate token
59
+ env:
60
+ GH_TOKEN: ${{ github.token }}
61
+ WP_PR_NUMBER: ${{ github.event.pull_request.number }}
62
+ run: pnpm wp-check-pr
@@ -1,7 +1,9 @@
1
1
  # Where the build's output is — read the printed path, never a remembered one
2
2
 
3
3
  `pnpm wp-build` and the PR gate's build stages send the build's **entire** stdout and stderr to a FILE.
4
- Your terminal gets a heartbeat and a summary; it never gets the build output. So every question about a
4
+ Your terminal gets a heartbeat and a summary; it normally never gets the build output. The deliberate
5
+ exception is a human answering Y to the build prompt in `wp-human-post-pr`: that interactive command
6
+ follows the same durable `build.log` live until `wp-build` completes. So every later question about a
5
7
  build ("what failed", "did the tests run", "what was that warning") is answered by reading a file — never
6
8
  by running the build again.
7
9
 
@@ -6,13 +6,14 @@ work that could not act on them anyway: step 3 needs a repo admin.
6
6
 
7
7
  ## What this is for
8
8
 
9
- Locally, `pr-creation-or-push-guard` blocks `gh pr create` and manual `git push`, so
10
- `wp-finish-upsert-pr` is the only way a PR gets opened — **for hooked developers**. The gap is an
11
- UNHOOKED teammate who pushes and opens a PR in the GitHub web UI. Nothing local can stop that.
12
-
13
- This CI check closes it: `wp-finish-upsert-pr` writes `HMAC(gateSalt, HEAD_sha)` into the PR body, and
14
- the workflow recomputes it from the committed salt and the PR head sha. A PR opened outside the gated
15
- flow carries no valid token and fails the check.
9
+ Locally, `pr-creation-or-push-guard` blocks direct `gh pr create` and manual `git push`. Hooked
10
+ developers have two supported posters: the normal automated `wp-finish-upsert-pr`, and the interactive
11
+ human-only `wp-human-post-pr` escape hatch, whose body visibly says review was skipped and whether its
12
+ optional local `wp-build` ran or validation was deferred to cloud CI.
13
+
14
+ Both supported paths write the same `HMAC(gateSalt, HEAD_sha)` into the PR body, and the workflow
15
+ recomputes it from the committed salt and PR head sha. The token proves a supported path minted it;
16
+ the visible PR body distinguishes automated-gate success from explicit human attestation.
16
17
 
17
18
  ## The three steps
18
19
 
@@ -32,6 +32,15 @@ verified, and stage ③ re-runs the build ONLY if HEAD moved since — three sta
32
32
  All three stages are required and none may be skipped: stage ③ refuses to post a PR unless stage ② has
33
33
  run on this branch AND summary.json exists.
34
34
 
35
+ ### Separate human-only escape hatch
36
+
37
+ `pnpm wp-human-post-pr` is not stage ④ and is never an AI cure. A human who has personally inspected the
38
+ work may run it interactively and answer its attestation. It requires a clean feature branch, a freshly
39
+ fetched `origin/main`, an exact pure-main fork point, and valid `summary.json`; it then creates or updates
40
+ offers to run `pnpm wp-build` locally while following `build.log` live, or defer validation to cloud CI, then posts
41
+ the PR with one push and a visible warning that automated reviewers were skipped and whether the local build ran. It never
42
+ updates a stale branch and never merges the PR. AI must not run it for a human or answer `human`.
43
+
35
44
  ### Emergency `/hotfix/` branches
36
45
 
37
46
  An exact, case-sensitive `/hotfix/` path segment selects the auditable emergency profile. Its flow is: