@webpieces/pr-gate 0.4.841 → 0.4.843

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/pr-gate",
3
- "version": "0.4.841",
3
+ "version": "0.4.843",
4
4
  "description": "Gated PR system: 3-point squash-merge, merge validation gate, and red/yellow/green PR dashboard. Standalone scripts, no Nx dependency required.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -16,12 +16,12 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@inversifyjs/binding-decorators": "1.1.5",
19
- "@webpieces/hook-runtime": "0.4.841",
20
- "@webpieces/rules-config": "0.4.841",
19
+ "@webpieces/hook-runtime": "0.4.843",
20
+ "@webpieces/rules-config": "0.4.843",
21
21
  "inversify": "7.10.4",
22
22
  "reflect-metadata": "0.2.2",
23
- "@webpieces/tooling-common": "0.4.841",
24
- "@webpieces/repo-workflow-core": "0.4.841"
23
+ "@webpieces/tooling-common": "0.4.843",
24
+ "@webpieces/repo-workflow-core": "0.4.843"
25
25
  },
26
26
  "publishConfig": {
27
27
  "access": "public"
@@ -336,12 +336,12 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
336
336
  'Run: pnpm wp-review-upsert-pr\n' +
337
337
  '(then spawn the reviewers it names, write summary.json, and re-run this command)');
338
338
  }
339
- if (receipt.headSha === headSha)
339
+ if (receipt.buildHeadSha === headSha)
340
340
  return true;
341
341
  // Not fatal, and never a re-review (issue #1053): a green or yellow verdict stands whatever changed
342
342
  // since, and only a RED with a round left ever opens another round. Suggesting a re-review here
343
343
  // would be an instruction the gate itself refuses. It is never silent either: the build re-runs.
