@webpieces/pr-gate 0.4.822 → 0.4.824

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/package.json +5 -3
  2. package/src/dashboard/checklist-comment-renderer.js +6 -4
  3. package/src/dashboard/checklist-comment-renderer.js.map +1 -1
  4. package/src/dashboard/dashboard.js +6 -1
  5. package/src/dashboard/dashboard.js.map +1 -1
  6. package/src/index.d.ts +1 -1
  7. package/src/index.js +1 -1
  8. package/src/index.js.map +1 -1
  9. package/src/scripts/commands/build-command.d.ts +3 -0
  10. package/src/scripts/commands/build-command.js +29 -17
  11. package/src/scripts/commands/build-command.js.map +1 -1
  12. package/src/scripts/commands/check-pr-command.d.ts +10 -3
  13. package/src/scripts/commands/check-pr-command.js +31 -10
  14. package/src/scripts/commands/check-pr-command.js.map +1 -1
  15. package/src/scripts/commands/finish-upsert-pr-command.d.ts +4 -1
  16. package/src/scripts/commands/finish-upsert-pr-command.js +26 -5
  17. package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
  18. package/src/scripts/commands/human-post-pr-command.d.ts +52 -0
  19. package/src/scripts/commands/human-post-pr-command.js +260 -0
  20. package/src/scripts/commands/human-post-pr-command.js.map +1 -0
  21. package/src/scripts/commands/review-upsert-pr-command.d.ts +3 -1
  22. package/src/scripts/commands/review-upsert-pr-command.js +40 -23
  23. package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
  24. package/src/scripts/commands/write-review-command.d.ts +3 -1
  25. package/src/scripts/commands/write-review-command.js +9 -3
  26. package/src/scripts/commands/write-review-command.js.map +1 -1
  27. package/src/scripts/commands/write-review-fixes-command.d.ts +21 -0
  28. package/src/scripts/commands/write-review-fixes-command.js +68 -0
  29. package/src/scripts/commands/write-review-fixes-command.js.map +1 -0
  30. package/src/scripts/pr-gate-app.d.ts +9 -1
  31. package/src/scripts/pr-gate-app.js +18 -1
  32. package/src/scripts/pr-gate-app.js.map +1 -1
  33. package/src/scripts/workflow/build-affected.d.ts +3 -0
  34. package/src/scripts/workflow/build-affected.js +16 -3
  35. package/src/scripts/workflow/build-affected.js.map +1 -1
  36. package/src/scripts/workflow/build-gate-log.d.ts +4 -1
  37. package/src/scripts/workflow/build-gate-log.js +20 -5
  38. package/src/scripts/workflow/build-gate-log.js.map +1 -1
  39. package/src/scripts/workflow/build-log-follower.d.ts +13 -0
  40. package/src/scripts/workflow/build-log-follower.js +48 -0
  41. package/src/scripts/workflow/build-log-follower.js.map +1 -0
  42. package/src/scripts/workflow/checklist-scanner.d.ts +1 -3
  43. package/src/scripts/workflow/checklist-scanner.js +6 -9
  44. package/src/scripts/workflow/checklist-scanner.js.map +1 -1
  45. package/src/scripts/workflow/gated-pr-publisher.d.ts +1 -1
  46. package/src/scripts/workflow/gated-pr-publisher.js +20 -7
  47. package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
  48. package/src/scripts/workflow/push-dev-state.js +30 -17
  49. package/src/scripts/workflow/push-dev-state.js.map +1 -1
  50. package/src/scripts/workflow/repo-config-testkit.js +2 -0
  51. package/src/scripts/workflow/repo-config-testkit.js.map +1 -1
  52. package/src/scripts/workflow/review-report.d.ts +7 -4
  53. package/src/scripts/workflow/review-report.js +44 -24
  54. package/src/scripts/workflow/review-report.js.map +1 -1
  55. package/src/scripts/workflow/review-round-state.d.ts +58 -0
  56. package/src/scripts/workflow/review-round-state.js +300 -0
  57. package/src/scripts/workflow/review-round-state.js.map +1 -0
  58. package/src/scripts/workflow/review-stage-receipt.d.ts +6 -0
  59. package/src/scripts/workflow/review-stage-receipt.js +13 -0
  60. package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
  61. package/src/scripts/workflow/reviewer-verdict-gate.js +6 -24
  62. package/src/scripts/workflow/reviewer-verdict-gate.js.map +1 -1
  63. package/src/scripts/workflow/verdict-provenance.d.ts +3 -8
  64. package/src/scripts/workflow/verdict-provenance.js +7 -17
  65. package/src/scripts/workflow/verdict-provenance.js.map +1 -1
  66. package/src/scripts/wp-human-post-pr.d.ts +2 -0
  67. package/src/scripts/wp-human-post-pr.js +15 -0
  68. package/src/scripts/wp-human-post-pr.js.map +1 -0
  69. package/src/scripts/wp-write-review-fixes.d.ts +2 -0
  70. package/src/scripts/wp-write-review-fixes.js +16 -0
  71. package/src/scripts/wp-write-review-fixes.js.map +1 -0
  72. package/src/scripts/workflow/git-validateUpToDate.d.ts +0 -1
  73. package/src/scripts/workflow/git-validateUpToDate.js +0 -70
  74. package/src/scripts/workflow/git-validateUpToDate.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"human-post-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/human-post-pr-command.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,2DAAqC;AACrC,0DAUiC;AACjC,yCAA2D;AAC3D,2EAAgE;AAChE,6DAAyD;AACzD,uEAAkE;AAClE,mDAA+C;AAC/C,yDAAqD;AACrD,mFAA8E;AAC9E,mDAA6D;AAE7D,MAAM,aAAa,GAAG,uBAAuB,CAAC;AAE9C,kFAAkF;AAClF,MAAa,aAAa;IACtB,MAAM,CAAS;IACf,GAAG,CAAS;IAEZ,YAAY,MAAc,EAAE,GAAW;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACnB,CAAC;CACJ;AARD,sCAQC;AAED;;;;;;GAMG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAEN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAZrB,YACqB,cAA8B,EAC9B,cAA8B,EAC9B,YAA0B,EAC1B,YAA0B,EAC1B,OAAgB,EAChB,UAAsB,EACtB,iBAAoC,EACpC,cAAqC,EACrC,gBAAkC,EAClC,SAA2B,EAC3B,cAAsC,EACtC,YAA0B;QAX1B,mBAAc,GAAd,cAAc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CAAC;gBAChB,EAAE,CAAC,KAAK,EAAE,CAAC;gBACX,OAAO,CAAC,MAAM,CAAC,CAAC;YACpB,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,EAAE,CAAC,OAAO,EAAE,GAAS,EAAE;gBACtB,IAAI,CAAC,QAAQ;oBAAE,OAAO,CAAC,EAAE,CAAC,CAAC;YAC/B,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;CACJ,CAAA;AAlSY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QACd,6BAAc;QAChB,4BAAY;QACZ,mCAAY;QACjB,kBAAO;QACJ,wBAAU;QACH,gCAAiB;QACpB,oCAAqB;QACnB,+BAAgB;QACvB,qCAAgB;QACX,iDAAsB;QACxB,4BAAY;GAbtC,kBAAkB,CAkS9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as readline from 'readline';\nimport {\n BranchIdentity,\n CliExitError,\n GateTokenService,\n MainSyncStatus,\n MainSyncStatusService,\n PrSummary,\n RepoRootFinder,\n ReviewJsonService,\n loadAndValidate,\n} from '@webpieces/rules-config';\nimport { bindingScopeValues, injectable } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { GatedPrPublisher } from '../workflow/gated-pr-publisher';\nimport { GitExec } from '../workflow/git-exec';\nimport { MergeState } from '../workflow/merge-state';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { BuildCommand, BuildOptions } from './build-command';\n\nconst RETRY_COMMAND = 'pnpm wp-human-post-pr';\n\n/** The PR identity returned by GitHub after posting. Data-only, per CLAUDE.md. */\nexport class HumanPostedPr {\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/**\n * Interactive, human-attested PR escape hatch.\n *\n * The first answer is an attestation, not identity detection: a process cannot prove who typed it. The\n * fail-closed ordering is the security property here — every answer except the literal normalized\n * `human` returns before repository discovery, git, GitHub, or any write.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class HumanPostPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly branchIdentity: BranchIdentity,\n private readonly branchNaming: BranchNaming,\n private readonly aiBranchName: AiBranchName,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly mainSyncStatus: MainSyncStatusService,\n private readonly gateTokenService: GateTokenService,\n private readonly publisher: GatedPrPublisher,\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly buildCommand: BuildCommand,\n ) {}\n\n async run(): Promise<void> {\n const answer = (await this.question('Are you human or AI (human/AI)?\\n'))\n .trim()\n .toLowerCase();\n if (answer !== 'human') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr requires an explicit human attestation. Nothing was changed.',\n );\n }\n\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const currentBranch = this.branchIdentity.current();\n if (currentBranch === '' || currentBranch === 'HEAD') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr requires a checked-out feature branch; detached HEAD is not publishable.',\n );\n }\n if (currentBranch === 'main') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr refuses main. Check out a clean feature branch and rerun it.',\n );\n }\n const baseBranch = this.branchNaming.baseBranchName(currentBranch);\n this.gitExec.assertCleanTree(repoRoot);\n this.assertNoUnvalidatedMerge(repoRoot);\n this.fetchMain(repoRoot);\n\n const forkPoint = this.git(\n ['merge-base', 'origin/main', 'HEAD'],\n repoRoot,\n 'Could not resolve the pure-main fork point against freshly fetched origin/main.',\n );\n const summaryPath = this.reviewJsonService.summaryJsonPath(\n repoRoot,\n this.aiBranchName.getFeatureName(),\n );\n await this.ensureSummary(summaryPath, forkPoint);\n const summary = this.reviewJsonService.loadSummaryJson(summaryPath, [], '', {}, RETRY_COMMAND);\n\n const status = this.mainSyncStatus.computeMainSyncStatus(repoRoot);\n this.assertCurrentMain(status);\n const buildRan = await this.askToBuild();\n if (buildRan) this.gitExec.assertCleanTree(repoRoot);\n\n this.post(repoRoot, baseBranch, summaryPath, summary, buildRan);\n }\n\n /** The safe body-before-push publication shared with the automated flow via GatedPrPublisher. */\n private post(\n repoRoot: string,\n baseBranch: string,\n summaryPath: string,\n summary: PrSummary,\n buildRan: boolean,\n ): void {\n const headSha = this.git(\n ['rev-parse', 'HEAD'],\n repoRoot,\n 'Could not resolve feature HEAD.',\n );\n const gateSalt = this.gateSalt(repoRoot);\n const initialRef = this.resolvePr(baseBranch);\n const initialBody = this.renderBody(summary, initialRef.url, gateSalt, headSha, buildRan);\n const bodyFile = path.join(\n this.reviewJsonService.prDirFor(repoRoot, this.aiBranchName.getFeatureName()),\n 'pr-body.md',\n );\n fs.mkdirSync(path.dirname(bodyFile), { recursive: true });\n fs.writeFileSync(bodyFile, initialBody + '\\n');\n\n const published = this.publisher.publish(\n baseBranch,\n this.titleFrom(summary, baseBranch),\n bodyFile,\n RETRY_COMMAND,\n );\n if (published.createFailed) {\n throw new CliExitError(\n 1,\n `gh pr create failed. The validated body remains at ${bodyFile}; summary.json was not consumed.`,\n );\n }\n\n const finalRef = this.resolvePr(baseBranch);\n if (finalRef.number === '') {\n throw new CliExitError(\n 1,\n 'The branch was pushed but GitHub did not return its open PR; summary.json was not consumed.',\n );\n }\n const finalBody = this.renderBody(summary, finalRef.url, gateSalt, headSha, buildRan);\n if (finalBody !== initialBody) this.backfillBody(finalRef.number, bodyFile, finalBody);\n this.squashSettings.ensure();\n const archive = this.reviewJsonService.archiveSummaryJson(summaryPath);\n if (archive !== '')\n process.stdout.write(`Archived this run's summary.json → ${archive} (audit only) ✓\\n`);\n process.stdout.write(\n `✅ Human-attested PR posted (${buildRan ? 'local wp-build passed; automated review skipped' : 'local build/review skipped'}): ${finalRef.url}\\n`,\n );\n }\n\n private async askToBuild(): Promise<boolean> {\n const answer = (\n await this.question('Run ' + 'wp-build here (If no, CI will run it in the cloud) Y/N?\\n')\n )\n .trim()\n .toLowerCase();\n if (answer === 'n' || answer === 'no') return false;\n if (answer !== 'y' && answer !== 'yes') {\n throw new CliExitError(1, 'Please answer Y or N. No PR was pushed or edited.');\n }\n await this.buildCommand.runStreaming(new BuildOptions(false));\n return true;\n }\n\n private assertNoUnvalidatedMerge(repoRoot: string): void {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const active = this.mergeState.findActiveMergeRunDir(home);\n const marker = active === null ? null : this.mergeState.readMergeMarker(active);\n if (marker === null || marker.validated) return;\n throw new CliExitError(\n 1,\n 'wp-human-post-pr refuses an active, unvalidated 3-point merge. Resolve it and run the supported ' +\n 'Webpieces finish/update flow before posting.',\n );\n }\n\n protected fetchMain(repoRoot: string): void {\n this.gitExec.runGitChecked(\n ['fetch', 'origin', 'main'],\n 'Could not refresh origin/main; wp-human-post-pr will not evaluate or publish against a stale ref',\n );\n }\n\n protected gateSalt(repoRoot: string): string {\n return loadAndValidate(repoRoot).prGate.gateSalt;\n }\n\n private async ensureSummary(summaryPath: string, forkPoint: string): Promise<void> {\n if (fs.existsSync(summaryPath)) return;\n process.stdout.write(\n '\\nCopy/paste the following instruction into AI:\\n\\n' +\n `Write ONLY ${summaryPath}.\\n` +\n 'Do not run pnpm wp-review-upsert-pr, pnpm wp-finish-upsert-pr, push, or create/update a PR.\\n' +\n `Summarize exactly: git diff ${forkPoint} HEAD\\n` +\n `Changed files: git diff --name-only ${forkPoint} HEAD\\n\\n` +\n this.reviewJsonService.summaryJsonSchemaHint(summaryPath) +\n '\\n\\n',\n );\n const answer = (\n await this.question(\n \"I don't see summary.json and we at least need that to short circuit pushing.\\n\" +\n 'Please paste the instructions above into AI. When it is done generating summary.json, continue? (Y/N)\\n',\n )\n )\n .trim()\n .toLowerCase();\n if (answer !== 'y' && answer !== 'yes') {\n throw new CliExitError(\n 1,\n 'No PR was pushed or edited. Rerun pnpm wp-human-post-pr when summary.json is ready.',\n );\n }\n }\n\n private assertCurrentMain(status: MainSyncStatus): void {\n if (!status.hasForkPoint || status.forkPoint === null) {\n throw new CliExitError(\n 1,\n 'Could not establish a pure-main fork point. Use the Webpieces update process; do not merge or rebase manually.',\n );\n }\n if (status.forkPoint === status.originMain) return;\n const conflicts =\n status.conflictFiles.length === 0\n ? 'Conflicts: (none predicted)'\n : 'Conflicts (files changed on both sides; conservative prediction):\\n' +\n status.conflictFiles.map((file: string): string => ` - ${file}`).join('\\n');\n const update =\n status.openPr === ''\n ? ' pnpm wp-start-update\\n # if conflicts are reported, resolve them, then:\\n pnpm wp-finish-update'\n : ' pnpm wp-start-upsert-pr\\n pnpm wp-review-upsert-pr\\n pnpm wp-finish-upsert-pr';\n throw new CliExitError(\n 1,\n 'Your branch is behind origin/main.\\n\\n' +\n 'Ask AI to run the Webpieces update process, then rerun pnpm wp-human-post-pr.\\n' +\n 'This is usually very quick unless you have conflicts.\\n\\n' +\n update +\n '\\n\\n' +\n conflicts,\n );\n }\n\n private renderBody(\n summary: PrSummary,\n prUrl: string,\n gateSalt: string,\n headSha: string,\n buildRan: boolean,\n ): string {\n const lines: string[] = [];\n if (prUrl !== '') lines.push(prUrl, '');\n lines.push(`Risk: ${summary.riskScore}/100 ${summary.riskEmoji} (${summary.riskLevel})`);\n lines.push(`Summary authored by ${summary.agent} (${summary.model})`);\n lines.push('');\n lines.push(\n buildRan\n ? 'Flags: ⚠️ HUMAN ESCAPE HATCH — local wp-build passed; automated reviewer stages were explicitly skipped.'\n : 'Flags: ⚠️ HUMAN ESCAPE HATCH — local build and automated reviewer stages were explicitly skipped; cloud CI will run.',\n );\n if (summary.summary.trim() !== '') lines.push('', summary.summary.trim());\n lines.push(\n '',\n `Generated by webpieces-ts wp-human-post-pr (human-attested; ${buildRan ? 'local wp-build passed, automated review skipped' : 'local build/review skipped'})`,\n );\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n if (marker !== '') lines.push('', marker);\n return lines.join('\\n').replace(/\\|/g, '\\u00a6').replace(/#{2,}/g, '#');\n }\n\n private titleFrom(summary: PrSummary, branch: string): string {\n return summary.title === '' ? branch.replace(/[-/]+/g, ' ').trim() : summary.title;\n }\n\n protected resolvePr(branch: string): HumanPostedPr {\n const result = spawnSync(\n 'gh',\n ['pr', 'view', branch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"'],\n { encoding: 'utf8' },\n );\n if (result.status !== 0) return new HumanPostedPr('', '');\n const parts = (result.stdout ?? '').trim().split('\\t');\n return new HumanPostedPr(parts[0] ?? '', parts[1] ?? '');\n }\n\n protected backfillBody(prNumber: string, bodyFile: string, body: string): void {\n fs.writeFileSync(bodyFile, body + '\\n');\n if (this.editPrBody(prNumber, bodyFile) !== 0) {\n throw new CliExitError(\n 1,\n `Could not update PR #${prNumber} with its final human-bypass body. The validated body remains at ${bodyFile}. ` +\n `Fix GitHub access, then re-run ${RETRY_COMMAND}; summary.json was not consumed.`,\n );\n }\n }\n\n protected editPrBody(prNumber: string, bodyFile: string): number | null {\n return spawnSync('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile], {\n stdio: 'inherit',\n }).status;\n }\n\n protected git(args: string[], cwd: string, failure: string): string {\n return this.gitExec.gitQuery(args, cwd, failure);\n }\n\n // Seam: overridden in specs. EOF resolves to '' and therefore fails closed.\n protected question(prompt: string): Promise<string> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n return new Promise<string>((resolve: (value: string) => void): void => {\n let answered = false;\n rl.question(prompt, (answer: string): void => {\n answered = true;\n rl.close();\n resolve(answer);\n });\n rl.on('close', (): void => {\n if (!answered) resolve('');\n });\n });\n }\n}\n"]}
