@webpieces/pr-gate 0.4.824 → 0.4.826

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 (33) hide show
  1. package/package.json +3 -3
  2. package/src/scripts/commands/await-reviews-command.js +1 -1
  3. package/src/scripts/commands/await-reviews-command.js.map +1 -1
  4. package/src/scripts/commands/finish-upsert-pr-command.js +16 -7
  5. package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
  6. package/src/scripts/commands/review-upsert-pr-command.js +1 -1
  7. package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
  8. package/src/scripts/commands/write-review-command.d.ts +23 -1
  9. package/src/scripts/commands/write-review-command.js +48 -2
  10. package/src/scripts/commands/write-review-command.js.map +1 -1
  11. package/src/scripts/commands/write-review-fixes-command.js +3 -0
  12. package/src/scripts/commands/write-review-fixes-command.js.map +1 -1
  13. package/src/scripts/pr-gate-app.d.ts +3 -1
  14. package/src/scripts/pr-gate-app.js +4 -0
  15. package/src/scripts/pr-gate-app.js.map +1 -1
  16. package/src/scripts/workflow/checklist-scanner.d.ts +29 -3
  17. package/src/scripts/workflow/checklist-scanner.js +51 -5
  18. package/src/scripts/workflow/checklist-scanner.js.map +1 -1
  19. package/src/scripts/workflow/hotfix-finish-preparer.js +1 -1
  20. package/src/scripts/workflow/hotfix-finish-preparer.js.map +1 -1
  21. package/src/scripts/workflow/review-report.js +4 -0
  22. package/src/scripts/workflow/review-report.js.map +1 -1
  23. package/src/scripts/workflow/review-round-state.d.ts +14 -0
  24. package/src/scripts/workflow/review-round-state.js +24 -1
  25. package/src/scripts/workflow/review-round-state.js.map +1 -1
  26. package/src/scripts/workflow/review-stage-receipt.d.ts +14 -1
  27. package/src/scripts/workflow/review-stage-receipt.js +21 -1
  28. package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
  29. package/src/scripts/workflow/verdict-provenance.d.ts +6 -0
  30. package/src/scripts/workflow/verdict-provenance.js +8 -2
  31. package/src/scripts/workflow/verdict-provenance.js.map +1 -1
  32. package/src/scripts/wp-write-review.js +7 -0
  33. package/src/scripts/wp-write-review.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/pr-gate",
3
- "version": "0.4.824",
3
+ "version": "0.4.826",
4
4
  "description": "Gated PR system: 3-point squash-merge, merge validation gate, and red/yellow/green PR dashboard. Standalone scripts, no Nx dependency required.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -16,8 +16,8 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@inversifyjs/binding-decorators": "1.1.5",
19
- "@webpieces/ai-hook-rules": "0.4.824",
20
- "@webpieces/rules-config": "0.4.824",
19
+ "@webpieces/ai-hook-rules": "0.4.826",
20
+ "@webpieces/rules-config": "0.4.826",
21
21
  "inversify": "7.10.4",
22
22
  "reflect-metadata": "0.2.2"
23
23
  },
@@ -59,7 +59,7 @@ let AwaitReviewsCommand = class AwaitReviewsCommand {
59
59
  // contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review
60
60
  // was briefed against, and rewriting it mid-review would restate the briefing under the
61
61
  // reviewers currently reading it.
62
- const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(true, ''));
62
+ const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(config.maxReviewerRounds, true, ''));
63
63
  if (scan.reviewersDisabled)
64
64
  return this.reportDisabled(scan.suppressed);
65
65
  if (scan.applicable.length === 0)
