@webpieces/pr-gate 0.4.991 → 0.4.993

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/pr-gate",
3
- "version": "0.4.991",
3
+ "version": "0.4.993",
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,18 +16,18 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@inversifyjs/binding-decorators": "1.1.5",
19
- "@webpieces/hook-runtime": "0.4.991",
20
- "@webpieces/rules-config": "0.4.991",
19
+ "@webpieces/hook-runtime": "0.4.993",
20
+ "@webpieces/rules-config": "0.4.993",
21
21
  "inversify": "7.10.4",
22
22
  "reflect-metadata": "0.2.2",
23
- "@webpieces/tooling-common": "0.4.991",
24
- "@webpieces/repo-workflow-core": "0.4.991"
23
+ "@webpieces/tooling-common": "0.4.993",
24
+ "@webpieces/repo-workflow-core": "0.4.993"
25
25
  },
26
26
  "publishConfig": {
27
27
  "access": "public"
28
28
  },
29
29
  "devDependencies": {
30
- "@webpieces/tooling-testkit": "0.4.991"
30
+ "@webpieces/tooling-testkit": "0.4.993"
31
31
  },
32
32
  "types": "./src/index.d.ts",
33
33
  "bin": {
@@ -171,7 +171,8 @@ export declare class FinishUpsertPrCommand {
171
171
  */
172
172
  private publishAll;
173
173
  /**
174
- * Re-publish the description now that the PR's own URL is known (create path only).
174
+ * Re-publish the description now that the PR's own URL is known (create path only, and only when the
175
+ * predicted URL was wrong or could not be predicted).
175
176
  *
176
177
  * Non-fatal on purpose. The PR exists, its body already carries a valid gate token for the pushed
177
178
  * head, and the code is up — the ONLY thing missing is the self-link on the first line. Aborting a
@@ -182,8 +183,8 @@ export declare class FinishUpsertPrCommand {
182
183
  private backfillPrBody;
183
184
  /**
184
185
  * The PR's web URL if one is already open for this branch, else '' — read BEFORE publishing so the
185
- * description can carry its own link on the first render. Only a brand-new PR gets '' (and then
186
- * {@link backfillPrBody} fixes it up after `gh pr create` returns a URL).
186
+ * description can carry its own link on the first render. Only a brand-new PR gets '' (the publisher
187
+ * then predicts its URL, and {@link backfillPrBody} fixes a wrong or missing prediction afterwards).
187
188
  */
188
189
  private existingPrUrl;
189
190
  /**
@@ -514,7 +514,8 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
514
514
  fs.mkdirSync(prDir, { recursive: true });
515
515
  const bodyFile = path.join(prDir, 'pr-body.md');
516
516
  fs.writeFileSync(bodyFile, request.body + '\n');
517
- const published = await this.publisher.publish(baseBranch, title, bodyFile);
517
+ const render = (prUrl) => this.dashboard.renderPrBody(input, prUrl) + request.tokenSuffix;
518
+ const published = await this.publisher.publish(baseBranch, title, new gated_pr_publisher_1.PrBodyDraft(bodyFile, request.body, render));
518
519
  if (published.createFailed) {
519
520
  process.stderr.write('⚠️ gh pr create failed — create the PR manually with the body in:\n ' + bodyFile + '\n');
520
521
  return new UpsertResult('', '', new pr_merger_1.MergeOutcome(false, false, '⚠️ did NOT merge — there is no PR to merge (gh pr create failed above)', pr_merger_1.MERGE_RESULT_FAILED));
@@ -536,13 +537,15 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
536
537
  * exists to remove. `pr-body-is-merge-body.spec.ts` pins it.
537
538
  *
538
539
  * The one wrinkle is the self-link. A brand-new PR has no URL until `gh pr create` returns, so the
539
- * body published a moment ago was rendered with `prUrl: ''`. Re-render now that the URL is known
540
- * and push the corrected description back, so the two strings match and the commit carries its own
541
- * link. Only the CREATE path pays that extra edit: on every later run the URL was already known
542
- * before publishing, `finalBody` matches what went up, and nothing is re-sent.
540
+ * publisher rendered it with the PREDICTED URL (issue #1418) — or with `prUrl: ''` when the
541
+ * prediction failed. Re-render with the REAL URL; when that differs from what went up (a wrong
542
+ * guess, or no guess), push the corrected description back, so the two strings match and the
543
+ * commit carries its own link. A correct guess needs no edit, so creating the PR fires one event.
544
+ * On every later run the URL was already known before publishing and nothing is re-sent.
543
545
  */
544
- const finalBody = this.dashboard.renderPrBody(input, ref.url) + request.tokenSuffix;
545
- if (finalBody !== request.body)
546
+ this.publisher.reportPredictedLink(published, ref.number);
547
+ const finalBody = render(ref.url);
548
+ if (finalBody !== published.body)
546
549
  await this.backfillPrBody(ref.number, bodyFile, finalBody);
547
550
  // The DURABLE copy of these bytes is the PR description published above; this is a throwaway
548
551
  // file because `--body-file` takes a path. `wp-land-pr` reads the description back from GitHub,
@@ -582,8 +585,8 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
582
585
  upsert.baseBranch = base;
583
586
  upsert.title = input.title;
584
587
  upsert.tokenSuffix = this.gateTokenBody(gateSalt, headSha);
585
- // `existingPrUrl` is '' only for a brand-new PR — there is no URL to self-link to until
586
- // `gh pr create` returns one, and upsertPr back-fills it the moment it does.
588
+ // `existingPrUrl` is '' only for a brand-new PR — the publisher then re-renders the body with the
589
+ // PREDICTED URL just before `gh pr create`, and upsertPr back-fills the real one on a miss.
587
590
  upsert.body = this.dashboard.renderPrBody(input, await this.existingPrUrl(base)) + upsert.tokenSuffix;
588
591
  // Rendering above already refused a stray closing reference; say out loud what merging WILL close.
589
592
  // `say`: a wrong closesIssue must be noticed BEFORE landing, so this may not end up only in the log.
@@ -603,7 +606,8 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
603
606
  return result;
604
607
  }
605
608
  /**
606
- * Re-publish the description now that the PR's own URL is known (create path only).
609
+ * Re-publish the description now that the PR's own URL is known (create path only, and only when the
610
+ * predicted URL was wrong or could not be predicted).
607
611
  *
608
612
  * Non-fatal on purpose. The PR exists, its body already carries a valid gate token for the pushed
609
613
  * head, and the code is up — the ONLY thing missing is the self-link on the first line. Aborting a
@@ -624,8 +628,8 @@ let FinishUpsertPrCommand = class FinishUpsertPrCommand {
624
628
  }
625
629
  /**
626
630
  * The PR's web URL if one is already open for this branch, else '' — read BEFORE publishing so the
627
- * description can carry its own link on the first render. Only a brand-new PR gets '' (and then
628
- * {@link backfillPrBody} fixes it up after `gh pr create` returns a URL).
631
+ * description can carry its own link on the first render. Only a brand-new PR gets '' (the publisher
632
+ * then predicts its URL, and {@link backfillPrBody} fixes a wrong or missing prediction afterwards).
629
633
  */
630
634
  async existingPrUrl(baseBranch) {
631
635
  return (await this.prRef(baseBranch)).url;
@@ -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,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAyM;AACzM,8DAA2F;AAC3F,iEAA6D;AAC7D,yCAA2D;AAC3D,2EAAgE;AAChE,6DAAyD;AACzD,qEAAsG;AACtG,6EAAwE;AACxE,mDAA+C;AAC/C,+DAA6E;AAC7E,+DAAsF;AACtF,yDAAqD;AACrD,2EAA6E;AAC7E,uEAAyE;AACzE,mEAAkF;AAClF,qDAAiG;AACjG,6DAA4E;AAC5E,2EAAqE;AACrE,uEAAkE;AAClE,yEAAuF;AACvF,yEAAsF;AACtF,mFAA8E;AAE9E,yDAA2G;AAC3G,2FAAgH;AAChH,iFAA4E;AAC5E,qEAAyE;AACzE,uEAAmE;AACnE,iEAA6D;AAE7D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;GAGG;AACH,MAAM,gBAAgB;IAClB,IAAI,CAAgB;IACpB,MAAM,CAAY;IAClB,UAAU,CAAmB;IAE7B,YAAY,IAAmB,EAAE,MAAiB,EAAE,UAA4B;QAC5E,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,eAAe;IACjB,QAAQ,GAAG,EAAE,CAAC;IACd,U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CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,mCAAY;QACZ,4BAAY;QACjB,kBAAO;QACD,8BAAa;QAClB,6BAAY;QACV,wBAAU;QACZ,oBAAQ;QACP,qCAAgB;QAChB,qBAAS;QACJ,wCAAsB;QAEpB,qDAAwB;QACxB,oCAAgB;QACrB,2CAAmB;QACb,gCAAiB;QAClB,+BAAgB;QAEd,wCAAkB;QAI5B,gDAAyB;QAC3B,4BAAY;QAGL,wCAAiB;QAEf,uCAAiB;QAGlB,iDAAsB;QACxB,iCAAc;QACZ,gCAAc;QACtB,4CAAuB;QAC1B,8BAAa;QACP,iCAAgB;GAtCvC,qBAAqB,CAujBjC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { loadAndValidate, prDirFor, summaryJsonPath, PrSummary, RequiredChecklist, ChecklistVerdict, writeTemplate, RepoRootFinder, ReviewJsonService, GateTokenService } from '@webpieces/rules-config';\nimport { GitProcessApi, InformAiError, NativeProcessApi } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { ReviewerVerdictGate } from '../workflow/reviewer-verdict-gate';\nimport { GitExec } from '../workflow/git-exec';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BuildGateLog, FINISH_STAGE, REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { MergeState } from '../workflow/merge-state';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewRoundStateService } from '../workflow/review-round-state';\nimport { StageOutputLog, FINISH_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { PrMerger, MergeIntent, MergeOutcome, MERGE_RESULT_FAILED } from '../workflow/pr-merger';\nimport { FinishBanner, FinishBannerInput } from '../workflow/finish-banner';\nimport { MergeBodyTempFile } from '../workflow/merge-body-temp-file';\nimport { GatedPrPublisher } from '../workflow/gated-pr-publisher';\nimport { ProvenanceEnforcer, ProvenanceReport } from '../workflow/provenance-enforcer';\nimport { PrCommentRequest, PrCommentUpserter } from '../workflow/pr-comment-upserter';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { TriggeredChecklist } from '../workflow/checklist-detector';\nimport { Dashboard, DashboardInput, ChecklistRow, DETAIL_COMMENT_MARKER } from '../../dashboard/dashboard';\nimport { ChecklistCommentRenderer, CHECKLIST_COMMENT_MARKER } from '../../dashboard/checklist-comment-renderer';\nimport { ChecklistCommentRow } from '../../dashboard/checklist-comment-row';\nimport { AuthorIdentityResolver } from '../../dashboard/author-identity';\nimport { IssueReferences } from '../../dashboard/issue-references';\nimport { HotfixRedirect } from '../workflow/hotfix-redirect';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The three inputs the PR COMMENTS are rendered from, bundled so `publishAll` takes one parameter for\n * them instead of three it only forwards. Data-only, per CLAUDE.md.\n */\nclass PrCommentSources {\n scan: ChecklistScan;\n review: PrSummary;\n provenance: ProvenanceReport;\n\n constructor(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport) {\n this.scan = scan;\n this.review = review;\n this.provenance = provenance;\n }\n}\n\n/**\n * Everything the PR upsert needs. Data-only, per CLAUDE.md — it replaced a 5-positional-parameter method\n * once `tokenSuffix` had to travel too, so the body can be re-rendered with the PR's own URL after\n * `gh pr create` returns it (see the INVARIANT comment in upsertPr).\n */\nclass PrUpsertRequest {\n repoRoot = '';\n baseBranch = '';\n title = '';\n /** The description as first published — rendered with whatever URL was known at the time. */\n body = '';\n /**\n * The hidden gate-token marker exactly as appended to `body`, so a re-render can reproduce the same\n * bytes. Kept separate from `body` because Dashboard renders the human/git-log half and must not know\n * about HMACs.\n */\n tokenSuffix = '';\n input: DashboardInput;\n\n constructor(input: DashboardInput) {\n this.input = input;\n }\n}\n\n// A resolved PR's number + web URL. Both '' when the PR can't be resolved (e.g. create failed).\nclass PrRef {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n// The outcome of the whole upsert: the PR number + web URL ('' each when unresolved) plus what actually\n// happened to the merge, so the final summary reports the REAL result rather than assuming success. The\n// URL is carried so the closing block can hand the AI a clickable link to relay to the user verbatim.\nclass UpsertResult {\n prNumber: string;\n prUrl: string;\n merge: MergeOutcome;\n\n constructor(prNumber: string, prUrl: string, merge: MergeOutcome) {\n this.prNumber = prNumber;\n this.prUrl = prUrl;\n this.merge = merge;\n }\n}\n\n// STAGE ③ — FINISH of the AI-first PR flow, and the ONLY command that posts PRs. Runs after\n// `wp-review-upsert-pr` verified the branch and the AI spawned the reviewers + wrote summary.json.\n//\n// In order: (1) REFUSE on an unvalidated 3-point merge and REQUIRE stage ②'s receipt; (2) REQUIRE\n// summary.json + every reviewer's verdict + provenance; (3) run the build gate UNLESS the receipt already\n// covers this exact HEAD; (4) render the dashboard; (5) create/update the PR via `gh`.\n//\n// It no longer FINALIZES a merge — stage ② does. Two commands owning conflict-resolution validation is two\n// implementations that drift, and finalizing here came too late to help anyway: the reviewers had already\n// reviewed the pre-merge tree by then.\n@injectable(bindingScopeValues.Singleton)\nexport class FinishUpsertPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildLog: BuildGateLog,\n private readonly mergeState: MergeState,\n private readonly prMerger: PrMerger,\n private readonly publisher: GatedPrPublisher,\n private readonly dashboard: Dashboard,\n private readonly authorIdentity: AuthorIdentityResolver,\n // The 2nd PR comment. Its own class because it is its own surface — see ChecklistCommentRenderer.\n private readonly checklistComment: ChecklistCommentRenderer,\n private readonly checklistScanner: ChecklistScanner,\n private readonly verdictGate: ReviewerVerdictGate,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly gateTokenService: GateTokenService,\n // Owns the reviewer-provenance integrity check and its audit record — see ProvenanceEnforcer.\n private readonly provenanceEnforcer: ProvenanceEnforcer,\n // NOTE: ChecklistInstructionsService is deliberately NOT injected here any more. Its \"You MUST run\n // these N reviewer subagent(s)\" block is now rendered by ReviewerVerdictGate and ONLY for checklists\n // that genuinely never ran, so no other code path in this command can print it at a refusal.\n private readonly receipts: ReviewStageReceiptService,\n private readonly banner: FinishBanner,\n // `gh pr merge --body-file` takes a path, so the bytes just published as the PR description are\n // spilled to a throwaway file for the length of one `gh` call. Nothing durable — the PR holds it.\n private readonly mergeBodyFile: MergeBodyTempFile,\n // ONE marker-keyed upsert, shared by both PR comments (the full dashboard and the checklist).\n private readonly commentUpserter: PrCommentUpserter,\n // Pins the two GitHub repo settings that decide whether a UI merge writes the body we just\n // rendered. Server-side, so no config can express them — see SquashSettingsEnforcer.\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly stageConsole: StageOutputLog,\n private readonly hotfixRedirect: HotfixRedirect,\n private readonly rounds: ReviewRoundStateService,\n private readonly git: GitProcessApi,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /**\n * Runs with this stage's console CAPTURED to a file (see StageOutputLog). What still reaches the\n * terminal is what an agent must act on: the build heartbeat and result, and the closing banner with\n * the PR link and whatever is still owed. The dashboard computation, the gh round trips and the\n * comment upserts are in the file.\n */\n async run(): Promise<void> {\n // A /hotfix/ branch is published by wp-upsert-hotfix-pr, never by this stage (issue #1057).\n this.hotfixRedirect.assertNotHotfix('wp-finish-upsert-pr');\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, FINISH_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n // Refresh the AI-facing workflow doc so it's present + current for any failure message to cite.\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n // 1. REQUIRE stage ② — see assertStageTwoRan. Returns true when its receipt covers THIS commit,\n // which is what lets the build gate below be skipped rather than re-run for a foregone answer.\n const featureName = await this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n const buildAlreadyGreen = await this.assertStageTwoRan(repoRoot);\n\n // 2. REQUIRE the AI-authored summary.json (throws InformAiError with the schema if missing/invalid).\n // Compute the consumer checklists this diff triggered FIRST so an unacknowledged BLOCK throws\n // here — BEFORE any `gh pr create` — matching the guarantee buildCommand already provides.\n // The SAME scan wp-review-upsert-pr runs, with filterAlreadyReviewed:true so `outstanding` is exactly what\n // still owes a verdict (Z of N of X). Sharing the computation is the point: the command that REPORTS\n // and the command that GATES must not be able to disagree about what is owed. review-round<N>-<id>.json files\n // persist locally, so a re-run re-validates the EXISTING verdicts against the (possibly changed)\n // applicable set for free — an unchanged checklist needs no re-review, a newly-applicable one refuses\n // until its file is written.\n // The scan judges ONLY the checklists that were briefed (issue #1053) — never one a later commit newly\n // triggered — and it has already folded every recorded orange fix into its results.\n const scan = await this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, 'stage3-finish'));\n const required = scan.applicable;\n // The applicable checklists that are supposed to HAVE a verdict — everything except the optional ones\n // nobody ran. Used for provenance and for the dashboard rows, both of which ask \"who reviewed this?\"\n // and would otherwise demand an answer from a review the human declined: provenance would refuse the\n // PR because a subagent that was never meant to run cannot be proven to have run, and the dashboard\n // would render a MISSING verdict for it.\n const verdicted = this.verdictedOf(scan);\n // FAIL FAST on an unclear checklist, BEFORE summary.json is parsed and before the build gate runs. A\n // missing reviewer is not a summary.json defect (folding it in made the AI fix the wrong thing), and\n // nobody should wait on a build to be told a reviewer never ran. ReviewerVerdictGate owns the\n // distinction between unreadable / ORANGE / REFUSED / never-ran.\n this.verdictGate.assertEveryReviewerRan(scan);\n const review = this.reviewJsonService.loadSummaryJson(summaryJsonPath(repoRoot, featureName), required, '', scan.orangeFixes);\n this.applyRoundAudits(review, scan, config.maxReviewerRounds);\n // FAIL FAST on a hand-written closing reference in the summary (issue #1310), before the build gate.\n // renderPrBody re-judges the final bytes; this only moves the common case ahead of a slow build.\n new IssueReferences().assertNoStrayClosingReferences(review.summary, review.addressesIssues, 'pnpm wp-finish-upsert-pr');\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 = await this.gitExec.currentBranch(process.cwd());\n const provenance = await 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 await 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(await this.gitExec.currentBranch(process.cwd()));\n\n process.stdout.write('\\n' + SEP + '📋 Dashboard + PR\\n' + SEP + '\\n');\n const title = await this.prTitleFrom(review);\n const input = await this.computeDashboardInput(repoRoot, true, review, title, verdicted, scan);\n const result = await this.publishAll(repoRoot, base, input, new PrCommentSources(scan, review, provenance));\n this.snapshotPublishedReview(repoRoot, featureName, result);\n\n // The closing recap + the clickable-link directive, BOTH derived from the real merge outcome.\n // Nothing here may hard-code success: a stranded PR under a green checkmark is how PRs got\n // abandoned (see FinishBanner).\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n // `say`: the PR link and what is still owed are the whole reason a caller ran this command, and a\n // not-done outcome carries the commands that fix it. Neither may end up only in a log file.\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n private applyRoundAudits(review: PrSummary, scan: ChecklistScan, maxReviewerRounds: number): void {\n for (const result of review.results) {\n const trail = this.rounds.auditTrail(scan.summaryPath, result.id, maxReviewerRounds);\n if (trail === '') continue;\n result.output = trail;\n if (result.remediation !== '') result.remediation = `${trail}\\n\\n#### Final state\\n${result.remediation}`;\n }\n }\n\n // Validate + commit + finalize a 3-point merge the AI resolved, if one is in progress. Finalizing here\n // does NOT push (pushRemote=false): this command pushes exactly ONCE, from GatedPrPublisher, and only\n // after summary.json + every BLOCK checklist + the build gate pass and the gated PR body is written.\n /**\n * The build gate — SKIPPED when stage ②'s receipt already covers this exact HEAD.\n *\n * The gate is authoritative per-COMMIT, not per-command: re-running it on a tree that has not moved\n * since stage ② verified it buys nothing and costs a full `nx affected`. That skip is what makes the\n * three-stage flow cost ONE build rather than two, and it is why moving the gate earlier was affordable.\n */\n private async runOrSkipBuildGate(repoRoot: string, alreadyGreen: boolean): Promise<void> {\n if (alreadyGreen) {\n // `say`, for the same reason the gate's own two lines are: a caller watching for a build needs\n // to be told, live, that there is not going to be one.\n this.stageConsole.say('\\n🛠️ Build gate: already green for this commit (stage ② receipt) — skipping the rebuild.\\n' + await 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 async skippedBuildLogNote(repoRoot: string): Promise<string> {\n const log = await 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 async assertStageTwoRan(repoRoot: string): Promise<boolean> {\n await this.assertNoUnvalidatedMerge(repoRoot);\n return this.assertReviewStageRan(repoRoot, await this.aiBranchName.getFeatureName(), await 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 async assertNoUnvalidatedMerge(repoRoot: string): Promise<void> {\n const home = this.mergeState.mergeDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return;\n throw new InformAiError(\n '⛔ NO PR — a 3-point merge on this branch is still unvalidated, so nothing here has been\\n' +\n 'verified: the conflict resolution is unchecked, the merged tree was never built, and any\\n' +\n 'reviewer that ran judged the PRE-merge code.\\n\\n' +\n `Conflicted file(s): ${marker.conflictedFiles.join(', ')}\\n\\n` +\n 'Resolve them (see .webpieces/instruct-ai/webpieces.mergeprocess.md), then run:\\n' +\n ' pnpm wp-review-upsert-pr\\n' +\n 'It validates the resolution, commits it, builds it, and re-briefs the reviewers.',\n );\n }\n\n /**\n * REQUIRE stage ② (`wp-review-upsert-pr`) to have run, and report whether it ran on THIS commit.\n *\n * Returns true when the receipt matches the current HEAD — the caller then skips its own build, because\n * the receipt IS the gate for that sha and rebuilding an unchanged tree is a second full `nx affected`\n * run for a foregone answer.\n *\n * Without this check a repo with NO checklists has nothing forcing stage ②: `assertEveryReviewerRan`\n * is vacuous, and summary.json — the only other interlock — is a file the AI writes itself. It could\n * write it and come straight here, skipping the merge validation and the build entirely.\n */\n private assertReviewStageRan(repoRoot: string, featureName: string, headSha: string): boolean {\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(\n '⛔ NO PR — stage ② never ran on this branch. That means the 3-point merge is unvalidated,\\n' +\n 'the build gate has not run, no diff was extracted, and no reviewer was briefed.\\n\\n' +\n 'Run: pnpm wp-review-upsert-pr\\n' +\n '(then spawn the reviewers it names, write summary.json, and re-run this command)',\n );\n }\n if (receipt.buildHeadSha === headSha) return true;\n // Not fatal, and never a re-review (issue #1053): a green or yellow verdict stands whatever changed\n // since, and only a RED with a round left ever opens another round. Suggesting a re-review here\n // would be an instruction the gate itself refuses. It is never silent either: the build re-runs.\n process.stderr.write(\n `\\n⚠️ HEAD moved since stage ② built (built ${receipt.buildHeadSha.slice(0, 8) || 'unknown'}, now ${headSha.slice(0, 8)}).\\n` +\n ' The build gate will re-run. No further review runs for this: every verdict is carried forward\\n' +\n ' from the reviewed tree, and the PR records that the reviewers judged an earlier commit.\\n\\n',\n );\n return false;\n }\n\n /**\n * Snapshot the published intent without consuming the active summary (issue #1114). A same-PR\n * update carries reviewer verdicts and can also carry unchanged intent. Stage ② requires the author\n * to refresh metadata that changed BEFORE reviewers read it. Snapshots never become active input.\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 snapshotPublishedReview(\n repoRoot: string,\n featureName: string,\n result: UpsertResult,\n ): 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 snapshot = this.reviewJsonService.snapshotSummaryJson(\n summaryJsonPath(repoRoot, featureName),\n );\n process.stdout.write(\n ` saved published summary → ${snapshot} (audit only); active summary.json retained ✓\\n`,\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(\n `⚠️ Could not snapshot summary.json (non-fatal — the PR is already up): ${error.message}\\n`,\n );\n }\n }\n\n private async gitOut(args: string[]): Promise<string> {\n const result = await this.git.run(args);\n return result.ok ? 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 async prTitleFrom(review: PrSummary): Promise<string> {\n if (review.title !== '') return review.title;\n return (await this.aiBranchName.getFeatureName()).replace(/[-/]+/g, ' ').trim();\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private async computeDashboardInput(repoRoot: string, buildPassed: boolean, review: PrSummary, title: string, required: readonly RequiredChecklist[], scan: ChecklistScan): Promise<DashboardInput> {\n const config = loadAndValidate(repoRoot).prGate;\n const forkPoint = await this.gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = await this.gitOut(['rev-parse', 'HEAD']);\n const mainHead = await this.gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = (await this.gitOut(['diff', range, '--name-only']))\n .split('\\n')\n .filter((f: string): boolean => f.trim() !== '');\n const patch = await this.gitOut(['diff', range]);\n\n const gateResults = this.dashboard.computeGateResults(config.gates, changedFiles);\n const disables = this.dashboard.countAddedDisables(patch);\n const rows = this.checklistRows(required, review);\n // buildCommand travels into the dashboard so the PR-body footer can NAME the command that vouched\n // for this commit. The footer used to assert \"build ran via nx affected\" on every repo, which was\n // simply false wherever buildCommand is not nx.\n // `scan.suppressed.length`, never `scan.reviewersDisabled` alone: the dashboard and the commit\n // body have to state HOW MANY reviewers were killed, because a suppressed 4 and an applicable 0\n // are different facts that both render as an empty `rows`. See DashboardInput.\n const input = new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, review, rows, this.buildAffected.resolveBuildCommand(repoRoot), scan.suppressed.length, this.authorIdentity.resolve(review.model), false);\n input.notBriefed = scan.notBriefed.map((r: RequiredChecklist): string => r.id);\n return input;\n }\n\n /**\n * The applicable checklists MINUS the optional ones nobody ran.\n *\n * Not folded into `ChecklistScan` as yet another field: `applicable` (what matched) and `optionalNotRun`\n * (what was declined) are both facts about the scan, whereas this is one command's view of them, and the\n * roster comment deliberately wants the OTHER view — it lists the declined ones precisely so the PR does\n * not imply they passed.\n */\n private verdictedOf(scan: ChecklistScan): RequiredChecklist[] {\n const skipped = new Set(scan.optionalNotRun.map((r: RequiredChecklist): string => r.id));\n return scan.applicable.filter((r: RequiredChecklist): boolean => !skipped.has(r.id));\n }\n\n // Pair each matched checklist with its resolved verdict for the dashboard.\n //\n // A checklist reaching this point is always PASS, WARN or OVERRIDDEN, and the reason is ReviewerVerdictGate\n // — NOT loadSummaryJson. The gate runs one line earlier and throws on every other state (FAIL, MISSING,\n // BAD_FORMAT), so loadSummaryJson's own checklist validation can no longer be the thing that rejects them;\n // it re-validates the same set and finds it clean. This comment used to credit loadSummaryJson, which made\n // the ordering look deliberate while the gate's generic \"no verdict yet\" message masked every refusal.\n // WARN belongs in that list: yellow SHIPS, so it is not outstanding and reaches the dashboard.\n private checklistRows(required: readonly RequiredChecklist[], review: PrSummary): ChecklistRow[] {\n return required.map((req: RequiredChecklist): ChecklistRow => {\n const verdict = this.reviewJsonService.resolveVerdict(req, review.results);\n return new ChecklistRow(req.id, verdict.status, verdict.detail);\n });\n }\n\n /**\n * One comment row per DEFINED checklist — matched or not — pairing the roster's match evidence with the\n * resolved verdict. Built from `scan.roster` rather than from the applicable set: the skipped ones are\n * absent from `applicable` by construction, and their \"why not\" evidence (the configured globs and the\n * changed-file total) exists nowhere else without recomputing the diff a second way.\n */\n private commentRows(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): ChecklistCommentRow[] {\n // checklist id -> did its reviewer open the diff. Absent ⇒ not assessed, which prints nothing (see ChecklistCommentRow.diffRead).\n const readByChecklist = new Map<string, boolean>();\n for (const e of provenance.evidence) readByChecklist.set(e.checklistId, e.readDiff);\n const judged = new Set(scan.applicable.map((r: RequiredChecklist): string => r.id));\n const notBriefed = new Set(scan.notBriefed.map((r: RequiredChecklist): string => r.id));\n return scan.roster.entries.map((entry: TriggeredChecklist): ChecklistCommentRow => {\n // A briefed checklist is judged whether or not the final diff still matches it (the set is\n // frozen at the briefing, issue #1053); a newly-triggered one is shown, never judged.\n const ran = judged.has(entry.def.id) || entry.matchedFiles.length > 0;\n const req = new RequiredChecklist(entry.def.id, entry.def.reviewer, entry.def.doc, entry.matchedFiles, entry.matchedPatterns, entry.def.required);\n // A skipped checklist has no verdict to resolve — asking for one would report it as MISSING,\n // i.e. as an unreviewed obligation, when in fact it never had one.\n const verdict = ran && !notBriefed.has(entry.def.id) ? this.reviewJsonService.resolveVerdict(req, review.results) : new ChecklistVerdict(entry.def.id, '', '');\n const identity = review.results.find((result): boolean => result.id === entry.def.id);\n const row = new ChecklistCommentRow(identity?.agent ?? 'unknown', identity?.model ?? 'unknown', entry.def.id, verdict.status, verdict.detail, ran, entry.def.patterns, entry.matchedPatterns, entry.matchedFiles, scan.roster.changedFileCount);\n row.required = entry.def.required;\n row.notBriefed = notBriefed.has(entry.def.id);\n const read = readByChecklist.get(entry.def.id);\n row.diffRead = read === undefined ? '' : read ? 'yes' : 'no';\n return row;\n });\n }\n\n // Hidden HMAC gate-token marker (with a leading blank line) to append to the PR body, or '' when the\n // repo sets no gateSalt (byte-identical body to before this feature). Bound to the pushed HEAD sha.\n private gateTokenBody(gateSalt: string, headSha: string): string {\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n return marker === '' ? '' : `\\n\\n${marker}\\n`;\n }\n\n /**\n * Publish the roster + every reviewer's full `output` as ONE combined PR comment, idempotently (find the\n * marker comment → PATCH it, else POST). Never fatal: by here the PR is already created/updated, so a\n * `gh` failure only warns.\n *\n * Posted on EVERY run of a repo that defines checklists — including one where nothing matched, because\n * \"all five were evaluated and none applied\" is the good news the old comment could not deliver. The\n * guard is `scan.defined.length`, deliberately NOT the number of rows that ran: a repo with no\n * checklists configured must still see no comment at all (see ChecklistCommentRenderer).\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private async postChecklistComment(repoRoot: string, prNumber: string, scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): Promise<void> {\n if (prNumber === '' || scan.defined.length === 0) return;\n if (!loadAndValidate(repoRoot).prGate.checklistComments) return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = CHECKLIST_COMMENT_MARKER;\n request.body = this.checklistComment.render(this.commentRows(scan, review, provenance), provenance.verified, scan.roster.baseResolved, scan.suppressed.length, false);\n request.payloadDir = prDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n request.payloadName = 'checklist-comment.json';\n request.label = 'checklist review comment';\n await 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 async upsertPr(request: PrUpsertRequest): Promise<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, await 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 = await 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 = await 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) await 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 = await 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 async publishAll(repoRoot: string, base: string, input: DashboardInput, sources: PrCommentSources): Promise<UpsertResult> {\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n const headSha = await 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, await this.existingPrUrl(base)) + upsert.tokenSuffix;\n // Rendering above already refused a stray closing reference; say out loud what merging WILL close.\n // `say`: a wrong closesIssue must be noticed BEFORE landing, so this may not end up only in the log.\n for (const warning of new IssueReferences().closeWarnings(input.review.addressesIssues)) this.stageConsole.say(`${warning}\\n`);\n const result = await 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 await this.postDetailComment(repoRoot, result.prNumber, input);\n await 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 await 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 async backfillPrBody(prNumber: string, bodyFile: string, finalBody: string): Promise<void> {\n if (prNumber === '') return;\n fs.writeFileSync(bodyFile, finalBody + '\\n');\n const res = await this.processes.run('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile]);\n if (!res.ok) {\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 async existingPrUrl(baseBranch: string): Promise<string> {\n return (await 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 async postDetailComment(repoRoot: string, prNumber: string, input: DashboardInput): Promise<void> {\n if (prNumber === '') return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = DETAIL_COMMENT_MARKER;\n const detail = this.dashboard.renderDetailComment(input);\n request.body = DETAIL_COMMENT_MARKER + '\\n' + detail;\n request.payloadDir = prDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n request.payloadName = 'detail-comment.json';\n request.label = 'full dashboard comment';\n await 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 async prRef(baseBranch: string): Promise<PrRef> {\n const result = await this.processes.run('gh', ['pr', 'view', baseBranch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"']);\n if (!result.ok) {\n return new PrRef('', '');\n }\n const parts = result.stdout.trim().split('\\t');\n return new PrRef(parts[0] ?? '', parts[1] ?? '');\n }\n}\n"]}
1
+ {"version":3,"file":"finish-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/finish-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAyM;AACzM,8DAA2F;AAC3F,iEAA6D;AAC7D,yCAA2D;AAC3D,2EAAgE;AAChE,6DAAyD;AACzD,qEAAsG;AACtG,6EAAwE;AACxE,mDAA+C;AAC/C,+DAA6E;AAC7E,+DAAsF;AACtF,yDAAqD;AACrD,2EAA6E;AAC7E,uEAAyE;AACzE,mEAAkF;AAClF,qDAAiG;AACjG,6DAA4E;AAC5E,2EAAqE;AACrE,uEAA+E;AAC/E,yEAAuF;AACvF,yEAAsF;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equiredChecklist, ChecklistVerdict, writeTemplate, RepoRootFinder, ReviewJsonService, GateTokenService } from '@webpieces/rules-config';\nimport { GitProcessApi, InformAiError, NativeProcessApi } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { ReviewerVerdictGate } from '../workflow/reviewer-verdict-gate';\nimport { GitExec } from '../workflow/git-exec';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BuildGateLog, FINISH_STAGE, REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { MergeState } from '../workflow/merge-state';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { ReviewRoundStateService } from '../workflow/review-round-state';\nimport { StageOutputLog, FINISH_CONSOLE_LOG } from '../workflow/stage-output-log';\nimport { PrMerger, MergeIntent, MergeOutcome, MERGE_RESULT_FAILED } from '../workflow/pr-merger';\nimport { FinishBanner, FinishBannerInput } from '../workflow/finish-banner';\nimport { MergeBodyTempFile } from '../workflow/merge-body-temp-file';\nimport { GatedPrPublisher, PrBodyDraft } 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 { IssueReferences } from '../../dashboard/issue-references';\nimport { HotfixRedirect } from '../workflow/hotfix-redirect';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The three inputs the PR COMMENTS are rendered from, bundled so `publishAll` takes one parameter for\n * them instead of three it only forwards. Data-only, per CLAUDE.md.\n */\nclass PrCommentSources {\n scan: ChecklistScan;\n review: PrSummary;\n provenance: ProvenanceReport;\n\n constructor(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport) {\n this.scan = scan;\n this.review = review;\n this.provenance = provenance;\n }\n}\n\n/**\n * Everything the PR upsert needs. Data-only, per CLAUDE.md — it replaced a 5-positional-parameter method\n * once `tokenSuffix` had to travel too, so the body can be re-rendered with the PR's own URL after\n * `gh pr create` returns it (see the INVARIANT comment in upsertPr).\n */\nclass PrUpsertRequest {\n repoRoot = '';\n baseBranch = '';\n title = '';\n /** The description as first published — rendered with whatever URL was known at the time. */\n body = '';\n /**\n * The hidden gate-token marker exactly as appended to `body`, so a re-render can reproduce the same\n * bytes. Kept separate from `body` because Dashboard renders the human/git-log half and must not know\n * about HMACs.\n */\n tokenSuffix = '';\n input: DashboardInput;\n\n constructor(input: DashboardInput) {\n this.input = input;\n }\n}\n\n// A resolved PR's number + web URL. Both '' when the PR can't be resolved (e.g. create failed).\nclass PrRef {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n// The outcome of the whole upsert: the PR number + web URL ('' each when unresolved) plus what actually\n// happened to the merge, so the final summary reports the REAL result rather than assuming success. The\n// URL is carried so the closing block can hand the AI a clickable link to relay to the user verbatim.\nclass UpsertResult {\n prNumber: string;\n prUrl: string;\n merge: MergeOutcome;\n\n constructor(prNumber: string, prUrl: string, merge: MergeOutcome) {\n this.prNumber = prNumber;\n this.prUrl = prUrl;\n this.merge = merge;\n }\n}\n\n// STAGE ③ — FINISH of the AI-first PR flow, and the ONLY command that posts PRs. Runs after\n// `wp-review-upsert-pr` verified the branch and the AI spawned the reviewers + wrote summary.json.\n//\n// In order: (1) REFUSE on an unvalidated 3-point merge and REQUIRE stage ②'s receipt; (2) REQUIRE\n// summary.json + every reviewer's verdict + provenance; (3) run the build gate UNLESS the receipt already\n// covers this exact HEAD; (4) render the dashboard; (5) create/update the PR via `gh`.\n//\n// It no longer FINALIZES a merge — stage ② does. Two commands owning conflict-resolution validation is two\n// implementations that drift, and finalizing here came too late to help anyway: the reviewers had already\n// reviewed the pre-merge tree by then.\n@injectable(bindingScopeValues.Singleton)\nexport class FinishUpsertPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildLog: BuildGateLog,\n private readonly mergeState: MergeState,\n private readonly prMerger: PrMerger,\n private readonly publisher: GatedPrPublisher,\n private readonly dashboard: Dashboard,\n private readonly authorIdentity: AuthorIdentityResolver,\n // The 2nd PR comment. Its own class because it is its own surface — see ChecklistCommentRenderer.\n private readonly checklistComment: ChecklistCommentRenderer,\n private readonly checklistScanner: ChecklistScanner,\n private readonly verdictGate: ReviewerVerdictGate,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly gateTokenService: GateTokenService,\n // Owns the reviewer-provenance integrity check and its audit record — see ProvenanceEnforcer.\n private readonly provenanceEnforcer: ProvenanceEnforcer,\n // NOTE: ChecklistInstructionsService is deliberately NOT injected here any more. Its \"You MUST run\n // these N reviewer subagent(s)\" block is now rendered by ReviewerVerdictGate and ONLY for checklists\n // that genuinely never ran, so no other code path in this command can print it at a refusal.\n private readonly receipts: ReviewStageReceiptService,\n private readonly banner: FinishBanner,\n // `gh pr merge --body-file` takes a path, so the bytes just published as the PR description are\n // spilled to a throwaway file for the length of one `gh` call. Nothing durable — the PR holds it.\n private readonly mergeBodyFile: MergeBodyTempFile,\n // ONE marker-keyed upsert, shared by both PR comments (the full dashboard and the checklist).\n private readonly commentUpserter: PrCommentUpserter,\n // Pins the two GitHub repo settings that decide whether a UI merge writes the body we just\n // rendered. Server-side, so no config can express them — see SquashSettingsEnforcer.\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly stageConsole: StageOutputLog,\n private readonly hotfixRedirect: HotfixRedirect,\n private readonly rounds: ReviewRoundStateService,\n private readonly git: GitProcessApi,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /**\n * Runs with this stage's console CAPTURED to a file (see StageOutputLog). What still reaches the\n * terminal is what an agent must act on: the build heartbeat and result, and the closing banner with\n * the PR link and whatever is still owed. The dashboard computation, the gh round trips and the\n * comment upserts are in the file.\n */\n async run(): Promise<void> {\n // A /hotfix/ branch is published by wp-upsert-hotfix-pr, never by this stage (issue #1057).\n this.hotfixRedirect.assertNotHotfix('wp-finish-upsert-pr');\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(repoRoot, FINISH_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot));\n }\n\n private async runStage(repoRoot: string): Promise<void> {\n // Refresh the AI-facing workflow doc so it's present + current for any failure message to cite.\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n // 1. REQUIRE stage ② — see assertStageTwoRan. Returns true when its receipt covers THIS commit,\n // which is what lets the build gate below be skipped rather than re-run for a foregone answer.\n const featureName = await this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n const buildAlreadyGreen = await this.assertStageTwoRan(repoRoot);\n\n // 2. REQUIRE the AI-authored summary.json (throws InformAiError with the schema if missing/invalid).\n // Compute the consumer checklists this diff triggered FIRST so an unacknowledged BLOCK throws\n // here — BEFORE any `gh pr create` — matching the guarantee buildCommand already provides.\n // The SAME scan wp-review-upsert-pr runs, with filterAlreadyReviewed:true so `outstanding` is exactly what\n // still owes a verdict (Z of N of X). Sharing the computation is the point: the command that REPORTS\n // and the command that GATES must not be able to disagree about what is owed. review-round<N>-<id>.json files\n // persist locally, so a re-run re-validates the EXISTING verdicts against the (possibly changed)\n // applicable set for free — an unchanged checklist needs no re-review, a newly-applicable one refuses\n // until its file is written.\n // The scan judges ONLY the checklists that were briefed (issue #1053) — never one a later commit newly\n // triggered — and it has already folded every recorded orange fix into its results.\n const scan = await this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, 'stage3-finish'));\n const required = scan.applicable;\n // The applicable checklists that are supposed to HAVE a verdict — everything except the optional ones\n // nobody ran. Used for provenance and for the dashboard rows, both of which ask \"who reviewed this?\"\n // and would otherwise demand an answer from a review the human declined: provenance would refuse the\n // PR because a subagent that was never meant to run cannot be proven to have run, and the dashboard\n // would render a MISSING verdict for it.\n const verdicted = this.verdictedOf(scan);\n // FAIL FAST on an unclear checklist, BEFORE summary.json is parsed and before the build gate runs. A\n // missing reviewer is not a summary.json defect (folding it in made the AI fix the wrong thing), and\n // nobody should wait on a build to be told a reviewer never ran. ReviewerVerdictGate owns the\n // distinction between unreadable / ORANGE / REFUSED / never-ran.\n this.verdictGate.assertEveryReviewerRan(scan);\n const review = this.reviewJsonService.loadSummaryJson(summaryJsonPath(repoRoot, featureName), required, '', scan.orangeFixes);\n this.applyRoundAudits(review, scan, config.maxReviewerRounds);\n // FAIL FAST on a hand-written closing reference in the summary (issue #1310), before the build gate.\n // renderPrBody re-judges the final bytes; this only moves the common case ahead of a slow build.\n new IssueReferences().assertNoStrayClosingReferences(review.summary, review.addressesIssues, 'pnpm wp-finish-upsert-pr');\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 = await this.gitExec.currentBranch(process.cwd());\n const provenance = await 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 await 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(await this.gitExec.currentBranch(process.cwd()));\n\n process.stdout.write('\\n' + SEP + '📋 Dashboard + PR\\n' + SEP + '\\n');\n const title = await this.prTitleFrom(review);\n const input = await this.computeDashboardInput(repoRoot, true, review, title, verdicted, scan);\n const result = await this.publishAll(repoRoot, base, input, new PrCommentSources(scan, review, provenance));\n this.snapshotPublishedReview(repoRoot, featureName, result);\n\n // The closing recap + the clickable-link directive, BOTH derived from the real merge outcome.\n // Nothing here may hard-code success: a stranded PR under a green checkmark is how PRs got\n // abandoned (see FinishBanner).\n const bannerInput = new FinishBannerInput(result.prNumber, result.prUrl, title, base, result.merge);\n // `say`: the PR link and what is still owed are the whole reason a caller ran this command, and a\n // not-done outcome carries the commands that fix it. Neither may end up only in a log file.\n this.stageConsole.say(this.banner.render(bannerInput));\n this.stageConsole.say(this.banner.linkDirective(bannerInput));\n }\n\n private applyRoundAudits(review: PrSummary, scan: ChecklistScan, maxReviewerRounds: number): void {\n for (const result of review.results) {\n const trail = this.rounds.auditTrail(scan.summaryPath, result.id, maxReviewerRounds);\n if (trail === '') continue;\n result.output = trail;\n if (result.remediation !== '') result.remediation = `${trail}\\n\\n#### Final state\\n${result.remediation}`;\n }\n }\n\n // Validate + commit + finalize a 3-point merge the AI resolved, if one is in progress. Finalizing here\n // does NOT push (pushRemote=false): this command pushes exactly ONCE, from GatedPrPublisher, and only\n // after summary.json + every BLOCK checklist + the build gate pass and the gated PR body is written.\n /**\n * The build gate — SKIPPED when stage ②'s receipt already covers this exact HEAD.\n *\n * The gate is authoritative per-COMMIT, not per-command: re-running it on a tree that has not moved\n * since stage ② verified it buys nothing and costs a full `nx affected`. That skip is what makes the\n * three-stage flow cost ONE build rather than two, and it is why moving the gate earlier was affordable.\n */\n private async runOrSkipBuildGate(repoRoot: string, alreadyGreen: boolean): Promise<void> {\n if (alreadyGreen) {\n // `say`, for the same reason the gate's own two lines are: a caller watching for a build needs\n // to be told, live, that there is not going to be one.\n this.stageConsole.say('\\n🛠️ Build gate: already green for this commit (stage ② receipt) — skipping the rebuild.\\n' + await 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 async skippedBuildLogNote(repoRoot: string): Promise<string> {\n const log = await 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 async assertStageTwoRan(repoRoot: string): Promise<boolean> {\n await this.assertNoUnvalidatedMerge(repoRoot);\n return this.assertReviewStageRan(repoRoot, await this.aiBranchName.getFeatureName(), await 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 async assertNoUnvalidatedMerge(repoRoot: string): Promise<void> {\n const home = this.mergeState.mergeDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return;\n throw new InformAiError(\n '⛔ NO PR — a 3-point merge on this branch is still unvalidated, so nothing here has been\\n' +\n 'verified: the conflict resolution is unchecked, the merged tree was never built, and any\\n' +\n 'reviewer that ran judged the PRE-merge code.\\n\\n' +\n `Conflicted file(s): ${marker.conflictedFiles.join(', ')}\\n\\n` +\n 'Resolve them (see .webpieces/instruct-ai/webpieces.mergeprocess.md), then run:\\n' +\n ' pnpm wp-review-upsert-pr\\n' +\n 'It validates the resolution, commits it, builds it, and re-briefs the reviewers.',\n );\n }\n\n /**\n * REQUIRE stage ② (`wp-review-upsert-pr`) to have run, and report whether it ran on THIS commit.\n *\n * Returns true when the receipt matches the current HEAD — the caller then skips its own build, because\n * the receipt IS the gate for that sha and rebuilding an unchanged tree is a second full `nx affected`\n * run for a foregone answer.\n *\n * Without this check a repo with NO checklists has nothing forcing stage ②: `assertEveryReviewerRan`\n * is vacuous, and summary.json — the only other interlock — is a file the AI writes itself. It could\n * write it and come straight here, skipping the merge validation and the build entirely.\n */\n private assertReviewStageRan(repoRoot: string, featureName: string, headSha: string): boolean {\n const receipt = this.receipts.read(repoRoot, featureName);\n if (receipt === null) {\n throw new InformAiError(\n '⛔ NO PR — stage ② never ran on this branch. That means the 3-point merge is unvalidated,\\n' +\n 'the build gate has not run, no diff was extracted, and no reviewer was briefed.\\n\\n' +\n 'Run: pnpm wp-review-upsert-pr\\n' +\n '(then spawn the reviewers it names, write summary.json, and re-run this command)',\n );\n }\n if (receipt.buildHeadSha === headSha) return true;\n // Not fatal, and never a re-review (issue #1053): a green or yellow verdict stands whatever changed\n // since, and only a RED with a round left ever opens another round. Suggesting a re-review here\n // would be an instruction the gate itself refuses. It is never silent either: the build re-runs.\n process.stderr.write(\n `\\n⚠️ HEAD moved since stage ② built (built ${receipt.buildHeadSha.slice(0, 8) || 'unknown'}, now ${headSha.slice(0, 8)}).\\n` +\n ' The build gate will re-run. No further review runs for this: every verdict is carried forward\\n' +\n ' from the reviewed tree, and the PR records that the reviewers judged an earlier commit.\\n\\n',\n );\n return false;\n }\n\n /**\n * Snapshot the published intent without consuming the active summary (issue #1114). A same-PR\n * update carries reviewer verdicts and can also carry unchanged intent. Stage ② requires the author\n * to refresh metadata that changed BEFORE reviewers read it. Snapshots never become active input.\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 snapshotPublishedReview(\n repoRoot: string,\n featureName: string,\n result: UpsertResult,\n ): 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 snapshot = this.reviewJsonService.snapshotSummaryJson(\n summaryJsonPath(repoRoot, featureName),\n );\n process.stdout.write(\n ` saved published summary → ${snapshot} (audit only); active summary.json retained ✓\\n`,\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(\n `⚠️ Could not snapshot summary.json (non-fatal — the PR is already up): ${error.message}\\n`,\n );\n }\n }\n\n private async gitOut(args: string[]): Promise<string> {\n const result = await this.git.run(args);\n return result.ok ? 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 async prTitleFrom(review: PrSummary): Promise<string> {\n if (review.title !== '') return review.title;\n return (await this.aiBranchName.getFeatureName()).replace(/[-/]+/g, ' ').trim();\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private async computeDashboardInput(repoRoot: string, buildPassed: boolean, review: PrSummary, title: string, required: readonly RequiredChecklist[], scan: ChecklistScan): Promise<DashboardInput> {\n const config = loadAndValidate(repoRoot).prGate;\n const forkPoint = await this.gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = await this.gitOut(['rev-parse', 'HEAD']);\n const mainHead = await this.gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = (await this.gitOut(['diff', range, '--name-only']))\n .split('\\n')\n .filter((f: string): boolean => f.trim() !== '');\n const patch = await this.gitOut(['diff', range]);\n\n const gateResults = this.dashboard.computeGateResults(config.gates, changedFiles);\n const disables = this.dashboard.countAddedDisables(patch);\n const rows = this.checklistRows(required, review);\n // buildCommand travels into the dashboard so the PR-body footer can NAME the command that vouched\n // for this commit. The footer used to assert \"build ran via nx affected\" on every repo, which was\n // simply false wherever buildCommand is not nx.\n // `scan.suppressed.length`, never `scan.reviewersDisabled` alone: the dashboard and the commit\n // body have to state HOW MANY reviewers were killed, because a suppressed 4 and an applicable 0\n // are different facts that both render as an empty `rows`. See DashboardInput.\n const input = new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, review, rows, this.buildAffected.resolveBuildCommand(repoRoot), scan.suppressed.length, this.authorIdentity.resolve(review.model), false);\n input.notBriefed = scan.notBriefed.map((r: RequiredChecklist): string => r.id);\n return input;\n }\n\n /**\n * The applicable checklists MINUS the optional ones nobody ran.\n *\n * Not folded into `ChecklistScan` as yet another field: `applicable` (what matched) and `optionalNotRun`\n * (what was declined) are both facts about the scan, whereas this is one command's view of them, and the\n * roster comment deliberately wants the OTHER view — it lists the declined ones precisely so the PR does\n * not imply they passed.\n */\n private verdictedOf(scan: ChecklistScan): RequiredChecklist[] {\n const skipped = new Set(scan.optionalNotRun.map((r: RequiredChecklist): string => r.id));\n return scan.applicable.filter((r: RequiredChecklist): boolean => !skipped.has(r.id));\n }\n\n // Pair each matched checklist with its resolved verdict for the dashboard.\n //\n // A checklist reaching this point is always PASS, WARN or OVERRIDDEN, and the reason is ReviewerVerdictGate\n // — NOT loadSummaryJson. The gate runs one line earlier and throws on every other state (FAIL, MISSING,\n // BAD_FORMAT), so loadSummaryJson's own checklist validation can no longer be the thing that rejects them;\n // it re-validates the same set and finds it clean. This comment used to credit loadSummaryJson, which made\n // the ordering look deliberate while the gate's generic \"no verdict yet\" message masked every refusal.\n // WARN belongs in that list: yellow SHIPS, so it is not outstanding and reaches the dashboard.\n private checklistRows(required: readonly RequiredChecklist[], review: PrSummary): ChecklistRow[] {\n return required.map((req: RequiredChecklist): ChecklistRow => {\n const verdict = this.reviewJsonService.resolveVerdict(req, review.results);\n return new ChecklistRow(req.id, verdict.status, verdict.detail);\n });\n }\n\n /**\n * One comment row per DEFINED checklist — matched or not — pairing the roster's match evidence with the\n * resolved verdict. Built from `scan.roster` rather than from the applicable set: the skipped ones are\n * absent from `applicable` by construction, and their \"why not\" evidence (the configured globs and the\n * changed-file total) exists nowhere else without recomputing the diff a second way.\n */\n private commentRows(scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): ChecklistCommentRow[] {\n // checklist id -> did its reviewer open the diff. Absent ⇒ not assessed, which prints nothing (see ChecklistCommentRow.diffRead).\n const readByChecklist = new Map<string, boolean>();\n for (const e of provenance.evidence) readByChecklist.set(e.checklistId, e.readDiff);\n const judged = new Set(scan.applicable.map((r: RequiredChecklist): string => r.id));\n const notBriefed = new Set(scan.notBriefed.map((r: RequiredChecklist): string => r.id));\n return scan.roster.entries.map((entry: TriggeredChecklist): ChecklistCommentRow => {\n // A briefed checklist is judged whether or not the final diff still matches it (the set is\n // frozen at the briefing, issue #1053); a newly-triggered one is shown, never judged.\n const ran = judged.has(entry.def.id) || entry.matchedFiles.length > 0;\n const req = new RequiredChecklist(entry.def.id, entry.def.reviewer, entry.def.doc, entry.matchedFiles, entry.matchedPatterns, entry.def.required);\n // A skipped checklist has no verdict to resolve — asking for one would report it as MISSING,\n // i.e. as an unreviewed obligation, when in fact it never had one.\n const verdict = ran && !notBriefed.has(entry.def.id) ? this.reviewJsonService.resolveVerdict(req, review.results) : new ChecklistVerdict(entry.def.id, '', '');\n const identity = review.results.find((result): boolean => result.id === entry.def.id);\n const row = new ChecklistCommentRow(identity?.agent ?? 'unknown', identity?.model ?? 'unknown', entry.def.id, verdict.status, verdict.detail, ran, entry.def.patterns, entry.matchedPatterns, entry.matchedFiles, scan.roster.changedFileCount);\n row.required = entry.def.required;\n row.notBriefed = notBriefed.has(entry.def.id);\n const read = readByChecklist.get(entry.def.id);\n row.diffRead = read === undefined ? '' : read ? 'yes' : 'no';\n return row;\n });\n }\n\n // Hidden HMAC gate-token marker (with a leading blank line) to append to the PR body, or '' when the\n // repo sets no gateSalt (byte-identical body to before this feature). Bound to the pushed HEAD sha.\n private gateTokenBody(gateSalt: string, headSha: string): string {\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n return marker === '' ? '' : `\\n\\n${marker}\\n`;\n }\n\n /**\n * Publish the roster + every reviewer's full `output` as ONE combined PR comment, idempotently (find the\n * marker comment → PATCH it, else POST). Never fatal: by here the PR is already created/updated, so a\n * `gh` failure only warns.\n *\n * Posted on EVERY run of a repo that defines checklists — including one where nothing matched, because\n * \"all five were evaluated and none applied\" is the good news the old comment could not deliver. The\n * guard is `scan.defined.length`, deliberately NOT the number of rows that ran: a repo with no\n * checklists configured must still see no comment at all (see ChecklistCommentRenderer).\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private async postChecklistComment(repoRoot: string, prNumber: string, scan: ChecklistScan, review: PrSummary, provenance: ProvenanceReport): Promise<void> {\n if (prNumber === '' || scan.defined.length === 0) return;\n if (!loadAndValidate(repoRoot).prGate.checklistComments) return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = CHECKLIST_COMMENT_MARKER;\n request.body = this.checklistComment.render(this.commentRows(scan, review, provenance), provenance.verified, scan.roster.baseResolved, scan.suppressed.length, false);\n request.payloadDir = prDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n request.payloadName = 'checklist-comment.json';\n request.label = 'checklist review comment';\n await 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 async upsertPr(request: PrUpsertRequest): Promise<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, await 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 render = (prUrl: string): string => this.dashboard.renderPrBody(input, prUrl) + request.tokenSuffix;\n const published = await this.publisher.publish(baseBranch, title, new PrBodyDraft(bodyFile, request.body, render));\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 = await 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 * publisher rendered it with the PREDICTED URL (issue #1418) — or with `prUrl: ''` when the\n * prediction failed. Re-render with the REAL URL; when that differs from what went up (a wrong\n * guess, or no guess), push the corrected description back, so the two strings match and the\n * commit carries its own link. A correct guess needs no edit, so creating the PR fires one event.\n * On every later run the URL was already known before publishing and nothing is re-sent.\n */\n this.publisher.reportPredictedLink(published, ref.number);\n const finalBody = render(ref.url);\n if (finalBody !== published.body) await 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 = await 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 async publishAll(repoRoot: string, base: string, input: DashboardInput, sources: PrCommentSources): Promise<UpsertResult> {\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n const headSha = await 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 — the publisher then re-renders the body with the\n // PREDICTED URL just before `gh pr create`, and upsertPr back-fills the real one on a miss.\n upsert.body = this.dashboard.renderPrBody(input, await this.existingPrUrl(base)) + upsert.tokenSuffix;\n // Rendering above already refused a stray closing reference; say out loud what merging WILL close.\n // `say`: a wrong closesIssue must be noticed BEFORE landing, so this may not end up only in the log.\n for (const warning of new IssueReferences().closeWarnings(input.review.addressesIssues)) this.stageConsole.say(`${warning}\\n`);\n const result = await 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 await this.postDetailComment(repoRoot, result.prNumber, input);\n await 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 await 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, and only when the\n * predicted URL was wrong or could not be predicted).\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 async backfillPrBody(prNumber: string, bodyFile: string, finalBody: string): Promise<void> {\n if (prNumber === '') return;\n fs.writeFileSync(bodyFile, finalBody + '\\n');\n const res = await this.processes.run('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile]);\n if (!res.ok) {\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 '' (the publisher\n * then predicts its URL, and {@link backfillPrBody} fixes a wrong or missing prediction afterwards).\n */\n private async existingPrUrl(baseBranch: string): Promise<string> {\n return (await 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 async postDetailComment(repoRoot: string, prNumber: string, input: DashboardInput): Promise<void> {\n if (prNumber === '') return;\n const request = new PrCommentRequest();\n request.prNumber = prNumber;\n request.marker = DETAIL_COMMENT_MARKER;\n const detail = this.dashboard.renderDetailComment(input);\n request.body = DETAIL_COMMENT_MARKER + '\\n' + detail;\n request.payloadDir = prDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n request.payloadName = 'detail-comment.json';\n request.label = 'full dashboard comment';\n await 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 async prRef(baseBranch: string): Promise<PrRef> {\n const result = await this.processes.run('gh', ['pr', 'view', baseBranch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"']);\n if (!result.ok) {\n return new PrRef('', '');\n }\n const parts = result.stdout.trim().split('\\t');\n return new PrRef(parts[0] ?? '', parts[1] ?? '');\n }\n}\n"]}
@@ -107,7 +107,8 @@ let HumanPostPrCommand = class HumanPostPrCommand {
107
107
  const bodyFile = path.join(this.reviewJsonService.prDirFor(repoRoot, await this.aiBranchName.getFeatureName()), 'pr-body.md');
108
108
  fs.mkdirSync(path.dirname(bodyFile), { recursive: true });
109
109
  fs.writeFileSync(bodyFile, initialBody + '\n');
110
- const published = await this.publisher.publish(baseBranch, this.titleFrom(summary, baseBranch), bodyFile, RETRY_COMMAND);
110
+ const render = (prUrl) => this.renderBody(summary, prUrl, gateSalt, headSha, buildRan);
111
+ const published = await this.publisher.publish(baseBranch, this.titleFrom(summary, baseBranch), new gated_pr_publisher_1.PrBodyDraft(bodyFile, initialBody, render), RETRY_COMMAND);
111
112
  if (published.createFailed) {
112
113
  throw new rules_config_1.CliExitError(1, `gh pr create failed. The validated body remains at ${bodyFile}; summary.json was not consumed.`);
113
114
  }
@@ -115,8 +116,9 @@ let HumanPostPrCommand = class HumanPostPrCommand {
115
116
  if (finalRef.number === '') {
116
117
  throw new rules_config_1.CliExitError(1, 'The branch was pushed but GitHub did not return its open PR; summary.json was not consumed.');
117
118
  }
118
- const finalBody = this.renderBody(summary, finalRef.url, gateSalt, headSha, buildRan);
119
- if (finalBody !== initialBody)
119
+ this.publisher.reportPredictedLink(published, finalRef.number);
120
+ const finalBody = render(finalRef.url);
121
+ if (finalBody !== published.body)
120
122
  await this.backfillBody(finalRef.number, bodyFile, finalBody);
121
123
  await this.squashSettings.ensure();
122
124
  const archive = this.reviewJsonService.archiveSummaryJson(summaryPath);
@@ -1 +1 @@
1
- {"version":3,"file":"human-post-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/human-post-pr-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,2DAAqC;AACrC,sEAAsG;AACtG,0DAAwI;AACxI,8DAA6D;AAC7D,yCAA2D;AAC3D,2EAAgE;AAChE,6DAAyD;AACzD,uEAAkE;AAClE,mDAA+C;AAC/C,yDAAqD;AACrD,mFAA8E;AAC9E,mDAA6D;AAC7D,uEAAmE;AAEnE,MAAM,aAAa,GAAG,uBAAuB,CAAC;AAE9C,kFAAkF;AAClF,MAAa,aAAa;IACtB,MAAM,CAAS;IACf,GAAG,CAAS;IAEZ,YAAY,MAAc,EAAE,GAAW;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACnB,CAAC;CACJ;AARD,sCAQC;AAED;;;;;;GAMG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAEN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAbrB,YACqB,cAA8B,EAC9B,cAA8B,EAC9B,YAA0B,EAC1B,YAA0B,EAC1B,OAAgB,EAChB,UAAsB,EACtB,iBAAoC,EACpC,cAAqC,EACrC,gBAAkC,EAClC,SAA2B,EAC3B,cAAsC,EACtC,YAA0B,EAC1B,SAA2B;QAZ3B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,iBAAY,GAAZ,YAAY,CAAc;QAC1B,iBAAY,GAAZ,YAAY,CAAc;QAC1B,YAAO,GAA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B;QACpB,0CAAqB;QACnB,+BAAgB;QACvB,qCAAgB;QACX,iDAAsB;QACxB,4BAAY;QACf,iCAAgB;GAdvC,kBAAkB,CA0S9B","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as readline from 'readline';\nimport { BranchIdentity, MainSyncStatus, MainSyncStatusService } from '@webpieces/repo-workflow-core';\nimport { CliExitError, GateTokenService, PrSummary, RepoRootFinder, ReviewJsonService, loadAndValidate } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { bindingScopeValues, injectable } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { GatedPrPublisher } from '../workflow/gated-pr-publisher';\nimport { GitExec } from '../workflow/git-exec';\nimport { MergeState } from '../workflow/merge-state';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { BuildCommand, BuildOptions } from './build-command';\nimport { IssueReferences } from '../../dashboard/issue-references';\n\nconst RETRY_COMMAND = 'pnpm wp-human-post-pr';\n\n/** The PR identity returned by GitHub after posting. Data-only, per CLAUDE.md. */\nexport class HumanPostedPr {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n/**\n * Interactive, human-attested PR escape hatch.\n *\n * The first answer is an attestation, not identity detection: a process cannot prove who typed it. The\n * fail-closed ordering is the security property here — every answer except the literal normalized\n * `human` returns before repository discovery, git, GitHub, or any write.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class HumanPostPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly branchIdentity: BranchIdentity,\n private readonly branchNaming: BranchNaming,\n private readonly aiBranchName: AiBranchName,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly mainSyncStatus: MainSyncStatusService,\n private readonly gateTokenService: GateTokenService,\n private readonly publisher: GatedPrPublisher,\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly buildCommand: BuildCommand,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async run(): Promise<void> {\n const answer = (await this.question('Are you human or AI (human/AI)?\\n'))\n .trim()\n .toLowerCase();\n if (answer !== 'human') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr requires an explicit human attestation. Nothing was changed.',\n );\n }\n\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const currentBranch = this.branchIdentity.current();\n if (currentBranch === '' || currentBranch === 'HEAD') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr requires a checked-out feature branch; detached HEAD is not publishable.',\n );\n }\n if (currentBranch === 'main') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr refuses main. Check out a clean feature branch and rerun it.',\n );\n }\n const baseBranch = this.branchNaming.baseBranchName(currentBranch);\n await this.gitExec.assertCleanTree(repoRoot);\n await this.assertNoUnvalidatedMerge(repoRoot);\n await this.fetchMain(repoRoot);\n\n const forkPoint = await this.git(\n ['merge-base', 'origin/main', 'HEAD'],\n repoRoot,\n 'Could not resolve the pure-main fork point against freshly fetched origin/main.',\n );\n const summaryPath = this.reviewJsonService.summaryJsonPath(\n repoRoot,\n await this.aiBranchName.getFeatureName(),\n );\n await this.ensureSummary(summaryPath, forkPoint);\n const summary = this.reviewJsonService.loadSummaryJson(summaryPath, [], '', {}, RETRY_COMMAND);\n // FAIL FAST on a hand-written closing reference (issue #1310), before the human is asked to build.\n new IssueReferences().assertNoStrayClosingReferences(summary.summary, summary.addressesIssues, RETRY_COMMAND);\n\n const status = await this.mainSyncStatus.computeMainSyncStatus(repoRoot);\n this.assertCurrentMain(status);\n const buildRan = await this.askToBuild();\n if (buildRan) await this.gitExec.assertCleanTree(repoRoot);\n\n await this.post(repoRoot, baseBranch, summaryPath, summary, buildRan);\n }\n\n /** The safe body-before-push publication shared with the automated flow via GatedPrPublisher. */\n private async post(\n repoRoot: string,\n baseBranch: string,\n summaryPath: string,\n summary: PrSummary,\n buildRan: boolean,\n ): Promise<void> {\n const headSha = await this.git(\n ['rev-parse', 'HEAD'],\n repoRoot,\n 'Could not resolve feature HEAD.',\n );\n const gateSalt = this.gateSalt(repoRoot);\n const initialRef = await this.resolvePr(baseBranch);\n const initialBody = this.renderBody(summary, initialRef.url, gateSalt, headSha, buildRan);\n for (const warning of new IssueReferences().closeWarnings(summary.addressesIssues)) process.stdout.write(`${warning}\\n`);\n const bodyFile = path.join(\n this.reviewJsonService.prDirFor(repoRoot, await this.aiBranchName.getFeatureName()),\n 'pr-body.md',\n );\n fs.mkdirSync(path.dirname(bodyFile), { recursive: true });\n fs.writeFileSync(bodyFile, initialBody + '\\n');\n\n const published = await this.publisher.publish(\n baseBranch,\n this.titleFrom(summary, baseBranch),\n bodyFile,\n RETRY_COMMAND,\n );\n if (published.createFailed) {\n throw new CliExitError(\n 1,\n `gh pr create failed. The validated body remains at ${bodyFile}; summary.json was not consumed.`,\n );\n }\n\n const finalRef = await this.resolvePr(baseBranch);\n if (finalRef.number === '') {\n throw new CliExitError(\n 1,\n 'The branch was pushed but GitHub did not return its open PR; summary.json was not consumed.',\n );\n }\n const finalBody = this.renderBody(summary, finalRef.url, gateSalt, headSha, buildRan);\n if (finalBody !== initialBody) await this.backfillBody(finalRef.number, bodyFile, finalBody);\n await this.squashSettings.ensure();\n const archive = this.reviewJsonService.archiveSummaryJson(summaryPath);\n if (archive !== '')\n process.stdout.write(`Archived this run's summary.json → ${archive} (audit only) ✓\\n`);\n process.stdout.write(\n `✅ Human-attested PR posted (${buildRan ? 'local wp-build passed; automated review skipped' : 'local build/review skipped'}): ${finalRef.url}\\n`,\n );\n }\n\n private async askToBuild(): Promise<boolean> {\n const answer = (\n await this.question('Run ' + 'wp-build here (If no, CI will run it in the cloud) Y/N?\\n')\n )\n .trim()\n .toLowerCase();\n if (answer === 'n' || answer === 'no') return false;\n if (answer !== 'y' && answer !== 'yes') {\n throw new CliExitError(1, 'Please answer Y or N. No PR was pushed or edited.');\n }\n await this.buildCommand.runStreaming(new BuildOptions(false));\n return true;\n }\n\n private async assertNoUnvalidatedMerge(repoRoot: string): Promise<void> {\n const home = this.mergeState.mergeDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n const active = this.mergeState.findActiveMergeRunDir(home);\n const marker = active === null ? null : this.mergeState.readMergeMarker(active);\n if (marker === null || marker.validated) return;\n throw new CliExitError(\n 1,\n 'wp-human-post-pr refuses an active, unvalidated 3-point merge. Resolve it and run the supported ' +\n 'Webpieces finish/update flow before posting.',\n );\n }\n\n protected fetchMain(repoRoot: string): Promise<void> {\n return this.gitExec.runGitChecked(\n ['fetch', 'origin', 'main'],\n 'Could not refresh origin/main; wp-human-post-pr will not evaluate or publish against a stale ref',\n );\n }\n\n protected gateSalt(repoRoot: string): string {\n return loadAndValidate(repoRoot).prGate.gateSalt;\n }\n\n private async ensureSummary(summaryPath: string, forkPoint: string): Promise<void> {\n if (fs.existsSync(summaryPath)) return;\n process.stdout.write(\n '\\nCopy/paste the following instruction into AI:\\n\\n' +\n `Write ONLY ${summaryPath}.\\n` +\n 'Do not run pnpm wp-review-upsert-pr, pnpm wp-finish-upsert-pr, push, or create/update a PR.\\n' +\n `Summarize exactly: git diff ${forkPoint} HEAD\\n` +\n `Changed files: git diff --name-only ${forkPoint} HEAD\\n\\n` +\n this.reviewJsonService.summaryJsonSchemaHint(summaryPath) +\n '\\n\\n',\n );\n const answer = (\n await this.question(\n \"I don't see summary.json and we at least need that to short circuit pushing.\\n\" +\n 'Please paste the instructions above into AI. When it is done generating summary.json, continue? (Y/N)\\n',\n )\n )\n .trim()\n .toLowerCase();\n if (answer !== 'y' && answer !== 'yes') {\n throw new CliExitError(\n 1,\n 'No PR was pushed or edited. Rerun pnpm wp-human-post-pr when summary.json is ready.',\n );\n }\n }\n\n private assertCurrentMain(status: MainSyncStatus): void {\n if (!status.hasForkPoint || status.forkPoint === null) {\n throw new CliExitError(\n 1,\n 'Could not establish a pure-main fork point. Use the Webpieces update process; do not merge or rebase manually.',\n );\n }\n if (status.forkPoint === status.originMain) return;\n const conflicts =\n status.conflictFiles.length === 0\n ? 'Conflicts: (none predicted)'\n : 'Conflicts (files changed on both sides; conservative prediction):\\n' +\n status.conflictFiles.map((file: string): string => ` - ${file}`).join('\\n');\n const update =\n status.openPr === ''\n ? ' pnpm wp-start-update\\n # if conflicts are reported, resolve them, then:\\n pnpm wp-finish-update'\n : ' pnpm wp-start-upsert-pr\\n pnpm wp-review-upsert-pr\\n pnpm wp-finish-upsert-pr';\n throw new CliExitError(\n 1,\n 'Your branch is behind origin/main.\\n\\n' +\n 'Ask AI to run the Webpieces update process, then rerun pnpm wp-human-post-pr.\\n' +\n 'This is usually very quick unless you have conflicts.\\n\\n' +\n update +\n '\\n\\n' +\n conflicts,\n );\n }\n\n private renderBody(\n summary: PrSummary,\n prUrl: string,\n gateSalt: string,\n headSha: string,\n buildRan: boolean,\n ): string {\n const lines: string[] = [];\n if (prUrl !== '') lines.push(prUrl, '');\n lines.push(`Risk: ${summary.riskScore}/100 ${summary.riskEmoji} (${summary.riskLevel})`);\n lines.push(`Summary authored by ${summary.agent} (${summary.model})`);\n lines.push('');\n lines.push(\n buildRan\n ? 'Flags: ⚠️ HUMAN ESCAPE HATCH — local wp-build passed; automated reviewer stages were explicitly skipped.'\n : 'Flags: ⚠️ HUMAN ESCAPE HATCH — local build and automated reviewer stages were explicitly skipped; cloud CI will run.',\n );\n const issues = new IssueReferences();\n const text = issues.withoutBlockLines(summary.summary.trim(), summary.addressesIssues);\n if (text !== '') lines.push('', text);\n // The same `Fixes <url>` / `Part of <url>` block wp-finish-upsert-pr renders (issue #1310).\n const ticketLines = issues.blockLines(summary.addressesIssues);\n if (ticketLines.length > 0) lines.push('', ...ticketLines);\n lines.push(\n '',\n `Generated by webpieces-ts wp-human-post-pr (human-attested; ${buildRan ? 'local wp-build passed, automated review skipped' : 'local build/review skipped'})`,\n );\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n if (marker !== '') lines.push('', marker);\n const body = lines.join('\\n').replace(/\\|/g, '\\u00a6').replace(/#{2,}/g, '#');\n issues.assertNoStrayClosingReferences(body, summary.addressesIssues, RETRY_COMMAND);\n return body;\n }\n\n private titleFrom(summary: PrSummary, branch: string): string {\n return summary.title === '' ? branch.replace(/[-/]+/g, ' ').trim() : summary.title;\n }\n\n protected async resolvePr(branch: string): Promise<HumanPostedPr> {\n const result = await this.processes.run(\n 'gh',\n ['pr', 'view', branch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"'],\n );\n if (!result.ok) return new HumanPostedPr('', '');\n const parts = result.stdout.trim().split('\\t');\n return new HumanPostedPr(parts[0] ?? '', parts[1] ?? '');\n }\n\n protected async backfillBody(prNumber: string, bodyFile: string, body: string): Promise<void> {\n fs.writeFileSync(bodyFile, body + '\\n');\n if (await this.editPrBody(prNumber, bodyFile) !== 0) {\n throw new CliExitError(\n 1,\n `Could not update PR #${prNumber} with its final human-bypass body. The validated body remains at ${bodyFile}. ` +\n `Fix GitHub access, then re-run ${RETRY_COMMAND}; summary.json was not consumed.`,\n );\n }\n }\n\n protected async editPrBody(prNumber: string, bodyFile: string): Promise<number> {\n return (await this.processes.passThrough('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile])).code;\n }\n\n protected git(args: string[], cwd: string, failure: string): Promise<string> {\n return this.gitExec.gitQuery(args, cwd, failure);\n }\n\n // Seam: overridden in specs. EOF resolves to '' and therefore fails closed.\n protected question(prompt: string): Promise<string> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n return new Promise<string>((resolve: (value: string) => void): void => {\n let answered = false;\n rl.question(prompt, (answer: string): void => {\n answered = true;\n rl.close();\n resolve(answer);\n });\n rl.on('close', (): void => {\n if (!answered) resolve('');\n });\n });\n }\n}\n"]}
1
+ {"version":3,"file":"human-post-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/human-post-pr-command.ts"],"names":[],"mappings":";;;;AAAA,+C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xB,4BAAY;QACf,iCAAgB;GAdvC,kBAAkB,CA4S9B","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as readline from 'readline';\nimport { BranchIdentity, MainSyncStatus, MainSyncStatusService } from '@webpieces/repo-workflow-core';\nimport { CliExitError, GateTokenService, PrSummary, RepoRootFinder, ReviewJsonService, loadAndValidate } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { bindingScopeValues, injectable } from 'inversify';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BranchNaming } from '../workflow/branch-naming';\nimport { GatedPrPublisher, PrBodyDraft } from '../workflow/gated-pr-publisher';\nimport { GitExec } from '../workflow/git-exec';\nimport { MergeState } from '../workflow/merge-state';\nimport { SquashSettingsEnforcer } from '../workflow/squash-settings-enforcer';\nimport { BuildCommand, BuildOptions } from './build-command';\nimport { IssueReferences } from '../../dashboard/issue-references';\n\nconst RETRY_COMMAND = 'pnpm wp-human-post-pr';\n\n/** The PR identity returned by GitHub after posting. Data-only, per CLAUDE.md. */\nexport class HumanPostedPr {\n number: string;\n url: string;\n\n constructor(number: string, url: string) {\n this.number = number;\n this.url = url;\n }\n}\n\n/**\n * Interactive, human-attested PR escape hatch.\n *\n * The first answer is an attestation, not identity detection: a process cannot prove who typed it. The\n * fail-closed ordering is the security property here — every answer except the literal normalized\n * `human` returns before repository discovery, git, GitHub, or any write.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class HumanPostPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly branchIdentity: BranchIdentity,\n private readonly branchNaming: BranchNaming,\n private readonly aiBranchName: AiBranchName,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly mainSyncStatus: MainSyncStatusService,\n private readonly gateTokenService: GateTokenService,\n private readonly publisher: GatedPrPublisher,\n private readonly squashSettings: SquashSettingsEnforcer,\n private readonly buildCommand: BuildCommand,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async run(): Promise<void> {\n const answer = (await this.question('Are you human or AI (human/AI)?\\n'))\n .trim()\n .toLowerCase();\n if (answer !== 'human') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr requires an explicit human attestation. Nothing was changed.',\n );\n }\n\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const currentBranch = this.branchIdentity.current();\n if (currentBranch === '' || currentBranch === 'HEAD') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr requires a checked-out feature branch; detached HEAD is not publishable.',\n );\n }\n if (currentBranch === 'main') {\n throw new CliExitError(\n 1,\n 'wp-human-post-pr refuses main. Check out a clean feature branch and rerun it.',\n );\n }\n const baseBranch = this.branchNaming.baseBranchName(currentBranch);\n await this.gitExec.assertCleanTree(repoRoot);\n await this.assertNoUnvalidatedMerge(repoRoot);\n await this.fetchMain(repoRoot);\n\n const forkPoint = await this.git(\n ['merge-base', 'origin/main', 'HEAD'],\n repoRoot,\n 'Could not resolve the pure-main fork point against freshly fetched origin/main.',\n );\n const summaryPath = this.reviewJsonService.summaryJsonPath(\n repoRoot,\n await this.aiBranchName.getFeatureName(),\n );\n await this.ensureSummary(summaryPath, forkPoint);\n const summary = this.reviewJsonService.loadSummaryJson(summaryPath, [], '', {}, RETRY_COMMAND);\n // FAIL FAST on a hand-written closing reference (issue #1310), before the human is asked to build.\n new IssueReferences().assertNoStrayClosingReferences(summary.summary, summary.addressesIssues, RETRY_COMMAND);\n\n const status = await this.mainSyncStatus.computeMainSyncStatus(repoRoot);\n this.assertCurrentMain(status);\n const buildRan = await this.askToBuild();\n if (buildRan) await this.gitExec.assertCleanTree(repoRoot);\n\n await this.post(repoRoot, baseBranch, summaryPath, summary, buildRan);\n }\n\n /** The safe body-before-push publication shared with the automated flow via GatedPrPublisher. */\n private async post(\n repoRoot: string,\n baseBranch: string,\n summaryPath: string,\n summary: PrSummary,\n buildRan: boolean,\n ): Promise<void> {\n const headSha = await this.git(\n ['rev-parse', 'HEAD'],\n repoRoot,\n 'Could not resolve feature HEAD.',\n );\n const gateSalt = this.gateSalt(repoRoot);\n const initialRef = await this.resolvePr(baseBranch);\n const initialBody = this.renderBody(summary, initialRef.url, gateSalt, headSha, buildRan);\n for (const warning of new IssueReferences().closeWarnings(summary.addressesIssues)) process.stdout.write(`${warning}\\n`);\n const bodyFile = path.join(\n this.reviewJsonService.prDirFor(repoRoot, await this.aiBranchName.getFeatureName()),\n 'pr-body.md',\n );\n fs.mkdirSync(path.dirname(bodyFile), { recursive: true });\n fs.writeFileSync(bodyFile, initialBody + '\\n');\n\n const render = (prUrl: string): string => this.renderBody(summary, prUrl, gateSalt, headSha, buildRan);\n const published = await this.publisher.publish(\n baseBranch,\n this.titleFrom(summary, baseBranch),\n new PrBodyDraft(bodyFile, initialBody, render),\n RETRY_COMMAND,\n );\n if (published.createFailed) {\n throw new CliExitError(\n 1,\n `gh pr create failed. The validated body remains at ${bodyFile}; summary.json was not consumed.`,\n );\n }\n\n const finalRef = await this.resolvePr(baseBranch);\n if (finalRef.number === '') {\n throw new CliExitError(\n 1,\n 'The branch was pushed but GitHub did not return its open PR; summary.json was not consumed.',\n );\n }\n this.publisher.reportPredictedLink(published, finalRef.number);\n const finalBody = render(finalRef.url);\n if (finalBody !== published.body) await this.backfillBody(finalRef.number, bodyFile, finalBody);\n await this.squashSettings.ensure();\n const archive = this.reviewJsonService.archiveSummaryJson(summaryPath);\n if (archive !== '')\n process.stdout.write(`Archived this run's summary.json → ${archive} (audit only) ✓\\n`);\n process.stdout.write(\n `✅ Human-attested PR posted (${buildRan ? 'local wp-build passed; automated review skipped' : 'local build/review skipped'}): ${finalRef.url}\\n`,\n );\n }\n\n private async askToBuild(): Promise<boolean> {\n const answer = (\n await this.question('Run ' + 'wp-build here (If no, CI will run it in the cloud) Y/N?\\n')\n )\n .trim()\n .toLowerCase();\n if (answer === 'n' || answer === 'no') return false;\n if (answer !== 'y' && answer !== 'yes') {\n throw new CliExitError(1, 'Please answer Y or N. No PR was pushed or edited.');\n }\n await this.buildCommand.runStreaming(new BuildOptions(false));\n return true;\n }\n\n private async assertNoUnvalidatedMerge(repoRoot: string): Promise<void> {\n const home = this.mergeState.mergeDirFor(repoRoot, await this.aiBranchName.getFeatureName());\n const active = this.mergeState.findActiveMergeRunDir(home);\n const marker = active === null ? null : this.mergeState.readMergeMarker(active);\n if (marker === null || marker.validated) return;\n throw new CliExitError(\n 1,\n 'wp-human-post-pr refuses an active, unvalidated 3-point merge. Resolve it and run the supported ' +\n 'Webpieces finish/update flow before posting.',\n );\n }\n\n protected fetchMain(repoRoot: string): Promise<void> {\n return this.gitExec.runGitChecked(\n ['fetch', 'origin', 'main'],\n 'Could not refresh origin/main; wp-human-post-pr will not evaluate or publish against a stale ref',\n );\n }\n\n protected gateSalt(repoRoot: string): string {\n return loadAndValidate(repoRoot).prGate.gateSalt;\n }\n\n private async ensureSummary(summaryPath: string, forkPoint: string): Promise<void> {\n if (fs.existsSync(summaryPath)) return;\n process.stdout.write(\n '\\nCopy/paste the following instruction into AI:\\n\\n' +\n `Write ONLY ${summaryPath}.\\n` +\n 'Do not run pnpm wp-review-upsert-pr, pnpm wp-finish-upsert-pr, push, or create/update a PR.\\n' +\n `Summarize exactly: git diff ${forkPoint} HEAD\\n` +\n `Changed files: git diff --name-only ${forkPoint} HEAD\\n\\n` +\n this.reviewJsonService.summaryJsonSchemaHint(summaryPath) +\n '\\n\\n',\n );\n const answer = (\n await this.question(\n \"I don't see summary.json and we at least need that to short circuit pushing.\\n\" +\n 'Please paste the instructions above into AI. When it is done generating summary.json, continue? (Y/N)\\n',\n )\n )\n .trim()\n .toLowerCase();\n if (answer !== 'y' && answer !== 'yes') {\n throw new CliExitError(\n 1,\n 'No PR was pushed or edited. Rerun pnpm wp-human-post-pr when summary.json is ready.',\n );\n }\n }\n\n private assertCurrentMain(status: MainSyncStatus): void {\n if (!status.hasForkPoint || status.forkPoint === null) {\n throw new CliExitError(\n 1,\n 'Could not establish a pure-main fork point. Use the Webpieces update process; do not merge or rebase manually.',\n );\n }\n if (status.forkPoint === status.originMain) return;\n const conflicts =\n status.conflictFiles.length === 0\n ? 'Conflicts: (none predicted)'\n : 'Conflicts (files changed on both sides; conservative prediction):\\n' +\n status.conflictFiles.map((file: string): string => ` - ${file}`).join('\\n');\n const update =\n status.openPr === ''\n ? ' pnpm wp-start-update\\n # if conflicts are reported, resolve them, then:\\n pnpm wp-finish-update'\n : ' pnpm wp-start-upsert-pr\\n pnpm wp-review-upsert-pr\\n pnpm wp-finish-upsert-pr';\n throw new CliExitError(\n 1,\n 'Your branch is behind origin/main.\\n\\n' +\n 'Ask AI to run the Webpieces update process, then rerun pnpm wp-human-post-pr.\\n' +\n 'This is usually very quick unless you have conflicts.\\n\\n' +\n update +\n '\\n\\n' +\n conflicts,\n );\n }\n\n private renderBody(\n summary: PrSummary,\n prUrl: string,\n gateSalt: string,\n headSha: string,\n buildRan: boolean,\n ): string {\n const lines: string[] = [];\n if (prUrl !== '') lines.push(prUrl, '');\n lines.push(`Risk: ${summary.riskScore}/100 ${summary.riskEmoji} (${summary.riskLevel})`);\n lines.push(`Summary authored by ${summary.agent} (${summary.model})`);\n lines.push('');\n lines.push(\n buildRan\n ? 'Flags: ⚠️ HUMAN ESCAPE HATCH — local wp-build passed; automated reviewer stages were explicitly skipped.'\n : 'Flags: ⚠️ HUMAN ESCAPE HATCH — local build and automated reviewer stages were explicitly skipped; cloud CI will run.',\n );\n const issues = new IssueReferences();\n const text = issues.withoutBlockLines(summary.summary.trim(), summary.addressesIssues);\n if (text !== '') lines.push('', text);\n // The same `Fixes <url>` / `Part of <url>` block wp-finish-upsert-pr renders (issue #1310).\n const ticketLines = issues.blockLines(summary.addressesIssues);\n if (ticketLines.length > 0) lines.push('', ...ticketLines);\n lines.push(\n '',\n `Generated by webpieces-ts wp-human-post-pr (human-attested; ${buildRan ? 'local wp-build passed, automated review skipped' : 'local build/review skipped'})`,\n );\n const marker = this.gateTokenService.gateTokenMarker(gateSalt, headSha);\n if (marker !== '') lines.push('', marker);\n const body = lines.join('\\n').replace(/\\|/g, '\\u00a6').replace(/#{2,}/g, '#');\n issues.assertNoStrayClosingReferences(body, summary.addressesIssues, RETRY_COMMAND);\n return body;\n }\n\n private titleFrom(summary: PrSummary, branch: string): string {\n return summary.title === '' ? branch.replace(/[-/]+/g, ' ').trim() : summary.title;\n }\n\n protected async resolvePr(branch: string): Promise<HumanPostedPr> {\n const result = await this.processes.run(\n 'gh',\n ['pr', 'view', branch, '--json', 'number,url', '--jq', '\"\\\\(.number)\\\\t\\\\(.url)\"'],\n );\n if (!result.ok) return new HumanPostedPr('', '');\n const parts = result.stdout.trim().split('\\t');\n return new HumanPostedPr(parts[0] ?? '', parts[1] ?? '');\n }\n\n protected async backfillBody(prNumber: string, bodyFile: string, body: string): Promise<void> {\n fs.writeFileSync(bodyFile, body + '\\n');\n if (await this.editPrBody(prNumber, bodyFile) !== 0) {\n throw new CliExitError(\n 1,\n `Could not update PR #${prNumber} with its final human-bypass body. The validated body remains at ${bodyFile}. ` +\n `Fix GitHub access, then re-run ${RETRY_COMMAND}; summary.json was not consumed.`,\n );\n }\n }\n\n protected async editPrBody(prNumber: string, bodyFile: string): Promise<number> {\n return (await this.processes.passThrough('gh', ['pr', 'edit', prNumber, '--body-file', bodyFile])).code;\n }\n\n protected git(args: string[], cwd: string, failure: string): Promise<string> {\n return this.gitExec.gitQuery(args, cwd, failure);\n }\n\n // Seam: overridden in specs. EOF resolves to '' and therefore fails closed.\n protected question(prompt: string): Promise<string> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n return new Promise<string>((resolve: (value: string) => void): void => {\n let answered = false;\n rl.question(prompt, (answer: string): void => {\n answered = true;\n rl.close();\n resolve(answer);\n });\n rl.on('close', (): void => {\n if (!answered) resolve('');\n });\n });\n }\n}\n"]}