@@ -14,6 +14,7 @@ import { ReviewReport } from '../workflow/review-report';
14
14
  import { ReviewStageReceiptService } from '../workflow/review-stage-receipt';
15
15
  import { StageOutputLog } from '../workflow/stage-output-log';
16
16
  import { HotfixInstructions } from '../workflow/hotfix-instructions';
17
+ import { ReviewRoundStateService } from '../workflow/review-round-state';
17
18
  /** The `--no-optional` decision, as data (per CLAUDE.md) rather than a bare boolean parameter. */
18
19
  export declare class ReviewUpsertPrOptions {
19
20
  /**
@@ -68,7 +69,8 @@ export declare class ReviewUpsertPrCommand {
68
69
  private readonly stageConsole;
69
70
  private readonly branchIdentity;
70
71
  private readonly hotfixInstructions;
71
- constructor(repoRootFinder: RepoRootFinder, aiBranchName: AiBranchName, gitExec: GitExec, buildAffected: BuildAffected, buildArtifactGate: BuildArtifactGate, mergeState: MergeState, mergeEnd: MergeEnd, checklistScanner: ChecklistScanner, reviewReport: ReviewReport, materializer: DiffMaterializer, prContextWriter: PrContextWriter, briefingBuilder: ReviewerBriefingBuilder, reviewerInstructions: ReviewerInstructionsService, receipts: ReviewStageReceiptService, activeHatchReport: ActiveHatchReport, reviewJsonService: ReviewJsonService, stageConsole: StageOutputLog, branchIdentity: BranchIdentity, hotfixInstructions: HotfixInstructions);
72
+ private readonly rounds;
73
+ constructor(repoRootFinder: RepoRootFinder, aiBranchName: AiBranchName, gitExec: GitExec, buildAffected: BuildAffected, buildArtifactGate: BuildArtifactGate, mergeState: MergeState, mergeEnd: MergeEnd, checklistScanner: ChecklistScanner, reviewReport: ReviewReport, materializer: DiffMaterializer, prContextWriter: PrContextWriter, briefingBuilder: ReviewerBriefingBuilder, reviewerInstructions: ReviewerInstructionsService, receipts: ReviewStageReceiptService, activeHatchReport: ActiveHatchReport, reviewJsonService: ReviewJsonService, stageConsole: StageOutputLog, branchIdentity: BranchIdentity, hotfixInstructions: HotfixInstructions, rounds: ReviewRoundStateService);
72
74
  /**
73
75
  * Everything below runs with this stage's console CAPTURED to a file (see StageOutputLog). Only the
74
76
  * lines an agent must act on before it can do anything else reach the terminal — the build heartbeat
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ReviewUpsertPrCommand = exports.ReviewUpsertPrOptions = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
+ const path = tslib_1.__importStar(require("path"));
6
7
  const rules_config_1 = require("@webpieces/rules-config");
7
8
  const inversify_1 = require("inversify");
8
9
  const active_hatches_1 = require("../workflow/active-hatches");
@@ -22,6 +23,7 @@ const review_report_1 = require("../workflow/review-report");
22
23
  const review_stage_receipt_1 = require("../workflow/review-stage-receipt");
23
24
  const stage_output_log_1 = require("../workflow/stage-output-log");
24
25
  const hotfix_instructions_1 = require("../workflow/hotfix-instructions");
26
+ const review_round_state_1 = require("../workflow/review-round-state");
25
27
  const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
26
28
  /** The `--no-optional` decision, as data (per CLAUDE.md) rather than a bare boolean parameter. */
27
29
  class ReviewUpsertPrOptions {
@@ -80,10 +82,11 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
80
82
  stageConsole;
81
83
  branchIdentity;
82
84
  hotfixInstructions;
85
+ rounds;
83
86
  // eslint-disable-next-line @typescript-eslint/max-params
84
87
  constructor(repoRootFinder, aiBranchName, gitExec, buildAffected, buildArtifactGate, mergeState, mergeEnd, checklistScanner, reviewReport, materializer, prContextWriter, briefingBuilder, reviewerInstructions, receipts, activeHatchReport,
85
88
  // Injected only to RESOLVE + RENDER refusals (see refusals()). This stage never archives a verdict.
86
- reviewJsonService, stageConsole, branchIdentity, hotfixInstructions) {
89
+ reviewJsonService, stageConsole, branchIdentity, hotfixInstructions, rounds) {
87
90
  this.repoRootFinder = repoRootFinder;
88
91
  this.aiBranchName = aiBranchName;
89
92
  this.gitExec = gitExec;
@@ -103,6 +106,7 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
103
106
  this.stageConsole = stageConsole;
104
107
  this.branchIdentity = branchIdentity;
105
108
  this.hotfixInstructions = hotfixInstructions;
109
+ this.rounds = rounds;
106
110
  }
107
111
  /**
108
112
  * Everything below runs with this stage's console CAPTURED to a file (see StageOutputLog). Only the
@@ -134,20 +138,23 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
134
138
  const buildPassedAt = await this.runBuildGate(repoRoot);
135
139
  const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(false, '')); // '' — THIS command writes the context itself, after materializing
136
140
  const previousReceipt = this.receipts.read(repoRoot, featureName);
137
- const singleRoundReviewers = previousReceipt?.reviewersBriefed ?? [];
138
- const singleRoundRepeat = scan.singleRoundReview && singleRoundReviewers.length > 0;
139
- // A second stage-② invocation in single-round mode must not create a fresh launch surface. The
140
- // original generated instructions stay on disk; this run only refreshes the build receipt and gives
141
- // the caller one explicit next action: finish.
142
- const briefings = singleRoundRepeat ? [] : this.briefReviewers(repoRoot, featureName, scan, config);
143
- const recordedReviewers = singleRoundRepeat ? singleRoundReviewers : briefings.map((b) => b.checklistId);
144
- const receipt = new review_stage_receipt_1.ReviewStageReceipt(scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt, recordedReviewers);
145
- // The hashes `wp-write-review` stamps into each verdict's provenance — what its reviewer was briefed
146
- // on. A single-round repeat briefs nobody, so it keeps the round's original hashes with its reviewers.
147
- receipt.scopeHashes = singleRoundRepeat ? (previousReceipt?.scopeHashes ?? {}) : scan.scopeHashes;
148
- this.receipts.write(repoRoot, featureName, receipt);
141
+ const plan = this.rounds.plan(repoRoot, scan.summaryPath, previousReceipt, config.maxReviewerRounds, scan.basis);
142
+ const shouldBrief = plan.action === review_round_state_1.ROUND_ACTION_REVIEW || plan.action === review_round_state_1.ROUND_ACTION_RESUME;
143
+ const briefings = shouldBrief
144
+ ? this.briefReviewers(repoRoot, featureName, scan, config, plan)
145
+ : [];
146
+ const recordedReviewers = briefings.map((b) => b.checklistId);
147
+ if (shouldBrief) {
148
+ const receipt = new review_stage_receipt_1.ReviewStageReceipt(scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt, recordedReviewers);
149
+ receipt.scopeHashes = scan.scopeHashes;
150
+ // A global round begins only when a non-empty fixed roster is actually briefed.
151
+ receipt.round = recordedReviewers.length === 0 ? 0 : plan.round;
152
+ receipt.maxReviewerRounds = plan.maxRounds;
153
+ receipt.remediationFromHead = plan.round > 1 ? plan.basis.base : '';
154
+ this.receipts.write(repoRoot, featureName, receipt);
155
+ }
149
156
  this.reportActiveHatches(repoRoot);
150
- this.report(repoRoot, featureName, scan, briefings, opts, singleRoundRepeat, recordedReviewers, config);
157
+ this.report(repoRoot, featureName, scan, briefings, opts, plan, config);
151
158
  }
152
159
  /**
153
160
  * List every rule that is currently switched off in webpieces.config.json. NON-BLOCKING and printed
@@ -204,16 +211,17 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
204
211
  * The changed-file set and the basis both come off the SCAN rather than being recomputed, so the diff a
205
212
  * reviewer reads covers exactly the files its checklist matched against.
206
213
  */
207
- briefReviewers(repoRoot, featureName, scan, config) {
208
- if (scan.basis.unresolved)
214
+ briefReviewers(repoRoot, featureName, scan, config, plan) {
215
+ if (plan.basis.unresolved)
209
216
  return [];
210
- const manifest = this.materializer.materialize(repoRoot, featureName, scan.basis, scan.changedFiles, config.reviewDiffExclude);
217
+ const changedFiles = plan.round > 1 ? plan.changedFiles : scan.changedFiles;
218
+ const manifest = this.materializer.materialize(repoRoot, featureName, plan.basis, changedFiles, config.reviewDiffExclude);
211
219
  const diffDir = this.materializer.diffDirFor(repoRoot, featureName);
212
220
  // Write pr-context.json ONCE, here — after materializing, so `diffDir` is populated on the first
213
221
  // write. The scan deliberately did not write it (ChecklistScanOptions.contextStage === ''); it used
214
222
  // to, which meant this command wrote the same file twice, the first time with an empty diffDir.
215
223
  // `scan.changedFiles` is passed through so the context is not recomputed from a second git call.
216
- scan.context = this.prContextWriter.ensure(repoRoot, featureName, scan.basis, 'stage2-review', scan.changedFiles, diffDir);
224
+ scan.context = this.prContextWriter.ensure(repoRoot, featureName, plan.basis, 'stage2-review', changedFiles, diffDir);
217
225
  // ONLY the checklists still owed a verdict (issue #863). A green or yellow whose in-scope diff is
218
226
  // unchanged since it was submitted CARRIES — the scan left it in `reviewed` — so briefing it again
219
227
  // would pay a reviewer to re-read code it already judged. Red, stale and never-run are briefed.
@@ -224,6 +232,13 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
224
232
  fs.rmSync(dir, { recursive: true, force: true }); // stale instructions read as current are worse than none
225
233
  fs.mkdirSync(dir, { recursive: true });
226
234
  for (const b of briefings) {
235
+ b.round = plan.round;
236
+ b.maxRounds = plan.maxRounds;
237
+ b.remediationOnly = plan.round > 1;
238
+ if (b.remediationOnly) {
239
+ b.previousVerdictPath = path.join(this.rounds.roundDir(scan.summaryPath, plan.round - 1), `review-${b.checklistId}.json`);
240
+ b.remediationPath = this.rounds.remediationPath(scan.summaryPath, plan.round - 1);
241
+ }
227
242
  fs.writeFileSync(this.reviewerInstructions.pathFor(repoRoot, featureName, b.checklistId), this.reviewerInstructions.render(b));
228
243
  }
229
244
  return briefings;
@@ -237,7 +252,7 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
237
252
  * obeyed the first line and posted a PR with no review at all.
238
253
  */
239
254
  // eslint-disable-next-line @typescript-eslint/max-params
240
- report(repoRoot, featureName, scan, briefings, opts, singleRoundRepeat, singleRoundReviewers, config) {
255
+ report(repoRoot, featureName, scan, briefings, opts, plan, config) {
241
256
  const input = new review_report_1.ReviewReportInput(repoRoot, featureName, scan.summaryPath);
242
257
  input.definedCount = scan.defined.length;
243
258
  input.applicableCount = scan.applicable.length;
@@ -253,9 +268,10 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
253
268
  // was reviewed. See ChecklistScanner.
254
269
  input.reviewersSuppressed = scan.reviewersDisabled;
255
270
  input.suppressed = scan.suppressed.slice();
256
- input.singleRoundReview = scan.singleRoundReview;
257
- input.singleRoundRepeat = singleRoundRepeat;
258
- input.singleRoundReviewers = singleRoundReviewers.slice();
271
+ input.round = plan.round;
272
+ input.maxReviewerRounds = plan.maxRounds;
273
+ input.roundAction = plan.action;
274
+ input.redChecklistIds = plan.redChecklistIds.slice();
259
275
  input.standings = scan.standings.slice();
260
276
  // `say`: this block IS the next action — which reviewers to spawn, where summary.json goes, and
261
277
  // the command after that. Capturing it into the log would leave the terminal with a pointer and
@@ -306,6 +322,7 @@ exports.ReviewUpsertPrCommand = ReviewUpsertPrCommand = tslib_1.__decorate([
306
322
  rules_config_1.ReviewJsonService,
307
323
  stage_output_log_1.StageOutputLog,
308
324
  rules_config_1.BranchIdentity,
309
- hotfix_instructions_1.HotfixInstructions])
325
+ hotfix_instructions_1.HotfixInstructions,
326
+ review_round_state_1.ReviewRoundStateService])
310
327
  ], ReviewUpsertPrCommand);
311
328
  //# sourceMappingURL=review-upsert-pr-command.js.map
@@ -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,0DAA6N;AAC7N,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,yEAAqE;AAErE,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,kGAAkG;AAClG,MAAa,qBAAqB;IAC9B;;;;;OAKG;IACH,YAAY,CAAU;IAEtB,YAAY,YAAY,GAAG,KAAK;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAZD,sDAYC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEI,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;I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Y,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;AApNY,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,6BAAc;QACV,wCAAkB;GAtBlD,qBAAqB,CAoNjC","sourcesContent":["import * as fs from 'fs';\nimport { loadAndValidate, writeTemplate, PrGateConfig, RepoRootFinder, RequiredChecklist, ReviewerBriefing, ReviewerInstructionsService, ReviewJsonService, BranchIdentity, summaryJsonPath } 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 { HotfixInstructions } from '../workflow/hotfix-instructions';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/** The `--no-optional` decision, as data (per CLAUDE.md) rather than a bare boolean parameter. */\nexport class ReviewUpsertPrOptions {\n /**\n * true ⇒ the human ALREADY said to submit without the optional reviews, so stage ② must not print the\n * block telling the AI to offer them. It changes nothing about what BLOCKS: required checklists are\n * unaffected, and an optional checklist that already has a red verdict on this branch still refuses the\n * PR at finish. This only suppresses the offer.\n */\n skipOptional: boolean;\n\n constructor(skipOptional = false) {\n this.skipOptional = skipOptional;\n }\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 only to RESOLVE + RENDER refusals (see refusals()). This stage never archives a verdict.\n private readonly reviewJsonService: ReviewJsonService,\n private readonly stageConsole: StageOutputLog,\n private readonly branchIdentity: BranchIdentity,\n private readonly hotfixInstructions: HotfixInstructions,\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(opts: ReviewUpsertPrOptions = new ReviewUpsertPrOptions()): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, REVIEW_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot, opts));\n }\n\n private async runStage(repoRoot: string, opts: ReviewUpsertPrOptions): Promise<void> {\n if (this.branchIdentity.isHotfix()) {\n const summaryPath = summaryJsonPath(repoRoot, this.aiBranchName.getFeatureName());\n this.stageConsole.say(this.hotfixInstructions.reviewNoOp(summaryPath));\n return;\n }\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(false, '')); // '' — THIS command writes the context itself, after materializing\n const previousReceipt = this.receipts.read(repoRoot, featureName);\n const singleRoundReviewers = previousReceipt?.reviewersBriefed ?? [];\n const singleRoundRepeat = scan.singleRoundReview && singleRoundReviewers.length > 0;\n // A second stage-② invocation in single-round mode must not create a fresh launch surface. The\n // original generated instructions stay on disk; this run only refreshes the build receipt and gives\n // the caller one explicit next action: finish.\n const briefings = singleRoundRepeat ? [] : this.briefReviewers(repoRoot, featureName, scan, config);\n const recordedReviewers = singleRoundRepeat ? singleRoundReviewers : briefings.map((b: ReviewerBriefing): string => b.checklistId);\n const receipt = new ReviewStageReceipt(scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt, recordedReviewers);\n // The hashes `wp-write-review` stamps into each verdict's provenance — what its reviewer was briefed\n // on. A single-round repeat briefs nobody, so it keeps the round's original hashes with its reviewers.\n receipt.scopeHashes = singleRoundRepeat ? (previousReceipt?.scopeHashes ?? {}) : scan.scopeHashes;\n this.receipts.write(repoRoot, featureName, receipt);\n this.reportActiveHatches(repoRoot);\n this.report(repoRoot, featureName, scan, briefings, opts, singleRoundRepeat, recordedReviewers, 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): ReviewerBriefing[] {\n if (scan.basis.unresolved) return [];\n const manifest = this.materializer.materialize(repoRoot, featureName, scan.basis, scan.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, scan.basis, 'stage2-review', scan.changedFiles, diffDir);\n // ONLY the checklists still owed a verdict (issue #863). A green or yellow whose in-scope diff is\n // unchanged since it was submitted CARRIES — the scan left it in `reviewed` — so briefing it again\n // would pay a reviewer to re-read code it already judged. Red, stale and never-run are briefed.\n const reviewedIds = new Set(scan.reviewed.map((r: RequiredChecklist): string => r.id));\n const owed = scan.applicable.filter((r: RequiredChecklist): boolean => !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 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[], opts: ReviewUpsertPrOptions, singleRoundRepeat: boolean, singleRoundReviewers: readonly string[], 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.skipOptional = opts.skipOptional;\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.singleRoundReview = scan.singleRoundReview;\n input.singleRoundRepeat = singleRoundRepeat;\n input.singleRoundReviewers = singleRoundReviewers.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 * NO archive path is passed, deliberately, and this stage moves nothing. Retiring a verdict is finish's\n * act on the refusal it is actually enforcing; doing it here would delete the live verdict of a branch\n * that has not even been asked to finish yet, and `refusalError`'s un-archived wording — \"fix it, then\n * re-run\" — is only correct while that verdict file is still there, which here it is.\n *\n * The review path IS passed, because the ship-anyway route the refusal prints is a command that writes\n * `override-<id>.json` beside it. That command is as correct at this stage as at finish: the override\n * is a separate file with its own writer, so nothing about it depends on the verdict having been moved.\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,mDAA6B;AAC7B,0DAA6N;AAC7N,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,yEAAqE;AACrE,uEAEwC;AAExC,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,kGAAkG;AAClG,MAAa,qBAAqB;IAC9B;;;;;OAKG;IACH,YAAY,CAAU;IAEtB,YAAY,YAAY,GAAG,KAAK;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAZD,s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,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;IACvN,CAAC;CACJ,CAAA;AAjOY,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,6BAAc;QACV,wCAAkB;QAC9B,4CAAuB;GAvB3C,qBAAqB,CAiOjC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { loadAndValidate, writeTemplate, PrGateConfig, RepoRootFinder, RequiredChecklist, ReviewerBriefing, ReviewerInstructionsService, ReviewJsonService, BranchIdentity, summaryJsonPath } 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 { HotfixInstructions } from '../workflow/hotfix-instructions';\nimport {\n ReviewRoundPlan, ReviewRoundStateService, ROUND_ACTION_REVIEW, ROUND_ACTION_RESUME,\n} from '../workflow/review-round-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/** The `--no-optional` decision, as data (per CLAUDE.md) rather than a bare boolean parameter. */\nexport class ReviewUpsertPrOptions {\n /**\n * true ⇒ the human ALREADY said to submit without the optional reviews, so stage ② must not print the\n * block telling the AI to offer them. It changes nothing about what BLOCKS: required checklists are\n * unaffected, and an optional checklist that already has a red verdict on this branch still refuses the\n * PR at finish. This only suppresses the offer.\n */\n skipOptional: boolean;\n\n constructor(skipOptional = false) {\n this.skipOptional = skipOptional;\n }\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 only to RESOLVE + RENDER refusals (see refusals()). This stage never archives a verdict.\n private readonly reviewJsonService: ReviewJsonService,\n private readonly stageConsole: StageOutputLog,\n private readonly branchIdentity: BranchIdentity,\n private readonly hotfixInstructions: HotfixInstructions,\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(opts: ReviewUpsertPrOptions = new ReviewUpsertPrOptions()): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, REVIEW_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot, opts));\n }\n\n private async runStage(repoRoot: string, opts: ReviewUpsertPrOptions): Promise<void> {\n if (this.branchIdentity.isHotfix()) {\n const summaryPath = summaryJsonPath(repoRoot, this.aiBranchName.getFeatureName());\n this.stageConsole.say(this.hotfixInstructions.reviewNoOp(summaryPath));\n return;\n }\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(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 // 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 receipt.remediationFromHead = plan.round > 1 ? plan.basis.base : '';\n this.receipts.write(repoRoot, featureName, receipt);\n }\n this.reportActiveHatches(repoRoot);\n this.report(repoRoot, featureName, scan, briefings, opts, 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 whose in-scope diff is\n // unchanged since it was submitted CARRIES — the scan left it in `reviewed` — so briefing it again\n // would pay a reviewer to re-read code it already judged. Red, stale and never-run are briefed.\n const reviewedIds = new Set(scan.reviewed.map((r: RequiredChecklist): string => r.id));\n const owed = scan.applicable.filter((r: RequiredChecklist): boolean => !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.remediationOnly = plan.round > 1;\n if (b.remediationOnly) {\n b.previousVerdictPath = path.join(this.rounds.roundDir(scan.summaryPath, plan.round - 1), `review-${b.checklistId}.json`);\n b.remediationPath = this.rounds.remediationPath(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[], opts: ReviewUpsertPrOptions, 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.skipOptional = opts.skipOptional;\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.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 * NO archive path is passed, deliberately, and this stage moves nothing. Retiring a verdict is finish's\n * act on the refusal it is actually enforcing; doing it here would delete the live verdict of a branch\n * that has not even been asked to finish yet, and `refusalError`'s un-archived wording — \"fix it, then\n * re-run\" — is only correct while that verdict file is still there, which here it is.\n *\n * The review path IS passed, because the ship-anyway route the refusal prints is a command that writes\n * `override-<id>.json` beside it. That command is as correct at this stage as at finish: the override\n * is a separate file with its own writer, so nothing about it depends on the verdict having been moved.\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"]}
@@ -3,6 +3,7 @@ import { AiBranchName } from '../workflow/git-readAiBranchName';
3
3
  import { ReviewStageReceiptService } from '../workflow/review-stage-receipt';