@@ -1 +1 @@
1
- {"version":3,"file":"await-reviews-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-reviews-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAGiC;AACjC,yCAA2D;AAE3D,uDAA2E;AAC3E,qEAAuF;AACvF,2EAAgE;AAChE,2EAA6E;AAC7E,mEAA8D;AAE9D;;;;;;;;;;;;;;;;;;;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":["import * as fs from 'fs';\nimport {\n ChecklistResult, ChecklistVerdict, CK_FAIL, CK_MISSING, CK_BAD_FORMAT, loadAndValidate,\n RepoRootFinder, RequiredChecklist, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/**\n * `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its\n * verdict, then print what each one said.\n *\n * ─── Why a command and not an instruction ──────────────────────────────────────────────────────────\n * An agent that has just spawned four reviewer subagents has nothing to do until they answer, and a\n * worktree-isolated subagent cannot simply wait: ending its turn ends its run. See {@link AwaitLoop}\n * for the full chain and the measurement (18.3% of all fleet tokens in one day spent on `echo .`).\n * A blocking Bash call is the only wait primitive it has, so webpieces provides one.\n *\n * ─── It INVENTS NO STATE ───────────────────────────────────────────────────────────────────────────\n * The set of reviewers a branch owes is `ChecklistScanner`'s answer — the SAME one `wp-review-upsert-pr`\n * lists and `wp-finish-upsert-pr` blocks on — and the verdicts are the `review-<id>.json` files those\n * two already read. Nothing here writes anything, and there is no third opinion about who is owed: a\n * waiter that computed its own set could finish while finish still refused, which is the one outcome\n * that would make waiting worse than not waiting.\n *\n * The scan runs ONCE. Its `applicable` set is a function of the diff, which does not change while the\n * agent sits still, so re-scanning per poll would re-run `git diff` every few seconds to re-derive an\n * unchanged answer. Only the verdict FILES are re-read, which is the only thing a reviewer changes.\n *\n * ─── What it does NOT do ───────────────────────────────────────────────────────────────────────────\n * It does not judge. A red verdict is a completed review, so this command RETURNS on it and prints it;\n * refusing the PR over it is `wp-finish-upsert-pr`'s job and stays there. It exits non-zero only when it\n * cannot do its own job at all.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitReviewsCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n private readonly receipts: ReviewStageReceiptService,\n private readonly aiBranchName: AiBranchName,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const config = loadAndValidate(repoRoot).prGate;\n // contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review\n // was briefed against, and rewriting it mid-review would restate the briefing under the\n // reviewers currently reading it.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(true, ''));\n if (scan.reviewersDisabled) return this.reportDisabled(scan.suppressed);\n if (scan.applicable.length === 0) return this.reportNothingOwed();\n // WAIT on the set finish blocks on (`outstanding`), REPORT on everything that applies. The two\n // sets differ by exactly the optional checklists nobody ran — `required: false` means the PR does\n // not wait for them, and a wait that did would never end, because nothing is ever going to write\n // a verdict for a reviewer that was deliberately never spawned. (The SET is shared with finish;\n // the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)\n // A verdict file older than the last stage ② is NOT an arrival: it is the stale green or rejected\n // file that stage just re-briefed (issue #863), and counting it would end the wait on the spot.\n const since = this.receipts.writtenAtMs(repoRoot, this.aiBranchName.getFeatureName());\n const probe = new ReviewerWaitProbe(\n this.reviewJsonService, scan.summaryPath, scan.outstanding, scan.applicable, since);\n const outcome = await this.awaitLoop.run(probe);\n this.report(probe, outcome);\n }\n\n // Nothing to wait for, and saying so is the whole value: an agent that got no answer here would\n // otherwise assume the wait is still owed and start spinning again.\n private reportNothingOwed(): void {\n this.stageConsole.say('\\n✅ No reviewer was requested for this branch — nothing to wait for.\\n');\n }\n\n private reportDisabled(suppressed: readonly RequiredChecklist[]): void {\n this.stageConsole.say(\n `\\n⚫ Every reviewer is switched off on this machine (experimental.turnOffAllReviewers), so `\n + `${String(suppressed.length)} checklist(s) that would have run are not running. There is `\n + 'nothing to wait for.\\n');\n }\n\n private report(probe: ReviewerWaitProbe, outcome: WaitOutcome): void {\n this.stageConsole.say(outcome.done ? probe.verdictReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/**\n * The reviewer wait itself: which checklists are owed, and what the files on disk say about them right\n * now. It owns the reporting too, because every line it prints is derived from the same verdict read —\n * a report that re-read the files could disagree with the answer that ended the wait.\n */\nexport class ReviewerWaitProbe implements WaitProbe {\n readonly label = 'reviewers';\n // Verdict files are local reads, so polling them costs nothing worth economizing on. Fast enough\n // that the command returns within seconds of the last reviewer finishing, which is the point.\n readonly pollMs = 3_000;\n\n private results: ChecklistResult[] = [];\n\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly summaryPath: string,\n private readonly waitedOn: readonly RequiredChecklist[],\n private readonly applicable: readonly RequiredChecklist[],\n // Epoch ms of the last stage ② (0 = none): a verdict file last written before it is not an answer.\n private readonly sinceMs: number,\n ) {\n this.reload();\n }\n\n /**\n * Done when every awaited reviewer has ANSWERED — not when every answer is a pass.\n *\n * That distinction is the whole contract of a wait, and getting it wrong makes the command useless\n * in the case it matters most. `ReviewJsonService.pendingChecklists` is finish's GATE predicate and\n * counts a RED verdict as still owed, correctly: the PR is refused until the finding is fixed. But\n * a red reviewer has finished; it will never write a different answer on its own, so waiting for it\n * to stop being red is waiting forever. The wait therefore ends on ARRIVAL — a verdict file that\n * exists, whatever it says — and `wp-finish-upsert-pr` keeps sole ownership of the gate.\n *\n * `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX\n * (four characters of JSON), not a thing to wait longer for.\n */\n done(): boolean {\n this.reload();\n return this.pending().length === 0;\n }\n\n describe(): string {\n const owed = this.pending().length;\n const total = this.waitedOn.length;\n return `${String(total - owed)} of ${String(total)} verdicts in`;\n }\n\n /** Every reviewer's answer, printed once the wait is over — the reason to wait rather than sleep. */\n verdictReport(outcome: WaitOutcome): string {\n // The headline counts what was WAITED ON; the list below covers everything that APPLIES, so an\n // optional checklist nobody ran shows as ❓ rather than being quietly dropped. Reporting only the\n // waited-on set would let a shorter list imply the others passed.\n const lines = [\n `\\n✅ All ${String(this.waitedOn.length)} awaited reviewer verdict(s) are in after `\n + `${String(outcome.waitedSeconds)}s:\\n`,\n ];\n for (const req of this.applicable) lines.push(this.oneVerdict(req));\n lines.push(this.nextStep());\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * The timeout report. It is a NORMAL exit and says so, because an agent that reads this as a failure\n * goes hunting for a broken reviewer instead of running one more plain command.\n */\n stillWaitingReport(outcome: WaitOutcome): string {\n const owed = this.pending();\n return `\\n⏳ Still waiting after ${String(outcome.waitedSeconds)}s — run me again: pnpm wp-await-reviews\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command, so a\\n'\n + ' long review costs a handful of calls instead of hundreds of keep-alive turns.)\\n\\n'\n + ` ${String(owed.length)} of ${String(this.waitedOn.length)} still owe a verdict: `\n + `${owed.map((r: RequiredChecklist): string => r.id).join(', ')}\\n`;\n }\n\n private oneVerdict(req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, this.results);\n return ` ${this.icon(verdict)} ${verdict.id} — ${verdict.status}${this.detail(verdict)}`;\n }\n\n // Only a NON-passing verdict's detail is printed. A green reviewer's output is already on the PR,\n // and reprinting four of them here would bury the one line that needs acting on.\n private detail(verdict: ChecklistVerdict): string {\n if (verdict.status !== CK_FAIL || verdict.detail === '') return '';\n return `\\n ${verdict.detail.split('\\n').join('\\n ')}`;\n }\n\n private icon(verdict: ChecklistVerdict): string {\n if (verdict.status === CK_FAIL) return '🔴';\n if (verdict.status === CK_MISSING || verdict.status === CK_BAD_FORMAT) return '❓';\n return '🟢';\n }\n\n // Named because a wait that ends without saying what it unblocked leaves the agent to guess, and\n // guessing here means spinning again. A red verdict changes the next move, so it is called out.\n private nextStep(): string {\n const anyRed = this.applicable.some((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_FAIL);\n return anyRed\n ? '\\n A reviewer REFUSED. Fix what it found — re-spawning it against unchanged code buys the\\n'\n + ' same answer — then re-run the review stage.\\n'\n : '\\n Nothing is owed on the review front.\\n';\n }\n\n // The awaited checklists whose verdict file has not appeared yet — see `done()` for why this is\n // arrival and not the gate's own \"still owed\".\n private pending(): RequiredChecklist[] {\n return this.waitedOn.filter((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_MISSING || this.predates(req));\n }\n\n private predates(req: RequiredChecklist): boolean {\n if (this.sinceMs === 0) return false;\n const file = this.reviewJsonService.checklistResultPath(this.summaryPath, req.id);\n return fs.existsSync(file) && fs.statSync(file).mtimeMs < this.sinceMs;\n }\n\n private reload(): void {\n this.results = this.reviewJsonService.loadChecklistResults(this.summaryPath, this.applicable);\n }\n}\n"]}
1
+ {"version":3,"file":"await-reviews-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-reviews-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAGiC;AACjC,yCAA2D;AAE3D,uDAA2E;AAC3E,qEAAuF;AACvF,2EAAgE;AAChE,2EAA6E;AAC7E,mEAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IACA;IACA;IACA;IACA;IACA;IAPrB,YACqB,cAA8B,EAC9B,gBAAkC,EAClC,iBAAoC,EACpC,SAAoB,EACpB,YAA4B,EAC5B,QAAmC,EACnC,YAA0B;QAN1B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,cAAS,GAAT,SAAS,CAAW;QACpB,iBAAY,GAAZ,YAAY,CAAgB;QAC5B,aAAQ,GAAR,QAAQ,CAA2B;QACnC,iBAAY,GA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C;IACxD,CAAC;IAED,gGAAgG;IAChG,+CAA+C;IACvC,OAAO;QACX,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAsB,EAAW,EAAE,CAC5D,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,yBAAU,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9G,CAAC;IAEO,QAAQ,CAAC,GAAsB;QACnC,IAAI,IAAI,CAAC,OAAO,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACrC,MAAM,IAAI,GAAG,IAAI,CAAC,iBAAiB,CAAC,mBAAmB,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QAClF,OAAO,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC3E,CAAC;IAEO,MAAM;QACV,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClG,CAAC;CACJ;AAnHD,8CAmHC","sourcesContent":["import * as fs from 'fs';\nimport {\n ChecklistResult, ChecklistVerdict, CK_FAIL, CK_MISSING, CK_BAD_FORMAT, loadAndValidate,\n RepoRootFinder, RequiredChecklist, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/**\n * `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its\n * verdict, then print what each one said.\n *\n * ─── Why a command and not an instruction ──────────────────────────────────────────────────────────\n * An agent that has just spawned four reviewer subagents has nothing to do until they answer, and a\n * worktree-isolated subagent cannot simply wait: ending its turn ends its run. See {@link AwaitLoop}\n * for the full chain and the measurement (18.3% of all fleet tokens in one day spent on `echo .`).\n * A blocking Bash call is the only wait primitive it has, so webpieces provides one.\n *\n * ─── It INVENTS NO STATE ───────────────────────────────────────────────────────────────────────────\n * The set of reviewers a branch owes is `ChecklistScanner`'s answer — the SAME one `wp-review-upsert-pr`\n * lists and `wp-finish-upsert-pr` blocks on — and the verdicts are the `review-<id>.json` files those\n * two already read. Nothing here writes anything, and there is no third opinion about who is owed: a\n * waiter that computed its own set could finish while finish still refused, which is the one outcome\n * that would make waiting worse than not waiting.\n *\n * The scan runs ONCE. Its `applicable` set is a function of the diff, which does not change while the\n * agent sits still, so re-scanning per poll would re-run `git diff` every few seconds to re-derive an\n * unchanged answer. Only the verdict FILES are re-read, which is the only thing a reviewer changes.\n *\n * ─── What it does NOT do ───────────────────────────────────────────────────────────────────────────\n * It does not judge. A red verdict is a completed review, so this command RETURNS on it and prints it;\n * refusing the PR over it is `wp-finish-upsert-pr`'s job and stays there. It exits non-zero only when it\n * cannot do its own job at all.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitReviewsCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n private readonly receipts: ReviewStageReceiptService,\n private readonly aiBranchName: AiBranchName,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const config = loadAndValidate(repoRoot).prGate;\n // contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review\n // was briefed against, and rewriting it mid-review would restate the briefing under the\n // reviewers currently reading it.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, ''));\n if (scan.reviewersDisabled) return this.reportDisabled(scan.suppressed);\n if (scan.applicable.length === 0) return this.reportNothingOwed();\n // WAIT on the set finish blocks on (`outstanding`), REPORT on everything that applies. The two\n // sets differ by exactly the optional checklists nobody ran — `required: false` means the PR does\n // not wait for them, and a wait that did would never end, because nothing is ever going to write\n // a verdict for a reviewer that was deliberately never spawned. (The SET is shared with finish;\n // the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)\n // A verdict file older than the last stage ② is NOT an arrival: it is the stale green or rejected\n // file that stage just re-briefed (issue #863), and counting it would end the wait on the spot.\n const since = this.receipts.writtenAtMs(repoRoot, this.aiBranchName.getFeatureName());\n const probe = new ReviewerWaitProbe(\n this.reviewJsonService, scan.summaryPath, scan.outstanding, scan.applicable, since);\n const outcome = await this.awaitLoop.run(probe);\n this.report(probe, outcome);\n }\n\n // Nothing to wait for, and saying so is the whole value: an agent that got no answer here would\n // otherwise assume the wait is still owed and start spinning again.\n private reportNothingOwed(): void {\n this.stageConsole.say('\\n✅ No reviewer was requested for this branch — nothing to wait for.\\n');\n }\n\n private reportDisabled(suppressed: readonly RequiredChecklist[]): void {\n this.stageConsole.say(\n `\\n⚫ Every reviewer is switched off on this machine (experimental.turnOffAllReviewers), so `\n + `${String(suppressed.length)} checklist(s) that would have run are not running. There is `\n + 'nothing to wait for.\\n');\n }\n\n private report(probe: ReviewerWaitProbe, outcome: WaitOutcome): void {\n this.stageConsole.say(outcome.done ? probe.verdictReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/**\n * The reviewer wait itself: which checklists are owed, and what the files on disk say about them right\n * now. It owns the reporting too, because every line it prints is derived from the same verdict read —\n * a report that re-read the files could disagree with the answer that ended the wait.\n */\nexport class ReviewerWaitProbe implements WaitProbe {\n readonly label = 'reviewers';\n // Verdict files are local reads, so polling them costs nothing worth economizing on. Fast enough\n // that the command returns within seconds of the last reviewer finishing, which is the point.\n readonly pollMs = 3_000;\n\n private results: ChecklistResult[] = [];\n\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly summaryPath: string,\n private readonly waitedOn: readonly RequiredChecklist[],\n private readonly applicable: readonly RequiredChecklist[],\n // Epoch ms of the last stage ② (0 = none): a verdict file last written before it is not an answer.\n private readonly sinceMs: number,\n ) {\n this.reload();\n }\n\n /**\n * Done when every awaited reviewer has ANSWERED — not when every answer is a pass.\n *\n * That distinction is the whole contract of a wait, and getting it wrong makes the command useless\n * in the case it matters most. `ReviewJsonService.pendingChecklists` is finish's GATE predicate and\n * counts a RED verdict as still owed, correctly: the PR is refused until the finding is fixed. But\n * a red reviewer has finished; it will never write a different answer on its own, so waiting for it\n * to stop being red is waiting forever. The wait therefore ends on ARRIVAL — a verdict file that\n * exists, whatever it says — and `wp-finish-upsert-pr` keeps sole ownership of the gate.\n *\n * `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX\n * (four characters of JSON), not a thing to wait longer for.\n */\n done(): boolean {\n this.reload();\n return this.pending().length === 0;\n }\n\n describe(): string {\n const owed = this.pending().length;\n const total = this.waitedOn.length;\n return `${String(total - owed)} of ${String(total)} verdicts in`;\n }\n\n /** Every reviewer's answer, printed once the wait is over — the reason to wait rather than sleep. */\n verdictReport(outcome: WaitOutcome): string {\n // The headline counts what was WAITED ON; the list below covers everything that APPLIES, so an\n // optional checklist nobody ran shows as ❓ rather than being quietly dropped. Reporting only the\n // waited-on set would let a shorter list imply the others passed.\n const lines = [\n `\\n✅ All ${String(this.waitedOn.length)} awaited reviewer verdict(s) are in after `\n + `${String(outcome.waitedSeconds)}s:\\n`,\n ];\n for (const req of this.applicable) lines.push(this.oneVerdict(req));\n lines.push(this.nextStep());\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * The timeout report. It is a NORMAL exit and says so, because an agent that reads this as a failure\n * goes hunting for a broken reviewer instead of running one more plain command.\n */\n stillWaitingReport(outcome: WaitOutcome): string {\n const owed = this.pending();\n return `\\n⏳ Still waiting after ${String(outcome.waitedSeconds)}s — run me again: pnpm wp-await-reviews\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command, so a\\n'\n + ' long review costs a handful of calls instead of hundreds of keep-alive turns.)\\n\\n'\n + ` ${String(owed.length)} of ${String(this.waitedOn.length)} still owe a verdict: `\n + `${owed.map((r: RequiredChecklist): string => r.id).join(', ')}\\n`;\n }\n\n private oneVerdict(req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, this.results);\n return ` ${this.icon(verdict)} ${verdict.id} — ${verdict.status}${this.detail(verdict)}`;\n }\n\n // Only a NON-passing verdict's detail is printed. A green reviewer's output is already on the PR,\n // and reprinting four of them here would bury the one line that needs acting on.\n private detail(verdict: ChecklistVerdict): string {\n if (verdict.status !== CK_FAIL || verdict.detail === '') return '';\n return `\\n ${verdict.detail.split('\\n').join('\\n ')}`;\n }\n\n private icon(verdict: ChecklistVerdict): string {\n if (verdict.status === CK_FAIL) return '🔴';\n if (verdict.status === CK_MISSING || verdict.status === CK_BAD_FORMAT) return '❓';\n return '🟢';\n }\n\n // Named because a wait that ends without saying what it unblocked leaves the agent to guess, and\n // guessing here means spinning again. A red verdict changes the next move, so it is called out.\n private nextStep(): string {\n const anyRed = this.applicable.some((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_FAIL);\n return anyRed\n ? '\\n A reviewer REFUSED. Fix what it found — re-spawning it against unchanged code buys the\\n'\n + ' same answer — then re-run the review stage.\\n'\n : '\\n Nothing is owed on the review front.\\n';\n }\n\n // The awaited checklists whose verdict file has not appeared yet — see `done()` for why this is\n // arrival and not the gate's own \"still owed\".\n private pending(): RequiredChecklist[] {\n return this.waitedOn.filter((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_MISSING || this.predates(req));\n }\n\n private predates(req: RequiredChecklist): boolean {\n if (this.sinceMs === 0) return false;\n const file = this.reviewJsonService.checklistResultPath(this.summaryPath, req.id);\n return fs.existsSync(file) && fs.statSync(file).mtimeMs < this.sinceMs;\n }\n\n private reload(): void {\n this.results = this.reviewJsonService.loadChecklistResults(this.summaryPath, this.applicable);\n }\n}\n"]}
@@ -189,7 +189,9 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
189
189
  }
190
190
  // 1. REQUIRE stage ② — see assertStageTwoRan. Returns true when its receipt covers THIS commit,
191
191
  // which is what lets the build gate below be skipped rather than re-run for a foregone answer.
192
- const buildAlreadyGreen = this.assertStageTwoRan(repoRoot);
192
+ const featureName = this.aiBranchName.getFeatureName();
193
+ const config = (0, rules_config_1.loadAndValidate)(repoRoot).prGate;
194
+ const buildAlreadyGreen = this.assertStageTwoRan(repoRoot, config.maxReviewerRounds);
193
195
  // 2. REQUIRE the AI-authored summary.json (throws InformAiError with the schema if missing/invalid).
194
196
  // Compute the consumer checklists this diff triggered FIRST so an unacknowledged BLOCK throws
195
197
  // here — BEFORE any `gh pr create` — matching the guarantee buildCommand already provides.
@@ -199,9 +201,7 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
199
201
  // persist locally, so a re-run re-validates the EXISTING verdicts against the (possibly changed)
200
202
  // applicable set for free — an unchanged checklist needs no re-review, a newly-applicable one refuses
201
203
  // until its file is written.
202
- const featureName = this.aiBranchName.getFeatureName();
203
- const config = (0, rules_config_1.loadAndValidate)(repoRoot).prGate;
204
- const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(true, 'stage3-finish'));
204
+ const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(config.maxReviewerRounds, true, 'stage3-finish'));
205
205
  const receipt = this.receipts.read(repoRoot, featureName);
206
206
  const remediations = this.rounds.capRemediations(repoRoot, scan.summaryPath, receipt, config.maxReviewerRounds);
207
207
  for (const result of scan.results)
@@ -305,9 +305,9 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
305
305
  * The two stage-② preconditions, together: no unvalidated merge, and a receipt proving stage ② ran.
306
306
  * Returns true when that receipt covers the CURRENT HEAD, i.e. the build gate can be skipped.
307
307
  */