344
- process.stderr.write(`\n⚠️ HEAD moved since stage ② ran (reviewed ${receipt.headSha.slice(0, 8)}, now ${headSha.slice(0, 8)}).\n` +
344
+ process.stderr.write(`\n⚠️ HEAD moved since stage ② built (built ${receipt.buildHeadSha.slice(0, 8) || 'unknown'}, now ${headSha.slice(0, 8)}).\n` +
345
345
  ' The build gate will re-run. No further review runs for this: every verdict is carried forward\n' +
346
346
  ' from the reviewed tree, and the PR records that the reviewers judged an earlier commit.\n\n');
347
347
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"finish-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/finish-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAyM;AACzM,8DAA0D;AAC1D,iEAA6D;AAC7D,yCAA2D;AAC3D,2EAAgE;AAChE,6DAAyD;AACzD,qEAAsG;AACtG,6EAAwE;AACxE,mDAA+C;AAC/C,+DAA6E;AAC7E,+DAAsF;AACtF,yDAAqD;AACrD,2EAA6E;AAC7E,uEAAyE;AACzE,mEAAkF;AAClF,qDAAiG;AACjG,6DAA4E;AAC5E,2EAAqE;AACrE,uEAAkE;AAClE,yEAAuF;AACvF,yEAAsF;AACtF,mFAA8E;AAE9E,yDAA2G;AAC3G,2FAAgH;AAChH,iFAA4E;AAC5E,qEAAyE;AACzE,iEAA6D;AAE7D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;GAGG;AACH,MAAM,gBAAgB;IAClB,IAAI,CAAgB;IACpB,MAAM,CAAY;IAClB,UAAU,CAAmB;IAE7B,YAAY,IAAmB,EAAE,MAAiB,EAAE,UAA4B;QAC5E,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,eAAe;IACjB,QAAQ,GAAG,EAAE,CAAC;IACd,UAAU,GAAG,EAAE,CAAC;IAChB,KAAK,GAAG,EAAE,CAAC;IACX,6FAA6F;IAC7F,IAAI,GAAG,EAAE,CAAC;IACV;;;;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AAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO,IAAI,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAC7B,CAAC;QACD,MAAM,KAAK,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACvD,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACrD,CAAC;CACJ,CAAA;AA7iBY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,mCAAY;QACZ,4BAAY;QACjB,kBAAO;QACD,8BAAa;QAClB,6BAAY;QACV,wBAAU;QACZ,oBAAQ;QACP,qCAAgB;QAChB,qBAAS;QACJ,wCAAsB;QAEpB,qDAAwB;QACxB,oCAAgB;QACrB,2CAAmB;QACb,gCAAiB;QAClB,+BAAgB;QAEd,wCAAkB;QAI5B,gDAAyB;QAC3B,4BAAY;QAGL,wCAAiB;QAEf,uCAAiB;QAGlB,iDAAsB;QACxB,iCAAc;QACZ,gCAAc;QACtB,4CAAuB;GApC3C,qBAAqB,CA6iBjC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { loadAndValidate, prDirFor, summaryJsonPath, PrSummary, RequiredChecklist, ChecklistVerdict, writeTemplate, RepoRootFinder, ReviewJsonService, GateTokenService } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { ReviewerVerdictGate } from '../workflow/reviewer-verdict-gate';\nimport { GitExec } from '../workflow/git-exec';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BuildGateLog, FINISH_STAGE, REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { MergeState } from '../workflow/merge-state';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewRoundStateService } from '../workflow/review-round-state';\nimport { StageOutputLog, FINISH_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { PrMerger, MergeIntent, MergeOutcome, MERGE_RESULT_FAILED } from '../workflow/pr-merger';\nimport { FinishBanner, FinishBannerInput } from '../workflow/finish-banner';\nimport { MergeBodyTempFile } from '../workflow/merge-body-temp-file';\nimport { GatedPrPublisher } from '../workflow/gated-pr-publisher';\nimport { ProvenanceEnforcer, ProvenanceReport } from '../workflow/provenance-enforcer';\nimport { PrCommentRequest, PrCommentUpserter } from '../workflow/pr-comment-upserter';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { TriggeredChecklist } from '../workflow/checklist-detector';\nimport { Dashboard, DashboardInput, ChecklistRow, DETAIL_COMMENT_MARKER } from '../../dashboard/dashboard';\nimport { ChecklistCommentRenderer, CHECKLIST_COMMENT_MARKER } from '../../dashboard/checklist-comment-renderer';\nimport { ChecklistCommentRow } from '../../dashboard/checklist-comment-row';\nimport { AuthorIdentityResolver } from '../../dashboard/author-identity';\nimport { HotfixRedirect } from '../workflow/hotfix-redirect';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The three inputs the PR COMMENTS are rendered from, bundled so `publishAll` takes one parameter for\n * them instead of three it only forwards. Data-only, per CLAUDE.md.\n */\nclass PrCommentSources {\n scan: ChecklistScan;\n review: PrSummary;\n provenance: ProvenanceReport;\n\n constructor(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport) {\n this.scan = scan;\n this.review = review;\n this.provenance = provenance;\n }\n}\n\n/**\n * Everything the PR upsert needs. Data-only, per CLAUDE.md — it replaced a 5-positional-parameter method\n * once `tokenSuffix` had to travel too, so the body can be re-rendered with the PR's own URL after\n * `gh pr create` returns it (see the INVARIANT comment in upsertPr).\n */\nclass PrUpsertRequest {\n repoRoot = '';\n baseBranch = '';\n title = '';\n /** The description as first published — rendered with whatever URL was known at the time. */\n body = '';\n /**\n * The hidden gate-token marker exactly as appended to `body`, so a re-render can reproduce the same\n * bytes. Kept separate from `body` because Dashboard renders the human/git-log half and must not know\n * about HMACs.\n */\n tokenSuffix = '';\n input: DashboardInput;\n\n constructor(input: DashboardInput) {\n this.input = input;\n }\n}\n\n// A resolved PR's number + web URL. Both '' when the PR can't be resolved (e.g. create failed).\nclass PrRef {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n// The outcome of the whole upsert: the PR number + web URL ('' each when unresolved) plus what actually\n// happened to the merge, so the final summary reports the REAL result rather than assuming success. The\n// URL is carried so the closing block can hand the AI a clickable link to relay to the user verbatim.\nclass UpsertResult {\n prNumber: string;\n prUrl: string;\n merge: MergeOutcome;\n\n constructor(prNumber: string, prUrl: string, merge: MergeOutcome) {\n this.prNumber = prNumber;\n this.prUrl = prUrl;\n this.merge = merge;\n }\n}\n\n// STAGE ③ — FINISH of the AI-first PR flow, and the ONLY command that posts PRs. Runs after\n// `wp-review-upsert-pr` verified the branch and the AI spawned the reviewers + wrote summary.json.\n//\n// In order: (1) REFUSE on an unvalidated 3-point merge and REQUIRE stage ②'s receipt; (2) REQUIRE\n// summary.json + every reviewer's verdict + provenance; (3) run the build gate UNLESS the receipt already\n// covers this exact HEAD; (4) render the dashboard; (5) create/update the PR via `gh`.\n//\n// It no longer FINALIZES a merge — stage ② does. Two commands owning conflict-resolution validation is two\n// implementations that drift, and finalizing here came too late to help anyway: the reviewers had already\n// reviewed the pre-merge tree by then.\n@injectable(bindingScopeValues.Singleton)\nexport class FinishUpsertPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildLog: BuildGateLog,\n private readonly mergeState: MergeState,\n private readonly prMerger: PrMerger,\n private readonly publisher: GatedPrPublisher,\n private readonly dashboard: Dashboard,\n private readonly authorIdentity: AuthorIdentityResolver,\n // The 2nd PR comment. Its own class because it is its own surface — see ChecklistCommentRenderer.\n private readonly checklistComment: ChecklistCommentRenderer,\n private readonly checklistScanner: ChecklistScanner,\n private readonly verdictGate: ReviewerVerdictGate,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly gateTokenService: GateTokenService,\n // Owns the reviewer-provenance integrity check and its audit record — see ProvenanceEnforcer.\n private readonly provenanceEnforcer: ProvenanceEnforcer,\n // NOTE: ChecklistInstructionsService is deliberately NOT injected here any more. Its \"You MUST run\n // these N reviewer subagent(s)\" block is now rendered by ReviewerVerdictGate and ONLY for checklists\n // that genuinely never ran, so no other code path in this command can print it at a refusal.\n private readonly receipts: ReviewStageReceiptService,\n private readonly banner: FinishBanner,\n // `gh pr merge --body-file` takes a path, so the bytes just published as the PR description are\n // spilled to a throwaway file for the length of one `gh` call. Nothing durable — the PR holds it.\n private readonly mergeBodyFile: MergeBodyTempFile,\n // ONE marker-keyed upsert, shared by both PR comments (the full dashboard and the checklist).\n private readonly commentUpserter: PrCommentUpserter,\n // Pins the two GitHub repo settings that decide whether a UI merge writes the body we just\n // rendered. Server-side, so no config can express them — see SquashSettingsEnforcer.\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly stageConsole: StageOutputLog,\n private readonly hotfixRedirect: HotfixRedirect,\n private readonly rounds: ReviewRoundStateService,\n ) {}\n\n /**\n * Runs with this stage's console CAPTURED to a file (see StageOutputLog). What still reaches the\n * terminal is what an agent must act on: the build heartbeat and result, and the closing banner with\n * the PR link and whatever is still owed. The dashboard computation, the gh round trips and the\n * comment upserts are in the file.\n */\n async run(): Promise<void> {\n // A /hotfix/ branch is published by wp-upsert-hotfix-pr, never by this stage (issue #1057).\n this.hotfixRedirect.assertNotHotfix('wp-finish-upsert-pr');\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, FINISH_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n // Refresh the AI-facing workflow doc so it's present + current for any failure message to cite.\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n // 1. REQUIRE stage ② — see assertStageTwoRan. Returns true when its receipt covers THIS commit,\n // which is what lets the build gate below be skipped rather than re-run for a foregone answer.\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n const buildAlreadyGreen = this.assertStageTwoRan(repoRoot);\n\n // 2. REQUIRE the AI-authored summary.json (throws InformAiError with the schema if missing/invalid).\n // Compute the consumer checklists this diff triggered FIRST so an unacknowledged BLOCK throws\n // here — BEFORE any `gh pr create` — matching the guarantee buildCommand already provides.\n // The SAME scan wp-review-upsert-pr runs, with filterAlreadyReviewed:true so `outstanding` is exactly what\n // still owes a verdict (Z of N of X). Sharing the computation is the point: the command that REPORTS\n // and the command that GATES must not be able to disagree about what is owed. review-round<N>-<id>.json files\n // persist locally, so a re-run re-validates the EXISTING verdicts against the (possibly changed)\n // applicable set for free — an unchanged checklist needs no re-review, a newly-applicable one refuses\n // until its file is written.\n // The scan judges ONLY the checklists that were briefed (issue #1053) — never one a later commit newly\n // triggered — and it has already folded every recorded orange fix into its results.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, 'stage3-finish'));\n const required = scan.applicable;\n // The applicable checklists that are supposed to HAVE a verdict — everything except the optional ones\n // nobody ran. Used for provenance and for the dashboard rows, both of which ask \"who reviewed this?\"\n // and would otherwise demand an answer from a review the human declined: provenance would refuse the\n // PR because a subagent that was never meant to run cannot be proven to have run, and the dashboard\n // would render a MISSING verdict for it.\n const verdicted = this.verdictedOf(scan);\n // FAIL FAST on an unclear checklist, BEFORE summary.json is parsed and before the build gate runs. A\n // missing reviewer is not a summary.json defect (folding it in made the AI fix the wrong thing), and\n // nobody should wait on a build to be told a reviewer never ran. ReviewerVerdictGate owns the\n // distinction between unreadable / ORANGE / REFUSED / never-ran.\n this.verdictGate.assertEveryReviewerRan(scan);\n const review = this.reviewJsonService.loadSummaryJson(summaryJsonPath(repoRoot, featureName), required, '', scan.orangeFixes);\n this.applyRoundAudits(review, scan, config.maxReviewerRounds);\n\n // 2c. For every verdicted checklist, VERIFY (from the harness's own artifacts) that a real reviewer\n // SUBAGENT actually ran on this branch — the coding agent may not self-certify. Its NAME is not\n // checked; see SubagentProvenanceService.isReviewerRun. Absent CLAUDE_CODE_SESSION_ID this skips with a warning (CI / plain terminal).\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const provenance = this.provenanceEnforcer.enforce(verdicted, currentBranch, repoRoot, config);\n\n // 2b. The build gate validates the WORKING TREE but we push HEAD — so they MUST be identical.\n this.gitExec.assertCleanTree(repoRoot);\n\n // 3. Build gate, then post the gated body, then push (that ORDER — see GatedPrPublisher).\n await this.runOrSkipBuildGate(repoRoot, buildAlreadyGreen);\n const base = this.branchNaming.baseBranchName(execSync('git branch --show-current', { encoding: 'utf8' }).trim());\n\n process.stdout.write('\\n' + SEP + '📋 Dashboard + PR\\n' + SEP + '\\n');\n const title = this.prTitleFrom(review);\n const input = this.computeDashboardInput(repoRoot, true, review, title, verdicted, scan);\n const result = this.publishAll(repoRoot, base, input, new PrCommentSources(scan, review, provenance));\n this.archiveConsumedReview(repoRoot, featureName, result);\n\n // The closing recap + the clickable-link directive, BOTH derived from the real merge outcome.\n // Nothing here may hard-code success: a stranded PR under a green checkmark is how PRs got\n // abandoned (see FinishBanner).\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n // `say`: the PR link and what is still owed are the whole reason a caller ran this command, and a\n // not-done outcome carries the commands that fix it. Neither may end up only in a log file.\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n private applyRoundAudits(review: PrSummary, scan: ChecklistScan, maxReviewerRounds: number): void {\n for (const result of review.results) {\n const trail = this.rounds.auditTrail(scan.summaryPath, result.id, maxReviewerRounds);\n if (trail === '') continue;\n result.output = trail;\n if (result.remediation !== '') result.remediation = `${trail}\\n\\n#### Final state\\n${result.remediation}`;\n }\n }\n\n // Validate + commit + finalize a 3-point merge the AI resolved, if one is in progress. Finalizing here\n // does NOT push (pushRemote=false): this command pushes exactly ONCE, from GatedPrPublisher, and only\n // after summary.json + every BLOCK checklist + the build gate pass and the gated PR body is written.\n /**\n * The build gate — SKIPPED when stage ②'s receipt already covers this exact HEAD.\n *\n * The gate is authoritative per-COMMIT, not per-command: re-running it on a tree that has not moved\n * since stage ② verified it buys nothing and costs a full `nx affected`. That skip is what makes the\n * three-stage flow cost ONE build rather than two, and it is why moving the gate earlier was affordable.\n */\n private async runOrSkipBuildGate(repoRoot: string, alreadyGreen: boolean): Promise<void> {\n if (alreadyGreen) {\n // `say`, for the same reason the gate's own two lines are: a caller watching for a build needs\n // to be told, live, that there is not going to be one.\n this.stageConsole.say('\\n🛠️ Build gate: already green for this commit (stage ② receipt) — skipping the rebuild.\\n' + this.skippedBuildLogNote(repoRoot));\n return;\n }\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions('🛠️ Build gate (authoritative)', 'pnpm wp-finish-upsert-pr', 'Build failed — no PR created/updated.', FINISH_STAGE));\n }\n\n /**\n * When the gate is SKIPPED and build-log capture is on, name STAGE ②'s log — the one build that\n * actually ran for this commit. Deliberately never names a finish-stage log: no finish build ran, and\n * pointing at a file this command did not write would claim a build that did not happen.\n *\n * The path is recomputed rather than stored, and that is sound precisely BECAUSE this branch is only\n * reached when the receipt covers the current HEAD: same worktree, same branch, same sha ⇒ the same\n * deterministic filename stage ② wrote. Empty string when the file is gone — a log that was reaped or\n * never written must not be named as though a reader could open it.\n */\n private skippedBuildLogNote(repoRoot: string): string {\n const log = this.buildLog.existingLogFor(repoRoot, REVIEW_STAGE);\n return log === '' ? '' : ` Stage ②'s full build output: ${log}\\n`;\n }\n\n /**\n * The two stage-② preconditions, together: no unvalidated merge, and a receipt proving stage ② ran.\n * Returns true when that receipt covers the CURRENT HEAD, i.e. the build gate can be skipped.\n */\n private assertStageTwoRan(repoRoot: string): boolean {\n this.assertNoUnvalidatedMerge(repoRoot);\n return this.assertReviewStageRan(repoRoot, this.aiBranchName.getFeatureName(), this.gitOut(['rev-parse', 'HEAD']));\n }\n\n /**\n * REFUSE while a 3-point merge is still unvalidated — do not finalize it here.\n *\n * This command used to do the finalizing itself. Finalizing means validating a conflict resolution, and\n * two commands owning that means two implementations that can drift; `PrContextWriter`'s docstring\n * records this codebase already paying for exactly that once. It also came too late to matter: by the\n * time finish ran, the reviewers had already reviewed the pre-merge tree.\n *\n * So stage ② owns it, and finish only checks. Nothing is lost — the recovery is one command away, and\n * running it also builds the merged tree and re-briefs the reviewers against it, which finalizing here\n * never did.\n */\n private assertNoUnvalidatedMerge(repoRoot: string): void {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return;\n throw new InformAiError(\n '⛔ NO PR — a 3-point merge on this branch is still unvalidated, so nothing here has been\\n' +\n 'verified: the conflict resolution is unchecked, the merged tree was never built, and any\\n' +\n 'reviewer that ran judged the PRE-merge code.\\n\\n' +\n `Conflicted file(s): ${marker.conflictedFiles.join(', ')}\\n\\n` +\n 'Resolve them (see .webpieces/instruct-ai/webpieces.mergeprocess.md), then run:\\n' +\n ' pnpm wp-review-upsert-pr\\n' +\n 'It validates the resolution, commits it, builds it, and re-briefs the reviewers.',\n );\n }\n\n /**\n * REQUIRE stage ② (`wp-review-upsert-pr`) to have run, and report whether it ran on THIS commit.\n *\n * Returns true when the receipt matches the current HEAD — the caller then skips its own build, because\n * the receipt IS the gate for that sha and rebuilding an unchanged tree is a second full `nx affected`\n * run for a foregone answer.\n *\n * Without this check a repo with NO checklists has nothing forcing stage ②: `assertEveryReviewerRan`\n * is vacuous, and summary.json — the only other interlock — is a file the AI writes itself. It could\n * write it and come straight here, skipping the merge validation and the build entirely.\n */\n private assertReviewStageRan(repoRoot: string, featureName: string, headSha: string): boolean {\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(\n '⛔ NO PR — stage ② never ran on this branch. That means the 3-point merge is unvalidated,\\n' +\n 'the build gate has not run, no diff was extracted, and no reviewer was briefed.\\n\\n' +\n 'Run: pnpm wp-review-upsert-pr\\n' +\n '(then spawn the reviewers it names, write summary.json, and re-run this command)',\n );\n }\n if (receipt.headSha === headSha) return true;\n // Not fatal, and never a re-review (issue #1053): a green or yellow verdict stands whatever changed\n // since, and only a RED with a round left ever opens another round. Suggesting a re-review here\n // would be an instruction the gate itself refuses. It is never silent either: the build re-runs.\n process.stderr.write(\n `\\n⚠️ HEAD moved since stage ② ran (reviewed ${receipt.headSha.slice(0, 8)}, now ${headSha.slice(0, 8)}).\\n` +\n ' The build gate will re-run. No further review runs for this: every verdict is carried forward\\n' +\n ' from the reviewed tree, and the PR records that the reviewers judged an earlier commit.\\n\\n',\n );\n return false;\n }\n\n /**\n * Retire the review this run just used — move summary.json to old-summary.json beside it, stamped as\n * audit-only (see ReviewJsonService.archiveSummaryJson).\n *\n * WHY it moves rather than staying put: summary.json left behind is a live-looking file describing a\n * review that has already shipped, and the next `wp-review-upsert-pr` on this branch finds it sitting\n * there. A reviewer subagent that judges the PR's stated INTENT — its title, summary or risk level —\n * then reads the previous round's review and can return GREEN against a title that no longer exists,\n * with nothing in the verdict distinguishing that from a real pass. Moving it makes the only route back\n * to this command a freshly-written review.\n *\n * ONLY on a PR that actually went up. A run that died before publishing must stay re-runnable without\n * making the AI rewrite a review that was never used, and prNumber === '' is exactly that case.\n * Non-fatal: the PR is live by here, so an unwritable archive warns rather than failing the command.\n */\n private archiveConsumedReview(repoRoot: string, featureName: string, result: UpsertResult): void {\n if (result.prNumber === '') return;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the PR is already up; a failed archive must not fail the command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const archived = this.reviewJsonService.archiveSummaryJson(summaryJsonPath(repoRoot, featureName));\n if (archived !== '') process.stdout.write(` archived this run's summary.json → ${archived} (audit only) ✓\\n`);\n // Beside it, so an archived review keeps the transcript links belonging to the round that\n // produced it — a review whose provenance was overwritten by the NEXT round audits nothing.\n this.provenanceEnforcer.archiveRecord(prDirFor(repoRoot, featureName));\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(`⚠️ Could not archive summary.json (non-fatal — the PR is already up): ${error.message}\\n`);\n }\n }\n\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // The user-facing PR title: the AI-authored review.title, or — if omitted — a readable fallback\n // derived from the stable feature name (NEVER the internal `Squash merge of <branch>` commit subject).\n private prTitleFrom(review: PrSummary): string {\n if (review.title !== '') return review.title;\n return this.aiBranchName.getFeatureName().replace(/[-/]+/g, ' ').trim();\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private computeDashboardInput(repoRoot: string, buildPassed: boolean, review: PrSummary, title: string, required: readonly RequiredChecklist[], scan: ChecklistScan): DashboardInput {\n const config = loadAndValidate(repoRoot).prGate;\n const forkPoint = this.gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = this.gitOut(['rev-parse', 'HEAD']);\n const mainHead = this.gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = this.gitOut(['diff', range, '--name-only'])\n .split('\\n')\n .filter((f: string): boolean => f.trim() !== '');\n const patch = this.gitOut(['diff', range]);\n\n const gateResults = this.dashboard.computeGateResults(config.gates, changedFiles);\n const disables = this.dashboard.countAddedDisables(patch);\n const rows = this.checklistRows(required, review);\n // buildCommand travels into the dashboard so the PR-body footer can NAME the command that vouched\n // for this commit. The footer used to assert \"build ran via nx affected\" on every repo, which was\n // simply false wherever buildCommand is not nx.\n // `scan.suppressed.length`, never `scan.reviewersDisabled` alone: the dashboard and the commit\n // body have to state HOW MANY reviewers were killed, because a suppressed 4 and an applicable 0\n // are different facts that both render as an empty `rows`. See DashboardInput.\n const input = new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, review, rows, this.buildAffected.resolveBuildCommand(repoRoot), scan.suppressed.length, this.authorIdentity.resolve(review.model), false);\n input.notBriefed = scan.notBriefed.map((r: RequiredChecklist): string => r.id);\n return input;\n }\n\n /**\n * The applicable checklists MINUS the optional ones nobody ran.\n *\n * Not folded into `ChecklistScan` as yet another field: `applicable` (what matched) and `optionalNotRun`\n * (what was declined) are both facts about the scan, whereas this is one command's view of them, and the\n * roster comment deliberately wants the OTHER view — it lists the declined ones precisely so the PR does\n * not imply they passed.\n */\n private verdictedOf(scan: ChecklistScan): RequiredChecklist[] {\n const skipped = new Set(scan.optionalNotRun.map((r: RequiredChecklist): string => r.id));\n return scan.applicable.filter((r: RequiredChecklist): boolean => !skipped.has(r.id));\n }\n\n // Pair each matched checklist with its resolved verdict for the dashboard.\n //\n // A checklist reaching this point is always PASS, WARN or OVERRIDDEN, and the reason is ReviewerVerdictGate\n // — NOT loadSummaryJson. The gate runs one line earlier and throws on every other state (FAIL, MISSING,\n // BAD_FORMAT), so loadSummaryJson's own checklist validation can no longer be the thing that rejects them;\n // it re-validates the same set and finds it clean. This comment used to credit loadSummaryJson, which made\n // the ordering look deliberate while the gate's generic \"no verdict yet\" message masked every refusal.\n // WARN belongs in that list: yellow SHIPS, so it is not outstanding and reaches the dashboard.\n private checklistRows(required: readonly RequiredChecklist[], review: PrSummary): ChecklistRow[] {\n return required.map((req: RequiredChecklist): ChecklistRow => {\n const verdict = this.reviewJsonService.resolveVerdict(req, review.results);\n return new ChecklistRow(req.id, verdict.status, verdict.detail);\n });\n }\n\n /**\n * One comment row per DEFINED checklist — matched or not — pairing the roster's match evidence with the\n * resolved verdict. Built from `scan.roster` rather than from the applicable set: the skipped ones are\n * absent from `applicable` by construction, and their \"why not\" evidence (the configured globs and the\n * changed-file total) exists nowhere else without recomputing the diff a second way.\n */\n private commentRows(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): ChecklistCommentRow[] {\n // checklist id -> did its reviewer open the diff. Absent ⇒ not assessed, which prints nothing (see ChecklistCommentRow.diffRead).\n const readByChecklist = new Map<string, boolean>();\n for (const e of provenance.evidence) readByChecklist.set(e.checklistId, e.readDiff);\n const judged = new Set(scan.applicable.map((r: RequiredChecklist): string => r.id));\n const notBriefed = new Set(scan.notBriefed.map((r: RequiredChecklist): string => r.id));\n return scan.roster.entries.map((entry: TriggeredChecklist): ChecklistCommentRow => {\n // A briefed checklist is judged whether or not the final diff still matches it (the set is\n // frozen at the briefing, issue #1053); a newly-triggered one is shown, never judged.\n const ran = judged.has(entry.def.id) || entry.matchedFiles.length > 0;\n const req = new RequiredChecklist(entry.def.id, entry.def.reviewer, entry.def.doc, entry.matchedFiles, entry.matchedPatterns, entry.def.required);\n // A skipped checklist has no verdict to resolve — asking for one would report it as MISSING,\n // i.e. as an unreviewed obligation, when in fact it never had one.\n const verdict = ran && !notBriefed.has(entry.def.id) ? this.reviewJsonService.resolveVerdict(req, review.results) : new ChecklistVerdict(entry.def.id, '', '');\n const identity = review.results.find((result): boolean => result.id === entry.def.id);\n const row = new ChecklistCommentRow(identity?.agent ?? 'unknown', identity?.model ?? 'unknown', entry.def.id, verdict.status, verdict.detail, ran, entry.def.patterns, entry.matchedPatterns, entry.matchedFiles, scan.roster.changedFileCount);\n row.required = entry.def.required;\n row.notBriefed = notBriefed.has(entry.def.id);\n const read = readByChecklist.get(entry.def.id);\n row.diffRead = read === undefined ? '' : read ? 'yes' : 'no';\n return row;\n });\n }\n\n // Hidden HMAC gate-token marker (with a leading blank line) to append to the PR body, or '' when the\n // repo sets no gateSalt (byte-identical body to before this feature). Bound to the pushed HEAD sha.\n private gateTokenBody(gateSalt: string, headSha: string): string {\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n return marker === '' ? '' : `\\n\\n${marker}\\n`;\n }\n\n /**\n * Publish the roster + every reviewer's full `output` as ONE combined PR comment, idempotently (find the\n * marker comment → PATCH it, else POST). Never fatal: by here the PR is already created/updated, so a\n * `gh` failure only warns.\n *\n * Posted on EVERY run of a repo that defines checklists — including one where nothing matched, because\n * \"all five were evaluated and none applied\" is the good news the old comment could not deliver. The\n * guard is `scan.defined.length`, deliberately NOT the number of rows that ran: a repo with no\n * checklists configured must still see no comment at all (see ChecklistCommentRenderer).\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private postChecklistComment(repoRoot: string, prNumber: string, scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): void {\n if (prNumber === '' || scan.defined.length === 0) return;\n if (!loadAndValidate(repoRoot).prGate.checklistComments) return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = CHECKLIST_COMMENT_MARKER;\n request.body = this.checklistComment.render(this.commentRows(scan, review, provenance), provenance.verified, scan.roster.baseResolved, scan.suppressed.length, false);\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'checklist-comment.json';\n request.label = 'checklist review comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR, the remote branch, and the local branch all share the one stable feature name. Look up /\n // create / merge against `baseBranch` (baseBranchName tolerates a leftover `…wpN` mid-transition).\n // GatedPrPublisher owns the edit/push/create half and its ORDERING — the gated body goes up before\n // the push, so CI's `synchronize` read cannot see the previous run's token.\n private upsertPr(request: PrUpsertRequest): UpsertResult {\n const repoRoot = request.repoRoot;\n const baseBranch = request.baseBranch;\n const title = request.title;\n const input = request.input;\n const prDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n fs.mkdirSync(prDir, { recursive: true });\n const bodyFile = path.join(prDir, 'pr-body.md');\n fs.writeFileSync(bodyFile, request.body + '\\n');\n\n const published = this.publisher.publish(baseBranch, title, bodyFile);\n if (published.createFailed) {\n process.stderr.write('⚠️ gh pr create failed — create the PR manually with the body in:\\n ' + bodyFile + '\\n');\n return new UpsertResult('', '', new MergeOutcome(false, false, '⚠️ did NOT merge — there is no PR to merge (gh pr create failed above)', MERGE_RESULT_FAILED));\n }\n const num = published.number;\n\n // Set the squash-merge SUBJECT to the PR title (+ the `(#N)` GitHub normally appends, which an\n // explicit --subject would otherwise drop) and the BODY to the compact commit summary, so main's\n // history carries the PR title + risk/flags/link — NOT the internal `Squash merge of <branch>`\n // subject GitHub would inherit from the single squash commit on the branch.\n const ref = this.prRef(baseBranch);\n const subject = ref.number !== '' ? `${title} (#${ref.number})` : title;\n\n /*\n * THE INVARIANT: the merge body IS the PR description, byte for byte.\n *\n * That is what makes every landing route agree — the GitHub Merge button and a bare `gh pr merge`\n * copy the description via `squash_merge_commit_message: PR_BODY`, while `wp-land-pr` and finish's\n * own auto-merge pass these bytes with `--body-file`. If the two strings could differ, which route\n * landed the commit would change what history says, which is precisely the bug this whole change\n * exists to remove. `pr-body-is-merge-body.spec.ts` pins it.\n *\n * The one wrinkle is the self-link. A brand-new PR has no URL until `gh pr create` returns, so the\n * body published a moment ago was rendered with `prUrl: ''`. Re-render now that the URL is known\n * and push the corrected description back, so the two strings match and the commit carries its own\n * link. Only the CREATE path pays that extra edit: on every later run the URL was already known\n * before publishing, `finalBody` matches what went up, and nothing is re-sent.\n */\n const finalBody = this.dashboard.renderPrBody(input, ref.url) + request.tokenSuffix;\n if (finalBody !== request.body) this.backfillPrBody(ref.number, bodyFile, finalBody);\n\n // The DURABLE copy of these bytes is the PR description published above; this is a throwaway\n // file because `--body-file` takes a path. `wp-land-pr` reads the description back from GitHub,\n // so nothing here has to survive the process (see decisions/0005).\n const mergeBodyFile = this.mergeBodyFile.write(finalBody + '\\n');\n // PrMerger owns the direct-merge / auto-merge-fallback decision AND checks every gh status, so a\n // merge that did not happen is reported as such instead of being swallowed (see pr-merger.ts).\n // REQUIRED config — no default here on purpose. A missing value (an older published\n // rules-config that has no such field) reaches PrMerger as '' and is treated as \"do not merge\".\n const mergeMode = loadAndValidate(repoRoot).prGate.mergeMode ?? '';\n // `false`: this caller is POLICY-driven — only a config that really says AUTO merges here.\n const outcome = this.prMerger.merge(baseBranch, subject, mergeBodyFile, new MergeIntent(mergeMode, false));\n return new UpsertResult(ref.number !== '' ? ref.number : num, ref.url, outcome);\n }\n\n /**\n * Everything the gated flow PUBLISHES, in the one order that is safe — the three surfaces plus the\n * merge, as a single unit.\n *\n * 1. the PR DESCRIPTION = the compact git-log body (+ the hidden gate token), written before the\n * push so CI's `synchronize` read can never see the previous run's token,\n * 2. the 1st comment = the full dashboard,\n * 3. the 2nd comment = each reviewer's output.\n *\n * The token is bound to the LOCAL HEAD sha and minted here because we only reach this line after the\n * build gate and every BLOCK checklist passed, so minting is legitimate. Nothing about\n * HMAC(salt, HEAD) needs the remote to have the commit yet.\n *\n * Extracted from `run` when the two comments made it 82 lines against a hard 80-line rule — and it\n * earns its own name: these four steps have a REQUIRED order, and the comment explaining that order\n * belongs with them rather than inside a method that also loads config and runs a build gate.\n */\n private publishAll(repoRoot: string, base: string, input: DashboardInput, sources: PrCommentSources): UpsertResult {\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n const headSha = this.gitOut(['rev-parse', 'HEAD']);\n const upsert = new PrUpsertRequest(input);\n upsert.repoRoot = repoRoot;\n upsert.baseBranch = base;\n upsert.title = input.title;\n upsert.tokenSuffix = this.gateTokenBody(gateSalt, headSha);\n // `existingPrUrl` is '' only for a brand-new PR — there is no URL to self-link to until\n // `gh pr create` returns one, and upsertPr back-fills it the moment it does.\n upsert.body = this.dashboard.renderPrBody(input, this.existingPrUrl(base)) + upsert.tokenSuffix;\n const result = this.upsertPr(upsert);\n\n // In the order the PR body's pointer promises: full dashboard 1st, reviewer output 2nd. Both are\n // idempotent by hidden marker and both non-fatal — the PR is up by now, so a `gh` hiccup on a\n // comment must not turn a finished run into a failed one.\n this.postDetailComment(repoRoot, result.prNumber, input);\n this.postChecklistComment(repoRoot, result.prNumber, sources.scan, sources.review, sources.provenance);\n\n // Having just written the description AS the commit body, make sure GitHub will actually use it.\n // Here rather than anywhere earlier because it is about what happens to the artifact we just\n // published, and it must run on EVERY repo — including mergeMode=NONE ones that never reach\n // PrMerger, which are exactly the repos where a UI merge decides what main's history says.\n this.squashSettings.ensure();\n return result;\n }\n\n /**\n * Re-publish the description now that the PR's own URL is known (create path only).\n *\n * Non-fatal on purpose. The PR exists, its body already carries a valid gate token for the pushed\n * head, and the code is up — the ONLY thing missing is the self-link on the first line. Aborting a\n * finished run over a cosmetic back-link would be a worse outcome than the missing link, and the very\n * next `wp-finish-upsert-pr` writes it (by then the URL is known before publishing, so it goes up with\n * the body). The merge body still gets the linked version regardless: it is filed from `finalBody`.\n */\n private backfillPrBody(prNumber: string, bodyFile: string, finalBody: string): void {\n if (prNumber === '') return;\n fs.writeFileSync(bodyFile, finalBody + '\\n');\n const res = spawnSync('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile], {\n encoding: 'utf8',\n });\n if (res.status !== 0) {\n process.stderr.write(\"⚠️ Could not add the PR's own link to its description (non-fatal — the PR and the gate\\n\" + ' token are already up). The next wp-finish-upsert-pr writes it.\\n');\n return;\n }\n process.stdout.write(' back-filled the PR description with its own link ✓\\n');\n }\n\n /**\n * The PR's web URL if one is already open for this branch, else '' — read BEFORE publishing so the\n * description can carry its own link on the first render. Only a brand-new PR gets '' (and then\n * {@link backfillPrBody} fixes it up after `gh pr create` returns a URL).\n */\n private existingPrUrl(baseBranch: string): string {\n return this.prRef(baseBranch).url;\n }\n\n /**\n * The 1st PR comment: the FULL dashboard — every row including the green ones, the whole summary, the\n * 3-point hash points. This is what the PR description used to be, and moving it here is the entire\n * point of the change: the description is now the git-log body, and a squash commit must not carry a\n * risk table.\n *\n * Posted unconditionally (any repo, checklists or not), because the description's last bullet PROMISES\n * a 1st comment holding the detail. A pointer to a comment that does not exist is worse than no\n * pointer. Non-fatal — the PR is already up, and the description alone is a complete, readable record.\n */\n private postDetailComment(repoRoot: string, prNumber: string, input: DashboardInput): void {\n if (prNumber === '') return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = DETAIL_COMMENT_MARKER;\n const detail = this.dashboard.renderDetailComment(input);\n request.body = DETAIL_COMMENT_MARKER + '\\n' + detail;\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'detail-comment.json';\n request.label = 'full dashboard comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR's number + web URL (for the merge subject `(#N)` and the commit-body back-link). Both ''\n // if it can't be resolved. Rendered via jq into one tab-separated line so no JSON parsing is needed.\n private prRef(baseBranch: string): PrRef {\n const result = spawnSync('gh', ['pr', 'view', baseBranch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"'], { encoding: 'utf8' });\n if (result.status !== 0) {\n return new PrRef('', '');\n }\n const parts = (result.stdout ?? '').trim().split('\\t');\n return new PrRef(parts[0] ?? '', parts[1] ?? '');\n }\n}\n"]}
1
+ {"version":3,"file":"finish-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/finish-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAyM;AACzM,8DAA0D;AAC1D,iEAA6D;AAC7D,yCAA2D;AAC3D,2EAAgE;AAChE,6DAAyD;AACzD,qEAAsG;AACtG,6EAAwE;AACxE,mDAA+C;AAC/C,+DAA6E;AAC7E,+DAAsF;AACtF,yDAAqD;AACrD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AAY;QACjB,kBAAO;QACD,8BAAa;QAClB,6BAAY;QACV,wBAAU;QACZ,oBAAQ;QACP,qCAAgB;QAChB,qBAAS;QACJ,wCAAsB;QAEpB,qDAAwB;QACxB,oCAAgB;QACrB,2CAAmB;QACb,gCAAiB;QAClB,+BAAgB;QAEd,wCAAkB;QAI5B,gDAAyB;QAC3B,4BAAY;QAGL,wCAAiB;QAEf,uCAAiB;QAGlB,iDAAsB;QACxB,iCAAc;QACZ,gCAAc;QACtB,4CAAuB;GApC3C,qBAAqB,CA6iBjC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { loadAndValidate, prDirFor, summaryJsonPath, PrSummary, RequiredChecklist, ChecklistVerdict, writeTemplate, RepoRootFinder, ReviewJsonService, GateTokenService } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { ReviewerVerdictGate } from '../workflow/reviewer-verdict-gate';\nimport { GitExec } from '../workflow/git-exec';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BuildGateLog, FINISH_STAGE, REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { MergeState } from '../workflow/merge-state';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewRoundStateService } from '../workflow/review-round-state';\nimport { StageOutputLog, FINISH_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { PrMerger, MergeIntent, MergeOutcome, MERGE_RESULT_FAILED } from '../workflow/pr-merger';\nimport { FinishBanner, FinishBannerInput } from '../workflow/finish-banner';\nimport { MergeBodyTempFile } from '../workflow/merge-body-temp-file';\nimport { GatedPrPublisher } from '../workflow/gated-pr-publisher';\nimport { ProvenanceEnforcer, ProvenanceReport } from '../workflow/provenance-enforcer';\nimport { PrCommentRequest, PrCommentUpserter } from '../workflow/pr-comment-upserter';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { TriggeredChecklist } from '../workflow/checklist-detector';\nimport { Dashboard, DashboardInput, ChecklistRow, DETAIL_COMMENT_MARKER } from '../../dashboard/dashboard';\nimport { ChecklistCommentRenderer, CHECKLIST_COMMENT_MARKER } from '../../dashboard/checklist-comment-renderer';\nimport { ChecklistCommentRow } from '../../dashboard/checklist-comment-row';\nimport { AuthorIdentityResolver } from '../../dashboard/author-identity';\nimport { HotfixRedirect } from '../workflow/hotfix-redirect';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The three inputs the PR COMMENTS are rendered from, bundled so `publishAll` takes one parameter for\n * them instead of three it only forwards. Data-only, per CLAUDE.md.\n */\nclass PrCommentSources {\n scan: ChecklistScan;\n review: PrSummary;\n provenance: ProvenanceReport;\n\n constructor(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport) {\n this.scan = scan;\n this.review = review;\n this.provenance = provenance;\n }\n}\n\n/**\n * Everything the PR upsert needs. Data-only, per CLAUDE.md — it replaced a 5-positional-parameter method\n * once `tokenSuffix` had to travel too, so the body can be re-rendered with the PR's own URL after\n * `gh pr create` returns it (see the INVARIANT comment in upsertPr).\n */\nclass PrUpsertRequest {\n repoRoot = '';\n baseBranch = '';\n title = '';\n /** The description as first published — rendered with whatever URL was known at the time. */\n body = '';\n /**\n * The hidden gate-token marker exactly as appended to `body`, so a re-render can reproduce the same\n * bytes. Kept separate from `body` because Dashboard renders the human/git-log half and must not know\n * about HMACs.\n */\n tokenSuffix = '';\n input: DashboardInput;\n\n constructor(input: DashboardInput) {\n this.input = input;\n }\n}\n\n// A resolved PR's number + web URL. Both '' when the PR can't be resolved (e.g. create failed).\nclass PrRef {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n// The outcome of the whole upsert: the PR number + web URL ('' each when unresolved) plus what actually\n// happened to the merge, so the final summary reports the REAL result rather than assuming success. The\n// URL is carried so the closing block can hand the AI a clickable link to relay to the user verbatim.\nclass UpsertResult {\n prNumber: string;\n prUrl: string;\n merge: MergeOutcome;\n\n constructor(prNumber: string, prUrl: string, merge: MergeOutcome) {\n this.prNumber = prNumber;\n this.prUrl = prUrl;\n this.merge = merge;\n }\n}\n\n// STAGE ③ — FINISH of the AI-first PR flow, and the ONLY command that posts PRs. Runs after\n// `wp-review-upsert-pr` verified the branch and the AI spawned the reviewers + wrote summary.json.\n//\n// In order: (1) REFUSE on an unvalidated 3-point merge and REQUIRE stage ②'s receipt; (2) REQUIRE\n// summary.json + every reviewer's verdict + provenance; (3) run the build gate UNLESS the receipt already\n// covers this exact HEAD; (4) render the dashboard; (5) create/update the PR via `gh`.\n//\n// It no longer FINALIZES a merge — stage ② does. Two commands owning conflict-resolution validation is two\n// implementations that drift, and finalizing here came too late to help anyway: the reviewers had already\n// reviewed the pre-merge tree by then.\n@injectable(bindingScopeValues.Singleton)\nexport class FinishUpsertPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildLog: BuildGateLog,\n private readonly mergeState: MergeState,\n private readonly prMerger: PrMerger,\n private readonly publisher: GatedPrPublisher,\n private readonly dashboard: Dashboard,\n private readonly authorIdentity: AuthorIdentityResolver,\n // The 2nd PR comment. Its own class because it is its own surface — see ChecklistCommentRenderer.\n private readonly checklistComment: ChecklistCommentRenderer,\n private readonly checklistScanner: ChecklistScanner,\n private readonly verdictGate: ReviewerVerdictGate,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly gateTokenService: GateTokenService,\n // Owns the reviewer-provenance integrity check and its audit record — see ProvenanceEnforcer.\n private readonly provenanceEnforcer: ProvenanceEnforcer,\n // NOTE: ChecklistInstructionsService is deliberately NOT injected here any more. Its \"You MUST run\n // these N reviewer subagent(s)\" block is now rendered by ReviewerVerdictGate and ONLY for checklists\n // that genuinely never ran, so no other code path in this command can print it at a refusal.\n private readonly receipts: ReviewStageReceiptService,\n private readonly banner: FinishBanner,\n // `gh pr merge --body-file` takes a path, so the bytes just published as the PR description are\n // spilled to a throwaway file for the length of one `gh` call. Nothing durable — the PR holds it.\n private readonly mergeBodyFile: MergeBodyTempFile,\n // ONE marker-keyed upsert, shared by both PR comments (the full dashboard and the checklist).\n private readonly commentUpserter: PrCommentUpserter,\n // Pins the two GitHub repo settings that decide whether a UI merge writes the body we just\n // rendered. Server-side, so no config can express them — see SquashSettingsEnforcer.\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly stageConsole: StageOutputLog,\n private readonly hotfixRedirect: HotfixRedirect,\n private readonly rounds: ReviewRoundStateService,\n ) {}\n\n /**\n * Runs with this stage's console CAPTURED to a file (see StageOutputLog). What still reaches the\n * terminal is what an agent must act on: the build heartbeat and result, and the closing banner with\n * the PR link and whatever is still owed. The dashboard computation, the gh round trips and the\n * comment upserts are in the file.\n */\n async run(): Promise<void> {\n // A /hotfix/ branch is published by wp-upsert-hotfix-pr, never by this stage (issue #1057).\n this.hotfixRedirect.assertNotHotfix('wp-finish-upsert-pr');\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, FINISH_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n // Refresh the AI-facing workflow doc so it's present + current for any failure message to cite.\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n // 1. REQUIRE stage ② — see assertStageTwoRan. Returns true when its receipt covers THIS commit,\n // which is what lets the build gate below be skipped rather than re-run for a foregone answer.\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n const buildAlreadyGreen = this.assertStageTwoRan(repoRoot);\n\n // 2. REQUIRE the AI-authored summary.json (throws InformAiError with the schema if missing/invalid).\n // Compute the consumer checklists this diff triggered FIRST so an unacknowledged BLOCK throws\n // here — BEFORE any `gh pr create` — matching the guarantee buildCommand already provides.\n // The SAME scan wp-review-upsert-pr runs, with filterAlreadyReviewed:true so `outstanding` is exactly what\n // still owes a verdict (Z of N of X). Sharing the computation is the point: the command that REPORTS\n // and the command that GATES must not be able to disagree about what is owed. review-round<N>-<id>.json files\n // persist locally, so a re-run re-validates the EXISTING verdicts against the (possibly changed)\n // applicable set for free — an unchanged checklist needs no re-review, a newly-applicable one refuses\n // until its file is written.\n // The scan judges ONLY the checklists that were briefed (issue #1053) — never one a later commit newly\n // triggered — and it has already folded every recorded orange fix into its results.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, 'stage3-finish'));\n const required = scan.applicable;\n // The applicable checklists that are supposed to HAVE a verdict — everything except the optional ones\n // nobody ran. Used for provenance and for the dashboard rows, both of which ask \"who reviewed this?\"\n // and would otherwise demand an answer from a review the human declined: provenance would refuse the\n // PR because a subagent that was never meant to run cannot be proven to have run, and the dashboard\n // would render a MISSING verdict for it.\n const verdicted = this.verdictedOf(scan);\n // FAIL FAST on an unclear checklist, BEFORE summary.json is parsed and before the build gate runs. A\n // missing reviewer is not a summary.json defect (folding it in made the AI fix the wrong thing), and\n // nobody should wait on a build to be told a reviewer never ran. ReviewerVerdictGate owns the\n // distinction between unreadable / ORANGE / REFUSED / never-ran.\n this.verdictGate.assertEveryReviewerRan(scan);\n const review = this.reviewJsonService.loadSummaryJson(summaryJsonPath(repoRoot, featureName), required, '', scan.orangeFixes);\n this.applyRoundAudits(review, scan, config.maxReviewerRounds);\n\n // 2c. For every verdicted checklist, VERIFY (from the harness's own artifacts) that a real reviewer\n // SUBAGENT actually ran on this branch — the coding agent may not self-certify. Its NAME is not\n // checked; see SubagentProvenanceService.isReviewerRun. Absent CLAUDE_CODE_SESSION_ID this skips with a warning (CI / plain terminal).\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const provenance = this.provenanceEnforcer.enforce(verdicted, currentBranch, repoRoot, config);\n\n // 2b. The build gate validates the WORKING TREE but we push HEAD — so they MUST be identical.\n this.gitExec.assertCleanTree(repoRoot);\n\n // 3. Build gate, then post the gated body, then push (that ORDER — see GatedPrPublisher).\n await this.runOrSkipBuildGate(repoRoot, buildAlreadyGreen);\n const base = this.branchNaming.baseBranchName(execSync('git branch --show-current', { encoding: 'utf8' }).trim());\n\n process.stdout.write('\\n' + SEP + '📋 Dashboard + PR\\n' + SEP + '\\n');\n const title = this.prTitleFrom(review);\n const input = this.computeDashboardInput(repoRoot, true, review, title, verdicted, scan);\n const result = this.publishAll(repoRoot, base, input, new PrCommentSources(scan, review, provenance));\n this.archiveConsumedReview(repoRoot, featureName, result);\n\n // The closing recap + the clickable-link directive, BOTH derived from the real merge outcome.\n // Nothing here may hard-code success: a stranded PR under a green checkmark is how PRs got\n // abandoned (see FinishBanner).\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n // `say`: the PR link and what is still owed are the whole reason a caller ran this command, and a\n // not-done outcome carries the commands that fix it. Neither may end up only in a log file.\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n private applyRoundAudits(review: PrSummary, scan: ChecklistScan, maxReviewerRounds: number): void {\n for (const result of review.results) {\n const trail = this.rounds.auditTrail(scan.summaryPath, result.id, maxReviewerRounds);\n if (trail === '') continue;\n result.output = trail;\n if (result.remediation !== '') result.remediation = `${trail}\\n\\n#### Final state\\n${result.remediation}`;\n }\n }\n\n // Validate + commit + finalize a 3-point merge the AI resolved, if one is in progress. Finalizing here\n // does NOT push (pushRemote=false): this command pushes exactly ONCE, from GatedPrPublisher, and only\n // after summary.json + every BLOCK checklist + the build gate pass and the gated PR body is written.\n /**\n * The build gate — SKIPPED when stage ②'s receipt already covers this exact HEAD.\n *\n * The gate is authoritative per-COMMIT, not per-command: re-running it on a tree that has not moved\n * since stage ② verified it buys nothing and costs a full `nx affected`. That skip is what makes the\n * three-stage flow cost ONE build rather than two, and it is why moving the gate earlier was affordable.\n */\n private async runOrSkipBuildGate(repoRoot: string, alreadyGreen: boolean): Promise<void> {\n if (alreadyGreen) {\n // `say`, for the same reason the gate's own two lines are: a caller watching for a build needs\n // to be told, live, that there is not going to be one.\n this.stageConsole.say('\\n🛠️ Build gate: already green for this commit (stage ② receipt) — skipping the rebuild.\\n' + this.skippedBuildLogNote(repoRoot));\n return;\n }\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions('🛠️ Build gate (authoritative)', 'pnpm wp-finish-upsert-pr', 'Build failed — no PR created/updated.', FINISH_STAGE));\n }\n\n /**\n * When the gate is SKIPPED and build-log capture is on, name STAGE ②'s log — the one build that\n * actually ran for this commit. Deliberately never names a finish-stage log: no finish build ran, and\n * pointing at a file this command did not write would claim a build that did not happen.\n *\n * The path is recomputed rather than stored, and that is sound precisely BECAUSE this branch is only\n * reached when the receipt covers the current HEAD: same worktree, same branch, same sha ⇒ the same\n * deterministic filename stage ② wrote. Empty string when the file is gone — a log that was reaped or\n * never written must not be named as though a reader could open it.\n */\n private skippedBuildLogNote(repoRoot: string): string {\n const log = this.buildLog.existingLogFor(repoRoot, REVIEW_STAGE);\n return log === '' ? '' : ` Stage ②'s full build output: ${log}\\n`;\n }\n\n /**\n * The two stage-② preconditions, together: no unvalidated merge, and a receipt proving stage ② ran.\n * Returns true when that receipt covers the CURRENT HEAD, i.e. the build gate can be skipped.\n */\n private assertStageTwoRan(repoRoot: string): boolean {\n this.assertNoUnvalidatedMerge(repoRoot);\n return this.assertReviewStageRan(repoRoot, this.aiBranchName.getFeatureName(), this.gitOut(['rev-parse', 'HEAD']));\n }\n\n /**\n * REFUSE while a 3-point merge is still unvalidated — do not finalize it here.\n *\n * This command used to do the finalizing itself. Finalizing means validating a conflict resolution, and\n * two commands owning that means two implementations that can drift; `PrContextWriter`'s docstring\n * records this codebase already paying for exactly that once. It also came too late to matter: by the\n * time finish ran, the reviewers had already reviewed the pre-merge tree.\n *\n * So stage ② owns it, and finish only checks. Nothing is lost — the recovery is one command away, and\n * running it also builds the merged tree and re-briefs the reviewers against it, which finalizing here\n * never did.\n */\n private assertNoUnvalidatedMerge(repoRoot: string): void {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return;\n throw new InformAiError(\n '⛔ NO PR — a 3-point merge on this branch is still unvalidated, so nothing here has been\\n' +\n 'verified: the conflict resolution is unchecked, the merged tree was never built, and any\\n' +\n 'reviewer that ran judged the PRE-merge code.\\n\\n' +\n `Conflicted file(s): ${marker.conflictedFiles.join(', ')}\\n\\n` +\n 'Resolve them (see .webpieces/instruct-ai/webpieces.mergeprocess.md), then run:\\n' +\n ' pnpm wp-review-upsert-pr\\n' +\n 'It validates the resolution, commits it, builds it, and re-briefs the reviewers.',\n );\n }\n\n /**\n * REQUIRE stage ② (`wp-review-upsert-pr`) to have run, and report whether it ran on THIS commit.\n *\n * Returns true when the receipt matches the current HEAD — the caller then skips its own build, because\n * the receipt IS the gate for that sha and rebuilding an unchanged tree is a second full `nx affected`\n * run for a foregone answer.\n *\n * Without this check a repo with NO checklists has nothing forcing stage ②: `assertEveryReviewerRan`\n * is vacuous, and summary.json — the only other interlock — is a file the AI writes itself. It could\n * write it and come straight here, skipping the merge validation and the build entirely.\n */\n private assertReviewStageRan(repoRoot: string, featureName: string, headSha: string): boolean {\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(\n '⛔ NO PR — stage ② never ran on this branch. That means the 3-point merge is unvalidated,\\n' +\n 'the build gate has not run, no diff was extracted, and no reviewer was briefed.\\n\\n' +\n 'Run: pnpm wp-review-upsert-pr\\n' +\n '(then spawn the reviewers it names, write summary.json, and re-run this command)',\n );\n }\n if (receipt.buildHeadSha === headSha) return true;\n // Not fatal, and never a re-review (issue #1053): a green or yellow verdict stands whatever changed\n // since, and only a RED with a round left ever opens another round. Suggesting a re-review here\n // would be an instruction the gate itself refuses. It is never silent either: the build re-runs.\n process.stderr.write(\n `\\n⚠️ HEAD moved since stage ② built (built ${receipt.buildHeadSha.slice(0, 8) || 'unknown'}, now ${headSha.slice(0, 8)}).\\n` +\n ' The build gate will re-run. No further review runs for this: every verdict is carried forward\\n' +\n ' from the reviewed tree, and the PR records that the reviewers judged an earlier commit.\\n\\n',\n );\n return false;\n }\n\n /**\n * Retire the review this run just used — move summary.json to old-summary.json beside it, stamped as\n * audit-only (see ReviewJsonService.archiveSummaryJson).\n *\n * WHY it moves rather than staying put: summary.json left behind is a live-looking file describing a\n * review that has already shipped, and the next `wp-review-upsert-pr` on this branch finds it sitting\n * there. A reviewer subagent that judges the PR's stated INTENT — its title, summary or risk level —\n * then reads the previous round's review and can return GREEN against a title that no longer exists,\n * with nothing in the verdict distinguishing that from a real pass. Moving it makes the only route back\n * to this command a freshly-written review.\n *\n * ONLY on a PR that actually went up. A run that died before publishing must stay re-runnable without\n * making the AI rewrite a review that was never used, and prNumber === '' is exactly that case.\n * Non-fatal: the PR is live by here, so an unwritable archive warns rather than failing the command.\n */\n private archiveConsumedReview(repoRoot: string, featureName: string, result: UpsertResult): void {\n if (result.prNumber === '') return;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the PR is already up; a failed archive must not fail the command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const archived = this.reviewJsonService.archiveSummaryJson(summaryJsonPath(repoRoot, featureName));\n if (archived !== '') process.stdout.write(` archived this run's summary.json → ${archived} (audit only) ✓\\n`);\n // Beside it, so an archived review keeps the transcript links belonging to the round that\n // produced it — a review whose provenance was overwritten by the NEXT round audits nothing.\n this.provenanceEnforcer.archiveRecord(prDirFor(repoRoot, featureName));\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(`⚠️ Could not archive summary.json (non-fatal — the PR is already up): ${error.message}\\n`);\n }\n }\n\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // The user-facing PR title: the AI-authored review.title, or — if omitted — a readable fallback\n // derived from the stable feature name (NEVER the internal `Squash merge of <branch>` commit subject).\n private prTitleFrom(review: PrSummary): string {\n if (review.title !== '') return review.title;\n return this.aiBranchName.getFeatureName().replace(/[-/]+/g, ' ').trim();\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private computeDashboardInput(repoRoot: string, buildPassed: boolean, review: PrSummary, title: string, required: readonly RequiredChecklist[], scan: ChecklistScan): DashboardInput {\n const config = loadAndValidate(repoRoot).prGate;\n const forkPoint = this.gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = this.gitOut(['rev-parse', 'HEAD']);\n const mainHead = this.gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = this.gitOut(['diff', range, '--name-only'])\n .split('\\n')\n .filter((f: string): boolean => f.trim() !== '');\n const patch = this.gitOut(['diff', range]);\n\n const gateResults = this.dashboard.computeGateResults(config.gates, changedFiles);\n const disables = this.dashboard.countAddedDisables(patch);\n const rows = this.checklistRows(required, review);\n // buildCommand travels into the dashboard so the PR-body footer can NAME the command that vouched\n // for this commit. The footer used to assert \"build ran via nx affected\" on every repo, which was\n // simply false wherever buildCommand is not nx.\n // `scan.suppressed.length`, never `scan.reviewersDisabled` alone: the dashboard and the commit\n // body have to state HOW MANY reviewers were killed, because a suppressed 4 and an applicable 0\n // are different facts that both render as an empty `rows`. See DashboardInput.\n const input = new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, review, rows, this.buildAffected.resolveBuildCommand(repoRoot), scan.suppressed.length, this.authorIdentity.resolve(review.model), false);\n input.notBriefed = scan.notBriefed.map((r: RequiredChecklist): string => r.id);\n return input;\n }\n\n /**\n * The applicable checklists MINUS the optional ones nobody ran.\n *\n * Not folded into `ChecklistScan` as yet another field: `applicable` (what matched) and `optionalNotRun`\n * (what was declined) are both facts about the scan, whereas this is one command's view of them, and the\n * roster comment deliberately wants the OTHER view — it lists the declined ones precisely so the PR does\n * not imply they passed.\n */\n private verdictedOf(scan: ChecklistScan): RequiredChecklist[] {\n const skipped = new Set(scan.optionalNotRun.map((r: RequiredChecklist): string => r.id));\n return scan.applicable.filter((r: RequiredChecklist): boolean => !skipped.has(r.id));\n }\n\n // Pair each matched checklist with its resolved verdict for the dashboard.\n //\n // A checklist reaching this point is always PASS, WARN or OVERRIDDEN, and the reason is ReviewerVerdictGate\n // — NOT loadSummaryJson. The gate runs one line earlier and throws on every other state (FAIL, MISSING,\n // BAD_FORMAT), so loadSummaryJson's own checklist validation can no longer be the thing that rejects them;\n // it re-validates the same set and finds it clean. This comment used to credit loadSummaryJson, which made\n // the ordering look deliberate while the gate's generic \"no verdict yet\" message masked every refusal.\n // WARN belongs in that list: yellow SHIPS, so it is not outstanding and reaches the dashboard.\n private checklistRows(required: readonly RequiredChecklist[], review: PrSummary): ChecklistRow[] {\n return required.map((req: RequiredChecklist): ChecklistRow => {\n const verdict = this.reviewJsonService.resolveVerdict(req, review.results);\n return new ChecklistRow(req.id, verdict.status, verdict.detail);\n });\n }\n\n /**\n * One comment row per DEFINED checklist — matched or not — pairing the roster's match evidence with the\n * resolved verdict. Built from `scan.roster` rather than from the applicable set: the skipped ones are\n * absent from `applicable` by construction, and their \"why not\" evidence (the configured globs and the\n * changed-file total) exists nowhere else without recomputing the diff a second way.\n */\n private commentRows(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): ChecklistCommentRow[] {\n // checklist id -> did its reviewer open the diff. Absent ⇒ not assessed, which prints nothing (see ChecklistCommentRow.diffRead).\n const readByChecklist = new Map<string, boolean>();\n for (const e of provenance.evidence) readByChecklist.set(e.checklistId, e.readDiff);\n const judged = new Set(scan.applicable.map((r: RequiredChecklist): string => r.id));\n const notBriefed = new Set(scan.notBriefed.map((r: RequiredChecklist): string => r.id));\n return scan.roster.entries.map((entry: TriggeredChecklist): ChecklistCommentRow => {\n // A briefed checklist is judged whether or not the final diff still matches it (the set is\n // frozen at the briefing, issue #1053); a newly-triggered one is shown, never judged.\n const ran = judged.has(entry.def.id) || entry.matchedFiles.length > 0;\n const req = new RequiredChecklist(entry.def.id, entry.def.reviewer, entry.def.doc, entry.matchedFiles, entry.matchedPatterns, entry.def.required);\n // A skipped checklist has no verdict to resolve — asking for one would report it as MISSING,\n // i.e. as an unreviewed obligation, when in fact it never had one.\n const verdict = ran && !notBriefed.has(entry.def.id) ? this.reviewJsonService.resolveVerdict(req, review.results) : new ChecklistVerdict(entry.def.id, '', '');\n const identity = review.results.find((result): boolean => result.id === entry.def.id);\n const row = new ChecklistCommentRow(identity?.agent ?? 'unknown', identity?.model ?? 'unknown', entry.def.id, verdict.status, verdict.detail, ran, entry.def.patterns, entry.matchedPatterns, entry.matchedFiles, scan.roster.changedFileCount);\n row.required = entry.def.required;\n row.notBriefed = notBriefed.has(entry.def.id);\n const read = readByChecklist.get(entry.def.id);\n row.diffRead = read === undefined ? '' : read ? 'yes' : 'no';\n return row;\n });\n }\n\n // Hidden HMAC gate-token marker (with a leading blank line) to append to the PR body, or '' when the\n // repo sets no gateSalt (byte-identical body to before this feature). Bound to the pushed HEAD sha.\n private gateTokenBody(gateSalt: string, headSha: string): string {\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n return marker === '' ? '' : `\\n\\n${marker}\\n`;\n }\n\n /**\n * Publish the roster + every reviewer's full `output` as ONE combined PR comment, idempotently (find the\n * marker comment → PATCH it, else POST). Never fatal: by here the PR is already created/updated, so a\n * `gh` failure only warns.\n *\n * Posted on EVERY run of a repo that defines checklists — including one where nothing matched, because\n * \"all five were evaluated and none applied\" is the good news the old comment could not deliver. The\n * guard is `scan.defined.length`, deliberately NOT the number of rows that ran: a repo with no\n * checklists configured must still see no comment at all (see ChecklistCommentRenderer).\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private postChecklistComment(repoRoot: string, prNumber: string, scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): void {\n if (prNumber === '' || scan.defined.length === 0) return;\n if (!loadAndValidate(repoRoot).prGate.checklistComments) return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = CHECKLIST_COMMENT_MARKER;\n request.body = this.checklistComment.render(this.commentRows(scan, review, provenance), provenance.verified, scan.roster.baseResolved, scan.suppressed.length, false);\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'checklist-comment.json';\n request.label = 'checklist review comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR, the remote branch, and the local branch all share the one stable feature name. Look up /\n // create / merge against `baseBranch` (baseBranchName tolerates a leftover `…wpN` mid-transition).\n // GatedPrPublisher owns the edit/push/create half and its ORDERING — the gated body goes up before\n // the push, so CI's `synchronize` read cannot see the previous run's token.\n private upsertPr(request: PrUpsertRequest): UpsertResult {\n const repoRoot = request.repoRoot;\n const baseBranch = request.baseBranch;\n const title = request.title;\n const input = request.input;\n const prDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n fs.mkdirSync(prDir, { recursive: true });\n const bodyFile = path.join(prDir, 'pr-body.md');\n fs.writeFileSync(bodyFile, request.body + '\\n');\n\n const published = this.publisher.publish(baseBranch, title, bodyFile);\n if (published.createFailed) {\n process.stderr.write('⚠️ gh pr create failed — create the PR manually with the body in:\\n ' + bodyFile + '\\n');\n return new UpsertResult('', '', new MergeOutcome(false, false, '⚠️ did NOT merge — there is no PR to merge (gh pr create failed above)', MERGE_RESULT_FAILED));\n }\n const num = published.number;\n\n // Set the squash-merge SUBJECT to the PR title (+ the `(#N)` GitHub normally appends, which an\n // explicit --subject would otherwise drop) and the BODY to the compact commit summary, so main's\n // history carries the PR title + risk/flags/link — NOT the internal `Squash merge of <branch>`\n // subject GitHub would inherit from the single squash commit on the branch.\n const ref = this.prRef(baseBranch);\n const subject = ref.number !== '' ? `${title} (#${ref.number})` : title;\n\n /*\n * THE INVARIANT: the merge body IS the PR description, byte for byte.\n *\n * That is what makes every landing route agree — the GitHub Merge button and a bare `gh pr merge`\n * copy the description via `squash_merge_commit_message: PR_BODY`, while `wp-land-pr` and finish's\n * own auto-merge pass these bytes with `--body-file`. If the two strings could differ, which route\n * landed the commit would change what history says, which is precisely the bug this whole change\n * exists to remove. `pr-body-is-merge-body.spec.ts` pins it.\n *\n * The one wrinkle is the self-link. A brand-new PR has no URL until `gh pr create` returns, so the\n * body published a moment ago was rendered with `prUrl: ''`. Re-render now that the URL is known\n * and push the corrected description back, so the two strings match and the commit carries its own\n * link. Only the CREATE path pays that extra edit: on every later run the URL was already known\n * before publishing, `finalBody` matches what went up, and nothing is re-sent.\n */\n const finalBody = this.dashboard.renderPrBody(input, ref.url) + request.tokenSuffix;\n if (finalBody !== request.body) this.backfillPrBody(ref.number, bodyFile, finalBody);\n\n // The DURABLE copy of these bytes is the PR description published above; this is a throwaway\n // file because `--body-file` takes a path. `wp-land-pr` reads the description back from GitHub,\n // so nothing here has to survive the process (see decisions/0005).\n const mergeBodyFile = this.mergeBodyFile.write(finalBody + '\\n');\n // PrMerger owns the direct-merge / auto-merge-fallback decision AND checks every gh status, so a\n // merge that did not happen is reported as such instead of being swallowed (see pr-merger.ts).\n // REQUIRED config — no default here on purpose. A missing value (an older published\n // rules-config that has no such field) reaches PrMerger as '' and is treated as \"do not merge\".\n const mergeMode = loadAndValidate(repoRoot).prGate.mergeMode ?? '';\n // `false`: this caller is POLICY-driven — only a config that really says AUTO merges here.\n const outcome = this.prMerger.merge(baseBranch, subject, mergeBodyFile, new MergeIntent(mergeMode, false));\n return new UpsertResult(ref.number !== '' ? ref.number : num, ref.url, outcome);\n }\n\n /**\n * Everything the gated flow PUBLISHES, in the one order that is safe — the three surfaces plus the\n * merge, as a single unit.\n *\n * 1. the PR DESCRIPTION = the compact git-log body (+ the hidden gate token), written before the\n * push so CI's `synchronize` read can never see the previous run's token,\n * 2. the 1st comment = the full dashboard,\n * 3. the 2nd comment = each reviewer's output.\n *\n * The token is bound to the LOCAL HEAD sha and minted here because we only reach this line after the\n * build gate and every BLOCK checklist passed, so minting is legitimate. Nothing about\n * HMAC(salt, HEAD) needs the remote to have the commit yet.\n *\n * Extracted from `run` when the two comments made it 82 lines against a hard 80-line rule — and it\n * earns its own name: these four steps have a REQUIRED order, and the comment explaining that order\n * belongs with them rather than inside a method that also loads config and runs a build gate.\n */\n private publishAll(repoRoot: string, base: string, input: DashboardInput, sources: PrCommentSources): UpsertResult {\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n const headSha = this.gitOut(['rev-parse', 'HEAD']);\n const upsert = new PrUpsertRequest(input);\n upsert.repoRoot = repoRoot;\n upsert.baseBranch = base;\n upsert.title = input.title;\n upsert.tokenSuffix = this.gateTokenBody(gateSalt, headSha);\n // `existingPrUrl` is '' only for a brand-new PR — there is no URL to self-link to until\n // `gh pr create` returns one, and upsertPr back-fills it the moment it does.\n upsert.body = this.dashboard.renderPrBody(input, this.existingPrUrl(base)) + upsert.tokenSuffix;\n const result = this.upsertPr(upsert);\n\n // In the order the PR body's pointer promises: full dashboard 1st, reviewer output 2nd. Both are\n // idempotent by hidden marker and both non-fatal — the PR is up by now, so a `gh` hiccup on a\n // comment must not turn a finished run into a failed one.\n this.postDetailComment(repoRoot, result.prNumber, input);\n this.postChecklistComment(repoRoot, result.prNumber, sources.scan, sources.review, sources.provenance);\n\n // Having just written the description AS the commit body, make sure GitHub will actually use it.\n // Here rather than anywhere earlier because it is about what happens to the artifact we just\n // published, and it must run on EVERY repo — including mergeMode=NONE ones that never reach\n // PrMerger, which are exactly the repos where a UI merge decides what main's history says.\n this.squashSettings.ensure();\n return result;\n }\n\n /**\n * Re-publish the description now that the PR's own URL is known (create path only).\n *\n * Non-fatal on purpose. The PR exists, its body already carries a valid gate token for the pushed\n * head, and the code is up — the ONLY thing missing is the self-link on the first line. Aborting a\n * finished run over a cosmetic back-link would be a worse outcome than the missing link, and the very\n * next `wp-finish-upsert-pr` writes it (by then the URL is known before publishing, so it goes up with\n * the body). The merge body still gets the linked version regardless: it is filed from `finalBody`.\n */\n private backfillPrBody(prNumber: string, bodyFile: string, finalBody: string): void {\n if (prNumber === '') return;\n fs.writeFileSync(bodyFile, finalBody + '\\n');\n const res = spawnSync('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile], {\n encoding: 'utf8',\n });\n if (res.status !== 0) {\n process.stderr.write(\"⚠️ Could not add the PR's own link to its description (non-fatal — the PR and the gate\\n\" + ' token are already up). The next wp-finish-upsert-pr writes it.\\n');\n return;\n }\n process.stdout.write(' back-filled the PR description with its own link ✓\\n');\n }\n\n /**\n * The PR's web URL if one is already open for this branch, else '' — read BEFORE publishing so the\n * description can carry its own link on the first render. Only a brand-new PR gets '' (and then\n * {@link backfillPrBody} fixes it up after `gh pr create` returns a URL).\n */\n private existingPrUrl(baseBranch: string): string {\n return this.prRef(baseBranch).url;\n }\n\n /**\n * The 1st PR comment: the FULL dashboard — every row including the green ones, the whole summary, the\n * 3-point hash points. This is what the PR description used to be, and moving it here is the entire\n * point of the change: the description is now the git-log body, and a squash commit must not carry a\n * risk table.\n *\n * Posted unconditionally (any repo, checklists or not), because the description's last bullet PROMISES\n * a 1st comment holding the detail. A pointer to a comment that does not exist is worse than no\n * pointer. Non-fatal — the PR is already up, and the description alone is a complete, readable record.\n */\n private postDetailComment(repoRoot: string, prNumber: string, input: DashboardInput): void {\n if (prNumber === '') return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = DETAIL_COMMENT_MARKER;\n const detail = this.dashboard.renderDetailComment(input);\n request.body = DETAIL_COMMENT_MARKER + '\\n' + detail;\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'detail-comment.json';\n request.label = 'full dashboard comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR's number + web URL (for the merge subject `(#N)` and the commit-body back-link). Both ''\n // if it can't be resolved. Rendered via jq into one tab-separated line so no JSON parsing is needed.\n private prRef(baseBranch: string): PrRef {\n const result = spawnSync('gh', ['pr', 'view', baseBranch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"'], { encoding: 'utf8' });\n if (result.status !== 0) {\n return new PrRef('', '');\n }\n const parts = (result.stdout ?? '').trim().split('\\t');\n return new PrRef(parts[0] ?? '', parts[1] ?? '');\n }\n}\n"]}
@@ -72,6 +72,8 @@ export declare class ReviewUpsertPrCommand {
72
72
  */
73
73
  run(): Promise<void>;
74
74
  private runStage;
75
+ /** Keep the original briefing, diff, roster and provenance intact while refreshing build evidence. */
76
+ private resumeRound;
75
77
  /**
76
78
  * List every rule that is currently switched off in webpieces.config.json. NON-BLOCKING and printed
77
79
  * before the instruction block, because it is context for the review rather than a step in it.
@@ -119,7 +119,14 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
119
119
  const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(config.maxReviewerRounds, false, '')); // '' — THIS command writes the context itself, after materializing
120
120
  const previousReceipt = this.receipts.read(repoRoot, featureName);
121
121
  const plan = this.rounds.plan(repoRoot, scan.summaryPath, previousReceipt, config.maxReviewerRounds, scan.basis);
122
- const shouldBrief = plan.action === review_round_state_1.ROUND_ACTION_REVIEW || plan.action === review_round_state_1.ROUND_ACTION_RESUME;
122
+ if (plan.action === review_round_state_1.ROUND_ACTION_RESUME && previousReceipt !== null) {
123
+ this.resumeRound(repoRoot, featureName, scan, previousReceipt, mergeValidated, buildPassedAt);
124
+ this.reportActiveHatches(repoRoot);
125
+ if (scan.reviewersDisabled)
126
+ this.report(repoRoot, featureName, scan, [], plan, config);
127
+ return;
128
+ }
129
+ const shouldBrief = plan.action === review_round_state_1.ROUND_ACTION_REVIEW;
123
130
  const briefings = shouldBrief
124
131
  ? this.briefReviewers(repoRoot, featureName, scan, config, plan)
125
132
  : [];
@@ -135,9 +142,40 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
135
142
  receipt.maxReviewerRounds = plan.maxRounds;
136
143
  this.receipts.write(repoRoot, featureName, receipt);
137
144
  }
145
+ else if (previousReceipt !== null) {
146
+ previousReceipt.buildHeadSha = scan.basis.headSha;
147
+ previousReceipt.mergeValidated = mergeValidated;
148
+ previousReceipt.buildCommand = this.buildAffected.resolveBuildCommand(repoRoot);
149
+ previousReceipt.buildPassedAt = buildPassedAt;
150
+ this.receipts.write(repoRoot, featureName, previousReceipt);
151
+ }
138
152
  this.reportActiveHatches(repoRoot);
139
153
  this.report(repoRoot, featureName, scan, briefings, plan, config);
140
154
  }
155
+ /** Keep the original briefing, diff, roster and provenance intact while refreshing build evidence. */
156
+ // eslint-disable-next-line @typescript-eslint/max-params
157
+ resumeRound(repoRoot, featureName, scan, receipt, mergeValidated, buildPassedAt) {
158
+ receipt.buildHeadSha = scan.basis.headSha;
159
+ receipt.mergeValidated = mergeValidated;
160
+ receipt.buildCommand = this.buildAffected.resolveBuildCommand(repoRoot);
161
+ receipt.buildPassedAt = buildPassedAt;
162
+ this.receipts.write(repoRoot, featureName, receipt);
163
+ // The scanner owns reviewer suppression. Keep the historical roster for later recovery, but
164
+ // never instruct it to run while the existing opt-out is active.
165
+ if (scan.reviewersDisabled)
166
+ return;
167
+ const pending = receipt.reviewersBriefed.filter((id) => !receipt.optionalBriefed.includes(id) &&
168
+ !this.rounds.hasVerdict(scan.summaryPath, id, receipt.round));
169
+ this.stageConsole.say(`\nResume the existing reviewer roster: round ${receipt.round} of ${receipt.maxReviewerRounds}.\n` +
170
+ `Build passed at ${receipt.buildHeadSha}; reviewers retain their briefing at ${receipt.headSha}.\n` +
171
+ 'Continue the existing reviewer agents; do not respawn them for a SHA or fork-point change.\n' +
172
+ pending
173
+ .map((id) => ` REQUIRED ${id}: ${this.reviewerInstructions.pathFor(repoRoot, featureName, id)}\n` +
174
+ ` Submit with: pnpm wp-write-review --checklist ${id} --file '<verdict JSON file>'\n`)
175
+ .join('') +
176
+ `\nAfter the remaining verdicts, write ${scan.summaryPath}:\n${(0, rules_config_1.summaryJsonSchemaHint)(scan.summaryPath)}\n` +
177
+ 'Then run: pnpm wp-review-upsert-pr (to plan any RED follow-up), followed by pnpm wp-finish-upsert-pr.\n');
178
+ }
141
179
  /**
142
180
  * List every rule that is currently switched off in webpieces.config.json. NON-BLOCKING and printed
143
181
  * before the instruction block, because it is context for the review rather than a step in it.
@@ -1 +1 @@
1
- {"version":3,"file":"review-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/review-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAA4L;AAC5L,yCAA2D;AAC3D,+DAA4E;AAC5E,2EAAgE;AAChE,+DAA6E;AAC7E,+DAA0D;AAC1D,yEAAoE;AACpE,qEAAsG;AACtG,qEAAiE;AACjE,mDAA+C;AAC/C,yDAAuD;AACvD,qDAAkE;AAClE,yDAAqD;AACrD,qEAAgE;AAChE,qFAAgF;AAChF,6DAA6F;AAC7F,2EAAiG;AACjG,mEAAkF;AAClF,iEAA6D;AAC7D,uEAEwC;AAExC,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEI,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;IAGT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IArBrB,yDAAyD;IACzD,YACqB,cAA8B,EAC9B,YAA0B,EAC1B,OAAgB,EAChB,aAA4B,EAC5B,iBAAoC,EACpC,UAAsB,EACtB,QAAkB,EAClB,gBAAkC,EAClC,YAA0B,EAC1B,YAA8B,EAC9B,eAAgC,EAChC,eAA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AY;QACZ,oCAAgB;QACb,mCAAe;QACf,mDAAuB;QAClB,0CAA2B;QACvC,gDAAyB;QAChB,kCAAiB;QAEjB,gCAAiB;QACtB,iCAAc;QACZ,gCAAc;QACtB,4CAAuB;GAtB3C,qBAAqB,CA8NjC","sourcesContent":["import * as fs from 'fs';\nimport { loadAndValidate, writeTemplate, PrGateConfig, RepoRootFinder, RequiredChecklist, ReviewerBriefing, ReviewerInstructionsService, ReviewJsonService } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ActiveHatch, ActiveHatchReport } from '../workflow/active-hatches';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { BuildArtifactGate } from '../workflow/build-artifact-gate';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { DiffMaterializer } from '../workflow/diff-materializer';\nimport { GitExec } from '../workflow/git-exec';\nimport { MergeContext } from '../workflow/merge-start';\nimport { MergeEnd, MergeEndOptions } from '../workflow/merge-end';\nimport { MergeState } from '../workflow/merge-state';\nimport { PrContextWriter } from '../workflow/pr-context-writer';\nimport { ReviewerBriefingBuilder } from '../workflow/reviewer-briefing-builder';\nimport { RefusedReviewer, ReviewReport, ReviewReportInput } from '../workflow/review-report';\nimport { ReviewStageReceipt, ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog, REVIEW_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { HotfixRedirect } from '../workflow/hotfix-redirect';\nimport {\n ReviewRoundPlan, ReviewRoundStateService, ROUND_ACTION_REVIEW, ROUND_ACTION_RESUME,\n} from '../workflow/review-round-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * `wp-review-upsert-pr` — STAGE ② of the three-stage PR flow, between `wp-start-upsert-pr` (sync from main)\n * and `wp-finish-upsert-pr` (post the PR).\n *\n * It exists because reviewing came before verifying. Under the old two-command flow the 3-point merge was\n * finalized and the build gate ran inside `wp-finish-upsert-pr` — i.e. AFTER the reviewers had already run.\n * A reviewer could therefore spend a full review on an unresolved merge, or on code that does not compile,\n * and only afterwards would the branch be checked. This command puts the verification first:\n *\n * 1. finalize + VALIDATE any in-progress 3-point merge (moved here from finish)\n * 2. assert a clean tree (meaningful now — step 1 committed the resolution)\n * 3. run the build gate (on the merged, committed tree)\n * 4. scan the checklists, EXTRACT the diff, BRIEF the reviewers\n * 5. write the stage receipt, then print what to spawn + the summary.json schema\n *\n * Unlike the report-only command it replaces — which always exited 0, because reporting is not gating — this\n * command CAN FAIL, at steps 1, 2 and 3. That is the point: it fails BEFORE any reviewer is spawned, so a\n * branch with an unresolved merge or a broken build costs zero reviewer tokens.\n *\n * The ordering of 1 → 2 → 3 is load-bearing. MergeEnd stages and commits the conflict resolution, so the\n * tree is clean by the time the build runs; building first would either build a dirty tree (proving nothing\n * about what ships) or refuse a tree that is legitimately mid-resolution.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewUpsertPrCommand {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildArtifactGate: BuildArtifactGate,\n private readonly mergeState: MergeState,\n private readonly mergeEnd: MergeEnd,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewReport: ReviewReport,\n private readonly materializer: DiffMaterializer,\n private readonly prContextWriter: PrContextWriter,\n private readonly briefingBuilder: ReviewerBriefingBuilder,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly receipts: ReviewStageReceiptService,\n private readonly activeHatchReport: ActiveHatchReport,\n // Injected to RESOLVE + RENDER refusals (see refusals()) and to name each round's verdict file.\n private readonly reviewJsonService: ReviewJsonService,\n private readonly stageConsole: StageOutputLog,\n private readonly hotfixRedirect: HotfixRedirect,\n private readonly rounds: ReviewRoundStateService,\n ) {}\n\n /**\n * Everything below runs with this stage's console CAPTURED to a file (see StageOutputLog). Only the\n * lines an agent must act on before it can do anything else reach the terminal — the build heartbeat\n * and result, and the closing instruction block. The merge validation, the hatch report, the checklist\n * scan and the diff extraction are all in the file, one `grep` away.\n *\n * This is the FIRST half of the fix for the piped-command watchdog kill: an agent pipes a command it\n * expects to flood, a pipe withholds every byte until exit, and the harness kills a command that has\n * printed nothing for 600 seconds — after a full build. Guarding the pipe without first shrinking the\n * output would only have traded that kill for a flooded context.\n */\n async run(): Promise<void> {\n // A /hotfix/ branch has no review stage — it publishes with wp-upsert-hotfix-pr (issue #1057).\n this.hotfixRedirect.assertNotHotfix('wp-review-upsert-pr');\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, REVIEW_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n writeTemplate(repoRoot, 'webpieces.review-checklists.md');\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n\n const mergeValidated = await this.finalizeAnyInProgressMerge(repoRoot);\n this.gitExec.assertCleanTree(repoRoot);\n const buildPassedAt = await this.runBuildGate(repoRoot);\n\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, false, '')); // '' — THIS command writes the context itself, after materializing\n const previousReceipt = this.receipts.read(repoRoot, featureName);\n const plan = this.rounds.plan(repoRoot, scan.summaryPath, previousReceipt, config.maxReviewerRounds, scan.basis);\n const shouldBrief = plan.action === ROUND_ACTION_REVIEW || plan.action === ROUND_ACTION_RESUME;\n const briefings = shouldBrief\n ? this.briefReviewers(repoRoot, featureName, scan, config, plan)\n : [];\n const recordedReviewers = briefings.map((b: ReviewerBriefing): string => b.checklistId);\n if (shouldBrief) {\n const receipt = new ReviewStageReceipt(scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt, recordedReviewers);\n receipt.scopeHashes = scan.scopeHashes;\n // Which briefed checklists are OPTIONAL: a round is complete once every REQUIRED one has a\n // verdict, and an optional one joins the round only if it actually submitted (issue #1062).\n receipt.optionalBriefed = briefings.filter((b: ReviewerBriefing): boolean => !b.required).map((b: ReviewerBriefing): string => b.checklistId);\n // A global round begins only when a non-empty fixed roster is actually briefed.\n receipt.round = recordedReviewers.length === 0 ? 0 : plan.round;\n receipt.maxReviewerRounds = plan.maxRounds;\n this.receipts.write(repoRoot, featureName, receipt);\n }\n this.reportActiveHatches(repoRoot);\n this.report(repoRoot, featureName, scan, briefings, plan, config);\n }\n\n /**\n * List every rule that is currently switched off in webpieces.config.json. NON-BLOCKING and printed\n * before the instruction block, because it is context for the review rather than a step in it.\n *\n * A hatch is the one config change that makes the build QUIETER, so no gate, reviewer or red check\n * will ever mention it — which is how a repo ends up with rules off for weeks that nobody chose to\n * leave off. This is the only place in the flow that says so out loud.\n */\n private reportActiveHatches(repoRoot: string): void {\n const hatches: ActiveHatch[] = this.activeHatchReport.scan(repoRoot);\n process.stdout.write(this.activeHatchReport.render(hatches));\n }\n\n /**\n * Validate + commit + finalize a conflict resolution, if one is in flight. MOVED here from\n * `wp-finish-upsert-pr` so that exactly one command owns merge finalization — two owners is the drift\n * failure `PrContextWriter`'s own docstring records having already happened once in this codebase.\n *\n * MergeEnd's three checks are what \"did the AI do the 3-point merge right?\" means concretely: no\n * conflict markers left in the scoped files, `git diff --diff-filter=U` empty, and a non-empty\n * merge-explanation.md beside every conflicted file.\n *\n * Returns true when a merge was finalized OR there was none to finalize; it throws rather than returning\n * false when validation fails, so the receipt can never record an unvalidated merge as validated.\n */\n private async finalizeAnyInProgressMerge(repoRoot: string): Promise<boolean> {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return true;\n process.stdout.write('\\n' + SEP + '① Validating your 3-point merge\\n' + SEP + '\\n');\n // pushRemote:false — finish still owns the single push.\n await this.mergeEnd.mergeEnd(repoRoot, 'wp-review-upsert-pr', activeDir, new MergeContext(marker.currentBranch, marker.squashBranch, marker.backupBranch, marker.prNumber), new MergeEndOptions(marker.conflictedFiles, false));\n return true;\n }\n\n /**\n * The build gate, run BEFORE any reviewer is briefed. Returns the ISO time it passed, for the receipt —\n * which is what lets `wp-finish-upsert-pr` skip its own gate when HEAD has not moved, so moving the gate\n * earlier did not turn one build into two.\n */\n private async runBuildGate(repoRoot: string): Promise<string> {\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions('🛠️ Build gate', 'pnpm wp-review-upsert-pr', 'Build failed — NO reviewer was briefed and no diff was extracted. Fix it, then re-run.', REVIEW_STAGE));\n // Repo-wide: the build must not have left anything uncommitted AND unstaged. Runs HERE, not in\n // finish, because this is the stage that ran buildCommand and is therefore holding the dirty\n // tree at the exact moment the question is answerable. Replaces the per-project\n // validate-di-graph-unchanged nx target — see BuildArtifactGate for why that one had to go.\n this.buildArtifactGate.assertBuildLeftNothingUncommitted(repoRoot);\n return new Date().toISOString();\n }\n\n /**\n * Extract the diff once, then write one instructions file per reviewer.\n *\n * The changed-file set and the basis both come off the SCAN rather than being recomputed, so the diff a\n * reviewer reads covers exactly the files its checklist matched against.\n */\n private briefReviewers(repoRoot: string, featureName: string, scan: ChecklistScan, config: PrGateConfig, plan: ReviewRoundPlan): ReviewerBriefing[] {\n if (plan.basis.unresolved) return [];\n const changedFiles = plan.round > 1 ? plan.changedFiles : scan.changedFiles;\n const manifest = this.materializer.materialize(repoRoot, featureName, plan.basis, changedFiles, config.reviewDiffExclude);\n const diffDir = this.materializer.diffDirFor(repoRoot, featureName);\n // Write pr-context.json ONCE, here — after materializing, so `diffDir` is populated on the first\n // write. The scan deliberately did not write it (ChecklistScanOptions.contextStage === ''); it used\n // to, which meant this command wrote the same file twice, the first time with an empty diffDir.\n // `scan.changedFiles` is passed through so the context is not recomputed from a second git call.\n scan.context = this.prContextWriter.ensure(repoRoot, featureName, plan.basis, 'stage2-review', changedFiles, diffDir);\n // ONLY the checklists still owed a verdict (issue #863). A green or yellow CARRIES whatever changed\n // since (issue #1053) — the scan left it in `reviewed` — so briefing it again would pay a reviewer to\n // re-read code it already judged. A later round re-briefs exactly the previous round's REDS.\n const reviewedIds = new Set(scan.reviewed.map((r: RequiredChecklist): string => r.id));\n const owed = scan.applicable.filter((r: RequiredChecklist): boolean => plan.round > 1\n ? plan.redChecklistIds.includes(r.id)\n : !reviewedIds.has(r.id));\n const briefings = this.briefingBuilder.build(repoRoot, scan, owed, manifest, diffDir, config);\n const dir = this.reviewerInstructions.instructionsDirFor(repoRoot, featureName);\n fs.rmSync(dir, { recursive: true, force: true }); // stale instructions read as current are worse than none\n fs.mkdirSync(dir, { recursive: true });\n for (const b of briefings) {\n b.round = plan.round;\n b.maxRounds = plan.maxRounds;\n b.verdictPath = this.reviewJsonService.checklistResultPath(scan.summaryPath, b.checklistId, plan.round);\n b.remediationOnly = plan.round > 1;\n if (b.remediationOnly) {\n b.previousVerdictPath = this.reviewJsonService.checklistResultPath(scan.summaryPath, b.checklistId, plan.round - 1);\n b.remediationPath = this.rounds.fixesPath(scan.summaryPath, plan.round - 1);\n }\n fs.writeFileSync(this.reviewerInstructions.pathFor(repoRoot, featureName, b.checklistId), this.reviewerInstructions.render(b));\n }\n return briefings;\n }\n\n /**\n * What the AI must do next — rendered by `ReviewReport`, which owns the ordering.\n *\n * The rendering moved OUT of this command so the ordering could be asserted on as a string. It had a\n * real bug: the zero-checklist notice signed off with \"Carry on and run: pnpm wp-finish-upsert-pr\"\n * while the block right beneath it said to write summary.json first. An agent that reads top to bottom\n * obeyed the first line and posted a PR with no review at all.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private report(repoRoot: string, featureName: string, scan: ChecklistScan, briefings: readonly ReviewerBriefing[], plan: ReviewRoundPlan, config: PrGateConfig): void {\n const input = new ReviewReportInput(repoRoot, featureName, scan.summaryPath);\n input.definedCount = scan.defined.length;\n input.applicableCount = scan.applicable.length;\n input.reviewed = scan.reviewed.slice();\n input.formatErrors = scan.formatErrors.slice();\n input.briefings = briefings.slice();\n input.refused = this.refusals(scan);\n input.reviewer = config.reviewer;\n // Straight off the SCAN — the one place `experimental.turnOffAllReviewers` is read. This command\n // deliberately does NOT consult the home config itself: a second read is a second answer, and the\n // command that lists and the command that blocks would be free to disagree about whether a branch\n // was reviewed. See ChecklistScanner.\n input.reviewersSuppressed = scan.reviewersDisabled;\n input.suppressed = scan.suppressed.slice();\n input.round = plan.round;\n input.maxReviewerRounds = plan.maxRounds;\n input.roundAction = plan.action;\n input.redChecklistIds = plan.redChecklistIds.slice();\n input.orangeChecklistIds = plan.orangeChecklistIds.slice();\n input.notBriefed = scan.notBriefed.slice();\n input.standings = scan.standings.slice();\n // `say`: this block IS the next action — which reviewers to spawn, where summary.json goes, and\n // the command after that. Capturing it into the log would leave the terminal with a pointer and\n // no instruction, which is the one thing this stage may never do.\n this.stageConsole.say(this.reviewReport.render(input));\n }\n\n /**\n * The applicable checklists that ALREADY ANSWERED and refused, each with its refusal rendered by the ONE\n * renderer `wp-finish-upsert-pr` also uses.\n *\n * Stage ② had the identical defect finish did: a refused checklist has no passing verdict, so it is not\n * in `scan.reviewed`, so it was printed as an ordinary owed reviewer and re-instructed word for word —\n * and an agent that obeys spawns it against unchanged code, gets the same refusal, and loops one stage\n * earlier than the loop that was reported.\n *\n * Nothing is moved: a red verdict stays on disk as its round's record, and the next round's verdict is a\n * new file (issue #1053). The review path IS passed, because the ship-anyway route the refusal prints is a\n * command that writes `override-<id>.json` beside it.\n */\n private refusals(scan: ChecklistScan): RefusedReviewer[] {\n const refused = this.reviewJsonService.refusedChecklists(scan.applicable, scan.results);\n return refused.map((req: RequiredChecklist): RefusedReviewer => new RefusedReviewer(req.id, this.reviewJsonService.refusalError(req, this.reviewJsonService.resolveVerdict(req, scan.results), scan.summaryPath)));\n }\n}\n"]}
1
+ {"version":3,"file":"review-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/review-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAAmN;AACnN,yCAA2D;AAC3D,+DAA4E;AAC5E,2EAAgE;AAChE,+DAA6E;AAC7E,+DAA0D;AAC1D,yEAAoE;AACpE,qEAAsG;AACtG,qEAAiE;AACjE,mDAA+C;AAC/C,yDAAuD;AACvD,qDAAkE;AAClE,yDAAqD;AACrD,qEAAgE;AAChE,qFAAgF;AAChF,6DAA6F;AAC7F,2EAAiG;AACjG,mEAAkF;AAClF,iEAA6D;AAC7D,uEAEwC;AAExC,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEI,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;IAGT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IArBrB,yDAAyD;IACzD,YACqB,cAA8B,EAC9B,YAA0B,EAC1B,OAAgB,EAChB,aAA4B,EAC5B,iBAAoC,EACpC,UAAsB,EACtB,QAAkB,EAClB,gBAAkC,EAClC,YAA0B,EAC1B,YAA8B,EAC9B,eAAgC,EAChC,eAAwC,EACxC,oBAAiD,EACjD,QAAmC,EACnC,iBAAoC;IACrD,gGAAgG;IAC/E,iBAAoC,EACpC,YAA4B,EAC5B,cAA8B,EAC9B,MAA+B;QAnB/B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,iBAAY,GAAZ,YAAY,CAAc;QAC1B,YAAO,GAAP,OAAO,CAAS;QAChB,kBAAa,GAAb,aAAa,CAAe;QAC5B,sBAAiB,GAAjB,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AAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACxF,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,GAAsB,EAAmB,EAAE,CAAC,IAAI,+BAAe,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,iBAAiB,CAAC,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;IACvN,CAAC;CACJ,CAAA;AAjRY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIA,6BAAc;QAChB,mCAAY;QACjB,kBAAO;QACD,8BAAa;QACT,uCAAiB;QACxB,wBAAU;QACZ,oBAAQ;QACA,oCAAgB;QACpB,4BAAY;QACZ,oCAAgB;QACb,mCAAe;QACf,mDAAuB;QAClB,0CAA2B;QACvC,gDAAyB;QAChB,kCAAiB;QAEjB,gCAAiB;QACtB,iCAAc;QACZ,gCAAc;QACtB,4CAAuB;GAtB3C,qBAAqB,CAiRjC","sourcesContent":["import * as fs from 'fs';\nimport { loadAndValidate, writeTemplate, PrGateConfig, RepoRootFinder, RequiredChecklist, ReviewerBriefing, ReviewerInstructionsService, ReviewJsonService, summaryJsonSchemaHint } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ActiveHatch, ActiveHatchReport } from '../workflow/active-hatches';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { BuildArtifactGate } from '../workflow/build-artifact-gate';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { DiffMaterializer } from '../workflow/diff-materializer';\nimport { GitExec } from '../workflow/git-exec';\nimport { MergeContext } from '../workflow/merge-start';\nimport { MergeEnd, MergeEndOptions } from '../workflow/merge-end';\nimport { MergeState } from '../workflow/merge-state';\nimport { PrContextWriter } from '../workflow/pr-context-writer';\nimport { ReviewerBriefingBuilder } from '../workflow/reviewer-briefing-builder';\nimport { RefusedReviewer, ReviewReport, ReviewReportInput } from '../workflow/review-report';\nimport { ReviewStageReceipt, ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog, REVIEW_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { HotfixRedirect } from '../workflow/hotfix-redirect';\nimport {\n ReviewRoundPlan, ReviewRoundStateService, ROUND_ACTION_REVIEW, ROUND_ACTION_RESUME,\n} from '../workflow/review-round-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * `wp-review-upsert-pr` — STAGE ② of the three-stage PR flow, between `wp-start-upsert-pr` (sync from main)\n * and `wp-finish-upsert-pr` (post the PR).\n *\n * It exists because reviewing came before verifying. Under the old two-command flow the 3-point merge was\n * finalized and the build gate ran inside `wp-finish-upsert-pr` — i.e. AFTER the reviewers had already run.\n * A reviewer could therefore spend a full review on an unresolved merge, or on code that does not compile,\n * and only afterwards would the branch be checked. This command puts the verification first:\n *\n * 1. finalize + VALIDATE any in-progress 3-point merge (moved here from finish)\n * 2. assert a clean tree (meaningful now — step 1 committed the resolution)\n * 3. run the build gate (on the merged, committed tree)\n * 4. scan the checklists, EXTRACT the diff, BRIEF the reviewers\n * 5. write the stage receipt, then print what to spawn + the summary.json schema\n *\n * Unlike the report-only command it replaces — which always exited 0, because reporting is not gating — this\n * command CAN FAIL, at steps 1, 2 and 3. That is the point: it fails BEFORE any reviewer is spawned, so a\n * branch with an unresolved merge or a broken build costs zero reviewer tokens.\n *\n * The ordering of 1 → 2 → 3 is load-bearing. MergeEnd stages and commits the conflict resolution, so the\n * tree is clean by the time the build runs; building first would either build a dirty tree (proving nothing\n * about what ships) or refuse a tree that is legitimately mid-resolution.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewUpsertPrCommand {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildArtifactGate: BuildArtifactGate,\n private readonly mergeState: MergeState,\n private readonly mergeEnd: MergeEnd,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewReport: ReviewReport,\n private readonly materializer: DiffMaterializer,\n private readonly prContextWriter: PrContextWriter,\n private readonly briefingBuilder: ReviewerBriefingBuilder,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly receipts: ReviewStageReceiptService,\n private readonly activeHatchReport: ActiveHatchReport,\n // Injected to RESOLVE + RENDER refusals (see refusals()) and to name each round's verdict file.\n private readonly reviewJsonService: ReviewJsonService,\n private readonly stageConsole: StageOutputLog,\n private readonly hotfixRedirect: HotfixRedirect,\n private readonly rounds: ReviewRoundStateService,\n ) {}\n\n /**\n * Everything below runs with this stage's console CAPTURED to a file (see StageOutputLog). Only the\n * lines an agent must act on before it can do anything else reach the terminal — the build heartbeat\n * and result, and the closing instruction block. The merge validation, the hatch report, the checklist\n * scan and the diff extraction are all in the file, one `grep` away.\n *\n * This is the FIRST half of the fix for the piped-command watchdog kill: an agent pipes a command it\n * expects to flood, a pipe withholds every byte until exit, and the harness kills a command that has\n * printed nothing for 600 seconds — after a full build. Guarding the pipe without first shrinking the\n * output would only have traded that kill for a flooded context.\n */\n async run(): Promise<void> {\n // A /hotfix/ branch has no review stage — it publishes with wp-upsert-hotfix-pr (issue #1057).\n this.hotfixRedirect.assertNotHotfix('wp-review-upsert-pr');\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, REVIEW_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n writeTemplate(repoRoot, 'webpieces.review-checklists.md');\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n\n const mergeValidated = await this.finalizeAnyInProgressMerge(repoRoot);\n this.gitExec.assertCleanTree(repoRoot);\n const buildPassedAt = await this.runBuildGate(repoRoot);\n\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, false, '')); // '' — THIS command writes the context itself, after materializing\n const previousReceipt = this.receipts.read(repoRoot, featureName);\n const plan = this.rounds.plan(repoRoot, scan.summaryPath, previousReceipt, config.maxReviewerRounds, scan.basis);\n if (plan.action === ROUND_ACTION_RESUME && previousReceipt !== null) {\n this.resumeRound(repoRoot, featureName, scan, previousReceipt, mergeValidated, buildPassedAt);\n this.reportActiveHatches(repoRoot);\n if (scan.reviewersDisabled) this.report(repoRoot, featureName, scan, [], plan, config);\n return;\n }\n const shouldBrief = plan.action === ROUND_ACTION_REVIEW;\n const briefings = shouldBrief\n ? this.briefReviewers(repoRoot, featureName, scan, config, plan)\n : [];\n const recordedReviewers = briefings.map((b: ReviewerBriefing): string => b.checklistId);\n if (shouldBrief) {\n const receipt = new ReviewStageReceipt(scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt, recordedReviewers);\n receipt.scopeHashes = scan.scopeHashes;\n // Which briefed checklists are OPTIONAL: a round is complete once every REQUIRED one has a\n // verdict, and an optional one joins the round only if it actually submitted (issue #1062).\n receipt.optionalBriefed = briefings.filter((b: ReviewerBriefing): boolean => !b.required).map((b: ReviewerBriefing): string => b.checklistId);\n // A global round begins only when a non-empty fixed roster is actually briefed.\n receipt.round = recordedReviewers.length === 0 ? 0 : plan.round;\n receipt.maxReviewerRounds = plan.maxRounds;\n this.receipts.write(repoRoot, featureName, receipt);\n } else if (previousReceipt !== null) {\n previousReceipt.buildHeadSha = scan.basis.headSha;\n previousReceipt.mergeValidated = mergeValidated;\n previousReceipt.buildCommand = this.buildAffected.resolveBuildCommand(repoRoot);\n previousReceipt.buildPassedAt = buildPassedAt;\n this.receipts.write(repoRoot, featureName, previousReceipt);\n }\n this.reportActiveHatches(repoRoot);\n this.report(repoRoot, featureName, scan, briefings, plan, config);\n }\n\n /** Keep the original briefing, diff, roster and provenance intact while refreshing build evidence. */\n // eslint-disable-next-line @typescript-eslint/max-params\n private resumeRound(\n repoRoot: string,\n featureName: string,\n scan: ChecklistScan,\n receipt: ReviewStageReceipt,\n mergeValidated: boolean,\n buildPassedAt: string,\n ): void {\n receipt.buildHeadSha = scan.basis.headSha;\n receipt.mergeValidated = mergeValidated;\n receipt.buildCommand = this.buildAffected.resolveBuildCommand(repoRoot);\n receipt.buildPassedAt = buildPassedAt;\n this.receipts.write(repoRoot, featureName, receipt);\n // The scanner owns reviewer suppression. Keep the historical roster for later recovery, but\n // never instruct it to run while the existing opt-out is active.\n if (scan.reviewersDisabled) return;\n const pending = receipt.reviewersBriefed.filter(\n (id: string): boolean =>\n !receipt.optionalBriefed.includes(id) &&\n !this.rounds.hasVerdict(scan.summaryPath, id, receipt.round),\n );\n this.stageConsole.say(\n `\\nResume the existing reviewer roster: round ${receipt.round} of ${receipt.maxReviewerRounds}.\\n` +\n `Build passed at ${receipt.buildHeadSha}; reviewers retain their briefing at ${receipt.headSha}.\\n` +\n 'Continue the existing reviewer agents; do not respawn them for a SHA or fork-point change.\\n' +\n pending\n .map(\n (id: string): string =>\n ` REQUIRED ${id}: ${this.reviewerInstructions.pathFor(repoRoot, featureName, id)}\\n` +\n ` Submit with: pnpm wp-write-review --checklist ${id} --file '<verdict JSON file>'\\n`,\n )\n .join('') +\n `\\nAfter the remaining verdicts, write ${scan.summaryPath}:\\n${summaryJsonSchemaHint(scan.summaryPath)}\\n` +\n 'Then run: pnpm wp-review-upsert-pr (to plan any RED follow-up), followed by pnpm wp-finish-upsert-pr.\\n',\n );\n }\n\n /**\n * List every rule that is currently switched off in webpieces.config.json. NON-BLOCKING and printed\n * before the instruction block, because it is context for the review rather than a step in it.\n *\n * A hatch is the one config change that makes the build QUIETER, so no gate, reviewer or red check\n * will ever mention it — which is how a repo ends up with rules off for weeks that nobody chose to\n * leave off. This is the only place in the flow that says so out loud.\n */\n private reportActiveHatches(repoRoot: string): void {\n const hatches: ActiveHatch[] = this.activeHatchReport.scan(repoRoot);\n process.stdout.write(this.activeHatchReport.render(hatches));\n }\n\n /**\n * Validate + commit + finalize a conflict resolution, if one is in flight. MOVED here from\n * `wp-finish-upsert-pr` so that exactly one command owns merge finalization — two owners is the drift\n * failure `PrContextWriter`'s own docstring records having already happened once in this codebase.\n *\n * MergeEnd's three checks are what \"did the AI do the 3-point merge right?\" means concretely: no\n * conflict markers left in the scoped files, `git diff --diff-filter=U` empty, and a non-empty\n * merge-explanation.md beside every conflicted file.\n *\n * Returns true when a merge was finalized OR there was none to finalize; it throws rather than returning\n * false when validation fails, so the receipt can never record an unvalidated merge as validated.\n */\n private async finalizeAnyInProgressMerge(repoRoot: string): Promise<boolean> {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return true;\n process.stdout.write('\\n' + SEP + '① Validating your 3-point merge\\n' + SEP + '\\n');\n // pushRemote:false — finish still owns the single push.\n await this.mergeEnd.mergeEnd(repoRoot, 'wp-review-upsert-pr', activeDir, new MergeContext(marker.currentBranch, marker.squashBranch, marker.backupBranch, marker.prNumber), new MergeEndOptions(marker.conflictedFiles, false));\n return true;\n }\n\n /**\n * The build gate, run BEFORE any reviewer is briefed. Returns the ISO time it passed, for the receipt —\n * which is what lets `wp-finish-upsert-pr` skip its own gate when HEAD has not moved, so moving the gate\n * earlier did not turn one build into two.\n */\n private async runBuildGate(repoRoot: string): Promise<string> {\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions('🛠️ Build gate', 'pnpm wp-review-upsert-pr', 'Build failed — NO reviewer was briefed and no diff was extracted. Fix it, then re-run.', REVIEW_STAGE));\n // Repo-wide: the build must not have left anything uncommitted AND unstaged. Runs HERE, not in\n // finish, because this is the stage that ran buildCommand and is therefore holding the dirty\n // tree at the exact moment the question is answerable. Replaces the per-project\n // validate-di-graph-unchanged nx target — see BuildArtifactGate for why that one had to go.\n this.buildArtifactGate.assertBuildLeftNothingUncommitted(repoRoot);\n return new Date().toISOString();\n }\n\n /**\n * Extract the diff once, then write one instructions file per reviewer.\n *\n * The changed-file set and the basis both come off the SCAN rather than being recomputed, so the diff a\n * reviewer reads covers exactly the files its checklist matched against.\n */\n private briefReviewers(repoRoot: string, featureName: string, scan: ChecklistScan, config: PrGateConfig, plan: ReviewRoundPlan): ReviewerBriefing[] {\n if (plan.basis.unresolved) return [];\n const changedFiles = plan.round > 1 ? plan.changedFiles : scan.changedFiles;\n const manifest = this.materializer.materialize(repoRoot, featureName, plan.basis, changedFiles, config.reviewDiffExclude);\n const diffDir = this.materializer.diffDirFor(repoRoot, featureName);\n // Write pr-context.json ONCE, here — after materializing, so `diffDir` is populated on the first\n // write. The scan deliberately did not write it (ChecklistScanOptions.contextStage === ''); it used\n // to, which meant this command wrote the same file twice, the first time with an empty diffDir.\n // `scan.changedFiles` is passed through so the context is not recomputed from a second git call.\n scan.context = this.prContextWriter.ensure(repoRoot, featureName, plan.basis, 'stage2-review', changedFiles, diffDir);\n // ONLY the checklists still owed a verdict (issue #863). A green or yellow CARRIES whatever changed\n // since (issue #1053) — the scan left it in `reviewed` — so briefing it again would pay a reviewer to\n // re-read code it already judged. A later round re-briefs exactly the previous round's REDS.\n const reviewedIds = new Set(scan.reviewed.map((r: RequiredChecklist): string => r.id));\n const owed = scan.applicable.filter((r: RequiredChecklist): boolean => plan.round > 1\n ? plan.redChecklistIds.includes(r.id)\n : !reviewedIds.has(r.id));\n const briefings = this.briefingBuilder.build(repoRoot, scan, owed, manifest, diffDir, config);\n const dir = this.reviewerInstructions.instructionsDirFor(repoRoot, featureName);\n fs.rmSync(dir, { recursive: true, force: true }); // stale instructions read as current are worse than none\n fs.mkdirSync(dir, { recursive: true });\n for (const b of briefings) {\n b.round = plan.round;\n b.maxRounds = plan.maxRounds;\n b.verdictPath = this.reviewJsonService.checklistResultPath(scan.summaryPath, b.checklistId, plan.round);\n b.remediationOnly = plan.round > 1;\n if (b.remediationOnly) {\n b.previousVerdictPath = this.reviewJsonService.checklistResultPath(scan.summaryPath, b.checklistId, plan.round - 1);\n b.remediationPath = this.rounds.fixesPath(scan.summaryPath, plan.round - 1);\n }\n fs.writeFileSync(this.reviewerInstructions.pathFor(repoRoot, featureName, b.checklistId), this.reviewerInstructions.render(b));\n }\n return briefings;\n }\n\n /**\n * What the AI must do next — rendered by `ReviewReport`, which owns the ordering.\n *\n * The rendering moved OUT of this command so the ordering could be asserted on as a string. It had a\n * real bug: the zero-checklist notice signed off with \"Carry on and run: pnpm wp-finish-upsert-pr\"\n * while the block right beneath it said to write summary.json first. An agent that reads top to bottom\n * obeyed the first line and posted a PR with no review at all.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private report(repoRoot: string, featureName: string, scan: ChecklistScan, briefings: readonly ReviewerBriefing[], plan: ReviewRoundPlan, config: PrGateConfig): void {\n const input = new ReviewReportInput(repoRoot, featureName, scan.summaryPath);\n input.definedCount = scan.defined.length;\n input.applicableCount = scan.applicable.length;\n input.reviewed = scan.reviewed.slice();\n input.formatErrors = scan.formatErrors.slice();\n input.briefings = briefings.slice();\n input.refused = this.refusals(scan);\n input.reviewer = config.reviewer;\n // Straight off the SCAN — the one place `experimental.turnOffAllReviewers` is read. This command\n // deliberately does NOT consult the home config itself: a second read is a second answer, and the\n // command that lists and the command that blocks would be free to disagree about whether a branch\n // was reviewed. See ChecklistScanner.\n input.reviewersSuppressed = scan.reviewersDisabled;\n input.suppressed = scan.suppressed.slice();\n input.round = plan.round;\n input.maxReviewerRounds = plan.maxRounds;\n input.roundAction = plan.action;\n input.redChecklistIds = plan.redChecklistIds.slice();\n input.orangeChecklistIds = plan.orangeChecklistIds.slice();\n input.notBriefed = scan.notBriefed.slice();\n input.standings = scan.standings.slice();\n // `say`: this block IS the next action — which reviewers to spawn, where summary.json goes, and\n // the command after that. Capturing it into the log would leave the terminal with a pointer and\n // no instruction, which is the one thing this stage may never do.\n this.stageConsole.say(this.reviewReport.render(input));\n }\n\n /**\n * The applicable checklists that ALREADY ANSWERED and refused, each with its refusal rendered by the ONE\n * renderer `wp-finish-upsert-pr` also uses.\n *\n * Stage ② had the identical defect finish did: a refused checklist has no passing verdict, so it is not\n * in `scan.reviewed`, so it was printed as an ordinary owed reviewer and re-instructed word for word —\n * and an agent that obeys spawns it against unchanged code, gets the same refusal, and loops one stage\n * earlier than the loop that was reported.\n *\n * Nothing is moved: a red verdict stays on disk as its round's record, and the next round's verdict is a\n * new file (issue #1053). The review path IS passed, because the ship-anyway route the refusal prints is a\n * command that writes `override-<id>.json` beside it.\n */\n private refusals(scan: ChecklistScan): RefusedReviewer[] {\n const refused = this.reviewJsonService.refusedChecklists(scan.applicable, scan.results);\n return refused.map((req: RequiredChecklist): RefusedReviewer => new RefusedReviewer(req.id, this.reviewJsonService.refusalError(req, this.reviewJsonService.resolveVerdict(req, scan.results), scan.summaryPath)));\n }\n}\n"]}
@@ -199,10 +199,8 @@ let ReviewRoundStateService = class ReviewRoundStateService {
199
199
  if (snap.round < 1)
200
200
  return new ReviewRoundPlan(exports.ROUND_ACTION_REVIEW, 1, maxRounds, fullBasis);
201
201
  if (!snap.complete) {
202
- if (snap.headSha !== fullBasis.headSha) {
203
- throw new tooling_common_1.InformAiError(`Reviewer round ${snap.round} of ${maxRounds} is still active at `
204
- + `${snap.headSha.slice(0, 8)}. Finish that fixed roster before changing the reviewed HEAD.`);
205
- }
202
+ // A sanctioned update changes the build basis, never the fixed roster or its historical
203
+ // briefing. Resume that roster without charging another round (issue #1087).
206
204
  return new ReviewRoundPlan(exports.ROUND_ACTION_RESUME, snap.round, maxRounds, fullBasis);
207
205
  }
208
206
  const reds = this.checklistIdsWithStatus(summaryPath, snap, rules_config_1.VERDICT_RED);
@@ -1 +1 @@
1
- {"version":3,"file":"review-round-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-round-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,iDAA0C;AAC1C,8DAAsE;AACtE,iEAA6D;AAC7D,0DAA0G;AAC1G,yCAA2D;AAE3D,6DAAgE;AAChE,6CAAyC;AAM5B,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC/B,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC/B,QAAA,gBAAgB,GAAG,KAAK,CAAC;AACzB,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC/B,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAE5C,gHAAgH;AAChH,MAAM,UAAU,GAAG,gCAAgC,CAAC;AACpD,MAAM,QAAQ,GAAG,OAAO,CAAC;AACzB,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAExC,MAAa,eAAe;IACxB,MAAM,CAAS;IACf,KAAK,CAAS;IACd,SAAS,CAAS;IAClB,KAAK,CAAY;IACjB,YAAY,CAAW;IACvB,eAAe,CAAW;IAC1B,uFAAuF;IACvF,kBAAkB,CAAW;IAE7B,yDAAyD;IACzD,YACI,MAAc,EAAE,KAAa,EAAE,SAAiB,EAAE,KAAgB,EAAE,eAAyB,EAAE,EAC/F,kBAA4B,EAAE,EAAE,qBAA+B,EAAE;QAEjE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,eAAe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;QAC3E,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAC7D,MAAM,OAAO,GAAG,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACxC,MAAM,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,IAAI,QAAQ,MAAM,CAAC,MAAM,IAAI,SAAS,EAAE,CAAC;QAC7G,MAAM,OAAO,GAAG,oCAAoC,OAAO,KAAK,MAAM,EAAE,CAAC;QACzE,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS;YAAE,MAAM,IAAI,8BAAa,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;QAC1F,MAAM,IAAI,8BAAa,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACJ,CAAA;AA7WY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,gCAAiB;QACjB,6CAAwB;QACxB,2BAAU;GAJlC,uBAAuB,CA6WnC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { spawnSync } from 'child_process';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { ChecklistResult, ReviewJsonService, VERDICT_ORANGE, VERDICT_RED } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ReviewStageReceipt } from './review-stage-receipt';\nimport { VerdictProvenanceService } from './verdict-provenance';\nimport { DiffBasis } from './diff-basis';\n\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonValue[] | JsonObject;\ninterface JsonObject { [key: string]: JsonValue }\n\nexport const ROUND_ACTION_REVIEW = 'review';\nexport const ROUND_ACTION_RESUME = 'resume';\nexport const ROUND_ACTION_FIX = 'fix';\nexport const ROUND_ACTION_RECORD = 'record';\nexport const ROUND_ACTION_FINISH = 'finish';\n\n/** Every round-numbered file of a branch's review lives beside summary.json under this prefix (issue #1053). */\nconst ROUND_FILE = /^review-round(\\d+)-(.+)\\.json$/;\nconst FIXES_ID = 'fixes';\nconst PROVENANCE_SUFFIX = '.provenance';\n\nexport class ReviewRoundPlan {\n action: string;\n round: number;\n maxRounds: number;\n basis: DiffBasis;\n changedFiles: string[];\n redChecklistIds: string[];\n /** The final round's ORANGE checklists — must-fix, never re-reviewed (issue #1053). */\n orangeChecklistIds: string[];\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n action: string, round: number, maxRounds: number, basis: DiffBasis, changedFiles: string[] = [],\n redChecklistIds: string[] = [], orangeChecklistIds: string[] = [],\n ) {\n this.action = action;\n this.round = round;\n this.maxRounds = maxRounds;\n this.basis = basis;\n this.changedFiles = changedFiles;\n this.redChecklistIds = redChecklistIds;\n this.orangeChecklistIds = orangeChecklistIds;\n }\n}\n\n/**\n * Where a branch's review stands, DERIVED from the round-numbered files on disk plus the stage-② receipt\n * (issue #1053). There is no separate round counter: `round` is the highest round any file or briefing\n * names. Data-only.\n */\nexport class RoundSnapshot {\n round: number; // 0 = no round has started\n roster: string[]; // the REQUIRED checklists briefed in `round`, plus the optional ones that submitted in it\n headSha: string; // the commit `round` was briefed on\n complete: boolean; // every REQUIRED checklist briefed in `round` has a verdict in it (issue #1062)\n\n constructor(round: number, roster: string[], headSha: string, complete: boolean) {\n this.round = round;\n this.roster = roster;\n this.headSha = headSha;\n this.complete = complete;\n }\n}\n\nexport class RemediationResponse {\n checklistId: string;\n resolution: string;\n files: string[];\n\n constructor(checklistId: string, resolution: string, files: string[]) {\n this.checklistId = checklistId;\n this.resolution = resolution;\n this.files = files;\n }\n}\n\n/** The author's recorded fixes for one completed round: `review-round<N>-fixes.json`. Data-only. */\nexport class ReviewRemediation {\n agent: string;\n model: string;\n fromHead: string;\n toHead: string;\n responses: RemediationResponse[];\n writtenAt: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(agent: string, model: string, fromHead: string, toHead: string, responses: RemediationResponse[]) {\n this.agent = agent;\n this.model = model;\n this.fromHead = fromHead;\n this.toHead = toHead;\n this.responses = responses;\n this.writtenAt = new Date().toISOString();\n }\n}\n\n/**\n * The reviewer rounds of one branch, read from their round-numbered files (issue #1053).\n *\n * `commands.pr-gate.maxReviewerRounds` is a HARD CEILING, not a quota: 1 round means 1 round. Three rules\n * follow from it, and everything here exists to hold them:\n *\n * 1. Every verdict is `review-round<N>-<id>.json` (+ `.provenance.json`), every author fix record is\n * `review-round<N>-fixes.json`, and nothing is ever overwritten. The live verdict of a checklist is its\n * highest round; the round the branch is on is the highest round any file names.\n * 2. A new round starts ONLY when the previous round has a RED and rounds remain, and it re-briefs only\n * those reds. A green or yellow stands whatever changes afterwards — staleness never re-reviews.\n * 3. The final round has no red. Its blocking color is ORANGE: the author fixes it best effort, records the\n * fix, and ships with the finding and its claimed fix stamped on the dashboard.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewRoundStateService {\n constructor(\n private readonly reviewJson: ReviewJsonService,\n private readonly provenance: VerdictProvenanceService,\n private readonly atomicFile: AtomicFile,\n ) {}\n\n /** The author's recorded fixes for one round: `review-round<N>-fixes.json`, beside summary.json. */\n fixesPath(summaryPath: string, round: number): string {\n return path.join(path.dirname(summaryPath), `review-round${round}-${FIXES_ID}.json`);\n }\n\n /** The highest round any round-numbered file names, or 0. */\n highestRound(summaryPath: string): number {\n let highest = 0;\n for (const name of this.roundFiles(summaryPath)) {\n const match = ROUND_FILE.exec(name);\n if (match !== null) highest = Math.max(highest, Number(match[1]));\n }\n return highest;\n }\n\n /** Every checklist that has a verdict in ANY round on this branch. */\n verdictChecklistIds(summaryPath: string): string[] {\n const ids = new Set<string>();\n for (const name of this.roundFiles(summaryPath)) {\n const id = this.verdictIdOf(name);\n if (id !== '') ids.add(id);\n }\n return [...ids].sort();\n }\n\n /** Where the branch's review stands — see {@link RoundSnapshot}. */\n snapshot(summaryPath: string, receipt: ReviewStageReceipt | null): RoundSnapshot {\n const briefed = receipt !== null && receipt.reviewersBriefed.length > 0 ? receipt.round : 0;\n const round = Math.max(this.highestRound(summaryPath), briefed);\n if (round < 1) return new RoundSnapshot(0, [], '', false);\n if (receipt !== null && receipt.round === round) {\n // Only a REQUIRED checklist holds the round open (issue #1062). An optional one counts only if it\n // actually ran — a red from it still opens the next round — and one nobody chose to run is not\n // waited on, so an all-optional briefing nobody ran is complete with an empty roster.\n const optional = new Set<string>(receipt.optionalBriefed);\n const required = receipt.reviewersBriefed.filter((id: string): boolean => !optional.has(id));\n const roster = receipt.reviewersBriefed.filter((id: string): boolean =>\n !optional.has(id) || this.hasVerdict(summaryPath, id, round));\n return new RoundSnapshot(round, roster, receipt.headSha, this.everyVerdictIn(summaryPath, required, round));\n }\n // The receipt names an older round (or is gone): the files are the record, so the roster is exactly\n // the checklists that have a verdict in this round, and the reviewed HEAD is what their provenance says.\n const roster = this.roundFiles(summaryPath)\n .filter((name: string): boolean => name.startsWith(`review-round${round}-`))\n .map((name: string): string => this.verdictIdOf(name))\n .filter((id: string): boolean => id !== '')\n .sort();\n const headSha = roster.length === 0 ? '' : this.provenance.read(summaryPath, roster[0], round)?.headSha ?? '';\n return new RoundSnapshot(round, roster, headSha, roster.length > 0);\n }\n\n /**\n * TRUE once a review round has started on this branch. From then on the checklist set is FROZEN (issue\n * #1053): finish judges only the checklists that were briefed, never ones a later commit newly triggers.\n */\n roundStarted(summaryPath: string, receipt: ReviewStageReceipt | null): boolean {\n return this.snapshot(summaryPath, receipt).round >= 1;\n }\n\n /**\n * The frozen checklist set: every checklist briefed in any round — see {@link roundStarted}. It keeps an\n * optional checklist that was offered but never run, so its dashboard row reads \"optional, not run\"\n * rather than \"not briefed\"; it never holds a round open (see {@link snapshot}).\n */\n briefedChecklistIds(summaryPath: string, receipt: ReviewStageReceipt | null): string[] {\n const ids = new Set<string>(this.verdictChecklistIds(summaryPath));\n if (receipt !== null && receipt.round >= 1) for (const id of receipt.reviewersBriefed) ids.add(id);\n return [...ids].sort();\n }\n\n /** Does `checklistId` already have a verdict in `round`? A round's verdict is never overwritten. */\n hasVerdict(summaryPath: string, checklistId: string, round: number): boolean {\n return fs.existsSync(this.reviewJson.checklistResultPath(summaryPath, checklistId, round));\n }\n\n /** The roster checklists whose verdict in the snapshot's round is `status`. */\n checklistIdsWithStatus(summaryPath: string, snap: RoundSnapshot, status: string): string[] {\n if (!snap.complete) return [];\n return snap.roster.filter((id: string): boolean => {\n const raw = this.readObject(this.reviewJson.checklistResultPath(summaryPath, id, snap.round));\n return raw !== null && raw['status'] === status;\n });\n }\n\n /** What stage ② does next. See the class comment for the three rules it holds. */\n plan(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt | null, maxRounds: number, fullBasis: DiffBasis): ReviewRoundPlan {\n const snap = this.snapshot(summaryPath, receipt);\n if (snap.round < 1) return new ReviewRoundPlan(ROUND_ACTION_REVIEW, 1, maxRounds, fullBasis);\n if (!snap.complete) {\n if (snap.headSha !== fullBasis.headSha) {\n throw new InformAiError(`Reviewer round ${snap.round} of ${maxRounds} is still active at `\n + `${snap.headSha.slice(0, 8)}. Finish that fixed roster before changing the reviewed HEAD.`);\n }\n return new ReviewRoundPlan(ROUND_ACTION_RESUME, snap.round, maxRounds, fullBasis);\n }\n const reds = this.checklistIdsWithStatus(summaryPath, snap, VERDICT_RED);\n const oranges = this.checklistIdsWithStatus(summaryPath, snap, VERDICT_ORANGE);\n // No red, or no round left: nothing is ever re-reviewed. Oranges are the author's to fix and record.\n if (reds.length === 0 || snap.round >= maxRounds) {\n return new ReviewRoundPlan(ROUND_ACTION_FINISH, snap.round, maxRounds, fullBasis, [], reds, oranges);\n }\n if (snap.headSha === fullBasis.headSha) {\n return new ReviewRoundPlan(ROUND_ACTION_FIX, snap.round, maxRounds, fullBasis, [], reds, oranges);\n }\n if (this.validFixes(repoRoot, summaryPath, snap) === null) {\n return new ReviewRoundPlan(ROUND_ACTION_RECORD, snap.round, maxRounds, fullBasis, [], reds, oranges);\n }\n const basis = new DiffBasis(\n snap.headSha, fullBasis.headSha, false, [],\n `git diff ${snap.headSha} ${fullBasis.headSha}`,\n `git diff ${snap.headSha} ${fullBasis.headSha} -- <file>`, fullBasis.hashMainHead);\n const changed = this.git(repoRoot, ['diff', '--name-only', snap.headSha, fullBasis.headSha])\n .split('\\n').filter((f: string): boolean => f.trim() !== '');\n return new ReviewRoundPlan(ROUND_ACTION_REVIEW, snap.round + 1, maxRounds, basis, changed, reds, oranges);\n }\n\n /**\n * Record the author's fixes for the latest completed round — one response per RED (a round that is not\n * the last) or ORANGE (the final round) — as `review-round<N>-fixes.json`.\n *\n * A record that still HOLDS is never overwritten. One that no longer holds — its `toHead` left HEAD's\n * history, which every `wp-start-upsert-pr` squash-update does — is kept beside it as\n * `review-round<N>-fixes.json.superseded-<k>` and a fresh record is written, so re-recording is always\n * the way past a stale record and nothing is ever lost.\n */\n writeRemediation(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt, json: string): string {\n const snap = this.snapshot(summaryPath, receipt);\n if (!snap.complete) {\n throw new InformAiError('wp-write-review-fixes: the active reviewer round is not complete yet.');\n }\n const blocking = this.blockingIds(summaryPath, snap);\n if (blocking.length === 0) {\n throw new InformAiError(`wp-write-review-fixes: round ${snap.round} has no red or orange verdict to fix.`);\n }\n const out = this.fixesPath(summaryPath, snap.round);\n const holding = this.validFixes(repoRoot, summaryPath, snap);\n if (holding !== null) {\n throw new InformAiError(`wp-write-review-fixes: the fixes for round ${snap.round} are already recorded in ${out}, and `\n + `that record still holds (its fixed commit ${holding.toHead.slice(0, 8)} is in HEAD's history), so it is not `\n + 'overwritten. Nothing more to record: re-run pnpm wp-review-upsert-pr, or pnpm wp-finish-upsert-pr after the last round.');\n }\n this.assertClean(repoRoot);\n const currentHead = this.git(repoRoot, ['rev-parse', 'HEAD']);\n if (currentHead === snap.headSha || this.git(repoRoot, ['diff', '--name-only', snap.headSha, currentHead]) === '') {\n throw new InformAiError('wp-write-review-fixes: remediation must contain a committed, non-empty delta after the reviewed HEAD.');\n }\n const raw = this.parseObject(json, 'wp-write-review-fixes: input must be one JSON object.');\n const agent = this.requiredText(raw, 'agent');\n const model = this.requiredText(raw, 'model');\n const responses = this.responses(raw['responses']);\n const ids = responses.map((r: RemediationResponse): string => r.checklistId);\n const unknown = ids.filter((id: string): boolean => !blocking.includes(id));\n const missing = blocking.filter((id: string): boolean => !ids.includes(id));\n if (unknown.length > 0 || missing.length > 0) {\n throw new InformAiError(`wp-write-review-fixes: responses must cover exactly the red/orange checklist(s) of round ${snap.round}. `\n + `Unknown: ${unknown.join(', ') || '(none)'}. Missing: ${missing.join(', ') || '(none)'}.`);\n }\n this.supersede(out);\n this.atomicFile.writeJsonAtomic(out, new ReviewRemediation(agent, model, snap.headSha, currentHead, responses));\n return out;\n }\n\n /**\n * Keep a record that no longer holds beside the new one, as `<file>.superseded-<k>` — a name no round\n * scan reads, so it is history and never a live record.\n */\n private supersede(file: string): void {\n if (!fs.existsSync(file)) return;\n let k = 1;\n while (fs.existsSync(`${file}.superseded-${k}`)) k++;\n fs.renameSync(file, `${file}.superseded-${k}`);\n }\n\n /**\n * The round's recorded fixes, or null when there are none that still hold: written from the reviewed\n * HEAD, to a later commit that is still in HEAD's history, covering exactly the round's red/orange set.\n */\n validFixes(repoRoot: string, summaryPath: string, snap: RoundSnapshot): ReviewRemediation | null {\n const record = this.readFixes(repoRoot, summaryPath, snap.round);\n if (record === null || record.fromHead !== snap.headSha) return null;\n const blocking = this.blockingIds(summaryPath, snap);\n const ids = record.responses.map((r: RemediationResponse): string => r.checklistId);\n if (blocking.some((id: string): boolean => !ids.includes(id)) || ids.some((id: string): boolean => !blocking.includes(id))) return null;\n return record;\n }\n\n /**\n * checklist id → the dashboard stamp for every ORANGE whose fix the author recorded (issue #1053):\n * \"orange at <fromHead>, author-fixed in <toHead>, not re-reviewed: <resolution>\". An orange with no\n * valid record is absent, and so still blocks.\n */\n orangeFixes(repoRoot: string, summaryPath: string, results: readonly ChecklistResult[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const result of results) {\n if (result.status !== VERDICT_ORANGE || result.problem !== '') continue;\n const record = this.readFixes(repoRoot, summaryPath, result.round);\n const response = record?.responses.find((r: RemediationResponse): boolean => r.checklistId === result.id);\n if (record === null || response === undefined) continue;\n out[result.id] = `orange at ${record.fromHead.slice(0, 8)}, author-fixed in ${record.toHead.slice(0, 8)}, `\n + `not re-reviewed: ${response.resolution}`;\n }\n return out;\n }\n\n auditTrail(summaryPath: string, checklistId: string, maxRounds: number): string {\n const lines: string[] = [];\n const highest = this.highestRound(summaryPath);\n for (let round = 1; round <= highest; round++) {\n const verdict = this.readObject(this.reviewJson.checklistResultPath(summaryPath, checklistId, round));\n if (verdict !== null) {\n lines.push(`#### Reviewer round ${round} of ${maxRounds}`);\n lines.push(`Reviewed SHA: ${this.provenance.read(summaryPath, checklistId, round)?.headSha || '(unknown)'}`);\n lines.push(`Status: ${this.text(verdict['status']).toUpperCase()}`);\n lines.push('', this.text(verdict['output']), '');\n }\n const remediation = this.readObject(this.fixesPath(summaryPath, round));\n if (remediation !== null && Array.isArray(remediation['responses'])) {\n const response = (remediation['responses'] as JsonValue[]).find((entry: JsonValue): boolean =>\n typeof entry === 'object' && entry !== null && !Array.isArray(entry)\n && (entry as JsonObject)['checklistId'] === checklistId);\n if (typeof response === 'object' && response !== null && !Array.isArray(response)) {\n const raw = response as JsonObject;\n lines.push(`#### Author fix after round ${round}`);\n lines.push(`Range: ${this.text(remediation['fromHead'])}..${this.text(remediation['toHead'])}`);\n lines.push('', this.text(raw['resolution']), '');\n }\n }\n }\n return lines.join('\\n').trim();\n }\n\n private blockingIds(summaryPath: string, snap: RoundSnapshot): string[] {\n return [\n ...this.checklistIdsWithStatus(summaryPath, snap, VERDICT_RED),\n ...this.checklistIdsWithStatus(summaryPath, snap, VERDICT_ORANGE),\n ];\n }\n\n /** A round's fix record, provided its `toHead` is still in HEAD's history; else null. */\n private readFixes(repoRoot: string, summaryPath: string, round: number): ReviewRemediation | null {\n const raw = this.readObject(this.fixesPath(summaryPath, round));\n if (raw === null) return null;\n const responses = this.responsesOrEmpty(raw['responses']);\n const fromHead = this.text(raw['fromHead']);\n const toHead = this.text(raw['toHead']);\n if (this.text(raw['agent']) === '' || this.text(raw['model']) === '' || responses.length === 0\n || fromHead === '' || toHead === '' || fromHead === toHead || !this.isAncestorOfHead(repoRoot, toHead)) return null;\n return new ReviewRemediation(this.text(raw['agent']), this.text(raw['model']), fromHead, toHead, responses);\n }\n\n private everyVerdictIn(summaryPath: string, roster: readonly string[], round: number): boolean {\n return roster.every((id: string): boolean => this.hasVerdict(summaryPath, id, round));\n }\n\n /** `review-round<N>-<id>.json` → `<id>`; '' for the fixes record, a provenance file, or anything else. */\n private verdictIdOf(name: string): string {\n const match = ROUND_FILE.exec(name);\n if (match === null) return '';\n const id = match[2];\n return id === FIXES_ID || id.endsWith(PROVENANCE_SUFFIX) ? '' : id;\n }\n\n private roundFiles(summaryPath: string): string[] {\n const dir = path.dirname(summaryPath);\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir).filter((name: string): boolean => ROUND_FILE.test(name));\n }\n\n private responses(value: JsonValue | undefined): RemediationResponse[] {\n const responses = this.responsesOrEmpty(value);\n if (responses.length === 0) throw new InformAiError('wp-write-review-fixes: \"responses\" must be a non-empty array.');\n return responses;\n }\n\n private responsesOrEmpty(value: JsonValue | undefined): RemediationResponse[] {\n if (!Array.isArray(value)) return [];\n const out: RemediationResponse[] = [];\n for (const entry of value) {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return [];\n const raw = entry as JsonObject;\n const id = this.text(raw['checklistId']);\n const resolution = this.text(raw['resolution']);\n const files = Array.isArray(raw['files']) ? raw['files'].filter((f: JsonValue): f is string => typeof f === 'string' && f.trim() !== '') : [];\n if (id === '' || resolution === '' || files.length === 0) return [];\n out.push(new RemediationResponse(id, resolution, files));\n }\n return out;\n }\n\n private requiredText(raw: JsonObject, key: string): string {\n const value = this.text(raw[key]);\n if (value === '') throw new InformAiError(`wp-write-review-fixes: \"${key}\" must be a non-empty string.`);\n return value;\n }\n\n private text(value: JsonValue | undefined): string {\n return typeof value === 'string' ? value.trim() : '';\n }\n\n private parseObject(json: string, message: string): JsonObject {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed author JSON becomes an actionable refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const value = JSON.parse(json) as JsonValue;\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value;\n // webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n throw new InformAiError(message);\n }\n\n private readObject(file: string): JsonObject | null {\n if (!fs.existsSync(file)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable durable state becomes an actionable refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const value = JSON.parse(fs.readFileSync(file, 'utf8')) as JsonValue;\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value;\n throw new InformAiError(`Review state file must contain one JSON object: ${file}`);\n // webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError) throw error;\n throw new InformAiError(`Could not read review state file ${file}: ${error.message}`, { cause: error });\n }\n }\n\n private assertClean(repoRoot: string): void {\n const status = this.git(repoRoot, ['status', '--porcelain', '--untracked-files=all']);\n if (status !== '') throw new InformAiError('wp-write-review-fixes: commit every remediation and leave no staged, unstaged, or untracked files first.');\n }\n\n /**\n * `git merge-base --is-ancestor`: exit 0 = yes, 1 = no. A `sha` git does not know (exit 128 with\n * \"Not a valid commit name\") is also no — the commit is gone from this clone, so it is not in HEAD's\n * history. Anything else is a real failure and refuses.\n */\n private isAncestorOfHead(repoRoot: string, sha: string): boolean {\n const result = spawnSync('git', ['merge-base', '--is-ancestor', sha, 'HEAD'], { cwd: repoRoot, encoding: 'utf8' });\n if (result.status === 0) return true;\n if (result.status === 1 || /not a valid (commit|object) name/i.test(result.stderr ?? '')) return false;\n const detail = (result.stderr ?? '').trim() || result.error?.message || `exit ${result.status ?? 'unknown'}`;\n const message = `Review-round Git command failed: git merge-base --is-ancestor ${sha} HEAD\\n${detail}`;\n if (result.error !== undefined) throw new InformAiError(message, { cause: result.error });\n throw new InformAiError(message);\n }\n\n private git(repoRoot: string, args: string[]): string {\n const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status === 0) return (result.stdout ?? '').trim();\n const command = `git ${args.join(' ')}`;\n const detail = (result.stderr ?? '').trim() || result.error?.message || `exit ${result.status ?? 'unknown'}`;\n const message = `Review-round Git command failed: ${command}\\n${detail}`;\n if (result.error !== undefined) throw new InformAiError(message, { cause: result.error });\n throw new InformAiError(message);\n }\n}\n"]}
1
+ {"version":3,"file":"review-round-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-round-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,iDAA0C;AAC1C,8DAAsE;AACtE,iEAA6D;AAC7D,0DAA0G;AAC1G,yCAA2D;AAE3D,6DAAgE;AAChE,6CAAyC;AAM5B,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC/B,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC/B,QAAA,gBAAgB,GAAG,KAAK,CAAC;AACzB,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC/B,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAE5C,gHAAgH;AAChH,MAAM,UAAU,GAAG,gCAAgC,CAAC;AACpD,MAAM,QAAQ,GAAG,OAAO,CAAC;AACzB,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAExC,MA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AAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;QAC1F,MAAM,IAAI,8BAAa,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAEO,GAAG,CAAC,QAAgB,EAAE,IAAc;QACxC,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAC3E,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAC7D,MAAM,OAAO,GAAG,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACxC,MAAM,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,IAAI,QAAQ,MAAM,CAAC,MAAM,IAAI,SAAS,EAAE,CAAC;QAC7G,MAAM,OAAO,GAAG,oCAAoC,OAAO,KAAK,MAAM,EAAE,CAAC;QACzE,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS;YAAE,MAAM,IAAI,8BAAa,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;QAC1F,MAAM,IAAI,8BAAa,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACJ,CAAA;AA3WY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,gCAAiB;QACjB,6CAAwB;QACxB,2BAAU;GAJlC,uBAAuB,CA2WnC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { spawnSync } from 'child_process';\nimport { AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { ChecklistResult, ReviewJsonService, VERDICT_ORANGE, VERDICT_RED } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ReviewStageReceipt } from './review-stage-receipt';\nimport { VerdictProvenanceService } from './verdict-provenance';\nimport { DiffBasis } from './diff-basis';\n\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonValue[] | JsonObject;\ninterface JsonObject { [key: string]: JsonValue }\n\nexport const ROUND_ACTION_REVIEW = 'review';\nexport const ROUND_ACTION_RESUME = 'resume';\nexport const ROUND_ACTION_FIX = 'fix';\nexport const ROUND_ACTION_RECORD = 'record';\nexport const ROUND_ACTION_FINISH = 'finish';\n\n/** Every round-numbered file of a branch's review lives beside summary.json under this prefix (issue #1053). */\nconst ROUND_FILE = /^review-round(\\d+)-(.+)\\.json$/;\nconst FIXES_ID = 'fixes';\nconst PROVENANCE_SUFFIX = '.provenance';\n\nexport class ReviewRoundPlan {\n action: string;\n round: number;\n maxRounds: number;\n basis: DiffBasis;\n changedFiles: string[];\n redChecklistIds: string[];\n /** The final round's ORANGE checklists — must-fix, never re-reviewed (issue #1053). */\n orangeChecklistIds: string[];\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n action: string, round: number, maxRounds: number, basis: DiffBasis, changedFiles: string[] = [],\n redChecklistIds: string[] = [], orangeChecklistIds: string[] = [],\n ) {\n this.action = action;\n this.round = round;\n this.maxRounds = maxRounds;\n this.basis = basis;\n this.changedFiles = changedFiles;\n this.redChecklistIds = redChecklistIds;\n this.orangeChecklistIds = orangeChecklistIds;\n }\n}\n\n/**\n * Where a branch's review stands, DERIVED from the round-numbered files on disk plus the stage-② receipt\n * (issue #1053). There is no separate round counter: `round` is the highest round any file or briefing\n * names. Data-only.\n */\nexport class RoundSnapshot {\n round: number; // 0 = no round has started\n roster: string[]; // the REQUIRED checklists briefed in `round`, plus the optional ones that submitted in it\n headSha: string; // the commit `round` was briefed on\n complete: boolean; // every REQUIRED checklist briefed in `round` has a verdict in it (issue #1062)\n\n constructor(round: number, roster: string[], headSha: string, complete: boolean) {\n this.round = round;\n this.roster = roster;\n this.headSha = headSha;\n this.complete = complete;\n }\n}\n\nexport class RemediationResponse {\n checklistId: string;\n resolution: string;\n files: string[];\n\n constructor(checklistId: string, resolution: string, files: string[]) {\n this.checklistId = checklistId;\n this.resolution = resolution;\n this.files = files;\n }\n}\n\n/** The author's recorded fixes for one completed round: `review-round<N>-fixes.json`. Data-only. */\nexport class ReviewRemediation {\n agent: string;\n model: string;\n fromHead: string;\n toHead: string;\n responses: RemediationResponse[];\n writtenAt: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(agent: string, model: string, fromHead: string, toHead: string, responses: RemediationResponse[]) {\n this.agent = agent;\n this.model = model;\n this.fromHead = fromHead;\n this.toHead = toHead;\n this.responses = responses;\n this.writtenAt = new Date().toISOString();\n }\n}\n\n/**\n * The reviewer rounds of one branch, read from their round-numbered files (issue #1053).\n *\n * `commands.pr-gate.maxReviewerRounds` is a HARD CEILING, not a quota: 1 round means 1 round. Three rules\n * follow from it, and everything here exists to hold them:\n *\n * 1. Every verdict is `review-round<N>-<id>.json` (+ `.provenance.json`), every author fix record is\n * `review-round<N>-fixes.json`, and nothing is ever overwritten. The live verdict of a checklist is its\n * highest round; the round the branch is on is the highest round any file names.\n * 2. A new round starts ONLY when the previous round has a RED and rounds remain, and it re-briefs only\n * those reds. A green or yellow stands whatever changes afterwards — staleness never re-reviews.\n * 3. The final round has no red. Its blocking color is ORANGE: the author fixes it best effort, records the\n * fix, and ships with the finding and its claimed fix stamped on the dashboard.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewRoundStateService {\n constructor(\n private readonly reviewJson: ReviewJsonService,\n private readonly provenance: VerdictProvenanceService,\n private readonly atomicFile: AtomicFile,\n ) {}\n\n /** The author's recorded fixes for one round: `review-round<N>-fixes.json`, beside summary.json. */\n fixesPath(summaryPath: string, round: number): string {\n return path.join(path.dirname(summaryPath), `review-round${round}-${FIXES_ID}.json`);\n }\n\n /** The highest round any round-numbered file names, or 0. */\n highestRound(summaryPath: string): number {\n let highest = 0;\n for (const name of this.roundFiles(summaryPath)) {\n const match = ROUND_FILE.exec(name);\n if (match !== null) highest = Math.max(highest, Number(match[1]));\n }\n return highest;\n }\n\n /** Every checklist that has a verdict in ANY round on this branch. */\n verdictChecklistIds(summaryPath: string): string[] {\n const ids = new Set<string>();\n for (const name of this.roundFiles(summaryPath)) {\n const id = this.verdictIdOf(name);\n if (id !== '') ids.add(id);\n }\n return [...ids].sort();\n }\n\n /** Where the branch's review stands — see {@link RoundSnapshot}. */\n snapshot(summaryPath: string, receipt: ReviewStageReceipt | null): RoundSnapshot {\n const briefed = receipt !== null && receipt.reviewersBriefed.length > 0 ? receipt.round : 0;\n const round = Math.max(this.highestRound(summaryPath), briefed);\n if (round < 1) return new RoundSnapshot(0, [], '', false);\n if (receipt !== null && receipt.round === round) {\n // Only a REQUIRED checklist holds the round open (issue #1062). An optional one counts only if it\n // actually ran — a red from it still opens the next round — and one nobody chose to run is not\n // waited on, so an all-optional briefing nobody ran is complete with an empty roster.\n const optional = new Set<string>(receipt.optionalBriefed);\n const required = receipt.reviewersBriefed.filter((id: string): boolean => !optional.has(id));\n const roster = receipt.reviewersBriefed.filter((id: string): boolean =>\n !optional.has(id) || this.hasVerdict(summaryPath, id, round));\n return new RoundSnapshot(round, roster, receipt.headSha, this.everyVerdictIn(summaryPath, required, round));\n }\n // The receipt names an older round (or is gone): the files are the record, so the roster is exactly\n // the checklists that have a verdict in this round, and the reviewed HEAD is what their provenance says.\n const roster = this.roundFiles(summaryPath)\n .filter((name: string): boolean => name.startsWith(`review-round${round}-`))\n .map((name: string): string => this.verdictIdOf(name))\n .filter((id: string): boolean => id !== '')\n .sort();\n const headSha = roster.length === 0 ? '' : this.provenance.read(summaryPath, roster[0], round)?.headSha ?? '';\n return new RoundSnapshot(round, roster, headSha, roster.length > 0);\n }\n\n /**\n * TRUE once a review round has started on this branch. From then on the checklist set is FROZEN (issue\n * #1053): finish judges only the checklists that were briefed, never ones a later commit newly triggers.\n */\n roundStarted(summaryPath: string, receipt: ReviewStageReceipt | null): boolean {\n return this.snapshot(summaryPath, receipt).round >= 1;\n }\n\n /**\n * The frozen checklist set: every checklist briefed in any round — see {@link roundStarted}. It keeps an\n * optional checklist that was offered but never run, so its dashboard row reads \"optional, not run\"\n * rather than \"not briefed\"; it never holds a round open (see {@link snapshot}).\n */\n briefedChecklistIds(summaryPath: string, receipt: ReviewStageReceipt | null): string[] {\n const ids = new Set<string>(this.verdictChecklistIds(summaryPath));\n if (receipt !== null && receipt.round >= 1) for (const id of receipt.reviewersBriefed) ids.add(id);\n return [...ids].sort();\n }\n\n /** Does `checklistId` already have a verdict in `round`? A round's verdict is never overwritten. */\n hasVerdict(summaryPath: string, checklistId: string, round: number): boolean {\n return fs.existsSync(this.reviewJson.checklistResultPath(summaryPath, checklistId, round));\n }\n\n /** The roster checklists whose verdict in the snapshot's round is `status`. */\n checklistIdsWithStatus(summaryPath: string, snap: RoundSnapshot, status: string): string[] {\n if (!snap.complete) return [];\n return snap.roster.filter((id: string): boolean => {\n const raw = this.readObject(this.reviewJson.checklistResultPath(summaryPath, id, snap.round));\n return raw !== null && raw['status'] === status;\n });\n }\n\n /** What stage ② does next. See the class comment for the three rules it holds. */\n plan(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt | null, maxRounds: number, fullBasis: DiffBasis): ReviewRoundPlan {\n const snap = this.snapshot(summaryPath, receipt);\n if (snap.round < 1) return new ReviewRoundPlan(ROUND_ACTION_REVIEW, 1, maxRounds, fullBasis);\n if (!snap.complete) {\n // A sanctioned update changes the build basis, never the fixed roster or its historical\n // briefing. Resume that roster without charging another round (issue #1087).\n return new ReviewRoundPlan(ROUND_ACTION_RESUME, snap.round, maxRounds, fullBasis);\n }\n const reds = this.checklistIdsWithStatus(summaryPath, snap, VERDICT_RED);\n const oranges = this.checklistIdsWithStatus(summaryPath, snap, VERDICT_ORANGE);\n // No red, or no round left: nothing is ever re-reviewed. Oranges are the author's to fix and record.\n if (reds.length === 0 || snap.round >= maxRounds) {\n return new ReviewRoundPlan(ROUND_ACTION_FINISH, snap.round, maxRounds, fullBasis, [], reds, oranges);\n }\n if (snap.headSha === fullBasis.headSha) {\n return new ReviewRoundPlan(ROUND_ACTION_FIX, snap.round, maxRounds, fullBasis, [], reds, oranges);\n }\n if (this.validFixes(repoRoot, summaryPath, snap) === null) {\n return new ReviewRoundPlan(ROUND_ACTION_RECORD, snap.round, maxRounds, fullBasis, [], reds, oranges);\n }\n const basis = new DiffBasis(\n snap.headSha, fullBasis.headSha, false, [],\n `git diff ${snap.headSha} ${fullBasis.headSha}`,\n `git diff ${snap.headSha} ${fullBasis.headSha} -- <file>`, fullBasis.hashMainHead);\n const changed = this.git(repoRoot, ['diff', '--name-only', snap.headSha, fullBasis.headSha])\n .split('\\n').filter((f: string): boolean => f.trim() !== '');\n return new ReviewRoundPlan(ROUND_ACTION_REVIEW, snap.round + 1, maxRounds, basis, changed, reds, oranges);\n }\n\n /**\n * Record the author's fixes for the latest completed round — one response per RED (a round that is not\n * the last) or ORANGE (the final round) — as `review-round<N>-fixes.json`.\n *\n * A record that still HOLDS is never overwritten. One that no longer holds — its `toHead` left HEAD's\n * history, which every `wp-start-upsert-pr` squash-update does — is kept beside it as\n * `review-round<N>-fixes.json.superseded-<k>` and a fresh record is written, so re-recording is always\n * the way past a stale record and nothing is ever lost.\n */\n writeRemediation(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt, json: string): string {\n const snap = this.snapshot(summaryPath, receipt);\n if (!snap.complete) {\n throw new InformAiError('wp-write-review-fixes: the active reviewer round is not complete yet.');\n }\n const blocking = this.blockingIds(summaryPath, snap);\n if (blocking.length === 0) {\n throw new InformAiError(`wp-write-review-fixes: round ${snap.round} has no red or orange verdict to fix.`);\n }\n const out = this.fixesPath(summaryPath, snap.round);\n const holding = this.validFixes(repoRoot, summaryPath, snap);\n if (holding !== null) {\n throw new InformAiError(`wp-write-review-fixes: the fixes for round ${snap.round} are already recorded in ${out}, and `\n + `that record still holds (its fixed commit ${holding.toHead.slice(0, 8)} is in HEAD's history), so it is not `\n + 'overwritten. Nothing more to record: re-run pnpm wp-review-upsert-pr, or pnpm wp-finish-upsert-pr after the last round.');\n }\n this.assertClean(repoRoot);\n const currentHead = this.git(repoRoot, ['rev-parse', 'HEAD']);\n if (currentHead === snap.headSha || this.git(repoRoot, ['diff', '--name-only', snap.headSha, currentHead]) === '') {\n throw new InformAiError('wp-write-review-fixes: remediation must contain a committed, non-empty delta after the reviewed HEAD.');\n }\n const raw = this.parseObject(json, 'wp-write-review-fixes: input must be one JSON object.');\n const agent = this.requiredText(raw, 'agent');\n const model = this.requiredText(raw, 'model');\n const responses = this.responses(raw['responses']);\n const ids = responses.map((r: RemediationResponse): string => r.checklistId);\n const unknown = ids.filter((id: string): boolean => !blocking.includes(id));\n const missing = blocking.filter((id: string): boolean => !ids.includes(id));\n if (unknown.length > 0 || missing.length > 0) {\n throw new InformAiError(`wp-write-review-fixes: responses must cover exactly the red/orange checklist(s) of round ${snap.round}. `\n + `Unknown: ${unknown.join(', ') || '(none)'}. Missing: ${missing.join(', ') || '(none)'}.`);\n }\n this.supersede(out);\n this.atomicFile.writeJsonAtomic(out, new ReviewRemediation(agent, model, snap.headSha, currentHead, responses));\n return out;\n }\n\n /**\n * Keep a record that no longer holds beside the new one, as `<file>.superseded-<k>` — a name no round\n * scan reads, so it is history and never a live record.\n */\n private supersede(file: string): void {\n if (!fs.existsSync(file)) return;\n let k = 1;\n while (fs.existsSync(`${file}.superseded-${k}`)) k++;\n fs.renameSync(file, `${file}.superseded-${k}`);\n }\n\n /**\n * The round's recorded fixes, or null when there are none that still hold: written from the reviewed\n * HEAD, to a later commit that is still in HEAD's history, covering exactly the round's red/orange set.\n */\n validFixes(repoRoot: string, summaryPath: string, snap: RoundSnapshot): ReviewRemediation | null {\n const record = this.readFixes(repoRoot, summaryPath, snap.round);\n if (record === null || record.fromHead !== snap.headSha) return null;\n const blocking = this.blockingIds(summaryPath, snap);\n const ids = record.responses.map((r: RemediationResponse): string => r.checklistId);\n if (blocking.some((id: string): boolean => !ids.includes(id)) || ids.some((id: string): boolean => !blocking.includes(id))) return null;\n return record;\n }\n\n /**\n * checklist id → the dashboard stamp for every ORANGE whose fix the author recorded (issue #1053):\n * \"orange at <fromHead>, author-fixed in <toHead>, not re-reviewed: <resolution>\". An orange with no\n * valid record is absent, and so still blocks.\n */\n orangeFixes(repoRoot: string, summaryPath: string, results: readonly ChecklistResult[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const result of results) {\n if (result.status !== VERDICT_ORANGE || result.problem !== '') continue;\n const record = this.readFixes(repoRoot, summaryPath, result.round);\n const response = record?.responses.find((r: RemediationResponse): boolean => r.checklistId === result.id);\n if (record === null || response === undefined) continue;\n out[result.id] = `orange at ${record.fromHead.slice(0, 8)}, author-fixed in ${record.toHead.slice(0, 8)}, `\n + `not re-reviewed: ${response.resolution}`;\n }\n return out;\n }\n\n auditTrail(summaryPath: string, checklistId: string, maxRounds: number): string {\n const lines: string[] = [];\n const highest = this.highestRound(summaryPath);\n for (let round = 1; round <= highest; round++) {\n const verdict = this.readObject(this.reviewJson.checklistResultPath(summaryPath, checklistId, round));\n if (verdict !== null) {\n lines.push(`#### Reviewer round ${round} of ${maxRounds}`);\n lines.push(`Reviewed SHA: ${this.provenance.read(summaryPath, checklistId, round)?.headSha || '(unknown)'}`);\n lines.push(`Status: ${this.text(verdict['status']).toUpperCase()}`);\n lines.push('', this.text(verdict['output']), '');\n }\n const remediation = this.readObject(this.fixesPath(summaryPath, round));\n if (remediation !== null && Array.isArray(remediation['responses'])) {\n const response = (remediation['responses'] as JsonValue[]).find((entry: JsonValue): boolean =>\n typeof entry === 'object' && entry !== null && !Array.isArray(entry)\n && (entry as JsonObject)['checklistId'] === checklistId);\n if (typeof response === 'object' && response !== null && !Array.isArray(response)) {\n const raw = response as JsonObject;\n lines.push(`#### Author fix after round ${round}`);\n lines.push(`Range: ${this.text(remediation['fromHead'])}..${this.text(remediation['toHead'])}`);\n lines.push('', this.text(raw['resolution']), '');\n }\n }\n }\n return lines.join('\\n').trim();\n }\n\n private blockingIds(summaryPath: string, snap: RoundSnapshot): string[] {\n return [\n ...this.checklistIdsWithStatus(summaryPath, snap, VERDICT_RED),\n ...this.checklistIdsWithStatus(summaryPath, snap, VERDICT_ORANGE),\n ];\n }\n\n /** A round's fix record, provided its `toHead` is still in HEAD's history; else null. */\n private readFixes(repoRoot: string, summaryPath: string, round: number): ReviewRemediation | null {\n const raw = this.readObject(this.fixesPath(summaryPath, round));\n if (raw === null) return null;\n const responses = this.responsesOrEmpty(raw['responses']);\n const fromHead = this.text(raw['fromHead']);\n const toHead = this.text(raw['toHead']);\n if (this.text(raw['agent']) === '' || this.text(raw['model']) === '' || responses.length === 0\n || fromHead === '' || toHead === '' || fromHead === toHead || !this.isAncestorOfHead(repoRoot, toHead)) return null;\n return new ReviewRemediation(this.text(raw['agent']), this.text(raw['model']), fromHead, toHead, responses);\n }\n\n private everyVerdictIn(summaryPath: string, roster: readonly string[], round: number): boolean {\n return roster.every((id: string): boolean => this.hasVerdict(summaryPath, id, round));\n }\n\n /** `review-round<N>-<id>.json` → `<id>`; '' for the fixes record, a provenance file, or anything else. */\n private verdictIdOf(name: string): string {\n const match = ROUND_FILE.exec(name);\n if (match === null) return '';\n const id = match[2];\n return id === FIXES_ID || id.endsWith(PROVENANCE_SUFFIX) ? '' : id;\n }\n\n private roundFiles(summaryPath: string): string[] {\n const dir = path.dirname(summaryPath);\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir).filter((name: string): boolean => ROUND_FILE.test(name));\n }\n\n private responses(value: JsonValue | undefined): RemediationResponse[] {\n const responses = this.responsesOrEmpty(value);\n if (responses.length === 0) throw new InformAiError('wp-write-review-fixes: \"responses\" must be a non-empty array.');\n return responses;\n }\n\n private responsesOrEmpty(value: JsonValue | undefined): RemediationResponse[] {\n if (!Array.isArray(value)) return [];\n const out: RemediationResponse[] = [];\n for (const entry of value) {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return [];\n const raw = entry as JsonObject;\n const id = this.text(raw['checklistId']);\n const resolution = this.text(raw['resolution']);\n const files = Array.isArray(raw['files']) ? raw['files'].filter((f: JsonValue): f is string => typeof f === 'string' && f.trim() !== '') : [];\n if (id === '' || resolution === '' || files.length === 0) return [];\n out.push(new RemediationResponse(id, resolution, files));\n }\n return out;\n }\n\n private requiredText(raw: JsonObject, key: string): string {\n const value = this.text(raw[key]);\n if (value === '') throw new InformAiError(`wp-write-review-fixes: \"${key}\" must be a non-empty string.`);\n return value;\n }\n\n private text(value: JsonValue | undefined): string {\n return typeof value === 'string' ? value.trim() : '';\n }\n\n private parseObject(json: string, message: string): JsonObject {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed author JSON becomes an actionable refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const value = JSON.parse(json) as JsonValue;\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value;\n // webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n throw new InformAiError(message);\n }\n\n private readObject(file: string): JsonObject | null {\n if (!fs.existsSync(file)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable durable state becomes an actionable refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const value = JSON.parse(fs.readFileSync(file, 'utf8')) as JsonValue;\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value;\n throw new InformAiError(`Review state file must contain one JSON object: ${file}`);\n // webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError) throw error;\n throw new InformAiError(`Could not read review state file ${file}: ${error.message}`, { cause: error });\n }\n }\n\n private assertClean(repoRoot: string): void {\n const status = this.git(repoRoot, ['status', '--porcelain', '--untracked-files=all']);\n if (status !== '') throw new InformAiError('wp-write-review-fixes: commit every remediation and leave no staged, unstaged, or untracked files first.');\n }\n\n /**\n * `git merge-base --is-ancestor`: exit 0 = yes, 1 = no. A `sha` git does not know (exit 128 with\n * \"Not a valid commit name\") is also no — the commit is gone from this clone, so it is not in HEAD's\n * history. Anything else is a real failure and refuses.\n */\n private isAncestorOfHead(repoRoot: string, sha: string): boolean {\n const result = spawnSync('git', ['merge-base', '--is-ancestor', sha, 'HEAD'], { cwd: repoRoot, encoding: 'utf8' });\n if (result.status === 0) return true;\n if (result.status === 1 || /not a valid (commit|object) name/i.test(result.stderr ?? '')) return false;\n const detail = (result.stderr ?? '').trim() || result.error?.message || `exit ${result.status ?? 'unknown'}`;\n const message = `Review-round Git command failed: git merge-base --is-ancestor ${sha} HEAD\\n${detail}`;\n if (result.error !== undefined) throw new InformAiError(message, { cause: result.error });\n throw new InformAiError(message);\n }\n\n private git(repoRoot: string, args: string[]): string {\n const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status === 0) return (result.stdout ?? '').trim();\n const command = `git ${args.join(' ')}`;\n const detail = (result.stderr ?? '').trim() || result.error?.message || `exit ${result.status ?? 'unknown'}`;\n const message = `Review-round Git command failed: ${command}\\n${detail}`;\n if (result.error !== undefined) throw new InformAiError(message, { cause: result.error });\n throw new InformAiError(message);\n }\n}\n"]}
@@ -5,6 +5,7 @@ export declare const RECEIPT_FILE = "review-stage.json";
5
5
  */
6
6
  export declare class ReviewStageReceipt {
7
7
  headSha: string;
8
+ buildHeadSha: string;
8
9
  mergeValidated: boolean;
9
10
  buildCommand: string;
10
11
  buildPassedAt: string;
@@ -18,8 +19,8 @@ export declare class ReviewStageReceipt {
18
19
  optionalBriefed: string[];
19
20
  /**
20
21
  * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`
21
- * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and the next stage ② carries
22
- * a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.
22
+ * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and later stages retain
23
+ * that historical scope when carrying accepted verdicts (issue #1053). Assigned after construction.
23
24
  */
24
25
  scopeHashes: Record<string, string>;
25
26
  /**
@@ -12,7 +12,8 @@ exports.RECEIPT_FILE = 'review-stage.json';
12
12
  * Proof that stage ② (`wp-review-upsert-pr`) actually ran, and on WHICH commit. Data-only (per CLAUDE.md).
13
13
  */
14
14
  class ReviewStageReceipt {
15
- headSha; // the sha the merge was validated and the build was run against
15
+ headSha; // historical SHA the fixed roster was briefed on
16
+ buildHeadSha; // current SHA the merge validation and build evidence apply to
16
17
  mergeValidated; // a 3-point merge was finalized here, or there was none to finalize
17
18
  buildCommand;
18
19
  buildPassedAt; // ISO; '' when the gate was skipped (mode OFF / no command)
@@ -26,8 +27,8 @@ class ReviewStageReceipt {
26
27
  optionalBriefed;
27
28
  /**
28
29
  * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`
29
- * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and the next stage ② carries
30
- * a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.
30
+ * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and later stages retain
31
+ * that historical scope when carrying accepted verdicts (issue #1053). Assigned after construction.
31
32
  */
32
33
  scopeHashes;
33
34
  /**
@@ -42,6 +43,7 @@ class ReviewStageReceipt {
42
43
  // eslint-disable-next-line @typescript-eslint/max-params
43
44
  constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed = []) {
44
45
  this.headSha = headSha;
46
+ this.buildHeadSha = headSha;
45
47
  this.mergeValidated = mergeValidated;
46
48
  this.buildCommand = buildCommand;
47
49
  this.buildPassedAt = buildPassedAt;
@@ -93,6 +95,7 @@ let ReviewStageReceiptService = class ReviewStageReceiptService {
93
95
  // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below
94
96
  const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
95
97
  const receipt = new ReviewStageReceipt(typeof raw['headSha'] === 'string' ? raw['headSha'] : '', raw['mergeValidated'] === true, typeof raw['buildCommand'] === 'string' ? raw['buildCommand'] : '', typeof raw['buildPassedAt'] === 'string' ? raw['buildPassedAt'] : '', Array.isArray(raw['reviewersBriefed']) ? raw['reviewersBriefed'] : []);
98
+ receipt.buildHeadSha = typeof raw['buildHeadSha'] === 'string' ? raw['buildHeadSha'] : '';
96
99
  receipt.optionalBriefed = Array.isArray(raw['optionalBriefed'])
97
100
  ? raw['optionalBriefed'].filter((id) => typeof id === 'string') : [];
98
101
  receipt.scopeHashes = this.stringMap(raw['scopeHashes']);
@@ -1 +1 @@
1
- {"version":3,"file":"review-stage-receipt.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-stage-receipt.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4D;AAC5D,iEAA6D;AAC7D,yCAA2D;AAE9C,QAAA,YAAY,GAAG,mBAAmB,CAAC;AAEhD;;GAEG;AACH,MAAa,kBAAkB;IAC3B,OAAO,CAAS,CAAU,gEAAgE;IAC1F,cAAc,CAAU,CAAE,oEAAoE;IAC9F,YAAY,CAAS;IACrB,aAAa,CAAS,CAAI,4DAA4D;IACtF,gBAAgB,CAAW;IAC3B;;;;;OAKG;IACH,eAAe,CAAW;IAC1B;;;;OAIG;IACH,WAAW,CAAyB;IACpC;;;;;OAKG;IACH,KAAK,CAAS;IACd,8FAA8F;IAC9F,iBAAiB,CAAS;IAE1B,yDAAyD;IACzD,YAAY,OAAO,GAAG,EAAE,EAAE,cAAc,GAAG,KAAK,EAAE,YAAY,GAAG,EAAE,EAAE,aAAa,GAAG,EAAE,EAAE,mBAA6B,EAAE;QACpH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QAC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ReviewJsonService } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nexport const RECEIPT_FILE = 'review-stage.json';\n\n/**\n * Proof that stage ② (`wp-review-upsert-pr`) actually ran, and on WHICH commit. Data-only (per CLAUDE.md).\n */\nexport class ReviewStageReceipt {\n headSha: string; // the sha the merge was validated and the build was run against\n mergeValidated: boolean; // a 3-point merge was finalized here, or there was none to finalize\n buildCommand: string;\n buildPassedAt: string; // ISO; '' when the gate was skipped (mode OFF / no command)\n reviewersBriefed: string[];\n /**\n * The OPTIONAL subset of `reviewersBriefed` (issue #1062). Every briefed checklist may submit a verdict,\n * but only the REQUIRED ones hold a round open: an optional checklist joins the round's roster only when\n * it actually submitted in that round, so one the human chose not to run never deadlocks the round.\n * Assigned after construction; a receipt written without the field reads as [].\n */\n optionalBriefed: string[];\n /**\n * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`\n * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and the next stage ② carries\n * a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.\n */\n scopeHashes: Record<string, string>;\n /**\n * The round stage ② BRIEFED `reviewersBriefed` for, and so the N every verdict submitted against this\n * receipt is written as (`review-round<N>-<id>.json`). Zero means no reviewer round has started. The\n * round the branch is on is DERIVED from the round-numbered files (issue #1053); this only says which\n * round the latest briefing opened.\n */\n round: number;\n /** Repository-owned cap copied from config, so `wp-write-review` refuses a round above it. */\n maxReviewerRounds: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed: string[] = []) {\n this.headSha = headSha;\n this.mergeValidated = mergeValidated;\n this.buildCommand = buildCommand;\n this.buildPassedAt = buildPassedAt;\n this.reviewersBriefed = reviewersBriefed;\n this.optionalBriefed = [];\n this.scopeHashes = {};\n this.round = 0;\n this.maxReviewerRounds = 0;\n }\n}\n\n/**\n * Reads/writes the stage-② receipt.\n *\n * WHY a receipt rather than relying on the artifacts that already exist: `wp-finish-upsert-pr` already\n * refuses when a reviewer has no verdict and when summary.json is absent, so a repo WITH checklists is\n * mostly interlocked already. A repo with NO checklists is not — summary.json is the only thing standing\n * between it and a PR, and the AI writes summary.json itself. Nothing stopped it from writing that file and\n * going straight to finish, skipping the merge validation and the build entirely.\n *\n * The receipt also pays for itself in the other direction: because it records the sha the build passed on,\n * finish can SKIP its own build when HEAD has not moved, so adding a gate in the middle did not cost a\n * second full `nx affected` run.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewStageReceiptService {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n receiptPath(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), RECEIPT_FILE);\n }\n\n write(repoRoot: string, featureName: string, receipt: ReviewStageReceipt): string {\n const p = this.receiptPath(repoRoot, featureName);\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(receipt, null, 2) + '\\n');\n return p;\n }\n\n /** The receipt, or null when stage ② never ran (or left something unreadable behind). */\n read(repoRoot: string, featureName: string): ReviewStageReceipt | null {\n const p = this.receiptPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable receipt is treated as absent, which re-runs stage ②\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n const receipt = new ReviewStageReceipt(\n typeof raw['headSha'] === 'string' ? (raw['headSha'] as string) : '',\n raw['mergeValidated'] === true,\n typeof raw['buildCommand'] === 'string' ? (raw['buildCommand'] as string) : '',\n typeof raw['buildPassedAt'] === 'string' ? (raw['buildPassedAt'] as string) : '',\n Array.isArray(raw['reviewersBriefed']) ? (raw['reviewersBriefed'] as string[]) : [],\n );\n receipt.optionalBriefed = Array.isArray(raw['optionalBriefed'])\n ? (raw['optionalBriefed'] as string[]).filter((id: string): boolean => typeof id === 'string') : [];\n receipt.scopeHashes = this.stringMap(raw['scopeHashes']);\n receipt.round = typeof raw['round'] === 'number' && Number.isInteger(raw['round']) ? raw['round'] as number : 0;\n receipt.maxReviewerRounds = typeof raw['maxReviewerRounds'] === 'number' && Number.isInteger(raw['maxReviewerRounds'])\n ? raw['maxReviewerRounds'] as number : 0;\n return receipt;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable ⇒ treated as absent, which re-runs stage ② (the safe direction)\n return null;\n }\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSON value, narrowed to string→string\n private stringMap(value: unknown): Record<string, string> {\n const out: Record<string, string> = {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return out;\n // webpieces-disable no-any-unknown -- entries of an opaque JSON object, each narrowed below\n const obj = value as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n const v = obj[key];\n if (typeof v === 'string') out[key] = v;\n }\n return out;\n }\n}\n"]}
1
+ {"version":3,"file":"review-stage-receipt.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-stage-receipt.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4D;AAC5D,iEAA6D;AAC7D,yCAA2D;AAE9C,QAAA,YAAY,GAAG,mBAAmB,CAAC;AAEhD;;GAEG;AACH,MAAa,kBAAkB;IAC3B,OAAO,CAAS,CAAU,iDAAiD;IAC3E,YAAY,CAAS,CAAK,+DAA+D;IACzF,cAAc,CAAU,CAAE,oEAAoE;IAC9F,YAAY,CAAS;IACrB,aAAa,CAAS,CAAI,4DAA4D;IACtF,gBAAgB,CAAW;IAC3B;;;;;OAKG;IACH,eAAe,CAAW;IAC1B;;;;OAIG;IACH,WAAW,C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A4F;QAC5F,MAAM,GAAG,GAAG,KAAgC,CAAC;QAC7C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACjC,MAAM,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;YACnB,IAAI,OAAO,CAAC,KAAK,QAAQ;gBAAE,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,GAAG,CAAC;IACf,CAAC;CACJ,CAAA;AAzDY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEW,gCAAiB;GADxD,yBAAyB,CAyDrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { ReviewJsonService } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nexport const RECEIPT_FILE = 'review-stage.json';\n\n/**\n * Proof that stage ② (`wp-review-upsert-pr`) actually ran, and on WHICH commit. Data-only (per CLAUDE.md).\n */\nexport class ReviewStageReceipt {\n headSha: string; // historical SHA the fixed roster was briefed on\n buildHeadSha: string; // current SHA the merge validation and build evidence apply to\n mergeValidated: boolean; // a 3-point merge was finalized here, or there was none to finalize\n buildCommand: string;\n buildPassedAt: string; // ISO; '' when the gate was skipped (mode OFF / no command)\n reviewersBriefed: string[];\n /**\n * The OPTIONAL subset of `reviewersBriefed` (issue #1062). Every briefed checklist may submit a verdict,\n * but only the REQUIRED ones hold a round open: an optional checklist joins the round's roster only when\n * it actually submitted in that round, so one the human chose not to run never deadlocks the round.\n * Assigned after construction; a receipt written without the field reads as [].\n */\n optionalBriefed: string[];\n /**\n * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`\n * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and later stages retain\n * that historical scope when carrying accepted verdicts (issue #1053). Assigned after construction.\n */\n scopeHashes: Record<string, string>;\n /**\n * The round stage ② BRIEFED `reviewersBriefed` for, and so the N every verdict submitted against this\n * receipt is written as (`review-round<N>-<id>.json`). Zero means no reviewer round has started. The\n * round the branch is on is DERIVED from the round-numbered files (issue #1053); this only says which\n * round the latest briefing opened.\n */\n round: number;\n /** Repository-owned cap copied from config, so `wp-write-review` refuses a round above it. */\n maxReviewerRounds: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed: string[] = []) {\n this.headSha = headSha;\n this.buildHeadSha = headSha;\n this.mergeValidated = mergeValidated;\n this.buildCommand = buildCommand;\n this.buildPassedAt = buildPassedAt;\n this.reviewersBriefed = reviewersBriefed;\n this.optionalBriefed = [];\n this.scopeHashes = {};\n this.round = 0;\n this.maxReviewerRounds = 0;\n }\n}\n\n/**\n * Reads/writes the stage-② receipt.\n *\n * WHY a receipt rather than relying on the artifacts that already exist: `wp-finish-upsert-pr` already\n * refuses when a reviewer has no verdict and when summary.json is absent, so a repo WITH checklists is\n * mostly interlocked already. A repo with NO checklists is not — summary.json is the only thing standing\n * between it and a PR, and the AI writes summary.json itself. Nothing stopped it from writing that file and\n * going straight to finish, skipping the merge validation and the build entirely.\n *\n * The receipt also pays for itself in the other direction: because it records the sha the build passed on,\n * finish can SKIP its own build when HEAD has not moved, so adding a gate in the middle did not cost a\n * second full `nx affected` run.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewStageReceiptService {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n receiptPath(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), RECEIPT_FILE);\n }\n\n write(repoRoot: string, featureName: string, receipt: ReviewStageReceipt): string {\n const p = this.receiptPath(repoRoot, featureName);\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(receipt, null, 2) + '\\n');\n return p;\n }\n\n /** The receipt, or null when stage ② never ran (or left something unreadable behind). */\n read(repoRoot: string, featureName: string): ReviewStageReceipt | null {\n const p = this.receiptPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable receipt is treated as absent, which re-runs stage ②\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n const receipt = new ReviewStageReceipt(\n typeof raw['headSha'] === 'string' ? (raw['headSha'] as string) : '',\n raw['mergeValidated'] === true,\n typeof raw['buildCommand'] === 'string' ? (raw['buildCommand'] as string) : '',\n typeof raw['buildPassedAt'] === 'string' ? (raw['buildPassedAt'] as string) : '',\n Array.isArray(raw['reviewersBriefed']) ? (raw['reviewersBriefed'] as string[]) : [],\n );\n receipt.buildHeadSha = typeof raw['buildHeadSha'] === 'string' ? raw['buildHeadSha'] as string : '';\n receipt.optionalBriefed = Array.isArray(raw['optionalBriefed'])\n ? (raw['optionalBriefed'] as string[]).filter((id: string): boolean => typeof id === 'string') : [];\n receipt.scopeHashes = this.stringMap(raw['scopeHashes']);\n receipt.round = typeof raw['round'] === 'number' && Number.isInteger(raw['round']) ? raw['round'] as number : 0;\n receipt.maxReviewerRounds = typeof raw['maxReviewerRounds'] === 'number' && Number.isInteger(raw['maxReviewerRounds'])\n ? raw['maxReviewerRounds'] as number : 0;\n return receipt;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable ⇒ treated as absent, which re-runs stage ② (the safe direction)\n return null;\n }\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSON value, narrowed to string→string\n private stringMap(value: unknown): Record<string, string> {\n const out: Record<string, string> = {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return out;\n // webpieces-disable no-any-unknown -- entries of an opaque JSON object, each narrowed below\n const obj = value as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n const v = obj[key];\n if (typeof v === 'string') out[key] = v;\n }\n return out;\n }\n}\n"]}
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StageOutputLog = exports.FINISH_CONSOLE_LOG = exports.REVIEW_CONSOLE_LOG = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
+ const rules_config_1 = require("@webpieces/rules-config");
7
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
6
8
  const inversify_1 = require("inversify");
7
9
  const gate_log_file_1 = require("./gate-log-file");
8
10
  // ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────
@@ -82,6 +84,14 @@ let StageOutputLog = class StageOutputLog {
82
84
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
83
85
  try {
84
86
  return await body();
87
+ // webpieces-disable no-any-unknown -- JavaScript may reject with any value; normalize for the diagnostic log
88
+ }
89
+ catch (err) {
90
+ const error = (0, to_error_1.toError)(err);
91
+ // Match runMain's terminal rendering, including a rule refusal's actionable options.
92
+ const message = error instanceof rules_config_1.RuleFailError ? (0, rules_config_1.renderRuleFailForHuman)(error) : error.message;
93
+ this.appendToLog(message + '\n');
94
+ throw err; // the global handler still owns terminal rendering and the exit status
85
95
  }
86
96
  finally {
87
97
  this.release();
@@ -1 +1 @@
1
- {"version":3,"file":"stage-output-log.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/stage-output-log.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,yCAA2D;AAE3D,mDAA8C;AAE9C,0GAA0G;AAC1G,2GAA2G;AAC3G,0GAA0G;AAC1G,yGAAyG;AACzG,+CAA+C;AAC/C,EAAE;AACF,0GAA0G;AAC1G,yGAAyG;AACzG,yGAAyG;AACzG,uGAAuG;AACvG,uGAAuG;AACvG,sEAAsE;AACtE,EAAE;AACF,oGAAoG;AACpG,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I,CAAC,EAAE,CAAC,CAAC;QACtB,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;QACb,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACtB,CAAC;IAED,sGAAsG;IAC9F,WAAW,CAAC,IAAY;QAC5B,IAAI,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;YAAE,OAAO;QAC3B,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACJ,CAAA;AAhFY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAED,2BAAW;GADtC,cAAc,CAgF1B","sourcesContent":["import * as fs from 'fs';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { GateLogFile } from './gate-log-file';\n\n// ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────\n// `wp-build` already solved this for the BUILD: its output goes to a FILE and the console gets a heartbeat\n// plus a pointer. Stage ② and stage ③ had not been given the same treatment, so they printed everything —\n// merge validation, the active-hatch report, the checklist scan, the diff extraction, the dashboard, the\n// gh round trips — straight down the terminal.\n//\n// The consequence was measured, and it is not \"a long transcript\". An agent that expects a wall of output\n// bounds it by reflex: `pnpm wp-review-upsert-pr 2>&1 | tail -50`. A PIPE WITHHOLDS EVERY BYTE UNTIL THE\n// COMMAND EXITS, so the harness sees a command that has printed nothing for 600 seconds and kills it — a\n// full build's worth of work thrown away, and then usually re-run the same way. In this repo's primary\n// tree alone the call log holds 85 piped `wp-*` invocations, 42 of them on a command that runs a build\n// (`wp-review-upsert-pr` 22, `wp-finish-upsert-pr` 17, `wp-build` 3).\n//\n// Shrinking the output is therefore the FIRST half of the fix and the guard against the pipe is the\n// second, in that order. Blocking the pipe while the command still printed a thousand lines would only\n// have traded a watchdog kill for a flooded context, and an agent would have routed around it with `>`.\n//\n// ─── Why it INTERCEPTS stdout instead of every writer calling it ───────────────────────────────────────\n// There are ~160 `process.stdout.write` sites across this package, in classes shared by six other bins.\n// Threading a logger through all of them would be a far larger diff with far more ways to miss one — and\n// a MISSED one is the whole failure, because a single verbose writer that still reaches the console keeps\n// the output big enough to be piped. Interception inverts the default: everything a stage prints is\n// captured unless it says out loud that it must be seen NOW, and the \"say it out loud\" list is short\n// enough to read (`say()` — the build heartbeat, the build result, the review instructions, the PR link).\n//\n// The interception is installed and removed by `withCapture`, in a `finally`, so a throw cannot leave a\n// process with a patched stdout. Child processes that inherit fd 1 write straight past it, which is why\n// the build gate redirects its child to a file of its own rather than relying on this.\n//\n// Also deliberately NOT intercepted: stderr. Failures must stay on the terminal — `runMain` renders every\n// thrown CliExitError / RuleFailError there, and a refusal an agent cannot see is worse than a long one.\n\n/** Stage ②'s console log. Named for the command, because that is what a reader is looking for. */\nexport const REVIEW_CONSOLE_LOG = 'wp-review-upsert-pr.log';\n\n/** Stage ③'s console log. */\nexport const FINISH_CONSOLE_LOG = 'wp-finish-upsert-pr.log';\n\n/** The write function this class swaps out and restores — Node's own `process.stdout.write`. */\ntype StdoutWrite = typeof process.stdout.write;\n\n/** The optional completion callback Node's `write` accepts, in either of its two argument positions. */\ntype StdoutCallback = (err?: Error) => void;\n\n/**\n * Captures a stage's verbose console output to a file, keeps the handful of lines the caller must act on\n * immediately on the terminal, and hands back the one-line pointer at the file.\n *\n * Singleton, and stateful FOR THE DURATION OF ONE `withCapture` call: a bin runs exactly one stage.\n * Re-entering it is a programming error, not a supported mode, and it throws rather than silently\n * capturing into the inner file and restoring the outer one.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class StageOutputLog {\n constructor(private readonly files: GateLogFile) {}\n\n // The open log, or '' when nothing is being captured. `say` works either way — outside a capture it\n // is a plain write to the terminal, which is what every other bin wants.\n private logPath = '';\n private fd = -1;\n private original: StdoutWrite | null = null;\n\n /**\n * Run `body` with this process's stdout captured to `<logs>/<fileName>`, then restore stdout and\n * print the pointer at the file.\n *\n * The pointer is printed in a `finally`, so it is there on the FAILURE path too — which is the path\n * where a reader most needs it, and the one where an uncaptured stage would have scrolled the cause\n * off the top of the terminal.\n */\n async withCapture<T>(repoRoot: string, fileName: string, body: () => Promise<T>): Promise<T> {\n if (this.original !== null) throw new Error(`StageOutputLog is already capturing to ${this.logPath}`);\n this.logPath = this.files.logsPath(repoRoot, fileName);\n this.files.rotate(this.logPath);\n this.fd = fs.openSync(this.logPath, 'w');\n // The REFERENCE, not a bound copy: `release` puts this exact function back, so a caller that\n // installed its own stdout before us (a spec, a wrapping bin) gets ITS function back rather than\n // a wrapper around it, and repeated captures cannot stack bound layers.\n this.original = process.stdout.write;\n process.stdout.write = this.intercept.bind(this) as StdoutWrite;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: stdout MUST be restored and the fd\n // closed whatever `body` does; the throw is re-raised untouched.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await body();\n } finally {\n this.release();\n }\n }\n\n /**\n * Print `text` to the TERMINAL as well as the log — for the few things a caller must act on before it\n * can do anything else: the build heartbeat (a silent command is a killed command), the build result,\n * the review instructions, the PR link, and anything naming a file to read.\n *\n * Outside a capture this is an ordinary write, so a class that calls it is not coupled to the stage.\n */\n say(text: string): void {\n this.appendToLog(text);\n // `.call`, because `original` is the raw reference rather than a bound copy — see withCapture.\n (this.original ?? process.stdout.write).call(process.stdout, text);\n }\n\n // The stdout replacement. Node calls this with (chunk), (chunk, encoding), (chunk, callback) or\n // (chunk, encoding, callback); a callback that is never invoked can stall a writer, so it is always\n // called. Returning true means \"not backpressured\", which is honest for a synchronous file write.\n private intercept(\n chunk: string | Uint8Array, encodingOrCallback?: BufferEncoding | StdoutCallback, callback?: StdoutCallback,\n ): boolean {\n this.appendToLog(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'));\n const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n if (done !== undefined) done();\n return true;\n }\n\n // Restore stdout, close the log, and print the pointer at it. Idempotent: a second call after the\n // `finally` has already run is a no-op rather than a double pointer.\n private release(): void {\n if (this.original === null) return;\n const restore = this.original;\n this.original = null;\n process.stdout.write = restore;\n fs.closeSync(this.fd);\n this.fd = -1;\n restore.call(process.stdout, `\\n${this.files.pointer(this.logPath)}`);\n this.logPath = '';\n }\n\n // Nothing is captured when no capture is open — `say` still reaches the terminal, which is the point.\n private appendToLog(text: string): void {\n if (this.fd === -1) return;\n fs.writeSync(this.fd, text);\n }\n}\n"]}
1
+ {"version":3,"file":"stage-output-log.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/stage-output-log.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAAgF;AAChF,iEAA6D;AAC7D,yCAA2D;AAE3D,mDAA8C;AAE9C,0GAA0G;AAC1G,2GAA2G;AAC3G,0GAA0G;AAC1G,yGAAyG;AACzG,+CAA+C;AAC/C,EAAE;AACF,0GAA0G;AAC1G,yGAAyG;AACzG,yGAAyG;AACzG,uGAAuG;AACvG,uGAAuG;AACvG,sEAAsE;AACtE,EAAE;AACF,oGAAoG;AACpG,uGAAuG;AACvG,wGAAwG;AACxG,EAAE;AACF,0GAA0G;AAC1G,wGAAwG;AACxG,yGAAyG;AACzG,0GAA0G;AAC1G,oGAAoG;AACpG,qGAAqG;AACrG,0GAA0G;AAC1G,EAAE;AACF,wGAAwG;AACxG,wGAAwG;AACxG,uFAAuF;AACvF,EAAE;AACF,0GAA0G;AAC1G,yGAAyG;AAEzG,kGAAkG;AACrF,QAAA,kBAAkB,GAAG,yBAAyB,CAAC;AAE5D,6BAA6B;AAChB,QAAA,kBAAkB,GAAG,yBAAyB,CAAC;AAQ5D;;;;;;;GAOG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IACM;IAA7B,YAA6B,KAAkB;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CAAC,CAAC;QACb,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACtB,CAAC;IAED,sGAAsG;IAC9F,WAAW,CAAC,IAAY;QAC5B,IAAI,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;YAAE,OAAO;QAC3B,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACJ,CAAA;AAxFY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAED,2BAAW;GADtC,cAAc,CAwF1B","sourcesContent":["import * as fs from 'fs';\nimport { RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { GateLogFile } from './gate-log-file';\n\n// ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────\n// `wp-build` already solved this for the BUILD: its output goes to a FILE and the console gets a heartbeat\n// plus a pointer. Stage ② and stage ③ had not been given the same treatment, so they printed everything —\n// merge validation, the active-hatch report, the checklist scan, the diff extraction, the dashboard, the\n// gh round trips — straight down the terminal.\n//\n// The consequence was measured, and it is not \"a long transcript\". An agent that expects a wall of output\n// bounds it by reflex: `pnpm wp-review-upsert-pr 2>&1 | tail -50`. A PIPE WITHHOLDS EVERY BYTE UNTIL THE\n// COMMAND EXITS, so the harness sees a command that has printed nothing for 600 seconds and kills it — a\n// full build's worth of work thrown away, and then usually re-run the same way. In this repo's primary\n// tree alone the call log holds 85 piped `wp-*` invocations, 42 of them on a command that runs a build\n// (`wp-review-upsert-pr` 22, `wp-finish-upsert-pr` 17, `wp-build` 3).\n//\n// Shrinking the output is therefore the FIRST half of the fix and the guard against the pipe is the\n// second, in that order. Blocking the pipe while the command still printed a thousand lines would only\n// have traded a watchdog kill for a flooded context, and an agent would have routed around it with `>`.\n//\n// ─── Why it INTERCEPTS stdout instead of every writer calling it ───────────────────────────────────────\n// There are ~160 `process.stdout.write` sites across this package, in classes shared by six other bins.\n// Threading a logger through all of them would be a far larger diff with far more ways to miss one — and\n// a MISSED one is the whole failure, because a single verbose writer that still reaches the console keeps\n// the output big enough to be piped. Interception inverts the default: everything a stage prints is\n// captured unless it says out loud that it must be seen NOW, and the \"say it out loud\" list is short\n// enough to read (`say()` — the build heartbeat, the build result, the review instructions, the PR link).\n//\n// The interception is installed and removed by `withCapture`, in a `finally`, so a throw cannot leave a\n// process with a patched stdout. Child processes that inherit fd 1 write straight past it, which is why\n// the build gate redirects its child to a file of its own rather than relying on this.\n//\n// Also deliberately NOT intercepted: stderr. Failures must stay on the terminal — `runMain` renders every\n// thrown CliExitError / RuleFailError there, and a refusal an agent cannot see is worse than a long one.\n\n/** Stage ②'s console log. Named for the command, because that is what a reader is looking for. */\nexport const REVIEW_CONSOLE_LOG = 'wp-review-upsert-pr.log';\n\n/** Stage ③'s console log. */\nexport const FINISH_CONSOLE_LOG = 'wp-finish-upsert-pr.log';\n\n/** The write function this class swaps out and restores — Node's own `process.stdout.write`. */\ntype StdoutWrite = typeof process.stdout.write;\n\n/** The optional completion callback Node's `write` accepts, in either of its two argument positions. */\ntype StdoutCallback = (err?: Error) => void;\n\n/**\n * Captures a stage's verbose console output to a file, keeps the handful of lines the caller must act on\n * immediately on the terminal, and hands back the one-line pointer at the file.\n *\n * Singleton, and stateful FOR THE DURATION OF ONE `withCapture` call: a bin runs exactly one stage.\n * Re-entering it is a programming error, not a supported mode, and it throws rather than silently\n * capturing into the inner file and restoring the outer one.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class StageOutputLog {\n constructor(private readonly files: GateLogFile) {}\n\n // The open log, or '' when nothing is being captured. `say` works either way — outside a capture it\n // is a plain write to the terminal, which is what every other bin wants.\n private logPath = '';\n private fd = -1;\n private original: StdoutWrite | null = null;\n\n /**\n * Run `body` with this process's stdout captured to `<logs>/<fileName>`, then restore stdout and\n * print the pointer at the file.\n *\n * The pointer is printed in a `finally`, so it is there on the FAILURE path too — which is the path\n * where a reader most needs it, and the one where an uncaptured stage would have scrolled the cause\n * off the top of the terminal.\n */\n async withCapture<T>(repoRoot: string, fileName: string, body: () => Promise<T>): Promise<T> {\n if (this.original !== null) throw new Error(`StageOutputLog is already capturing to ${this.logPath}`);\n this.logPath = this.files.logsPath(repoRoot, fileName);\n this.files.rotate(this.logPath);\n this.fd = fs.openSync(this.logPath, 'w');\n // The REFERENCE, not a bound copy: `release` puts this exact function back, so a caller that\n // installed its own stdout before us (a spec, a wrapping bin) gets ITS function back rather than\n // a wrapper around it, and repeated captures cannot stack bound layers.\n this.original = process.stdout.write;\n process.stdout.write = this.intercept.bind(this) as StdoutWrite;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: stdout MUST be restored and the fd\n // closed whatever `body` does; the throw is re-raised untouched.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await body();\n // webpieces-disable no-any-unknown -- JavaScript may reject with any value; normalize for the diagnostic log\n } catch (err: unknown) {\n const error = toError(err);\n // Match runMain's terminal rendering, including a rule refusal's actionable options.\n const message =\n error instanceof RuleFailError ? renderRuleFailForHuman(error) : error.message;\n this.appendToLog(message + '\\n');\n throw err; // the global handler still owns terminal rendering and the exit status\n } finally {\n this.release();\n }\n }\n\n /**\n * Print `text` to the TERMINAL as well as the log — for the few things a caller must act on before it\n * can do anything else: the build heartbeat (a silent command is a killed command), the build result,\n * the review instructions, the PR link, and anything naming a file to read.\n *\n * Outside a capture this is an ordinary write, so a class that calls it is not coupled to the stage.\n */\n say(text: string): void {\n this.appendToLog(text);\n // `.call`, because `original` is the raw reference rather than a bound copy — see withCapture.\n (this.original ?? process.stdout.write).call(process.stdout, text);\n }\n\n // The stdout replacement. Node calls this with (chunk), (chunk, encoding), (chunk, callback) or\n // (chunk, encoding, callback); a callback that is never invoked can stall a writer, so it is always\n // called. Returning true means \"not backpressured\", which is honest for a synchronous file write.\n private intercept(\n chunk: string | Uint8Array, encodingOrCallback?: BufferEncoding | StdoutCallback, callback?: StdoutCallback,\n ): boolean {\n this.appendToLog(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'));\n const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n if (done !== undefined) done();\n return true;\n }\n\n // Restore stdout, close the log, and print the pointer at it. Idempotent: a second call after the\n // `finally` has already run is a no-op rather than a double pointer.\n private release(): void {\n if (this.original === null) return;\n const restore = this.original;\n this.original = null;\n process.stdout.write = restore;\n fs.closeSync(this.fd);\n this.fd = -1;\n restore.call(process.stdout, `\\n${this.files.pointer(this.logPath)}`);\n this.logPath = '';\n }\n\n // Nothing is captured when no capture is open — `say` still reaches the terminal, which is the point.\n private appendToLog(text: string): void {\n if (this.fd === -1) return;\n fs.writeSync(this.fd, text);\n }\n}\n"]}