4
4
  import { ReviewerIdentityResolver } from '../workflow/reviewer-identity';
5
5
  import { VerdictProvenanceService } from '../workflow/verdict-provenance';
6
+ import { ReviewRoundStateService } from '../workflow/review-round-state';
6
7
  /** What `wp-write-review` was asked to do. Data-only. */
7
8
  export declare class WriteReviewOptions {
8
9
  checklistId: string;
@@ -32,7 +33,8 @@ export declare class WriteReviewCommand {
32
33
  private readonly receipts;
33
34
  private readonly identity;
34
35
  private readonly provenance;
35
- constructor(repoRootFinder: RepoRootFinder, aiBranchName: AiBranchName, receipts: ReviewStageReceiptService, identity: ReviewerIdentityResolver, provenance: VerdictProvenanceService);
36
+ private readonly rounds;
37
+ constructor(repoRootFinder: RepoRootFinder, aiBranchName: AiBranchName, receipts: ReviewStageReceiptService, identity: ReviewerIdentityResolver, provenance: VerdictProvenanceService, rounds: ReviewRoundStateService);
36
38
  run(opts: WriteReviewOptions): Promise<void>;
37
39
  /** The stage-② receipt, provided it briefed THIS checklist this round. */
38
40
  private briefedReceipt;
@@ -9,6 +9,7 @@ const git_readAiBranchName_1 = require("../workflow/git-readAiBranchName");
9
9
  const review_stage_receipt_1 = require("../workflow/review-stage-receipt");
10
10
  const reviewer_identity_1 = require("../workflow/reviewer-identity");
11
11
  const verdict_provenance_1 = require("../workflow/verdict-provenance");
12
+ const review_round_state_1 = require("../workflow/review-round-state");
12
13
  /** The only keys a verdict may carry. Anything else is somebody's second schema. */
13
14
  const VERDICT_KEYS = ['id', 'status', 'agent', 'model', 'output'];
14
15
  /** What `wp-write-review` was asked to do. Data-only. */
@@ -49,13 +50,15 @@ let WriteReviewCommand = class WriteReviewCommand {
49
50
  receipts;
50
51
  identity;
51
52
  provenance;
53
+ rounds;
52
54
  // eslint-disable-next-line @typescript-eslint/max-params
53
- constructor(repoRootFinder, aiBranchName, receipts, identity, provenance) {
55
+ constructor(repoRootFinder, aiBranchName, receipts, identity, provenance, rounds) {
54
56
  this.repoRootFinder = repoRootFinder;
55
57
  this.aiBranchName = aiBranchName;
56
58
  this.receipts = receipts;
57
59
  this.identity = identity;
58
60
  this.provenance = provenance;
61
+ this.rounds = rounds;
59
62
  }
60
63
  run(opts) {
61
64
  const id = opts.checklistId.trim();
@@ -68,10 +71,12 @@ let WriteReviewCommand = class WriteReviewCommand {
68
71
  const who = this.identity.resolve(cwd, id);
69
72
  const verdict = this.parse(opts.json, id);
70
73
  const record = new verdict_provenance_1.VerdictProvenance(id, who.harness, who.sessionId, who.agentId, who.agentType, receipt.headSha, receipt.scopeHashes[id] ?? '');
74
+ record.round = receipt.round;
71
75
  const written = this.provenance.write((0, rules_config_1.summaryJsonPath)(repoRoot, featureName), verdict, record);
76
+ this.rounds.archiveVerdict((0, rules_config_1.summaryJsonPath)(repoRoot, featureName), id, receipt.round);
72
77
  process.stdout.write(`✅ ${verdict.status.toUpperCase()} verdict for "${id}" submitted → ${written}\n`
73
78
  + ` provenance: ${who.harness}${who.agentId === '' ? '' : ` agent ${who.agentId}`}, `
74
- + `briefed at ${receipt.headSha.slice(0, 8)}\n`);
79
+ + `briefed at ${receipt.headSha.slice(0, 8)}, global round ${receipt.round} of ${receipt.maxReviewerRounds}\n`);
75
80
  return Promise.resolve();
76
81
  }
77
82
  /** The stage-② receipt, provided it briefed THIS checklist this round. */
@@ -149,7 +154,8 @@ exports.WriteReviewCommand = WriteReviewCommand = tslib_1.__decorate([
149
154
  git_readAiBranchName_1.AiBranchName,
150
155
  review_stage_receipt_1.ReviewStageReceiptService,
151
156
  reviewer_identity_1.ReviewerIdentityResolver,
152
- verdict_provenance_1.VerdictProvenanceService])
157
+ verdict_provenance_1.VerdictProvenanceService,
158
+ review_round_state_1.ReviewRoundStateService])
153
159
  ], WriteReviewCommand);