308
- assertStageTwoRan(repoRoot) {
308
+ assertStageTwoRan(repoRoot, maxReviewerRounds) {
309
309
  this.assertNoUnvalidatedMerge(repoRoot);
310
- return this.assertReviewStageRan(repoRoot, this.aiBranchName.getFeatureName(), this.gitOut(['rev-parse', 'HEAD']));
310
+ return this.assertReviewStageRan(repoRoot, this.aiBranchName.getFeatureName(), this.gitOut(['rev-parse', 'HEAD']), maxReviewerRounds);
311
311
  }
312
312
  /**
313
313
  * REFUSE while a 3-point merge is still unvalidated — do not finalize it here.
@@ -346,7 +346,8 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
346
346
  * is vacuous, and summary.json — the only other interlock — is a file the AI writes itself. It could
347
347
  * write it and come straight here, skipping the merge validation and the build entirely.
348
348
  */
349
- assertReviewStageRan(repoRoot, featureName, headSha) {
349
+ // eslint-disable-next-line @typescript-eslint/max-params
350
+ assertReviewStageRan(repoRoot, featureName, headSha, maxReviewerRounds) {
350
351
  const receipt = this.receipts.read(repoRoot, featureName);
351
352
  if (receipt === null) {
352
353
  throw new rules_config_1.InformAiError('⛔ NO PR — stage ② never ran on this branch. That means the 3-point merge is unvalidated,\n' +
@@ -356,6 +357,14 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
356
357
  }
357
358
  if (receipt.headSha === headSha)
358
359
  return true;
360
+ if (this.rounds.capSpent((0, rules_config_1.summaryJsonPath)(repoRoot, featureName), receipt, maxReviewerRounds)) {
361
+ // The budget is spent (issue #1051): no review round will run again, so suggesting one here is
362
+ // an instruction the gate itself would refuse. Say what the PR records instead.
363
+ process.stderr.write(`\n⚠️ HEAD moved since the last reviewer round (reviewed ${receipt.headSha.slice(0, 8)}, now ${headSha.slice(0, 8)}).\n` +
364
+ ` All ${maxReviewerRounds} reviewer round(s) are spent, so no further review runs: the build gate will\n` +
365
+ ' re-run, and the PR records every verdict as carried forward from the reviewed tree.\n\n');
366
+ return false;
367
+ }
359
368
  // Not fatal. Re-reviewing on every follow-up commit would be intolerable, and most drift is a typo
360
369
  // fix. But it is never silent: the build re-runs here, and the PR says the reviewers saw an older tree.
361
370
  process.stderr.write(`\n⚠️ HEAD moved since stage ② ran (reviewed ${receipt.headSha.slice(0, 8)}, now ${headSha.slice(0, 8)}).\n` +
@@ -1 +1 @@
1
- {"version":3,"file":"finish-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/finish-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAiP;AACjP,yCAA2D;AAC3D,2EAAgE;AAChE,6DAAyD;AACzD,qEAAsG;AACtG,6EAAwE;AACxE,mDAA+C;AAC/C,+DAA6E;AAC7E,+DAAsF;AACtF,yDAAqD;AACrD,2EAA6E;AAC7E,uEAAyE;AACzE,mEAAkF;AAClF,qDAAiG;AACjG,6DAA4E;AAC5E,2EAAqE;AACrE,uEAAkE;AAClE,yEAAuF;AACvF,yEAAsF;AACtF,mFAA8E;AAE9E,yDAA2G;AAC3G,2FAAgH;AAChH,iFAA4E;AAC5E,qEAAyE;AACzE,+EAA0E;AAE1E,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;GAGG;AACH,MAAM,gBAAgB;IAClB,IAAI,CAAgB;IACpB,MAAM,CAAY;IAClB,UAAU,CAAmB;IAE7B,YAAY,IAAmB,EAAE,MAAiB,EAAE,UAA4B;QAC5E,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,eAAe;IACjB,QAAQ,GAAG,EAAE,CAAC;IACd,UAAU,GAAG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AAK,CAAC,EAAE,CAAC;YACtB,OAAO,IAAI,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAC7B,CAAC;QACD,MAAM,KAAK,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACvD,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACrD,CAAC;CACJ,CAAA;AAxjBY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,mCAAY;QACZ,4BAAY;QACjB,kBAAO;QACD,8BAAa;QAClB,6BAAY;QACV,wBAAU;QACZ,oBAAQ;QACP,qCAAgB;QAChB,qBAAS;QACJ,wCAAsB;QAEpB,qDAAwB;QACxB,oCAAgB;QACrB,2CAAmB;QACb,gCAAiB;QAClB,+BAAgB;QAEd,wCAAkB;QAI5B,gDAAyB;QAC3B,4BAAY;QAGL,wCAAiB;QAEf,uCAAiB;QAGlB,iDAAsB;QACxB,iCAAc;QACZ,6BAAc;QAChB,6CAAoB;QAC1B,4CAAuB;GArC3C,qBAAqB,CAwjBjC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { loadAndValidate, prDirFor, summaryJsonPath, PrSummary, RequiredChecklist, ChecklistVerdict, writeTemplate, RepoRootFinder, ReviewJsonService, GateTokenService, InformAiError, toError, BranchIdentity } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { ReviewerVerdictGate } from '../workflow/reviewer-verdict-gate';\nimport { GitExec } from '../workflow/git-exec';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BuildGateLog, FINISH_STAGE, REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { MergeState } from '../workflow/merge-state';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewRoundStateService } from '../workflow/review-round-state';\nimport { StageOutputLog, FINISH_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { PrMerger, MergeIntent, MergeOutcome, MERGE_RESULT_FAILED } from '../workflow/pr-merger';\nimport { FinishBanner, FinishBannerInput } from '../workflow/finish-banner';\nimport { MergeBodyTempFile } from '../workflow/merge-body-temp-file';\nimport { GatedPrPublisher } from '../workflow/gated-pr-publisher';\nimport { ProvenanceEnforcer, ProvenanceReport } from '../workflow/provenance-enforcer';\nimport { PrCommentRequest, PrCommentUpserter } from '../workflow/pr-comment-upserter';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { TriggeredChecklist } from '../workflow/checklist-detector';\nimport { Dashboard, DashboardInput, ChecklistRow, DETAIL_COMMENT_MARKER } from '../../dashboard/dashboard';\nimport { ChecklistCommentRenderer, CHECKLIST_COMMENT_MARKER } from '../../dashboard/checklist-comment-renderer';\nimport { ChecklistCommentRow } from '../../dashboard/checklist-comment-row';\nimport { AuthorIdentityResolver } from '../../dashboard/author-identity';\nimport { HotfixFinishPreparer } from '../workflow/hotfix-finish-preparer';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The three inputs the PR COMMENTS are rendered from, bundled so `publishAll` takes one parameter for\n * them instead of three it only forwards. Data-only, per CLAUDE.md.\n */\nclass PrCommentSources {\n scan: ChecklistScan;\n review: PrSummary;\n provenance: ProvenanceReport;\n\n constructor(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport) {\n this.scan = scan;\n this.review = review;\n this.provenance = provenance;\n }\n}\n\n/**\n * Everything the PR upsert needs. Data-only, per CLAUDE.md — it replaced a 5-positional-parameter method\n * once `tokenSuffix` had to travel too, so the body can be re-rendered with the PR's own URL after\n * `gh pr create` returns it (see the INVARIANT comment in upsertPr).\n */\nclass PrUpsertRequest {\n repoRoot = '';\n baseBranch = '';\n title = '';\n /** The description as first published — rendered with whatever URL was known at the time. */\n body = '';\n /**\n * The hidden gate-token marker exactly as appended to `body`, so a re-render can reproduce the same\n * bytes. Kept separate from `body` because Dashboard renders the human/git-log half and must not know\n * about HMACs.\n */\n tokenSuffix = '';\n input: DashboardInput;\n\n constructor(input: DashboardInput) {\n this.input = input;\n }\n}\n\n// A resolved PR's number + web URL. Both '' when the PR can't be resolved (e.g. create failed).\nclass PrRef {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n// The outcome of the whole upsert: the PR number + web URL ('' each when unresolved) plus what actually\n// happened to the merge, so the final summary reports the REAL result rather than assuming success. The\n// URL is carried so the closing block can hand the AI a clickable link to relay to the user verbatim.\nclass UpsertResult {\n prNumber: string;\n prUrl: string;\n merge: MergeOutcome;\n\n constructor(prNumber: string, prUrl: string, merge: MergeOutcome) {\n this.prNumber = prNumber;\n this.prUrl = prUrl;\n this.merge = merge;\n }\n}\n\n// STAGE ③ — FINISH of the AI-first PR flow, and the ONLY command that posts PRs. Runs after\n// `wp-review-upsert-pr` verified the branch and the AI spawned the reviewers + wrote summary.json.\n//\n// In order: (1) REFUSE on an unvalidated 3-point merge and REQUIRE stage ②'s receipt; (2) REQUIRE\n// summary.json + every reviewer's verdict + provenance; (3) run the build gate UNLESS the receipt already\n// covers this exact HEAD; (4) render the dashboard; (5) create/update the PR via `gh`.\n//\n// It no longer FINALIZES a merge — stage ② does. Two commands owning conflict-resolution validation is two\n// implementations that drift, and finalizing here came too late to help anyway: the reviewers had already\n// reviewed the pre-merge tree by then.\n@injectable(bindingScopeValues.Singleton)\nexport class FinishUpsertPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildLog: BuildGateLog,\n private readonly mergeState: MergeState,\n private readonly prMerger: PrMerger,\n private readonly publisher: GatedPrPublisher,\n private readonly dashboard: Dashboard,\n private readonly authorIdentity: AuthorIdentityResolver,\n // The 2nd PR comment. Its own class because it is its own surface — see ChecklistCommentRenderer.\n private readonly checklistComment: ChecklistCommentRenderer,\n private readonly checklistScanner: ChecklistScanner,\n private readonly verdictGate: ReviewerVerdictGate,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly gateTokenService: GateTokenService,\n // Owns the reviewer-provenance integrity check and its audit record — see ProvenanceEnforcer.\n private readonly provenanceEnforcer: ProvenanceEnforcer,\n // NOTE: ChecklistInstructionsService is deliberately NOT injected here any more. Its \"You MUST run\n // these N reviewer subagent(s)\" block is now rendered by ReviewerVerdictGate and ONLY for checklists\n // that genuinely never ran, so no other code path in this command can print it at a refusal.\n private readonly receipts: ReviewStageReceiptService,\n private readonly banner: FinishBanner,\n // `gh pr merge --body-file` takes a path, so the bytes just published as the PR description are\n // spilled to a throwaway file for the length of one `gh` call. Nothing durable — the PR holds it.\n private readonly mergeBodyFile: MergeBodyTempFile,\n // ONE marker-keyed upsert, shared by both PR comments (the full dashboard and the checklist).\n private readonly commentUpserter: PrCommentUpserter,\n // Pins the two GitHub repo settings that decide whether a UI merge writes the body we just\n // rendered. Server-side, so no config can express them — see SquashSettingsEnforcer.\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly stageConsole: StageOutputLog,\n private readonly branchIdentity: BranchIdentity,\n private readonly hotfixFinish: HotfixFinishPreparer,\n private readonly rounds: ReviewRoundStateService,\n ) {}\n\n /**\n * Runs with this stage's console CAPTURED to a file (see StageOutputLog). What still reaches the\n * terminal is what an agent must act on: the build heartbeat and result, and the closing banner with\n * the PR link and whatever is still owed. The dashboard computation, the gh round trips and the\n * comment upserts are in the file.\n */\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, FINISH_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n // Refresh the AI-facing workflow doc so it's present + current for any failure message to cite.\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n if (this.branchIdentity.isHotfix()) {\n await this.runHotfixStage(repoRoot);\n return;\n }\n // 1. REQUIRE stage ② — see assertStageTwoRan. Returns true when its receipt covers THIS commit,\n // which is what lets the build gate below be skipped rather than re-run for a foregone answer.\n const buildAlreadyGreen = this.assertStageTwoRan(repoRoot);\n\n // 2. REQUIRE the AI-authored summary.json (throws InformAiError with the schema if missing/invalid).\n // Compute the consumer checklists this diff triggered FIRST so an unacknowledged BLOCK throws\n // here — BEFORE any `gh pr create` — matching the guarantee buildCommand already provides.\n // The SAME scan wp-review-upsert-pr runs, with filterAlreadyReviewed:true so `outstanding` is exactly what\n // still owes a verdict (Z of N of X). Sharing the computation is the point: the command that REPORTS\n // and the command that GATES must not be able to disagree about what is owed. review-<id>.json files\n // persist locally, so a re-run re-validates the EXISTING verdicts against the (possibly changed)\n // applicable set for free — an unchanged checklist needs no re-review, a newly-applicable one refuses\n // until its file is written.\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(true, 'stage3-finish'));\n const receipt = this.receipts.read(repoRoot, featureName);\n const remediations = this.rounds.capRemediations(repoRoot, scan.summaryPath, receipt, config.maxReviewerRounds);\n for (const result of scan.results) result.remediation = remediations[result.id] ?? '';\n scan.outstanding = scan.outstanding.filter((req: RequiredChecklist): boolean => remediations[req.id] === undefined);\n const required = scan.applicable;\n // The applicable checklists that are supposed to HAVE a verdict — everything except the optional ones\n // nobody ran. Used for provenance and for the dashboard rows, both of which ask \"who reviewed this?\"\n // and would otherwise demand an answer from a review the human declined: provenance would refuse the\n // PR because a subagent that was never meant to run cannot be proven to have run, and the dashboard\n // would render a MISSING verdict for it.\n const verdicted = this.verdictedOf(scan);\n // FAIL FAST on an unclear checklist, BEFORE summary.json is parsed and before the build gate runs. A\n // missing reviewer is not a summary.json defect (folding it in made the AI fix the wrong thing), and\n // nobody should wait on a build to be told a reviewer never ran. ReviewerVerdictGate owns the\n // distinction between unreadable / REFUSED / never-ran, and retires the red verdicts it acts on.\n this.verdictGate.assertEveryReviewerRan(scan);\n const review = this.reviewJsonService.loadSummaryJson(summaryJsonPath(repoRoot, featureName), required, '', remediations);\n this.applyRoundAudits(review, scan, receipt);\n\n // 2c. For every verdicted checklist, VERIFY (from the harness's own artifacts) that a real reviewer\n // SUBAGENT actually ran on this branch — the coding agent may not self-certify. Its NAME is not\n // checked; see SubagentProvenanceService.isReviewerRun. Absent CLAUDE_CODE_SESSION_ID this skips with a warning (CI / plain terminal).\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const provenance = this.provenanceEnforcer.enforce(verdicted, currentBranch, repoRoot, config);\n\n // 2b. The build gate validates the WORKING TREE but we push HEAD — so they MUST be identical.\n this.gitExec.assertCleanTree(repoRoot);\n\n // 3. Build gate, then post the gated body, then push (that ORDER — see GatedPrPublisher).\n await this.runOrSkipBuildGate(repoRoot, buildAlreadyGreen);\n const base = this.branchNaming.baseBranchName(execSync('git branch --show-current', { encoding: 'utf8' }).trim());\n\n process.stdout.write('\\n' + SEP + '📋 Dashboard + PR\\n' + SEP + '\\n');\n const title = this.prTitleFrom(review);\n const input = this.computeDashboardInput(repoRoot, true, review, title, verdicted, scan);\n const result = this.publishAll(repoRoot, base, input, new PrCommentSources(scan, review, provenance));\n this.archiveConsumedReview(repoRoot, featureName, result);\n\n // The closing recap + the clickable-link directive, BOTH derived from the real merge outcome.\n // Nothing here may hard-code success: a stranded PR under a green checkmark is how PRs got\n // abandoned (see FinishBanner).\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n // `say`: the PR link and what is still owed are the whole reason a caller ran this command, and a\n // not-done outcome carries the commands that fix it. Neither may end up only in a log file.\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n private applyRoundAudits(review: PrSummary, scan: ChecklistScan, receipt: ReturnType<ReviewStageReceiptService['read']>): void {\n for (const result of review.results) {\n const trail = this.rounds.auditTrail(scan.summaryPath, result.id, receipt);\n if (trail === '') continue;\n result.output = trail;\n if (result.remediation !== '') result.remediation = `${trail}\\n\\n#### Final state\\n${result.remediation}`;\n }\n }\n\n /** Hotfix finish owns every prerequisite normally split between stages ② and ③. */\n private async runHotfixStage(repoRoot: string): Promise<void> {\n const state = await this.hotfixFinish.prepare(repoRoot);\n const base = this.branchNaming.baseBranchName(state.currentBranch);\n const title = this.prTitleFrom(state.review);\n const input = this.computeDashboardInput(repoRoot, true, state.review, title, [], state.scan, true);\n const sources = new PrCommentSources(state.scan, state.review, state.provenance);\n const result = this.publishAll(repoRoot, base, input, sources);\n this.archiveConsumedReview(repoRoot, state.featureName, result);\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n // Validate + commit + finalize a 3-point merge the AI resolved, if one is in progress. Finalizing here\n // does NOT push (pushRemote=false): this command pushes exactly ONCE, from GatedPrPublisher, and only\n // after summary.json + every BLOCK checklist + the build gate pass and the gated PR body is written.\n /**\n * The build gate — SKIPPED when stage ②'s receipt already covers this exact HEAD.\n *\n * The gate is authoritative per-COMMIT, not per-command: re-running it on a tree that has not moved\n * since stage ② verified it buys nothing and costs a full `nx affected`. That skip is what makes the\n * three-stage flow cost ONE build rather than two, and it is why moving the gate earlier was affordable.\n */\n private async runOrSkipBuildGate(repoRoot: string, alreadyGreen: boolean): Promise<void> {\n if (alreadyGreen) {\n // `say`, for the same reason the gate's own two lines are: a caller watching for a build needs\n // to be told, live, that there is not going to be one.\n this.stageConsole.say('\\n🛠️ Build gate: already green for this commit (stage ② receipt) — skipping the rebuild.\\n' + this.skippedBuildLogNote(repoRoot));\n return;\n }\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions('🛠️ Build gate (authoritative)', 'pnpm wp-finish-upsert-pr', 'Build failed — no PR created/updated.', FINISH_STAGE));\n }\n\n /**\n * When the gate is SKIPPED and build-log capture is on, name STAGE ②'s log — the one build that\n * actually ran for this commit. Deliberately never names a finish-stage log: no finish build ran, and\n * pointing at a file this command did not write would claim a build that did not happen.\n *\n * The path is recomputed rather than stored, and that is sound precisely BECAUSE this branch is only\n * reached when the receipt covers the current HEAD: same worktree, same branch, same sha ⇒ the same\n * deterministic filename stage ② wrote. Empty string when the file is gone — a log that was reaped or\n * never written must not be named as though a reader could open it.\n */\n private skippedBuildLogNote(repoRoot: string): string {\n const log = this.buildLog.existingLogFor(repoRoot, REVIEW_STAGE);\n return log === '' ? '' : ` Stage ②'s full build output: ${log}\\n`;\n }\n\n /**\n * The two stage-② preconditions, together: no unvalidated merge, and a receipt proving stage ② ran.\n * Returns true when that receipt covers the CURRENT HEAD, i.e. the build gate can be skipped.\n */\n private assertStageTwoRan(repoRoot: string): boolean {\n this.assertNoUnvalidatedMerge(repoRoot);\n return this.assertReviewStageRan(repoRoot, this.aiBranchName.getFeatureName(), this.gitOut(['rev-parse', 'HEAD']));\n }\n\n /**\n * REFUSE while a 3-point merge is still unvalidated — do not finalize it here.\n *\n * This command used to do the finalizing itself. Finalizing means validating a conflict resolution, and\n * two commands owning that means two implementations that can drift; `PrContextWriter`'s docstring\n * records this codebase already paying for exactly that once. It also came too late to matter: by the\n * time finish ran, the reviewers had already reviewed the pre-merge tree.\n *\n * So stage ② owns it, and finish only checks. Nothing is lost — the recovery is one command away, and\n * running it also builds the merged tree and re-briefs the reviewers against it, which finalizing here\n * never did.\n */\n private assertNoUnvalidatedMerge(repoRoot: string): void {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return;\n throw new InformAiError(\n '⛔ NO PR — a 3-point merge on this branch is still unvalidated, so nothing here has been\\n' +\n 'verified: the conflict resolution is unchecked, the merged tree was never built, and any\\n' +\n 'reviewer that ran judged the PRE-merge code.\\n\\n' +\n `Conflicted file(s): ${marker.conflictedFiles.join(', ')}\\n\\n` +\n 'Resolve them (see .webpieces/instruct-ai/webpieces.mergeprocess.md), then run:\\n' +\n ' pnpm wp-review-upsert-pr\\n' +\n 'It validates the resolution, commits it, builds it, and re-briefs the reviewers.',\n );\n }\n\n /**\n * REQUIRE stage ② (`wp-review-upsert-pr`) to have run, and report whether it ran on THIS commit.\n *\n * Returns true when the receipt matches the current HEAD — the caller then skips its own build, because\n * the receipt IS the gate for that sha and rebuilding an unchanged tree is a second full `nx affected`\n * run for a foregone answer.\n *\n * Without this check a repo with NO checklists has nothing forcing stage ②: `assertEveryReviewerRan`\n * is vacuous, and summary.json — the only other interlock — is a file the AI writes itself. It could\n * write it and come straight here, skipping the merge validation and the build entirely.\n */\n private assertReviewStageRan(repoRoot: string, featureName: string, headSha: string): boolean {\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(\n '⛔ NO PR — stage ② never ran on this branch. That means the 3-point merge is unvalidated,\\n' +\n 'the build gate has not run, no diff was extracted, and no reviewer was briefed.\\n\\n' +\n 'Run: pnpm wp-review-upsert-pr\\n' +\n '(then spawn the reviewers it names, write summary.json, and re-run this command)',\n );\n }\n if (receipt.headSha === headSha) return true;\n // Not fatal. Re-reviewing on every follow-up commit would be intolerable, and most drift is a typo\n // fix. But it is never silent: the build re-runs here, and the PR says the reviewers saw an older tree.\n process.stderr.write(\n `\\n⚠️ HEAD moved since stage ② ran (reviewed ${receipt.headSha.slice(0, 8)}, now ${headSha.slice(0, 8)}).\\n` +\n ' The build gate will re-run, and the PR will record that reviewers judged an earlier tree.\\n' +\n ' If the change was substantive, re-run pnpm wp-review-upsert-pr and re-spawn the reviewers.\\n\\n',\n );\n return false;\n }\n\n /**\n * Retire the review this run just used — move summary.json to old-summary.json beside it, stamped as\n * audit-only (see ReviewJsonService.archiveSummaryJson).\n *\n * WHY it moves rather than staying put: summary.json left behind is a live-looking file describing a\n * review that has already shipped, and the next `wp-review-upsert-pr` on this branch finds it sitting\n * there. A reviewer subagent that judges the PR's stated INTENT — its title, summary or risk level —\n * then reads the previous round's review and can return GREEN against a title that no longer exists,\n * with nothing in the verdict distinguishing that from a real pass. Moving it makes the only route back\n * to this command a freshly-written review.\n *\n * ONLY on a PR that actually went up. A run that died before publishing must stay re-runnable without\n * making the AI rewrite a review that was never used, and prNumber === '' is exactly that case.\n * Non-fatal: the PR is live by here, so an unwritable archive warns rather than failing the command.\n */\n private archiveConsumedReview(repoRoot: string, featureName: string, result: UpsertResult): void {\n if (result.prNumber === '') return;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the PR is already up; a failed archive must not fail the command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const archived = this.reviewJsonService.archiveSummaryJson(summaryJsonPath(repoRoot, featureName));\n if (archived !== '') process.stdout.write(` archived this run's summary.json → ${archived} (audit only) ✓\\n`);\n // Beside it, so an archived review keeps the transcript links belonging to the round that\n // produced it — a review whose provenance was overwritten by the NEXT round audits nothing.\n this.provenanceEnforcer.archiveRecord(prDirFor(repoRoot, featureName));\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(`⚠️ Could not archive summary.json (non-fatal — the PR is already up): ${error.message}\\n`);\n }\n }\n\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // The user-facing PR title: the AI-authored review.title, or — if omitted — a readable fallback\n // derived from the stable feature name (NEVER the internal `Squash merge of <branch>` commit subject).\n private prTitleFrom(review: PrSummary): string {\n if (review.title !== '') return review.title;\n return this.aiBranchName.getFeatureName().replace(/[-/]+/g, ' ').trim();\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private computeDashboardInput(repoRoot: string, buildPassed: boolean, review: PrSummary, title: string, required: readonly RequiredChecklist[], scan: ChecklistScan, hotfix = false): DashboardInput {\n const config = loadAndValidate(repoRoot).prGate;\n const forkPoint = this.gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = this.gitOut(['rev-parse', 'HEAD']);\n const mainHead = this.gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = this.gitOut(['diff', range, '--name-only'])\n .split('\\n')\n .filter((f: string): boolean => f.trim() !== '');\n const patch = this.gitOut(['diff', range]);\n\n const gateResults = this.dashboard.computeGateResults(config.gates, changedFiles);\n const disables = this.dashboard.countAddedDisables(patch);\n const rows = this.checklistRows(required, review);\n // buildCommand travels into the dashboard so the PR-body footer can NAME the command that vouched\n // for this commit. The footer used to assert \"build ran via nx affected\" on every repo, which was\n // simply false wherever buildCommand is not nx.\n // `scan.suppressed.length`, never `scan.reviewersDisabled` alone: the dashboard and the commit\n // body have to state HOW MANY reviewers were killed, because a suppressed 4 and an applicable 0\n // are different facts that both render as an empty `rows`. See DashboardInput.\n return new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, review, rows, this.buildAffected.resolveBuildCommand(repoRoot), scan.suppressed.length, this.authorIdentity.resolve(review.model), hotfix);\n }\n\n /**\n * The applicable checklists MINUS the optional ones nobody ran.\n *\n * Not folded into `ChecklistScan` as yet another field: `applicable` (what matched) and `optionalNotRun`\n * (what was declined) are both facts about the scan, whereas this is one command's view of them, and the\n * roster comment deliberately wants the OTHER view — it lists the declined ones precisely so the PR does\n * not imply they passed.\n */\n private verdictedOf(scan: ChecklistScan): RequiredChecklist[] {\n const skipped = new Set(scan.optionalNotRun.map((r: RequiredChecklist): string => r.id));\n return scan.applicable.filter((r: RequiredChecklist): boolean => !skipped.has(r.id));\n }\n\n // Pair each matched checklist with its resolved verdict for the dashboard.\n //\n // A checklist reaching this point is always PASS, WARN or OVERRIDDEN, and the reason is ReviewerVerdictGate\n // — NOT loadSummaryJson. The gate runs one line earlier and throws on every other state (FAIL, MISSING,\n // BAD_FORMAT), so loadSummaryJson's own checklist validation can no longer be the thing that rejects them;\n // it re-validates the same set and finds it clean. This comment used to credit loadSummaryJson, which made\n // the ordering look deliberate while the gate's generic \"no verdict yet\" message masked every refusal.\n // WARN belongs in that list: yellow SHIPS, so it is not outstanding and reaches the dashboard.\n private checklistRows(required: readonly RequiredChecklist[], review: PrSummary): ChecklistRow[] {\n return required.map((req: RequiredChecklist): ChecklistRow => {\n const verdict = this.reviewJsonService.resolveVerdict(req, review.results);\n return new ChecklistRow(req.id, verdict.status, verdict.detail);\n });\n }\n\n /**\n * One comment row per DEFINED checklist — matched or not — pairing the roster's match evidence with the\n * resolved verdict. Built from `scan.roster` rather than from the applicable set: the skipped ones are\n * absent from `applicable` by construction, and their \"why not\" evidence (the configured globs and the\n * changed-file total) exists nowhere else without recomputing the diff a second way.\n */\n private commentRows(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): ChecklistCommentRow[] {\n // checklist id -> did its reviewer open the diff. Absent ⇒ not assessed, which prints nothing (see ChecklistCommentRow.diffRead).\n const readByChecklist = new Map<string, boolean>();\n for (const e of provenance.evidence) readByChecklist.set(e.checklistId, e.readDiff);\n return scan.roster.entries.map((entry: TriggeredChecklist): ChecklistCommentRow => {\n const ran = entry.matchedFiles.length > 0;\n const req = new RequiredChecklist(entry.def.id, entry.def.reviewer, entry.def.doc, entry.matchedFiles, entry.matchedPatterns, entry.def.required);\n // A skipped checklist has no verdict to resolve — asking for one would report it as MISSING,\n // i.e. as an unreviewed obligation, when in fact it never had one.\n const verdict = ran ? this.reviewJsonService.resolveVerdict(req, review.results) : new ChecklistVerdict(entry.def.id, '', '');\n const identity = review.results.find((result): boolean => result.id === entry.def.id);\n const row = new ChecklistCommentRow(identity?.agent ?? 'unknown', identity?.model ?? 'unknown', entry.def.id, verdict.status, verdict.detail, ran, entry.def.patterns, entry.matchedPatterns, entry.matchedFiles, scan.roster.changedFileCount);\n row.required = entry.def.required;\n const read = readByChecklist.get(entry.def.id);\n row.diffRead = read === undefined ? '' : read ? 'yes' : 'no';\n return row;\n });\n }\n\n // Hidden HMAC gate-token marker (with a leading blank line) to append to the PR body, or '' when the\n // repo sets no gateSalt (byte-identical body to before this feature). Bound to the pushed HEAD sha.\n private gateTokenBody(gateSalt: string, headSha: string): string {\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n return marker === '' ? '' : `\\n\\n${marker}\\n`;\n }\n\n /**\n * Publish the roster + every reviewer's full `output` as ONE combined PR comment, idempotently (find the\n * marker comment → PATCH it, else POST). Never fatal: by here the PR is already created/updated, so a\n * `gh` failure only warns.\n *\n * Posted on EVERY run of a repo that defines checklists — including one where nothing matched, because\n * \"all five were evaluated and none applied\" is the good news the old comment could not deliver. The\n * guard is `scan.defined.length`, deliberately NOT the number of rows that ran: a repo with no\n * checklists configured must still see no comment at all (see ChecklistCommentRenderer).\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private postChecklistComment(repoRoot: string, prNumber: string, scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): void {\n if (prNumber === '' || scan.defined.length === 0) return;\n if (!loadAndValidate(repoRoot).prGate.checklistComments) return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = CHECKLIST_COMMENT_MARKER;\n request.body = this.checklistComment.render(this.commentRows(scan, review, provenance), provenance.verified, scan.roster.baseResolved, scan.suppressed.length, this.branchIdentity.isHotfix());\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'checklist-comment.json';\n request.label = 'checklist review comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR, the remote branch, and the local branch all share the one stable feature name. Look up /\n // create / merge against `baseBranch` (baseBranchName tolerates a leftover `…wpN` mid-transition).\n // GatedPrPublisher owns the edit/push/create half and its ORDERING — the gated body goes up before\n // the push, so CI's `synchronize` read cannot see the previous run's token.\n private upsertPr(request: PrUpsertRequest): UpsertResult {\n const repoRoot = request.repoRoot;\n const baseBranch = request.baseBranch;\n const title = request.title;\n const input = request.input;\n const prDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n fs.mkdirSync(prDir, { recursive: true });\n const bodyFile = path.join(prDir, 'pr-body.md');\n fs.writeFileSync(bodyFile, request.body + '\\n');\n\n const published = this.publisher.publish(baseBranch, title, bodyFile);\n if (published.createFailed) {\n process.stderr.write('⚠️ gh pr create failed — create the PR manually with the body in:\\n ' + bodyFile + '\\n');\n return new UpsertResult('', '', new MergeOutcome(false, false, '⚠️ did NOT merge — there is no PR to merge (gh pr create failed above)', MERGE_RESULT_FAILED));\n }\n const num = published.number;\n\n // Set the squash-merge SUBJECT to the PR title (+ the `(#N)` GitHub normally appends, which an\n // explicit --subject would otherwise drop) and the BODY to the compact commit summary, so main's\n // history carries the PR title + risk/flags/link — NOT the internal `Squash merge of <branch>`\n // subject GitHub would inherit from the single squash commit on the branch.\n const ref = this.prRef(baseBranch);\n const subject = ref.number !== '' ? `${title} (#${ref.number})` : title;\n\n /*\n * THE INVARIANT: the merge body IS the PR description, byte for byte.\n *\n * That is what makes every landing route agree — the GitHub Merge button and a bare `gh pr merge`\n * copy the description via `squash_merge_commit_message: PR_BODY`, while `wp-land-pr` and finish's\n * own auto-merge pass these bytes with `--body-file`. If the two strings could differ, which route\n * landed the commit would change what history says, which is precisely the bug this whole change\n * exists to remove. `pr-body-is-merge-body.spec.ts` pins it.\n *\n * The one wrinkle is the self-link. A brand-new PR has no URL until `gh pr create` returns, so the\n * body published a moment ago was rendered with `prUrl: ''`. Re-render now that the URL is known\n * and push the corrected description back, so the two strings match and the commit carries its own\n * link. Only the CREATE path pays that extra edit: on every later run the URL was already known\n * before publishing, `finalBody` matches what went up, and nothing is re-sent.\n */\n const finalBody = this.dashboard.renderPrBody(input, ref.url) + request.tokenSuffix;\n if (finalBody !== request.body) this.backfillPrBody(ref.number, bodyFile, finalBody);\n\n // The DURABLE copy of these bytes is the PR description published above; this is a throwaway\n // file because `--body-file` takes a path. `wp-land-pr` reads the description back from GitHub,\n // so nothing here has to survive the process (see decisions/0005).\n const mergeBodyFile = this.mergeBodyFile.write(finalBody + '\\n');\n // PrMerger owns the direct-merge / auto-merge-fallback decision AND checks every gh status, so a\n // merge that did not happen is reported as such instead of being swallowed (see pr-merger.ts).\n // REQUIRED config — no default here on purpose. A missing value (an older published\n // rules-config that has no such field) reaches PrMerger as '' and is treated as \"do not merge\".\n const mergeMode = loadAndValidate(repoRoot).prGate.mergeMode ?? '';\n // `false`: this caller is POLICY-driven — only a config that really says AUTO merges here.\n const outcome = this.prMerger.merge(baseBranch, subject, mergeBodyFile, new MergeIntent(mergeMode, false));\n return new UpsertResult(ref.number !== '' ? ref.number : num, ref.url, outcome);\n }\n\n /**\n * Everything the gated flow PUBLISHES, in the one order that is safe — the three surfaces plus the\n * merge, as a single unit.\n *\n * 1. the PR DESCRIPTION = the compact git-log body (+ the hidden gate token), written before the\n * push so CI's `synchronize` read can never see the previous run's token,\n * 2. the 1st comment = the full dashboard,\n * 3. the 2nd comment = each reviewer's output.\n *\n * The token is bound to the LOCAL HEAD sha and minted here because we only reach this line after the\n * build gate and every BLOCK checklist passed, so minting is legitimate. Nothing about\n * HMAC(salt, HEAD) needs the remote to have the commit yet.\n *\n * Extracted from `run` when the two comments made it 82 lines against a hard 80-line rule — and it\n * earns its own name: these four steps have a REQUIRED order, and the comment explaining that order\n * belongs with them rather than inside a method that also loads config and runs a build gate.\n */\n private publishAll(repoRoot: string, base: string, input: DashboardInput, sources: PrCommentSources): UpsertResult {\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n const headSha = this.gitOut(['rev-parse', 'HEAD']);\n const upsert = new PrUpsertRequest(input);\n upsert.repoRoot = repoRoot;\n upsert.baseBranch = base;\n upsert.title = input.title;\n upsert.tokenSuffix = this.gateTokenBody(gateSalt, headSha);\n // `existingPrUrl` is '' only for a brand-new PR — there is no URL to self-link to until\n // `gh pr create` returns one, and upsertPr back-fills it the moment it does.\n upsert.body = this.dashboard.renderPrBody(input, this.existingPrUrl(base)) + upsert.tokenSuffix;\n const result = this.upsertPr(upsert);\n\n // In the order the PR body's pointer promises: full dashboard 1st, reviewer output 2nd. Both are\n // idempotent by hidden marker and both non-fatal — the PR is up by now, so a `gh` hiccup on a\n // comment must not turn a finished run into a failed one.\n this.postDetailComment(repoRoot, result.prNumber, input);\n this.postChecklistComment(repoRoot, result.prNumber, sources.scan, sources.review, sources.provenance);\n\n // Having just written the description AS the commit body, make sure GitHub will actually use it.\n // Here rather than anywhere earlier because it is about what happens to the artifact we just\n // published, and it must run on EVERY repo — including mergeMode=NONE ones that never reach\n // PrMerger, which are exactly the repos where a UI merge decides what main's history says.\n this.squashSettings.ensure();\n return result;\n }\n\n /**\n * Re-publish the description now that the PR's own URL is known (create path only).\n *\n * Non-fatal on purpose. The PR exists, its body already carries a valid gate token for the pushed\n * head, and the code is up — the ONLY thing missing is the self-link on the first line. Aborting a\n * finished run over a cosmetic back-link would be a worse outcome than the missing link, and the very\n * next `wp-finish-upsert-pr` writes it (by then the URL is known before publishing, so it goes up with\n * the body). The merge body still gets the linked version regardless: it is filed from `finalBody`.\n */\n private backfillPrBody(prNumber: string, bodyFile: string, finalBody: string): void {\n if (prNumber === '') return;\n fs.writeFileSync(bodyFile, finalBody + '\\n');\n const res = spawnSync('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile], {\n encoding: 'utf8',\n });\n if (res.status !== 0) {\n process.stderr.write(\"⚠️ Could not add the PR's own link to its description (non-fatal — the PR and the gate\\n\" + ' token are already up). The next wp-finish-upsert-pr writes it.\\n');\n return;\n }\n process.stdout.write(' back-filled the PR description with its own link ✓\\n');\n }\n\n /**\n * The PR's web URL if one is already open for this branch, else '' — read BEFORE publishing so the\n * description can carry its own link on the first render. Only a brand-new PR gets '' (and then\n * {@link backfillPrBody} fixes it up after `gh pr create` returns a URL).\n */\n private existingPrUrl(baseBranch: string): string {\n return this.prRef(baseBranch).url;\n }\n\n /**\n * The 1st PR comment: the FULL dashboard — every row including the green ones, the whole summary, the\n * 3-point hash points. This is what the PR description used to be, and moving it here is the entire\n * point of the change: the description is now the git-log body, and a squash commit must not carry a\n * risk table.\n *\n * Posted unconditionally (any repo, checklists or not), because the description's last bullet PROMISES\n * a 1st comment holding the detail. A pointer to a comment that does not exist is worse than no\n * pointer. Non-fatal — the PR is already up, and the description alone is a complete, readable record.\n */\n private postDetailComment(repoRoot: string, prNumber: string, input: DashboardInput): void {\n if (prNumber === '') return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = DETAIL_COMMENT_MARKER;\n const detail = this.dashboard.renderDetailComment(input);\n request.body = input.hotfix ? detail + '\\n\\n' + DETAIL_COMMENT_MARKER : DETAIL_COMMENT_MARKER + '\\n' + detail;\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'detail-comment.json';\n request.label = 'full dashboard comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR's number + web URL (for the merge subject `(#N)` and the commit-body back-link). Both ''\n // if it can't be resolved. Rendered via jq into one tab-separated line so no JSON parsing is needed.\n private prRef(baseBranch: string): PrRef {\n const result = spawnSync('gh', ['pr', 'view', baseBranch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"'], { encoding: 'utf8' });\n if (result.status !== 0) {\n return new PrRef('', '');\n }\n const parts = (result.stdout ?? '').trim().split('\\t');\n return new PrRef(parts[0] ?? '', parts[1] ?? '');\n }\n}\n"]}
1
+ {"version":3,"file":"finish-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/finish-upsert-pr-command.ts"],"names":[],"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EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,0BAA0B,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAC7I,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO,IAAI,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAC7B,CAAC;QACD,MAAM,KAAK,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACvD,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACrD,CAAC;CACJ,CAAA;AAnkBY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,mCAAY;QACZ,4BAAY;QACjB,kBAAO;QACD,8BAAa;QAClB,6BAAY;QACV,wBAAU;QACZ,oBAAQ;QACP,qCAAgB;QAChB,qBAAS;QACJ,wCAAsB;QAEpB,qDAAwB;QACxB,oCAAgB;QACrB,2CAAmB;QACb,gCAAiB;QAClB,+BAAgB;QAEd,wCAAkB;QAI5B,gDAAyB;QAC3B,4BAAY;QAGL,wCAAiB;QAEf,uCAAiB;QAGlB,iDAAsB;QACxB,iCAAc;QACZ,6BAAc;QAChB,6CAAoB;QAC1B,4CAAuB;GArC3C,qBAAqB,CAmkBjC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { loadAndValidate, prDirFor, summaryJsonPath, PrSummary, RequiredChecklist, ChecklistVerdict, writeTemplate, RepoRootFinder, ReviewJsonService, GateTokenService, InformAiError, toError, BranchIdentity } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { ReviewerVerdictGate } from '../workflow/reviewer-verdict-gate';\nimport { GitExec } from '../workflow/git-exec';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BuildGateLog, FINISH_STAGE, REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { MergeState } from '../workflow/merge-state';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewRoundStateService } from '../workflow/review-round-state';\nimport { StageOutputLog, FINISH_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { PrMerger, MergeIntent, MergeOutcome, MERGE_RESULT_FAILED } from '../workflow/pr-merger';\nimport { FinishBanner, FinishBannerInput } from '../workflow/finish-banner';\nimport { MergeBodyTempFile } from '../workflow/merge-body-temp-file';\nimport { GatedPrPublisher } from '../workflow/gated-pr-publisher';\nimport { ProvenanceEnforcer, ProvenanceReport } from '../workflow/provenance-enforcer';\nimport { PrCommentRequest, PrCommentUpserter } from '../workflow/pr-comment-upserter';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { TriggeredChecklist } from '../workflow/checklist-detector';\nimport { Dashboard, DashboardInput, ChecklistRow, DETAIL_COMMENT_MARKER } from '../../dashboard/dashboard';\nimport { ChecklistCommentRenderer, CHECKLIST_COMMENT_MARKER } from '../../dashboard/checklist-comment-renderer';\nimport { ChecklistCommentRow } from '../../dashboard/checklist-comment-row';\nimport { AuthorIdentityResolver } from '../../dashboard/author-identity';\nimport { HotfixFinishPreparer } from '../workflow/hotfix-finish-preparer';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The three inputs the PR COMMENTS are rendered from, bundled so `publishAll` takes one parameter for\n * them instead of three it only forwards. Data-only, per CLAUDE.md.\n */\nclass PrCommentSources {\n scan: ChecklistScan;\n review: PrSummary;\n provenance: ProvenanceReport;\n\n constructor(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport) {\n this.scan = scan;\n this.review = review;\n this.provenance = provenance;\n }\n}\n\n/**\n * Everything the PR upsert needs. Data-only, per CLAUDE.md — it replaced a 5-positional-parameter method\n * once `tokenSuffix` had to travel too, so the body can be re-rendered with the PR's own URL after\n * `gh pr create` returns it (see the INVARIANT comment in upsertPr).\n */\nclass PrUpsertRequest {\n repoRoot = '';\n baseBranch = '';\n title = '';\n /** The description as first published — rendered with whatever URL was known at the time. */\n body = '';\n /**\n * The hidden gate-token marker exactly as appended to `body`, so a re-render can reproduce the same\n * bytes. Kept separate from `body` because Dashboard renders the human/git-log half and must not know\n * about HMACs.\n */\n tokenSuffix = '';\n input: DashboardInput;\n\n constructor(input: DashboardInput) {\n this.input = input;\n }\n}\n\n// A resolved PR's number + web URL. Both '' when the PR can't be resolved (e.g. create failed).\nclass PrRef {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n// The outcome of the whole upsert: the PR number + web URL ('' each when unresolved) plus what actually\n// happened to the merge, so the final summary reports the REAL result rather than assuming success. The\n// URL is carried so the closing block can hand the AI a clickable link to relay to the user verbatim.\nclass UpsertResult {\n prNumber: string;\n prUrl: string;\n merge: MergeOutcome;\n\n constructor(prNumber: string, prUrl: string, merge: MergeOutcome) {\n this.prNumber = prNumber;\n this.prUrl = prUrl;\n this.merge = merge;\n }\n}\n\n// STAGE ③ — FINISH of the AI-first PR flow, and the ONLY command that posts PRs. Runs after\n// `wp-review-upsert-pr` verified the branch and the AI spawned the reviewers + wrote summary.json.\n//\n// In order: (1) REFUSE on an unvalidated 3-point merge and REQUIRE stage ②'s receipt; (2) REQUIRE\n// summary.json + every reviewer's verdict + provenance; (3) run the build gate UNLESS the receipt already\n// covers this exact HEAD; (4) render the dashboard; (5) create/update the PR via `gh`.\n//\n// It no longer FINALIZES a merge — stage ② does. Two commands owning conflict-resolution validation is two\n// implementations that drift, and finalizing here came too late to help anyway: the reviewers had already\n// reviewed the pre-merge tree by then.\n@injectable(bindingScopeValues.Singleton)\nexport class FinishUpsertPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildLog: BuildGateLog,\n private readonly mergeState: MergeState,\n private readonly prMerger: PrMerger,\n private readonly publisher: GatedPrPublisher,\n private readonly dashboard: Dashboard,\n private readonly authorIdentity: AuthorIdentityResolver,\n // The 2nd PR comment. Its own class because it is its own surface — see ChecklistCommentRenderer.\n private readonly checklistComment: ChecklistCommentRenderer,\n private readonly checklistScanner: ChecklistScanner,\n private readonly verdictGate: ReviewerVerdictGate,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly gateTokenService: GateTokenService,\n // Owns the reviewer-provenance integrity check and its audit record — see ProvenanceEnforcer.\n private readonly provenanceEnforcer: ProvenanceEnforcer,\n // NOTE: ChecklistInstructionsService is deliberately NOT injected here any more. Its \"You MUST run\n // these N reviewer subagent(s)\" block is now rendered by ReviewerVerdictGate and ONLY for checklists\n // that genuinely never ran, so no other code path in this command can print it at a refusal.\n private readonly receipts: ReviewStageReceiptService,\n private readonly banner: FinishBanner,\n // `gh pr merge --body-file` takes a path, so the bytes just published as the PR description are\n // spilled to a throwaway file for the length of one `gh` call. Nothing durable — the PR holds it.\n private readonly mergeBodyFile: MergeBodyTempFile,\n // ONE marker-keyed upsert, shared by both PR comments (the full dashboard and the checklist).\n private readonly commentUpserter: PrCommentUpserter,\n // Pins the two GitHub repo settings that decide whether a UI merge writes the body we just\n // rendered. Server-side, so no config can express them — see SquashSettingsEnforcer.\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly stageConsole: StageOutputLog,\n private readonly branchIdentity: BranchIdentity,\n private readonly hotfixFinish: HotfixFinishPreparer,\n private readonly rounds: ReviewRoundStateService,\n ) {}\n\n /**\n * Runs with this stage's console CAPTURED to a file (see StageOutputLog). What still reaches the\n * terminal is what an agent must act on: the build heartbeat and result, and the closing banner with\n * the PR link and whatever is still owed. The dashboard computation, the gh round trips and the\n * comment upserts are in the file.\n */\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, FINISH_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n // Refresh the AI-facing workflow doc so it's present + current for any failure message to cite.\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n if (this.branchIdentity.isHotfix()) {\n await this.runHotfixStage(repoRoot);\n return;\n }\n // 1. REQUIRE stage ② — see assertStageTwoRan. Returns true when its receipt covers THIS commit,\n // which is what lets the build gate below be skipped rather than re-run for a foregone answer.\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n const buildAlreadyGreen = this.assertStageTwoRan(repoRoot, config.maxReviewerRounds);\n\n // 2. REQUIRE the AI-authored summary.json (throws InformAiError with the schema if missing/invalid).\n // Compute the consumer checklists this diff triggered FIRST so an unacknowledged BLOCK throws\n // here — BEFORE any `gh pr create` — matching the guarantee buildCommand already provides.\n // The SAME scan wp-review-upsert-pr runs, with filterAlreadyReviewed:true so `outstanding` is exactly what\n // still owes a verdict (Z of N of X). Sharing the computation is the point: the command that REPORTS\n // and the command that GATES must not be able to disagree about what is owed. review-<id>.json files\n // persist locally, so a re-run re-validates the EXISTING verdicts against the (possibly changed)\n // applicable set for free — an unchanged checklist needs no re-review, a newly-applicable one refuses\n // until its file is written.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, 'stage3-finish'));\n const receipt = this.receipts.read(repoRoot, featureName);\n const remediations = this.rounds.capRemediations(repoRoot, scan.summaryPath, receipt, config.maxReviewerRounds);\n for (const result of scan.results) result.remediation = remediations[result.id] ?? '';\n scan.outstanding = scan.outstanding.filter((req: RequiredChecklist): boolean => remediations[req.id] === undefined);\n const required = scan.applicable;\n // The applicable checklists that are supposed to HAVE a verdict — everything except the optional ones\n // nobody ran. Used for provenance and for the dashboard rows, both of which ask \"who reviewed this?\"\n // and would otherwise demand an answer from a review the human declined: provenance would refuse the\n // PR because a subagent that was never meant to run cannot be proven to have run, and the dashboard\n // would render a MISSING verdict for it.\n const verdicted = this.verdictedOf(scan);\n // FAIL FAST on an unclear checklist, BEFORE summary.json is parsed and before the build gate runs. A\n // missing reviewer is not a summary.json defect (folding it in made the AI fix the wrong thing), and\n // nobody should wait on a build to be told a reviewer never ran. ReviewerVerdictGate owns the\n // distinction between unreadable / REFUSED / never-ran, and retires the red verdicts it acts on.\n this.verdictGate.assertEveryReviewerRan(scan);\n const review = this.reviewJsonService.loadSummaryJson(summaryJsonPath(repoRoot, featureName), required, '', remediations);\n this.applyRoundAudits(review, scan, receipt);\n\n // 2c. For every verdicted checklist, VERIFY (from the harness's own artifacts) that a real reviewer\n // SUBAGENT actually ran on this branch — the coding agent may not self-certify. Its NAME is not\n // checked; see SubagentProvenanceService.isReviewerRun. Absent CLAUDE_CODE_SESSION_ID this skips with a warning (CI / plain terminal).\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const provenance = this.provenanceEnforcer.enforce(verdicted, currentBranch, repoRoot, config);\n\n // 2b. The build gate validates the WORKING TREE but we push HEAD — so they MUST be identical.\n this.gitExec.assertCleanTree(repoRoot);\n\n // 3. Build gate, then post the gated body, then push (that ORDER — see GatedPrPublisher).\n await this.runOrSkipBuildGate(repoRoot, buildAlreadyGreen);\n const base = this.branchNaming.baseBranchName(execSync('git branch --show-current', { encoding: 'utf8' }).trim());\n\n process.stdout.write('\\n' + SEP + '📋 Dashboard + PR\\n' + SEP + '\\n');\n const title = this.prTitleFrom(review);\n const input = this.computeDashboardInput(repoRoot, true, review, title, verdicted, scan);\n const result = this.publishAll(repoRoot, base, input, new PrCommentSources(scan, review, provenance));\n this.archiveConsumedReview(repoRoot, featureName, result);\n\n // The closing recap + the clickable-link directive, BOTH derived from the real merge outcome.\n // Nothing here may hard-code success: a stranded PR under a green checkmark is how PRs got\n // abandoned (see FinishBanner).\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n // `say`: the PR link and what is still owed are the whole reason a caller ran this command, and a\n // not-done outcome carries the commands that fix it. Neither may end up only in a log file.\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n private applyRoundAudits(review: PrSummary, scan: ChecklistScan, receipt: ReturnType<ReviewStageReceiptService['read']>): void {\n for (const result of review.results) {\n const trail = this.rounds.auditTrail(scan.summaryPath, result.id, receipt);\n if (trail === '') continue;\n result.output = trail;\n if (result.remediation !== '') result.remediation = `${trail}\\n\\n#### Final state\\n${result.remediation}`;\n }\n }\n\n /** Hotfix finish owns every prerequisite normally split between stages ② and ③. */\n private async runHotfixStage(repoRoot: string): Promise<void> {\n const state = await this.hotfixFinish.prepare(repoRoot);\n const base = this.branchNaming.baseBranchName(state.currentBranch);\n const title = this.prTitleFrom(state.review);\n const input = this.computeDashboardInput(repoRoot, true, state.review, title, [], state.scan, true);\n const sources = new PrCommentSources(state.scan, state.review, state.provenance);\n const result = this.publishAll(repoRoot, base, input, sources);\n this.archiveConsumedReview(repoRoot, state.featureName, result);\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n // Validate + commit + finalize a 3-point merge the AI resolved, if one is in progress. Finalizing here\n // does NOT push (pushRemote=false): this command pushes exactly ONCE, from GatedPrPublisher, and only\n // after summary.json + every BLOCK checklist + the build gate pass and the gated PR body is written.\n /**\n * The build gate — SKIPPED when stage ②'s receipt already covers this exact HEAD.\n *\n * The gate is authoritative per-COMMIT, not per-command: re-running it on a tree that has not moved\n * since stage ② verified it buys nothing and costs a full `nx affected`. That skip is what makes the\n * three-stage flow cost ONE build rather than two, and it is why moving the gate earlier was affordable.\n */\n private async runOrSkipBuildGate(repoRoot: string, alreadyGreen: boolean): Promise<void> {\n if (alreadyGreen) {\n // `say`, for the same reason the gate's own two lines are: a caller watching for a build needs\n // to be told, live, that there is not going to be one.\n this.stageConsole.say('\\n🛠️ Build gate: already green for this commit (stage ② receipt) — skipping the rebuild.\\n' + this.skippedBuildLogNote(repoRoot));\n return;\n }\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions('🛠️ Build gate (authoritative)', 'pnpm wp-finish-upsert-pr', 'Build failed — no PR created/updated.', FINISH_STAGE));\n }\n\n /**\n * When the gate is SKIPPED and build-log capture is on, name STAGE ②'s log — the one build that\n * actually ran for this commit. Deliberately never names a finish-stage log: no finish build ran, and\n * pointing at a file this command did not write would claim a build that did not happen.\n *\n * The path is recomputed rather than stored, and that is sound precisely BECAUSE this branch is only\n * reached when the receipt covers the current HEAD: same worktree, same branch, same sha ⇒ the same\n * deterministic filename stage ② wrote. Empty string when the file is gone — a log that was reaped or\n * never written must not be named as though a reader could open it.\n */\n private skippedBuildLogNote(repoRoot: string): string {\n const log = this.buildLog.existingLogFor(repoRoot, REVIEW_STAGE);\n return log === '' ? '' : ` Stage ②'s full build output: ${log}\\n`;\n }\n\n /**\n * The two stage-② preconditions, together: no unvalidated merge, and a receipt proving stage ② ran.\n * Returns true when that receipt covers the CURRENT HEAD, i.e. the build gate can be skipped.\n */\n private assertStageTwoRan(repoRoot: string, maxReviewerRounds: number): boolean {\n this.assertNoUnvalidatedMerge(repoRoot);\n return this.assertReviewStageRan(repoRoot, this.aiBranchName.getFeatureName(), this.gitOut(['rev-parse', 'HEAD']), maxReviewerRounds);\n }\n\n /**\n * REFUSE while a 3-point merge is still unvalidated — do not finalize it here.\n *\n * This command used to do the finalizing itself. Finalizing means validating a conflict resolution, and\n * two commands owning that means two implementations that can drift; `PrContextWriter`'s docstring\n * records this codebase already paying for exactly that once. It also came too late to matter: by the\n * time finish ran, the reviewers had already reviewed the pre-merge tree.\n *\n * So stage ② owns it, and finish only checks. Nothing is lost — the recovery is one command away, and\n * running it also builds the merged tree and re-briefs the reviewers against it, which finalizing here\n * never did.\n */\n private assertNoUnvalidatedMerge(repoRoot: string): void {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return;\n throw new InformAiError(\n '⛔ NO PR — a 3-point merge on this branch is still unvalidated, so nothing here has been\\n' +\n 'verified: the conflict resolution is unchecked, the merged tree was never built, and any\\n' +\n 'reviewer that ran judged the PRE-merge code.\\n\\n' +\n `Conflicted file(s): ${marker.conflictedFiles.join(', ')}\\n\\n` +\n 'Resolve them (see .webpieces/instruct-ai/webpieces.mergeprocess.md), then run:\\n' +\n ' pnpm wp-review-upsert-pr\\n' +\n 'It validates the resolution, commits it, builds it, and re-briefs the reviewers.',\n );\n }\n\n /**\n * REQUIRE stage ② (`wp-review-upsert-pr`) to have run, and report whether it ran on THIS commit.\n *\n * Returns true when the receipt matches the current HEAD — the caller then skips its own build, because\n * the receipt IS the gate for that sha and rebuilding an unchanged tree is a second full `nx affected`\n * run for a foregone answer.\n *\n * Without this check a repo with NO checklists has nothing forcing stage ②: `assertEveryReviewerRan`\n * is vacuous, and summary.json — the only other interlock — is a file the AI writes itself. It could\n * write it and come straight here, skipping the merge validation and the build entirely.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private assertReviewStageRan(repoRoot: string, featureName: string, headSha: string, maxReviewerRounds: number): boolean {\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(\n '⛔ NO PR — stage ② never ran on this branch. That means the 3-point merge is unvalidated,\\n' +\n 'the build gate has not run, no diff was extracted, and no reviewer was briefed.\\n\\n' +\n 'Run: pnpm wp-review-upsert-pr\\n' +\n '(then spawn the reviewers it names, write summary.json, and re-run this command)',\n );\n }\n if (receipt.headSha === headSha) return true;\n if (this.rounds.capSpent(summaryJsonPath(repoRoot, featureName), receipt, maxReviewerRounds)) {\n // The budget is spent (issue #1051): no review round will run again, so suggesting one here is\n // an instruction the gate itself would refuse. Say what the PR records instead.\n process.stderr.write(\n `\\n⚠️ HEAD moved since the last reviewer round (reviewed ${receipt.headSha.slice(0, 8)}, now ${headSha.slice(0, 8)}).\\n` +\n ` All ${maxReviewerRounds} reviewer round(s) are spent, so no further review runs: the build gate will\\n` +\n ' re-run, and the PR records every verdict as carried forward from the reviewed tree.\\n\\n',\n );\n return false;\n }\n // Not fatal. Re-reviewing on every follow-up commit would be intolerable, and most drift is a typo\n // fix. But it is never silent: the build re-runs here, and the PR says the reviewers saw an older tree.\n process.stderr.write(\n `\\n⚠️ HEAD moved since stage ② ran (reviewed ${receipt.headSha.slice(0, 8)}, now ${headSha.slice(0, 8)}).\\n` +\n ' The build gate will re-run, and the PR will record that reviewers judged an earlier tree.\\n' +\n ' If the change was substantive, re-run pnpm wp-review-upsert-pr and re-spawn the reviewers.\\n\\n',\n );\n return false;\n }\n\n /**\n * Retire the review this run just used — move summary.json to old-summary.json beside it, stamped as\n * audit-only (see ReviewJsonService.archiveSummaryJson).\n *\n * WHY it moves rather than staying put: summary.json left behind is a live-looking file describing a\n * review that has already shipped, and the next `wp-review-upsert-pr` on this branch finds it sitting\n * there. A reviewer subagent that judges the PR's stated INTENT — its title, summary or risk level —\n * then reads the previous round's review and can return GREEN against a title that no longer exists,\n * with nothing in the verdict distinguishing that from a real pass. Moving it makes the only route back\n * to this command a freshly-written review.\n *\n * ONLY on a PR that actually went up. A run that died before publishing must stay re-runnable without\n * making the AI rewrite a review that was never used, and prNumber === '' is exactly that case.\n * Non-fatal: the PR is live by here, so an unwritable archive warns rather than failing the command.\n */\n private archiveConsumedReview(repoRoot: string, featureName: string, result: UpsertResult): void {\n if (result.prNumber === '') return;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the PR is already up; a failed archive must not fail the command\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const archived = this.reviewJsonService.archiveSummaryJson(summaryJsonPath(repoRoot, featureName));\n if (archived !== '') process.stdout.write(` archived this run's summary.json → ${archived} (audit only) ✓\\n`);\n // Beside it, so an archived review keeps the transcript links belonging to the round that\n // produced it — a review whose provenance was overwritten by the NEXT round audits nothing.\n this.provenanceEnforcer.archiveRecord(prDirFor(repoRoot, featureName));\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(`⚠️ Could not archive summary.json (non-fatal — the PR is already up): ${error.message}\\n`);\n }\n }\n\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // The user-facing PR title: the AI-authored review.title, or — if omitted — a readable fallback\n // derived from the stable feature name (NEVER the internal `Squash merge of <branch>` commit subject).\n private prTitleFrom(review: PrSummary): string {\n if (review.title !== '') return review.title;\n return this.aiBranchName.getFeatureName().replace(/[-/]+/g, ' ').trim();\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private computeDashboardInput(repoRoot: string, buildPassed: boolean, review: PrSummary, title: string, required: readonly RequiredChecklist[], scan: ChecklistScan, hotfix = false): DashboardInput {\n const config = loadAndValidate(repoRoot).prGate;\n const forkPoint = this.gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = this.gitOut(['rev-parse', 'HEAD']);\n const mainHead = this.gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = this.gitOut(['diff', range, '--name-only'])\n .split('\\n')\n .filter((f: string): boolean => f.trim() !== '');\n const patch = this.gitOut(['diff', range]);\n\n const gateResults = this.dashboard.computeGateResults(config.gates, changedFiles);\n const disables = this.dashboard.countAddedDisables(patch);\n const rows = this.checklistRows(required, review);\n // buildCommand travels into the dashboard so the PR-body footer can NAME the command that vouched\n // for this commit. The footer used to assert \"build ran via nx affected\" on every repo, which was\n // simply false wherever buildCommand is not nx.\n // `scan.suppressed.length`, never `scan.reviewersDisabled` alone: the dashboard and the commit\n // body have to state HOW MANY reviewers were killed, because a suppressed 4 and an applicable 0\n // are different facts that both render as an empty `rows`. See DashboardInput.\n return new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, review, rows, this.buildAffected.resolveBuildCommand(repoRoot), scan.suppressed.length, this.authorIdentity.resolve(review.model), hotfix);\n }\n\n /**\n * The applicable checklists MINUS the optional ones nobody ran.\n *\n * Not folded into `ChecklistScan` as yet another field: `applicable` (what matched) and `optionalNotRun`\n * (what was declined) are both facts about the scan, whereas this is one command's view of them, and the\n * roster comment deliberately wants the OTHER view — it lists the declined ones precisely so the PR does\n * not imply they passed.\n */\n private verdictedOf(scan: ChecklistScan): RequiredChecklist[] {\n const skipped = new Set(scan.optionalNotRun.map((r: RequiredChecklist): string => r.id));\n return scan.applicable.filter((r: RequiredChecklist): boolean => !skipped.has(r.id));\n }\n\n // Pair each matched checklist with its resolved verdict for the dashboard.\n //\n // A checklist reaching this point is always PASS, WARN or OVERRIDDEN, and the reason is ReviewerVerdictGate\n // — NOT loadSummaryJson. The gate runs one line earlier and throws on every other state (FAIL, MISSING,\n // BAD_FORMAT), so loadSummaryJson's own checklist validation can no longer be the thing that rejects them;\n // it re-validates the same set and finds it clean. This comment used to credit loadSummaryJson, which made\n // the ordering look deliberate while the gate's generic \"no verdict yet\" message masked every refusal.\n // WARN belongs in that list: yellow SHIPS, so it is not outstanding and reaches the dashboard.\n private checklistRows(required: readonly RequiredChecklist[], review: PrSummary): ChecklistRow[] {\n return required.map((req: RequiredChecklist): ChecklistRow => {\n const verdict = this.reviewJsonService.resolveVerdict(req, review.results);\n return new ChecklistRow(req.id, verdict.status, verdict.detail);\n });\n }\n\n /**\n * One comment row per DEFINED checklist — matched or not — pairing the roster's match evidence with the\n * resolved verdict. Built from `scan.roster` rather than from the applicable set: the skipped ones are\n * absent from `applicable` by construction, and their \"why not\" evidence (the configured globs and the\n * changed-file total) exists nowhere else without recomputing the diff a second way.\n */\n private commentRows(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): ChecklistCommentRow[] {\n // checklist id -> did its reviewer open the diff. Absent ⇒ not assessed, which prints nothing (see ChecklistCommentRow.diffRead).\n const readByChecklist = new Map<string, boolean>();\n for (const e of provenance.evidence) readByChecklist.set(e.checklistId, e.readDiff);\n return scan.roster.entries.map((entry: TriggeredChecklist): ChecklistCommentRow => {\n const ran = entry.matchedFiles.length > 0;\n const req = new RequiredChecklist(entry.def.id, entry.def.reviewer, entry.def.doc, entry.matchedFiles, entry.matchedPatterns, entry.def.required);\n // A skipped checklist has no verdict to resolve — asking for one would report it as MISSING,\n // i.e. as an unreviewed obligation, when in fact it never had one.\n const verdict = ran ? this.reviewJsonService.resolveVerdict(req, review.results) : new ChecklistVerdict(entry.def.id, '', '');\n const identity = review.results.find((result): boolean => result.id === entry.def.id);\n const row = new ChecklistCommentRow(identity?.agent ?? 'unknown', identity?.model ?? 'unknown', entry.def.id, verdict.status, verdict.detail, ran, entry.def.patterns, entry.matchedPatterns, entry.matchedFiles, scan.roster.changedFileCount);\n row.required = entry.def.required;\n const read = readByChecklist.get(entry.def.id);\n row.diffRead = read === undefined ? '' : read ? 'yes' : 'no';\n return row;\n });\n }\n\n // Hidden HMAC gate-token marker (with a leading blank line) to append to the PR body, or '' when the\n // repo sets no gateSalt (byte-identical body to before this feature). Bound to the pushed HEAD sha.\n private gateTokenBody(gateSalt: string, headSha: string): string {\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n return marker === '' ? '' : `\\n\\n${marker}\\n`;\n }\n\n /**\n * Publish the roster + every reviewer's full `output` as ONE combined PR comment, idempotently (find the\n * marker comment → PATCH it, else POST). Never fatal: by here the PR is already created/updated, so a\n * `gh` failure only warns.\n *\n * Posted on EVERY run of a repo that defines checklists — including one where nothing matched, because\n * \"all five were evaluated and none applied\" is the good news the old comment could not deliver. The\n * guard is `scan.defined.length`, deliberately NOT the number of rows that ran: a repo with no\n * checklists configured must still see no comment at all (see ChecklistCommentRenderer).\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private postChecklistComment(repoRoot: string, prNumber: string, scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): void {\n if (prNumber === '' || scan.defined.length === 0) return;\n if (!loadAndValidate(repoRoot).prGate.checklistComments) return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = CHECKLIST_COMMENT_MARKER;\n request.body = this.checklistComment.render(this.commentRows(scan, review, provenance), provenance.verified, scan.roster.baseResolved, scan.suppressed.length, this.branchIdentity.isHotfix());\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'checklist-comment.json';\n request.label = 'checklist review comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR, the remote branch, and the local branch all share the one stable feature name. Look up /\n // create / merge against `baseBranch` (baseBranchName tolerates a leftover `…wpN` mid-transition).\n // GatedPrPublisher owns the edit/push/create half and its ORDERING — the gated body goes up before\n // the push, so CI's `synchronize` read cannot see the previous run's token.\n private upsertPr(request: PrUpsertRequest): UpsertResult {\n const repoRoot = request.repoRoot;\n const baseBranch = request.baseBranch;\n const title = request.title;\n const input = request.input;\n const prDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n fs.mkdirSync(prDir, { recursive: true });\n const bodyFile = path.join(prDir, 'pr-body.md');\n fs.writeFileSync(bodyFile, request.body + '\\n');\n\n const published = this.publisher.publish(baseBranch, title, bodyFile);\n if (published.createFailed) {\n process.stderr.write('⚠️ gh pr create failed — create the PR manually with the body in:\\n ' + bodyFile + '\\n');\n return new UpsertResult('', '', new MergeOutcome(false, false, '⚠️ did NOT merge — there is no PR to merge (gh pr create failed above)', MERGE_RESULT_FAILED));\n }\n const num = published.number;\n\n // Set the squash-merge SUBJECT to the PR title (+ the `(#N)` GitHub normally appends, which an\n // explicit --subject would otherwise drop) and the BODY to the compact commit summary, so main's\n // history carries the PR title + risk/flags/link — NOT the internal `Squash merge of <branch>`\n // subject GitHub would inherit from the single squash commit on the branch.\n const ref = this.prRef(baseBranch);\n const subject = ref.number !== '' ? `${title} (#${ref.number})` : title;\n\n /*\n * THE INVARIANT: the merge body IS the PR description, byte for byte.\n *\n * That is what makes every landing route agree — the GitHub Merge button and a bare `gh pr merge`\n * copy the description via `squash_merge_commit_message: PR_BODY`, while `wp-land-pr` and finish's\n * own auto-merge pass these bytes with `--body-file`. If the two strings could differ, which route\n * landed the commit would change what history says, which is precisely the bug this whole change\n * exists to remove. `pr-body-is-merge-body.spec.ts` pins it.\n *\n * The one wrinkle is the self-link. A brand-new PR has no URL until `gh pr create` returns, so the\n * body published a moment ago was rendered with `prUrl: ''`. Re-render now that the URL is known\n * and push the corrected description back, so the two strings match and the commit carries its own\n * link. Only the CREATE path pays that extra edit: on every later run the URL was already known\n * before publishing, `finalBody` matches what went up, and nothing is re-sent.\n */\n const finalBody = this.dashboard.renderPrBody(input, ref.url) + request.tokenSuffix;\n if (finalBody !== request.body) this.backfillPrBody(ref.number, bodyFile, finalBody);\n\n // The DURABLE copy of these bytes is the PR description published above; this is a throwaway\n // file because `--body-file` takes a path. `wp-land-pr` reads the description back from GitHub,\n // so nothing here has to survive the process (see decisions/0005).\n const mergeBodyFile = this.mergeBodyFile.write(finalBody + '\\n');\n // PrMerger owns the direct-merge / auto-merge-fallback decision AND checks every gh status, so a\n // merge that did not happen is reported as such instead of being swallowed (see pr-merger.ts).\n // REQUIRED config — no default here on purpose. A missing value (an older published\n // rules-config that has no such field) reaches PrMerger as '' and is treated as \"do not merge\".\n const mergeMode = loadAndValidate(repoRoot).prGate.mergeMode ?? '';\n // `false`: this caller is POLICY-driven — only a config that really says AUTO merges here.\n const outcome = this.prMerger.merge(baseBranch, subject, mergeBodyFile, new MergeIntent(mergeMode, false));\n return new UpsertResult(ref.number !== '' ? ref.number : num, ref.url, outcome);\n }\n\n /**\n * Everything the gated flow PUBLISHES, in the one order that is safe — the three surfaces plus the\n * merge, as a single unit.\n *\n * 1. the PR DESCRIPTION = the compact git-log body (+ the hidden gate token), written before the\n * push so CI's `synchronize` read can never see the previous run's token,\n * 2. the 1st comment = the full dashboard,\n * 3. the 2nd comment = each reviewer's output.\n *\n * The token is bound to the LOCAL HEAD sha and minted here because we only reach this line after the\n * build gate and every BLOCK checklist passed, so minting is legitimate. Nothing about\n * HMAC(salt, HEAD) needs the remote to have the commit yet.\n *\n * Extracted from `run` when the two comments made it 82 lines against a hard 80-line rule — and it\n * earns its own name: these four steps have a REQUIRED order, and the comment explaining that order\n * belongs with them rather than inside a method that also loads config and runs a build gate.\n */\n private publishAll(repoRoot: string, base: string, input: DashboardInput, sources: PrCommentSources): UpsertResult {\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n const headSha = this.gitOut(['rev-parse', 'HEAD']);\n const upsert = new PrUpsertRequest(input);\n upsert.repoRoot = repoRoot;\n upsert.baseBranch = base;\n upsert.title = input.title;\n upsert.tokenSuffix = this.gateTokenBody(gateSalt, headSha);\n // `existingPrUrl` is '' only for a brand-new PR — there is no URL to self-link to until\n // `gh pr create` returns one, and upsertPr back-fills it the moment it does.\n upsert.body = this.dashboard.renderPrBody(input, this.existingPrUrl(base)) + upsert.tokenSuffix;\n const result = this.upsertPr(upsert);\n\n // In the order the PR body's pointer promises: full dashboard 1st, reviewer output 2nd. Both are\n // idempotent by hidden marker and both non-fatal — the PR is up by now, so a `gh` hiccup on a\n // comment must not turn a finished run into a failed one.\n this.postDetailComment(repoRoot, result.prNumber, input);\n this.postChecklistComment(repoRoot, result.prNumber, sources.scan, sources.review, sources.provenance);\n\n // Having just written the description AS the commit body, make sure GitHub will actually use it.\n // Here rather than anywhere earlier because it is about what happens to the artifact we just\n // published, and it must run on EVERY repo — including mergeMode=NONE ones that never reach\n // PrMerger, which are exactly the repos where a UI merge decides what main's history says.\n this.squashSettings.ensure();\n return result;\n }\n\n /**\n * Re-publish the description now that the PR's own URL is known (create path only).\n *\n * Non-fatal on purpose. The PR exists, its body already carries a valid gate token for the pushed\n * head, and the code is up — the ONLY thing missing is the self-link on the first line. Aborting a\n * finished run over a cosmetic back-link would be a worse outcome than the missing link, and the very\n * next `wp-finish-upsert-pr` writes it (by then the URL is known before publishing, so it goes up with\n * the body). The merge body still gets the linked version regardless: it is filed from `finalBody`.\n */\n private backfillPrBody(prNumber: string, bodyFile: string, finalBody: string): void {\n if (prNumber === '') return;\n fs.writeFileSync(bodyFile, finalBody + '\\n');\n const res = spawnSync('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile], {\n encoding: 'utf8',\n });\n if (res.status !== 0) {\n process.stderr.write(\"⚠️ Could not add the PR's own link to its description (non-fatal — the PR and the gate\\n\" + ' token are already up). The next wp-finish-upsert-pr writes it.\\n');\n return;\n }\n process.stdout.write(' back-filled the PR description with its own link ✓\\n');\n }\n\n /**\n * The PR's web URL if one is already open for this branch, else '' — read BEFORE publishing so the\n * description can carry its own link on the first render. Only a brand-new PR gets '' (and then\n * {@link backfillPrBody} fixes it up after `gh pr create` returns a URL).\n */\n private existingPrUrl(baseBranch: string): string {\n return this.prRef(baseBranch).url;\n }\n\n /**\n * The 1st PR comment: the FULL dashboard — every row including the green ones, the whole summary, the\n * 3-point hash points. This is what the PR description used to be, and moving it here is the entire\n * point of the change: the description is now the git-log body, and a squash commit must not carry a\n * risk table.\n *\n * Posted unconditionally (any repo, checklists or not), because the description's last bullet PROMISES\n * a 1st comment holding the detail. A pointer to a comment that does not exist is worse than no\n * pointer. Non-fatal — the PR is already up, and the description alone is a complete, readable record.\n */\n private postDetailComment(repoRoot: string, prNumber: string, input: DashboardInput): void {\n if (prNumber === '') return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = DETAIL_COMMENT_MARKER;\n const detail = this.dashboard.renderDetailComment(input);\n request.body = input.hotfix ? detail + '\\n\\n' + DETAIL_COMMENT_MARKER : DETAIL_COMMENT_MARKER + '\\n' + detail;\n request.payloadDir = prDirFor(repoRoot, this.aiBranchName.getFeatureName());\n request.payloadName = 'detail-comment.json';\n request.label = 'full dashboard comment';\n this.commentUpserter.upsert(request);\n }\n\n // The PR's number + web URL (for the merge subject `(#N)` and the commit-body back-link). Both ''\n // if it can't be resolved. Rendered via jq into one tab-separated line so no JSON parsing is needed.\n private prRef(baseBranch: string): PrRef {\n const result = spawnSync('gh', ['pr', 'view', baseBranch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"'], { encoding: 'utf8' });\n if (result.status !== 0) {\n return new PrRef('', '');\n }\n const parts = (result.stdout ?? '').trim().split('\\t');\n return new PrRef(parts[0] ?? '', parts[1] ?? '');\n }\n}\n"]}
@@ -136,7 +136,7 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
136
136
  const mergeValidated = await this.finalizeAnyInProgressMerge(repoRoot);
137
137
  this.gitExec.assertCleanTree(repoRoot);
138
138
  const buildPassedAt = await this.runBuildGate(repoRoot);
139
- const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(false, '')); // '' — THIS command writes the context itself, after materializing
139
+ const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(config.maxReviewerRounds, false, '')); // '' — THIS command writes the context itself, after materializing
140
140
  const previousReceipt = this.receipts.read(repoRoot, featureName);
141
141
  const plan = this.rounds.plan(repoRoot, scan.summaryPath, previousReceipt, config.maxReviewerRounds, scan.basis);
142
142
  const shouldBrief = plan.action === review_round_state_1.ROUND_ACTION_REVIEW || plan.action === review_round_state_1.ROUND_ACTION_RESUME;