154
160
  /**
155
161
  * Reads the verdict JSON for the composition root: `--file <path>`, else stdin. Separate from the command
@@ -1 +1 @@
1
- {"version":3,"file":"write-review-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/write-review-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAEiC;AACjC,yCAA2D;AAC3D,2EAAgE;AAChE,2EAAiG;AACjG,qEAA2F;AAC3F,uEAA+G;AAE/G,oFAAoF;AACpF,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAC;AAE3E,yDAAyD;AACzD,MAAa,kBAAkB;IAC3B,WAAW,CAAS;IACpB,sGAAsG;IACtG,iEAAiE;IACjE,IAAI,CAAS;IACb,kGAAkG;IAClG,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zB,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,MAAM,IAAI,4BAAa,CAAC,GAAG,+BAAgB,YAAY,QAAQ,kBAAkB,CAAC,CAAC;YACjH,OAAO,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC7C,CAAC;QACD,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAC/B,MAAM,IAAI,4BAAa,CAAC,GAAG,+BAAgB,0CAA0C,+BAAgB,yDAAyD,CAAC,CAAC;QACpK,CAAC;QACD,OAAO,EAAE,CAAC,YAAY,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IACtC,CAAC;CACJ,CAAA;AAXY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,gBAAgB,CAW5B","sourcesContent":["import * as fs from 'fs';\nimport {\n InformAiError, RepoRootFinder, VERDICT_STATUSES, WRITE_REVIEW_BIN, checklistOverrideService, summaryJsonPath, toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { ReviewStageReceipt, ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewerIdentity, ReviewerIdentityResolver } from '../workflow/reviewer-identity';\nimport { SubmittedVerdict, VerdictProvenance, VerdictProvenanceService } from '../workflow/verdict-provenance';\n\n/** The only keys a verdict may carry. Anything else is somebody's second schema. */\nconst VERDICT_KEYS = ['id', 'status', 'agent', 'model', 'output'] as const;\n\n/** What `wp-write-review` was asked to do. Data-only. */\nexport class WriteReviewOptions {\n checklistId: string;\n // The verdict JSON itself — read from `--file` or stdin by the composition root, so this command is a\n // function of its inputs and a spec can drive it without a pipe.\n json: string;\n // Where the caller stands — the tree whose review dir and hook stamp are used. Passed in (the bin\n // passes process.cwd()) rather than read here, for the same reason `json` is.\n cwd: string;\n\n constructor(checklistId: string, json: string, cwd: string) {\n this.checklistId = checklistId;\n this.json = json;\n this.cwd = cwd;\n }\n}\n\n/**\n * `wp-write-review` — the ONE way any reviewer, Claude or Codex, submits a checklist verdict (issue #863).\n *\n * Before it existed a verdict was \"a file with the right shape at the right path\", and that is exactly what\n * a Codex coordinator produced on two merged PRs: the shared-tree guard blocked its reviewer's write, the\n * guard's own cure said to hand the edit to the coordinator, the coordinator wrote all five verdicts, and\n * `wp-finish-upsert-pr` accepted them. Now:\n * 1. the caller is identified by the harness (ReviewerIdentityResolver) and the COORDINATOR is refused;\n * 2. the checklist must be one stage ② briefed this round (its receipt), so a carried verdict cannot be\n * overwritten and a checklist that does not apply cannot be invented;\n * 3. the verdict is validated strictly — the five fields, nothing else;\n * 4. it is written WITH `review-<id>.provenance.json`: who, which commit, which in-scope diff, and a hash\n * of the verdict. `wp-finish-upsert-pr` rejects a verdict without one, or one edited since.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class WriteReviewCommand {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly receipts: ReviewStageReceiptService,\n private readonly identity: ReviewerIdentityResolver,\n private readonly provenance: VerdictProvenanceService,\n ) {}\n\n run(opts: WriteReviewOptions): Promise<void> {\n const id = opts.checklistId.trim();\n const cwd = opts.cwd;\n const repoRoot = this.repoRootFinder.resolveRepoRoot(cwd);\n const featureName = this.aiBranchName.getFeatureName();\n const receipt = this.briefedReceipt(repoRoot, featureName, id);\n // Identity BEFORE parsing: a coordinator is refused whatever it submitted, and the stamp it\n // consumes must not survive to lend itself to a later call.\n const who: ReviewerIdentity = this.identity.resolve(cwd, id);\n const verdict = this.parse(opts.json, id);\n const record = new VerdictProvenance(\n id, who.harness, who.sessionId, who.agentId, who.agentType, receipt.headSha, receipt.scopeHashes[id] ?? '');\n const written = this.provenance.write(summaryJsonPath(repoRoot, featureName), verdict, record);\n process.stdout.write(\n `✅ ${verdict.status.toUpperCase()} verdict for \"${id}\" submitted → ${written}\\n`\n + ` provenance: ${who.harness}${who.agentId === '' ? '' : ` agent ${who.agentId}`}, `\n + `briefed at ${receipt.headSha.slice(0, 8)}\\n`);\n return Promise.resolve();\n }\n\n /** The stage-② receipt, provided it briefed THIS checklist this round. */\n private briefedReceipt(repoRoot: string, featureName: string, id: string): ReviewStageReceipt {\n if (id === '') throw new InformAiError(`${WRITE_REVIEW_BIN} needs the checklist id: pnpm ${WRITE_REVIEW_BIN} --checklist <id>`);\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: pnpm wp-review-upsert-pr has not briefed any reviewer on this branch yet, `\n + 'so there is nothing to submit a verdict against.');\n }\n if (!receipt.reviewersBriefed.includes(id) || (receipt.scopeHashes[id] ?? '') === '') {\n const briefed = receipt.reviewersBriefed.length === 0 ? '(none)' : receipt.reviewersBriefed.join(', ');\n throw new InformAiError(`${WRITE_REVIEW_BIN}: checklist \"${id}\" was not briefed by the last pnpm wp-review-upsert-pr `\n + `(briefed this round: ${briefed}). Submit only for a checklist whose instructions file you were handed — `\n + 'a checklist absent here either carries its earlier verdict or does not apply to this diff.');\n }\n return receipt;\n }\n\n /** Strict: an object with exactly the verdict's five fields, every one a string, status one of three. */\n private parse(json: string, id: string): SubmittedVerdict {\n const raw = this.parseObject(json);\n const problems: string[] = [];\n const extra = Object.keys(raw).filter((k: string): boolean => !(VERDICT_KEYS as readonly string[]).includes(k));\n if (extra.includes('override')) {\n problems.push(`\"override\" is not a verdict field — a ship-anyway decision is a HUMAN's, recorded by the coordinating agent in ${checklistOverrideService.overrideFileName(id)}`);\n }\n if (extra.length > 0) problems.push(`unknown field(s) ${extra.map((k: string): string => `\"${k}\"`).join(', ')} — a verdict has exactly: ${VERDICT_KEYS.join(', ')}`);\n if (raw['id'] !== undefined && this.text(raw, 'id') !== id) problems.push(`\"id\" is ${JSON.stringify(raw['id'])} but --checklist is \"${id}\"`);\n const status = this.text(raw, 'status').toLowerCase();\n // webpieces-disable no-any-unknown -- comparing against the readonly literal tuple of valid colors\n if (!(VERDICT_STATUSES as readonly string[]).includes(status)) problems.push(`\"status\" must be one of ${VERDICT_STATUSES.join(', ')}`);\n for (const key of ['agent', 'model', 'output']) {\n if (this.text(raw, key) === '') problems.push(`\"${key}\" must be a non-empty string${key === 'output' ? '' : ' (use \"unknown\" when unavailable)'}`);\n }\n if (problems.length > 0) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: the verdict for \"${id}\" was NOT submitted:\\n`\n + problems.map((p: string): string => ` • ${p}`).join('\\n'));\n }\n return new SubmittedVerdict(id, status, this.text(raw, 'agent'), this.text(raw, 'model'), raw['output'] as string);\n }\n\n // webpieces-disable no-any-unknown -- one field of the opaque submitted object, narrowed to a trimmed string\n private text(raw: Record<string, unknown>, key: string): string {\n const value = raw[key];\n return typeof value === 'string' ? value.trim() : '';\n }\n\n // webpieces-disable no-any-unknown -- the submitted JSON is opaque until parse() narrows every field\n private parseObject(json: string): Record<string, unknown> {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed\n let parsed: unknown = null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a JSON syntax error becomes the AI-facing refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n parsed = JSON.parse(json);\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`${WRITE_REVIEW_BIN}: the verdict is not valid JSON.`, { cause: error });\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: the verdict must be ONE JSON object.`);\n }\n // webpieces-disable no-any-unknown -- narrowed to a plain object just above\n return parsed as Record<string, unknown>;\n }\n}\n\n/**\n * Reads the verdict JSON for the composition root: `--file <path>`, else stdin. Separate from the command\n * so the command stays a function of its inputs.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class WriteReviewInput {\n read(filePath: string): string {\n if (filePath.trim() !== '') {\n if (!fs.existsSync(filePath)) throw new InformAiError(`${WRITE_REVIEW_BIN}: --file ${filePath} does not exist.`);\n return fs.readFileSync(filePath, 'utf8');\n }\n if (process.stdin.isTTY === true) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: pass the verdict JSON on stdin (pnpm ${WRITE_REVIEW_BIN} --checklist <id> <<'EOF' … EOF) or with --file <path>.`);\n }\n return fs.readFileSync(0, 'utf8');\n }\n}\n"]}
1
+ {"version":3,"file":"write-review-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/write-review-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAEiC;AACjC,yCAA2D;AAC3D,2EAAgE;AAChE,2EAAiG;AACjG,qEAA2F;AAC3F,uEAA+G;AAC/G,uEAAyE;AAEzE,oFAAoF;AACpF,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAC;AAE3E,yDAAyD;AACzD,MAAa,kBAAkB;IAC3B,WAAW,CAAS;IACpB,sGAAsG;IACtG,iEAAiE;IACjE,IAAI,CAAS;IACb,kGAAkG;IAClG,8EAA8E;IAC9E,GAAG,CAAS;IAEZ,YAAY,WAAmB,EAAE,IAAY,EAAE,GAAW;QACtD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACnB,CAAC;CACJ;AAdD,gDAcC;AAED;;;;;;;;;;;;;;;GAeG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAGN;IACA;IACA;IACA;IACA;IACA;IAPrB,yDAAyD;IACzD,YACqB,cAA8B,EAC9B,YAA0B,EAC1B,QAAmC,EACnC,QAAkC,EAClC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Y,QAAQ,kBAAkB,CAAC,CAAC;YACjH,OAAO,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC7C,CAAC;QACD,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAC/B,MAAM,IAAI,4BAAa,CAAC,GAAG,+BAAgB,0CAA0C,+BAAgB,yDAAyD,CAAC,CAAC;QACpK,CAAC;QACD,OAAO,EAAE,CAAC,YAAY,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IACtC,CAAC;CACJ,CAAA;AAXY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,gBAAgB,CAW5B","sourcesContent":["import * as fs from 'fs';\nimport {\n InformAiError, RepoRootFinder, VERDICT_STATUSES, WRITE_REVIEW_BIN, checklistOverrideService, summaryJsonPath, toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { ReviewStageReceipt, ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewerIdentity, ReviewerIdentityResolver } from '../workflow/reviewer-identity';\nimport { SubmittedVerdict, VerdictProvenance, VerdictProvenanceService } from '../workflow/verdict-provenance';\nimport { ReviewRoundStateService } from '../workflow/review-round-state';\n\n/** The only keys a verdict may carry. Anything else is somebody's second schema. */\nconst VERDICT_KEYS = ['id', 'status', 'agent', 'model', 'output'] as const;\n\n/** What `wp-write-review` was asked to do. Data-only. */\nexport class WriteReviewOptions {\n checklistId: string;\n // The verdict JSON itself — read from `--file` or stdin by the composition root, so this command is a\n // function of its inputs and a spec can drive it without a pipe.\n json: string;\n // Where the caller stands — the tree whose review dir and hook stamp are used. Passed in (the bin\n // passes process.cwd()) rather than read here, for the same reason `json` is.\n cwd: string;\n\n constructor(checklistId: string, json: string, cwd: string) {\n this.checklistId = checklistId;\n this.json = json;\n this.cwd = cwd;\n }\n}\n\n/**\n * `wp-write-review` — the ONE way any reviewer, Claude or Codex, submits a checklist verdict (issue #863).\n *\n * Before it existed a verdict was \"a file with the right shape at the right path\", and that is exactly what\n * a Codex coordinator produced on two merged PRs: the shared-tree guard blocked its reviewer's write, the\n * guard's own cure said to hand the edit to the coordinator, the coordinator wrote all five verdicts, and\n * `wp-finish-upsert-pr` accepted them. Now:\n * 1. the caller is identified by the harness (ReviewerIdentityResolver) and the COORDINATOR is refused;\n * 2. the checklist must be one stage ② briefed this round (its receipt), so a carried verdict cannot be\n * overwritten and a checklist that does not apply cannot be invented;\n * 3. the verdict is validated strictly — the five fields, nothing else;\n * 4. it is written WITH `review-<id>.provenance.json`: who, which commit, which in-scope diff, and a hash\n * of the verdict. `wp-finish-upsert-pr` rejects a verdict without one, or one edited since.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class WriteReviewCommand {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly receipts: ReviewStageReceiptService,\n private readonly identity: ReviewerIdentityResolver,\n private readonly provenance: VerdictProvenanceService,\n private readonly rounds: ReviewRoundStateService,\n ) {}\n\n run(opts: WriteReviewOptions): Promise<void> {\n const id = opts.checklistId.trim();\n const cwd = opts.cwd;\n const repoRoot = this.repoRootFinder.resolveRepoRoot(cwd);\n const featureName = this.aiBranchName.getFeatureName();\n const receipt = this.briefedReceipt(repoRoot, featureName, id);\n // Identity BEFORE parsing: a coordinator is refused whatever it submitted, and the stamp it\n // consumes must not survive to lend itself to a later call.\n const who: ReviewerIdentity = this.identity.resolve(cwd, id);\n const verdict = this.parse(opts.json, id);\n const record = new VerdictProvenance(\n id, who.harness, who.sessionId, who.agentId, who.agentType, receipt.headSha, receipt.scopeHashes[id] ?? '');\n record.round = receipt.round;\n const written = this.provenance.write(summaryJsonPath(repoRoot, featureName), verdict, record);\n this.rounds.archiveVerdict(summaryJsonPath(repoRoot, featureName), id, receipt.round);\n process.stdout.write(\n `✅ ${verdict.status.toUpperCase()} verdict for \"${id}\" submitted → ${written}\\n`\n + ` provenance: ${who.harness}${who.agentId === '' ? '' : ` agent ${who.agentId}`}, `\n + `briefed at ${receipt.headSha.slice(0, 8)}, global round ${receipt.round} of ${receipt.maxReviewerRounds}\\n`);\n return Promise.resolve();\n }\n\n /** The stage-② receipt, provided it briefed THIS checklist this round. */\n private briefedReceipt(repoRoot: string, featureName: string, id: string): ReviewStageReceipt {\n if (id === '') throw new InformAiError(`${WRITE_REVIEW_BIN} needs the checklist id: pnpm ${WRITE_REVIEW_BIN} --checklist <id>`);\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: pnpm wp-review-upsert-pr has not briefed any reviewer on this branch yet, `\n + 'so there is nothing to submit a verdict against.');\n }\n if (!receipt.reviewersBriefed.includes(id) || (receipt.scopeHashes[id] ?? '') === '') {\n const briefed = receipt.reviewersBriefed.length === 0 ? '(none)' : receipt.reviewersBriefed.join(', ');\n throw new InformAiError(`${WRITE_REVIEW_BIN}: checklist \"${id}\" was not briefed by the last pnpm wp-review-upsert-pr `\n + `(briefed this round: ${briefed}). Submit only for a checklist whose instructions file you were handed — `\n + 'a checklist absent here either carries its earlier verdict or does not apply to this diff.');\n }\n return receipt;\n }\n\n /** Strict: an object with exactly the verdict's five fields, every one a string, status one of three. */\n private parse(json: string, id: string): SubmittedVerdict {\n const raw = this.parseObject(json);\n const problems: string[] = [];\n const extra = Object.keys(raw).filter((k: string): boolean => !(VERDICT_KEYS as readonly string[]).includes(k));\n if (extra.includes('override')) {\n problems.push(`\"override\" is not a verdict field — a ship-anyway decision is a HUMAN's, recorded by the coordinating agent in ${checklistOverrideService.overrideFileName(id)}`);\n }\n if (extra.length > 0) problems.push(`unknown field(s) ${extra.map((k: string): string => `\"${k}\"`).join(', ')} — a verdict has exactly: ${VERDICT_KEYS.join(', ')}`);\n if (raw['id'] !== undefined && this.text(raw, 'id') !== id) problems.push(`\"id\" is ${JSON.stringify(raw['id'])} but --checklist is \"${id}\"`);\n const status = this.text(raw, 'status').toLowerCase();\n // webpieces-disable no-any-unknown -- comparing against the readonly literal tuple of valid colors\n if (!(VERDICT_STATUSES as readonly string[]).includes(status)) problems.push(`\"status\" must be one of ${VERDICT_STATUSES.join(', ')}`);\n for (const key of ['agent', 'model', 'output']) {\n if (this.text(raw, key) === '') problems.push(`\"${key}\" must be a non-empty string${key === 'output' ? '' : ' (use \"unknown\" when unavailable)'}`);\n }\n if (problems.length > 0) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: the verdict for \"${id}\" was NOT submitted:\\n`\n + problems.map((p: string): string => ` • ${p}`).join('\\n'));\n }\n return new SubmittedVerdict(id, status, this.text(raw, 'agent'), this.text(raw, 'model'), raw['output'] as string);\n }\n\n // webpieces-disable no-any-unknown -- one field of the opaque submitted object, narrowed to a trimmed string\n private text(raw: Record<string, unknown>, key: string): string {\n const value = raw[key];\n return typeof value === 'string' ? value.trim() : '';\n }\n\n // webpieces-disable no-any-unknown -- the submitted JSON is opaque until parse() narrows every field\n private parseObject(json: string): Record<string, unknown> {\n // webpieces-disable no-any-unknown -- parsed JSON is opaque until narrowed\n let parsed: unknown = null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a JSON syntax error becomes the AI-facing refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n parsed = JSON.parse(json);\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`${WRITE_REVIEW_BIN}: the verdict is not valid JSON.`, { cause: error });\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: the verdict must be ONE JSON object.`);\n }\n // webpieces-disable no-any-unknown -- narrowed to a plain object just above\n return parsed as Record<string, unknown>;\n }\n}\n\n/**\n * Reads the verdict JSON for the composition root: `--file <path>`, else stdin. Separate from the command\n * so the command stays a function of its inputs.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class WriteReviewInput {\n read(filePath: string): string {\n if (filePath.trim() !== '') {\n if (!fs.existsSync(filePath)) throw new InformAiError(`${WRITE_REVIEW_BIN}: --file ${filePath} does not exist.`);\n return fs.readFileSync(filePath, 'utf8');\n }\n if (process.stdin.isTTY === true) {\n throw new InformAiError(`${WRITE_REVIEW_BIN}: pass the verdict JSON on stdin (pnpm ${WRITE_REVIEW_BIN} --checklist <id> <<'EOF' … EOF) or with --file <path>.`);\n }\n return fs.readFileSync(0, 'utf8');\n }\n}\n"]}
@@ -0,0 +1,21 @@
1
+ import { RepoRootFinder } from '@webpieces/rules-config';
2
+ import { AiBranchName } from '../workflow/git-readAiBranchName';
3
+ import { ReviewRoundStateService } from '../workflow/review-round-state';
4
+ import { ReviewStageReceiptService } from '../workflow/review-stage-receipt';
5
+ export declare class WriteReviewFixesOptions {
6
+ json: string;
7
+ cwd: string;
8
+ constructor(json: string, cwd: string);
9
+ }
10
+ /** Coordinator-owned writer for the SHA-bound response to a completed red reviewer round. */
11
+ export declare class WriteReviewFixesCommand {
12
+ private readonly repoRootFinder;
13
+ private readonly aiBranchName;
14
+ private readonly receipts;
15
+ private readonly rounds;
16
+ constructor(repoRootFinder: RepoRootFinder, aiBranchName: AiBranchName, receipts: ReviewStageReceiptService, rounds: ReviewRoundStateService);
17
+ run(opts: WriteReviewFixesOptions): Promise<void>;
18
+ }
19
+ export declare class WriteReviewFixesInput {
20
+ read(filePath: string): string;
21
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WriteReviewFixesInput = exports.WriteReviewFixesCommand = exports.WriteReviewFixesOptions = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const rules_config_1 = require("@webpieces/rules-config");
7
+ const inversify_1 = require("inversify");
8
+ const git_readAiBranchName_1 = require("../workflow/git-readAiBranchName");
9
+ const review_round_state_1 = require("../workflow/review-round-state");
10
+ const review_stage_receipt_1 = require("../workflow/review-stage-receipt");
11
+ class WriteReviewFixesOptions {
12
+ json;
13
+ cwd;
14
+ constructor(json, cwd) {
15
+ this.json = json;
16
+ this.cwd = cwd;
17
+ }
18
+ }
19
+ exports.WriteReviewFixesOptions = WriteReviewFixesOptions;
20
+ /** Coordinator-owned writer for the SHA-bound response to a completed red reviewer round. */
21
+ let WriteReviewFixesCommand = class WriteReviewFixesCommand {
22
+ repoRootFinder;
23
+ aiBranchName;
24
+ receipts;
25
+ rounds;
26
+ constructor(repoRootFinder, aiBranchName, receipts, rounds) {
27
+ this.repoRootFinder = repoRootFinder;
28
+ this.aiBranchName = aiBranchName;
29
+ this.receipts = receipts;
30
+ this.rounds = rounds;
31
+ }
32
+ run(opts) {
33
+ const repoRoot = this.repoRootFinder.resolveRepoRoot(opts.cwd);
34
+ const featureName = this.aiBranchName.getFeatureName();
35
+ const receipt = this.receipts.read(repoRoot, featureName);
36
+ if (receipt === null)
37
+ throw new rules_config_1.InformAiError('wp-write-review-fixes: no reviewer round has started on this branch.');
38
+ const written = this.rounds.writeRemediation(repoRoot, (0, rules_config_1.summaryJsonPath)(repoRoot, featureName), receipt, opts.json);
39
+ process.stdout.write(`✅ SHA-bound remediation for global round ${receipt.round} recorded → ${written}\n`);
40
+ return Promise.resolve();
41
+ }
42
+ };
43
+ exports.WriteReviewFixesCommand = WriteReviewFixesCommand;
44
+ exports.WriteReviewFixesCommand = WriteReviewFixesCommand = tslib_1.__decorate([
45
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
46
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.RepoRootFinder,
47
+ git_readAiBranchName_1.AiBranchName,
48
+ review_stage_receipt_1.ReviewStageReceiptService,
49
+ review_round_state_1.ReviewRoundStateService])
50
+ ], WriteReviewFixesCommand);
51
+ let WriteReviewFixesInput = class WriteReviewFixesInput {
52
+ read(filePath) {
53
+ if (filePath.trim() !== '') {
54
+ if (!fs.existsSync(filePath))
55
+ throw new rules_config_1.InformAiError(`wp-write-review-fixes: --file ${filePath} does not exist.`);
56
+ return fs.readFileSync(filePath, 'utf8');
57
+ }
58
+ if (process.stdin.isTTY === true) {
59
+ throw new rules_config_1.InformAiError('wp-write-review-fixes: pass JSON on stdin or with --file <path>.');
60
+ }
61
+ return fs.readFileSync(0, 'utf8');
62
+ }
63
+ };
64
+ exports.WriteReviewFixesInput = WriteReviewFixesInput;
65
+ exports.WriteReviewFixesInput = WriteReviewFixesInput = tslib_1.__decorate([
66
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
67
+ ], WriteReviewFixesInput);
68
+ //# sourceMappingURL=write-review-fixes-command.js.map