@webpieces/pr-gate 0.4.815 → 0.4.817
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 +3 -3
- package/src/dashboard/author-identity.d.ts +2 -2
- package/src/dashboard/author-identity.js +2 -2
- package/src/dashboard/author-identity.js.map +1 -1
- package/src/dashboard/dashboard.d.ts +5 -5
- package/src/dashboard/dashboard.js +4 -4
- package/src/dashboard/dashboard.js.map +1 -1
- package/src/dashboard/review-identity-renderer.d.ts +1 -1
- package/src/dashboard/review-identity-renderer.js +1 -1
- package/src/dashboard/review-identity-renderer.js.map +1 -1
- package/src/scripts/commands/await-reviews-command.d.ts +2 -2
- package/src/scripts/commands/await-reviews-command.js +6 -6
- package/src/scripts/commands/await-reviews-command.js.map +1 -1
- package/src/scripts/commands/check-pr-command.js +1 -1
- package/src/scripts/commands/check-pr-command.js.map +1 -1
- package/src/scripts/commands/finish-upsert-pr-command.d.ts +4 -4
- package/src/scripts/commands/finish-upsert-pr-command.js +18 -18
- package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/land-pr-command.d.ts +3 -3
- package/src/scripts/commands/land-pr-command.js +6 -6
- package/src/scripts/commands/land-pr-command.js.map +1 -1
- package/src/scripts/commands/review-upsert-pr-command.d.ts +2 -2
- package/src/scripts/commands/review-upsert-pr-command.js +5 -5
- package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/start-update-command.js +1 -1
- package/src/scripts/commands/start-update-command.js.map +1 -1
- package/src/scripts/commands/start-upsert-pr-command.d.ts +3 -3
- package/src/scripts/commands/start-upsert-pr-command.js +7 -7
- package/src/scripts/commands/start-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/write-review-command.js +1 -1
- package/src/scripts/commands/write-review-command.js.map +1 -1
- package/src/scripts/pr-gate-app.d.ts +1 -1
- package/src/scripts/pr-gate-app.js +1 -1
- package/src/scripts/pr-gate-app.js.map +1 -1
- package/src/scripts/workflow/checklist-detector.js +1 -1
- package/src/scripts/workflow/checklist-detector.js.map +1 -1
- package/src/scripts/workflow/checklist-notice.d.ts +1 -1
- package/src/scripts/workflow/checklist-notice.js +1 -1
- package/src/scripts/workflow/checklist-notice.js.map +1 -1
- package/src/scripts/workflow/checklist-scanner.d.ts +2 -2
- package/src/scripts/workflow/checklist-scanner.js +11 -11
- package/src/scripts/workflow/checklist-scanner.js.map +1 -1
- package/src/scripts/workflow/gated-pr-publisher.d.ts +1 -1
- package/src/scripts/workflow/gated-pr-publisher.js +1 -1
- package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
- package/src/scripts/workflow/merge-end.d.ts +1 -1
- package/src/scripts/workflow/merge-end.js +2 -2
- package/src/scripts/workflow/merge-end.js.map +1 -1
- package/src/scripts/workflow/open-pr-check.js +1 -1
- package/src/scripts/workflow/open-pr-check.js.map +1 -1
- package/src/scripts/workflow/provenance-enforcer.d.ts +2 -2
- package/src/scripts/workflow/provenance-enforcer.js +6 -6
- package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
- package/src/scripts/workflow/review-report.d.ts +9 -9
- package/src/scripts/workflow/review-report.js +19 -19
- package/src/scripts/workflow/review-report.js.map +1 -1
- package/src/scripts/workflow/review-stage-receipt.d.ts +3 -3
- package/src/scripts/workflow/review-stage-receipt.js +3 -3
- package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
- package/src/scripts/workflow/reviewer-briefing-builder.js +1 -1
- package/src/scripts/workflow/reviewer-briefing-builder.js.map +1 -1
- package/src/scripts/workflow/reviewer-verdict-gate.d.ts +1 -1
- package/src/scripts/workflow/reviewer-verdict-gate.js +6 -6
- package/src/scripts/workflow/reviewer-verdict-gate.js.map +1 -1
- package/src/scripts/workflow/verdict-provenance.d.ts +4 -4
- package/src/scripts/workflow/verdict-provenance.js +10 -10
- package/src/scripts/workflow/verdict-provenance.js.map +1 -1
- package/src/scripts/wp-start-upsert-pr.js +1 -1
- package/src/scripts/wp-start-upsert-pr.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gated-pr-publisher.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gated-pr-publisher.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuD;AACvD,yCAA2D;AAC3D,yCAAqC;AAErC,gDAAgD;AAChD,MAAa,WAAW;IACpB,kFAAkF;IAClF,MAAM,CAAS;IACf,6FAA6F;IAC7F,YAAY,CAAU;IAEtB,YAAY,MAAc,EAAE,YAAqB;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,kCAUC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IACI;IAA7B,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IAEjD;;;;OAIG;IACH,OAAO,CAAC,UAAkB,EAAE,KAAa,EAAE,QAAgB;QACvD,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QAE7C,oGAAoG;QACpG,IAAI,QAAQ,KAAK,EAAE,EAAE,CAAC;YAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,QAAQ,2DAA2D,CAAC,CAAC;YAC1G,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;YAC9C,4FAA4F;YAC5F,gGAAgG;YAChG,gGAAgG;YAChG,OAAO,CAAC,MAAM,CAAC,KAAK,CAChB,6FAA6F;gBAC7F,2FAA2F;gBAC3F,kEAAkE,CACrE,CAAC;QACN,CAAC;QAED,+FAA+F;QAC/F,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAEtB,oGAAoG;QACpG,IAAI,QAAQ,KAAK,EAAE;YAAE,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,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;IACnI,CAAC;IAES,QAAQ,CAAC,UAAkB,EAAE,KAAa,EAAE,QAAgB;QAClE,OAAO,IAAA,yBAAS,EAAC,IAAI,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;IACnK,CAAC;IAED,mGAAmG;IACnG,oGAAoG;IAC1F,IAAI,CAAC,UAAkB;QAC7B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;IAC1C,CAAC;CACJ,CAAA;AAnEY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEC,kBAAO;GADpC,gBAAgB,CAmE5B","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitExec } from './git-exec';\n\n// Which PR the gated body landed on. Data-only.\nexport class PublishedPr {\n // The PR that already existed and was edited; '' when this run had to create one.\n number: string;\n // True only on the create path, when `gh pr create` itself failed — there is no PR to merge.\n createFailed: boolean;\n\n constructor(number: string, createFailed: boolean) {\n this.number = number;\n this.createFailed = createFailed;\n }\n}\n\n/**\n * Owns the ONE ordering constraint that lets the webpieces gate be a single required check: the PR body\n * — which carries `HMAC(gateSalt, HEAD_sha)` — is written BEFORE the push.\n *\n * WHY the order matters. Pushing first fires `pull_request:synchronize`, and CI (`wp-check-pr`) reads the\n * PR body it finds at that instant. If the body edit has not landed yet, that read sees the PREVIOUS\n * run's token, which is bound to the parent sha, and the check goes red on a timing coin-flip. #485\n * papered over this by also posting a `webpieces/pr-gate` commit status, whose newest post supersedes an\n * older one — recovery rather than prevention, and it left consumers with two entries on every PR and no\n * way to tell which one to mark required.\n *\n * The sha is already known locally: nothing about minting `HMAC(gateSalt, git rev-parse HEAD)` needs the\n * remote to have the commit. So write the body first and the `synchronize` read can only ever see the\n * right token. A brand-new PR is unaffected either way — `gh pr create` composes the body after the push,\n * so the `opened` event already sees the final body.\n *\n * THIS IS THE ONLY PUSH IN THE PR FLOW. `wp-start-upsert-pr` used to push twice (its own `ensurePushed`,\n * and the force-push inside the 3-point merge finalize), which put code on the remote before
|
|
1
|
+
{"version":3,"file":"gated-pr-publisher.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gated-pr-publisher.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuD;AACvD,yCAA2D;AAC3D,yCAAqC;AAErC,gDAAgD;AAChD,MAAa,WAAW;IACpB,kFAAkF;IAClF,MAAM,CAAS;IACf,6FAA6F;IAC7F,YAAY,CAAU;IAEtB,YAAY,MAAc,EAAE,YAAqB;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,kCAUC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IACI;IAA7B,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IAEjD;;;;OAIG;IACH,OAAO,CAAC,UAAkB,EAAE,KAAa,EAAE,QAAgB;QACvD,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QAE7C,oGAAoG;QACpG,IAAI,QAAQ,KAAK,EAAE,EAAE,CAAC;YAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,QAAQ,2DAA2D,CAAC,CAAC;YAC1G,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC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EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnE,CAAC;IAES,MAAM,CAAC,QAAgB,EAAE,KAAa,EAAE,QAAgB;QAC9D,OAAO,IAAA,yBAAS,EAAC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;IACnI,CAAC;IAES,QAAQ,CAAC,UAAkB,EAAE,KAAa,EAAE,QAAgB;QAClE,OAAO,IAAA,yBAAS,EAAC,IAAI,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;IACnK,CAAC;IAED,mGAAmG;IACnG,oGAAoG;IAC1F,IAAI,CAAC,UAAkB;QAC7B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;IAC1C,CAAC;CACJ,CAAA;AAnEY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEC,kBAAO;GADpC,gBAAgB,CAmE5B","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitExec } from './git-exec';\n\n// Which PR the gated body landed on. Data-only.\nexport class PublishedPr {\n // The PR that already existed and was edited; '' when this run had to create one.\n number: string;\n // True only on the create path, when `gh pr create` itself failed — there is no PR to merge.\n createFailed: boolean;\n\n constructor(number: string, createFailed: boolean) {\n this.number = number;\n this.createFailed = createFailed;\n }\n}\n\n/**\n * Owns the ONE ordering constraint that lets the webpieces gate be a single required check: the PR body\n * — which carries `HMAC(gateSalt, HEAD_sha)` — is written BEFORE the push.\n *\n * WHY the order matters. Pushing first fires `pull_request:synchronize`, and CI (`wp-check-pr`) reads the\n * PR body it finds at that instant. If the body edit has not landed yet, that read sees the PREVIOUS\n * run's token, which is bound to the parent sha, and the check goes red on a timing coin-flip. #485\n * papered over this by also posting a `webpieces/pr-gate` commit status, whose newest post supersedes an\n * older one — recovery rather than prevention, and it left consumers with two entries on every PR and no\n * way to tell which one to mark required.\n *\n * The sha is already known locally: nothing about minting `HMAC(gateSalt, git rev-parse HEAD)` needs the\n * remote to have the commit. So write the body first and the `synchronize` read can only ever see the\n * right token. A brand-new PR is unaffected either way — `gh pr create` composes the body after the push,\n * so the `opened` event already sees the final body.\n *\n * THIS IS THE ONLY PUSH IN THE PR FLOW. `wp-start-upsert-pr` used to push twice (its own `ensurePushed`,\n * and the force-push inside the 3-point merge finalize), which put code on the remote before summary.json\n * and the checklists had even run, and fired `synchronize` against a PR body still carrying the previous\n * run's token. Both are gone — the merge finalize now takes `MergeEndOptions.pushRemote=false` in the PR\n * flow. So the single `synchronize` of a cycle arrives strictly after the body edit below, and can only\n * ever read the correct token.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GatedPrPublisher {\n constructor(private readonly gitExec: GitExec) {}\n\n /**\n * Land `bodyFile` on the PR for `baseBranch` and push, in the gate-safe order.\n *\n * @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha\n */\n publish(baseBranch: string, title: string, bodyFile: string): PublishedPr {\n const existing = this.findOpenPr(baseBranch);\n\n // 1. Body FIRST, so a `synchronize` read arriving the instant after the push finds the right token.\n if (existing !== '') {\n process.stdout.write(`Updating PR #${existing} (body before push, so CI cannot read a stale token)...\\n`);\n this.editPrOrAbort(existing, title, bodyFile);\n // Say the consequence BEFORE the push can fail: from here the PR advertises a token for the\n // local HEAD, so a failed push leaves the PR pointing at the old commit and the gate check goes\n // RED. That is the deliberate fail-CLOSED direction, and it self-corrects on the next good run.\n process.stdout.write(\n ' body updated. Pushing now — if this push FAILS, the PR advertises a token for a commit\\n' +\n ' the remote does not have, so the webpieces gate check goes RED (never falsely green)\\n' +\n ' until you fix the push and re-run pnpm wp-finish-upsert-pr.\\n',\n );\n }\n\n // 2. THEN push. Nothing was pushed above, so an edit failure left the remote wholly untouched.\n this.push(baseBranch);\n\n // 3. Only a brand-new PR is created, and only after the push — `gh pr create` needs the remote ref.\n if (existing !== '') return new PublishedPr(existing, false);\n process.stdout.write('Creating PR...\\n');\n return new PublishedPr('', !this.createPr(baseBranch, title, bodyFile));\n }\n\n // Edit the PR body/title, aborting BEFORE the push if `gh` failed. Warning-and-continuing here would\n // push code that the PR body does not vouch for; aborting leaves the PR on its previous body, whose\n // token is still valid for the sha the remote still has. Nothing is half-done either way.\n private editPrOrAbort(prNumber: string, title: string, bodyFile: string): void {\n if (this.editPr(prNumber, title, bodyFile)) return;\n throw new CliExitError(1,\n `❌ gh pr edit failed on PR #${prNumber} — NOTHING was pushed, so the PR and the remote branch are\\n` +\n ` both unchanged and still consistent. Fix gh (auth / network / permissions) and re-run\\n` +\n ` pnpm wp-finish-upsert-pr. The new body is in:\\n ${bodyFile}`);\n }\n\n // The `gh`/push seams, protected so the spec can drive the ordering with no gh, no network, no repo.\n\n // The open PR whose head is `baseBranch`, or '' when there is none (or `gh` failed — treated the same,\n // so the create path then fails loudly rather than silently editing the wrong PR).\n protected findOpenPr(baseBranch: string): string {\n const result = spawnSync('gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n protected editPr(prNumber: string, title: string, bodyFile: string): boolean {\n return spawnSync('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile], { stdio: 'inherit' }).status === 0;\n }\n\n protected createPr(baseBranch: string, title: string, bodyFile: string): boolean {\n return spawnSync('gh', ['pr', 'create', '--head', baseBranch, '--base', 'main', '--title', title, '--body-file', bodyFile], { stdio: 'inherit' }).status === 0;\n }\n\n // Throws (CliExitError, via runGitChecked) when the push fails — deliberately NOT caught here: the\n // consequence is already printed above, and swallowing it would report a PR that was never updated.\n protected push(baseBranch: string): void {\n this.gitExec.ensurePushed(baseBranch);\n }\n}\n"]}
|
|
@@ -10,7 +10,7 @@ export declare class MergeEndOptions {
|
|
|
10
10
|
* Whether finalizing may push the squashed branch to origin.
|
|
11
11
|
*
|
|
12
12
|
* FALSE for the PR flow (`wp-start-upsert-pr` / `wp-finish-upsert-pr`), which pushes EXACTLY ONCE,
|
|
13
|
-
* from GatedPrPublisher, after
|
|
13
|
+
* from GatedPrPublisher, after summary.json + every BLOCK checklist + the authoritative build gate
|
|
14
14
|
* have passed and the gated PR body is already up. Code must not reach the remote ahead of its
|
|
15
15
|
* review, and an early push here is also what fires `pull_request:synchronize` against a PR body
|
|
16
16
|
* still carrying the previous run's gate token — the flap the whole gate redesign is removing.
|
|
@@ -36,7 +36,7 @@ class MergeEndOptions {
|
|
|
36
36
|
* Whether finalizing may push the squashed branch to origin.
|
|
37
37
|
*
|
|
38
38
|
* FALSE for the PR flow (`wp-start-upsert-pr` / `wp-finish-upsert-pr`), which pushes EXACTLY ONCE,
|
|
39
|
-
* from GatedPrPublisher, after
|
|
39
|
+
* from GatedPrPublisher, after summary.json + every BLOCK checklist + the authoritative build gate
|
|
40
40
|
* have passed and the gated PR body is already up. Code must not reach the remote ahead of its
|
|
41
41
|
* review, and an early push here is also what fires `pull_request:synchronize` against a PR body
|
|
42
42
|
* still carrying the previous run's gate token — the flap the whole gate redesign is removing.
|
|
@@ -178,7 +178,7 @@ let MergeEnd = class MergeEnd {
|
|
|
178
178
|
// Say WHY nothing was pushed, so an unpushed branch never looks like a failure. Always returns false
|
|
179
179
|
// (nothing was pushed), which also keeps the pre-merge snapshot alive — see the backupKept comment.
|
|
180
180
|
explainNoPush() {
|
|
181
|
-
process.stdout.write('Not pushing — the PR flow pushes exactly ONCE, from pnpm wp-finish-upsert-pr, after
|
|
181
|
+
process.stdout.write('Not pushing — the PR flow pushes exactly ONCE, from pnpm wp-finish-upsert-pr, after summary.json\n' +
|
|
182
182
|
'and the build gate pass and the gated PR body is written. Your work stays local until then\n' +
|
|
183
183
|
'(the pre-merge snapshot below is kept as well, so nothing is only in one place).\n');
|
|
184
184
|
return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merge-end.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-end.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAGiC;AACjC,yCAA2D;AAC3D,mDAA+C;AAC/C,yCAAsC;AACtC,yCAAqC;AAErC,+CAA2C;AAE3C,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,sGAAsG;AACtG,kGAAkG;AAClG,MAAM,SAAS;IACX,MAAM,CAAU;IAChB,YAAY,CAAU;IACtB,WAAW,CAAU;IACrB,UAAU,CAAU;IAEpB,YAAY,MAAe,EAAE,YAAqB,EAAE,WAAoB,EAAE,UAAmB;QACzF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAED,qGAAqG;AACrG,yEAAyE;AACzE,MAAa,eAAe;IACxB,oGAAoG;IACpG,4EAA4E;IAC5E,eAAe,CAAkB;IAEjC;;;;;;;;;;;OAWG;IACH,UAAU,CAAU;IAEpB,YAAY,eAAgC,EAAE,UAAmB;QAC7D,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAvBD,0CAuBC;AAED,s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AAE,YAAoB,EAAE,QAAgB,EAAE,KAAgB;QAC5F,MAAM,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACpC,MAAM,UAAU,GAAG,IAAI,CAAC,eAAe,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QAClE,MAAM,UAAU,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,gDAAgD,CAAC;QACrH,MAAM,KAAK,GAAG,UAAU;YACpB,CAAC,CAAC,sCAAsC,YAAY,YAAY,UAAU,GAAG;YAC7E,CAAC,CAAC,sCAAsC,YAAY,+CAA+C,CAAC;QACxG,MAAM,OAAO,GAAG,UAAU;YACtB,CAAC,CAAC,oDAAoD,OAAO,cAAc;gBACzE,gGAAgG;gBAChG,0DAA0D,YAAY,MAAM;YAC9E,CAAC,CAAC,IAAI,CAAC;QACX,OAAO,CAAC,MAAM,CAAC,KAAK,CAChB,IAAI,GAAG,GAAG,GAAG,gDAAgD,GAAG,GAAG,GAAG,IAAI;YAC1E,SAAS,KAAK,IAAI;YAClB,4BAA4B;YAC5B,2CAA2C;YAC3C,SAAS,UAAU,MAAM;YACzB,OAAO,CACV,CAAC;IACN,CAAC;CACJ,CAAA;AAtMY,4BAAQ;mBAAR,QAAQ;IADpB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGF,4BAAY;QACT,mBAAQ;QAChB,kBAAO;QACJ,wBAAU;GALlC,QAAQ,CAsMpB","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n MERGE_EXPLANATION_FILE, stampCleanMainSyncStatus, CliExitError,\n MutationVerb, BranchMutationEvent, logBranchMutation,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BranchNaming } from './branch-naming';\nimport { CleanTmp } from './cleanTmp';\nimport { GitExec } from './git-exec';\nimport { MergeContext } from './merge-start';\nimport { MergeState } from './merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n// What finalizing actually did, for the recap. Data-only. `pushed` and `pushDeferred` are distinct on\n// purpose: \"we chose not to push yet\" must not be reported like \"there was no remote to push to\".\nclass SyncRecap {\n pushed: boolean;\n pushDeferred: boolean;\n hadConflict: boolean;\n backupKept: boolean;\n\n constructor(pushed: boolean, pushDeferred: boolean, hadConflict: boolean, backupKept: boolean) {\n this.pushed = pushed;\n this.pushDeferred = pushDeferred;\n this.hadConflict = hadConflict;\n this.backupKept = backupKept;\n }\n}\n\n// How a merge should be finalized. Data-only (per CLAUDE.md, classes for data) — bundled rather than\n// added as more positional params, which mergeEnd already has enough of.\nexport class MergeEndOptions {\n // Non-null means the AI resolved a conflict and it must be validated + committed before finalizing.\n // Null means merge-START already committed a clean merge, so finalize only.\n conflictedFiles: string[] | null;\n\n /**\n * Whether finalizing may push the squashed branch to origin.\n *\n * FALSE for the PR flow (`wp-start-upsert-pr` / `wp-finish-upsert-pr`), which pushes EXACTLY ONCE,\n * from GatedPrPublisher, after review.json + every BLOCK checklist + the authoritative build gate\n * have passed and the gated PR body is already up. Code must not reach the remote ahead of its\n * review, and an early push here is also what fires `pull_request:synchronize` against a PR body\n * still carrying the previous run's gate token — the flap the whole gate redesign is removing.\n *\n * TRUE for the update-only flow (`wp-start-update` / `wp-finish-update`), which has no later push;\n * finalizing IS the end of that flow, so not pushing would silently strand the rewrite locally.\n */\n pushRemote: boolean;\n\n constructor(conflictedFiles: string[] | null, pushRemote: boolean) {\n this.conflictedFiles = conflictedFiles;\n this.pushRemote = pushRemote;\n }\n}\n\n// merge-END: the second half of the 3-point squash-merge lifecycle, symmetric with merge-START. Given\n// the branch context, it (optionally) validates + commits the AI's conflict resolution, then ALWAYS\n// finalizes — force-pushes `<branch>Squash` to the stable feature branch and renames it BACK to that\n// same feature name (local == remote == PR head), stamps a clean main-sync status, clears the marker,\n// and sweeps stale tmp. RunUpdate (clean path / validated resume), wp-finish-update, and\n// wp-finish-upsert-pr (conflict resolution) all call THIS, so finalization happens in exactly one place.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeEnd {\n constructor(\n private readonly branchNaming: BranchNaming,\n private readonly cleanTmpService: CleanTmp,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n ) {}\n\n /**\n * Complete a 3-point squash merge. See {@link MergeEndOptions} for what `conflictedFiles` and\n * `pushRemote` mean. Either way the merge ends fully finalized on the feature branch.\n */\n async mergeEnd(\n repoRoot: string, verb: MutationVerb, mergeDir: string, ctx: MergeContext, options: MergeEndOptions,\n ): Promise<void> {\n const conflictedFiles = options.conflictedFiles;\n if (conflictedFiles !== null) {\n process.stdout.write('\\n' + SEP + '🔎 Validating Merge Resolution\\n' + SEP + '\\n');\n this.validateResolution(repoRoot, verb, mergeDir, conflictedFiles);\n // Stage the AI's resolved conflicts, but NEVER sweep untracked files into the squash commit.\n // Fail on untracked so the AI commits or deletes them explicitly; then `git add -u` stages\n // tracked resolutions only.\n this.gitExec.assertNoUntracked(repoRoot);\n this.gitExec.runGitChecked(['add', '-u'], 'Failed to stage resolved files');\n\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (!nothingStaged) {\n this.gitExec.runGitChecked(\n ['commit', '-m', `Squash merge of ${ctx.currentBranch} (conflicts resolved)`],\n 'Failed to commit resolved merge',\n );\n }\n fs.writeFileSync(path.join(mergeDir, 'conflicts-resolved'), '');\n process.stdout.write('\\n✅ Merge validated and committed.\\n');\n }\n\n // A marker in THIS run dir means the sync hit conflicts (marker is written only on hand-back).\n // Read it BEFORE clearMergeMarker so finalize knows whether to keep the pre-merge snapshot.\n const hadConflict = this.mergeState.readMergeMarker(mergeDir) !== null;\n this.finalizeBranch(repoRoot, verb, ctx, hadConflict, options.pushRemote);\n this.mergeState.clearMergeMarker(mergeDir);\n await this.cleanTmpService.cleanTmp();\n }\n\n // Validate the AI's resolution of the conflicted files. Throws CliExitError with a fix instruction\n // on any failure; returns only when all three checks pass.\n // `verb` is the bin the AI actually ran (wp-finish-update or wp-finish-upsert-pr) — every \"re-run\"\n // instruction below is rendered from it. It used to be hardcoded to wp-finish-upsert-pr, which told\n // someone in the update-only flow to finish with the PR command: a pairing that does not exist.\n private validateResolution(repoRoot: string, verb: MutationVerb, mergeDir: string, conflictedFiles: string[]): void {\n const reRun = `pnpm ${verb}`;\n // 1. Scoped conflict-marker scan (only the conflicted files — O(conflicts), not O(repo)).\n const scan = this.mergeState.scanConflictMarkers(repoRoot, conflictedFiles);\n if (!scan.clean) {\n throw new CliExitError(1,\n '❌ Unresolved conflict markers (<<<<<<< / ======= / >>>>>>>) remain in:\\n' +\n scan.filesWithMarkers.map((file: string): string => ` - ${file}`).join('\\n') +\n `\\n\\nResolve them, then re-run: ${reRun}`,\n );\n }\n\n // 2. Ensure git itself has no remaining unmerged entries.\n const unmerged = execSync('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();\n if (unmerged !== '') {\n throw new CliExitError(1,\n '❌ Git still reports unmerged files:\\n' + unmerged +\n '\\n\\nResolve and `git add` them, then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ No conflict markers in resolved files.\\n');\n\n // 3. Explanation check — every conflicted file must have a non-empty merge-explanation.md in its\n // per-file context dir, proving the AI deliberately 3-point merged it (and recording how).\n const explanations = this.mergeState.scanMergeExplanations(mergeDir, conflictedFiles);\n if (!explanations.clean) {\n const missing = explanations.filesWithMarkers\n .map((file: string): string => ` - ${file}\\n → ${path.join(this.mergeState.perFileContextDir(mergeDir, file), MERGE_EXPLANATION_FILE)}`)\n .join('\\n');\n throw new CliExitError(1,\n `❌ Missing/empty merge explanation (${MERGE_EXPLANATION_FILE}) for:\\n` +\n missing +\n '\\n\\nWrite a few sentences on how you resolved each (which side, what you combined, why),\\n' +\n 'then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ Merge explanations present for all resolved files.\\n');\n }\n\n // Seam: overridden in the spec so the push/backup decisions are testable with no git and no repo.\n protected localBranchExists(name: string): boolean {\n return spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;\n }\n\n // Force-push the squash branch to the stable feature branch (where the single PR lives) — unless the\n // caller owns the push (see MergeEndOptions.pushRemote) — then RENAME the local squash branch back to\n // that SAME feature name. On a CLEAN sync the pre-merge snapshot is disposable, so it's deleted at the\n // very end; a CONFLICT sync — or a sync we did not push — keeps it.\n // eslint-disable-next-line @typescript-eslint/max-params\n private finalizeBranch(repoRoot: string, verb: MutationVerb, ctx: MergeContext, hadConflict: boolean, pushRemote: boolean): void {\n process.stdout.write('\\n' + SEP + '🗑️ Finalizing\\n' + SEP + '\\n');\n const base = this.branchNaming.baseBranchName(ctx.currentBranch);\n this.gitExec.runGitChecked(['branch', '-D', ctx.currentBranch], 'Failed to delete old feature branch');\n\n const pushed = pushRemote ? this.pushFinalized(ctx, base) : this.explainNoPush();\n this.gitExec.runGitChecked(['checkout', ctx.squashBranch], 'Failed to checkout squash branch');\n // Free the rename target: `base` is normally the branch we just deleted, but a backward-compat\n // sync from a leftover `…wpN` can leave a separate stale `base` lingering — drop it too.\n if (base !== ctx.currentBranch && this.localBranchExists(base)) {\n this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');\n }\n this.gitExec.runGitChecked(['branch', '-m', base], 'Failed to rename squash branch to the feature name');\n const renameEvent = new BranchMutationEvent(verb, 'RENAME');\n renameEvent.fromBranch = ctx.currentBranch;\n renameEvent.toBranch = base;\n logBranchMutation(repoRoot, renameEvent);\n\n // Branch now contains origin/main — stamp a clean main-sync status so the feature-branch-guard\n // unblocks edits immediately (no wait for the async refresher).\n stampCleanMainSyncStatus(repoRoot);\n\n // Clean sync → the pre-merge snapshot was never needed; delete it LAST. Conflict sync → keep it.\n // ALSO keep it when we did not push: the squash rewrite then exists ONLY in this working copy, so\n // deleting the snapshot would leave a history rewrite with no copy anywhere. It is disposable only\n // once origin has the result, and in the PR flow that does not happen until wp-finish-upsert-pr.\n const backupKept = hadConflict || !pushed;\n if (!backupKept && this.localBranchExists(ctx.backupBranch)) {\n this.gitExec.runGitChecked(['branch', '-D', ctx.backupBranch], 'Failed to delete clean-merge backup');\n }\n\n const finalizeEvent = new BranchMutationEvent(verb, 'FINALIZE');\n finalizeEvent.fromBranch = ctx.currentBranch;\n finalizeEvent.toBranch = base;\n finalizeEvent.outcome = 'finalized';\n finalizeEvent.artifacts = [backupKept ? `backup=${ctx.backupBranch}` : `backupDeleted=${ctx.backupBranch}`, `remotePR=${base}`];\n logBranchMutation(repoRoot, finalizeEvent);\n\n this.printSyncRecap(base, ctx.backupBranch, ctx.prNumber, new SyncRecap(pushed, !pushRemote, hadConflict, backupKept));\n }\n\n // Say WHY nothing was pushed, so an unpushed branch never looks like a failure. Always returns false\n // (nothing was pushed), which also keeps the pre-merge snapshot alive — see the backupKept comment.\n private explainNoPush(): boolean {\n process.stdout.write(\n 'Not pushing — the PR flow pushes exactly ONCE, from pnpm wp-finish-upsert-pr, after review.json\\n' +\n 'and the build gate pass and the gated PR body is written. Your work stays local until then\\n' +\n '(the pre-merge snapshot below is kept as well, so nothing is only in one place).\\n',\n );\n return false;\n }\n\n // Push the finalized squash branch to the stable feature branch. Returns whether a push actually\n // happened — false when there is no remote branch yet (a brand-new branch is local until something\n // creates it, which in the PR flow is `gh pr create` after GatedPrPublisher's push).\n protected pushFinalized(ctx: MergeContext, base: string): boolean {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', base]).status === 0;\n if (!remoteExists) {\n process.stdout.write('No remote branch — local only.\\n');\n return false;\n }\n process.stdout.write(ctx.prNumber ? `Updating PR #${ctx.prNumber} (force-with-lease)...\\n` : 'Updating remote branch (force-with-lease)...\\n');\n this.gitExec.runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${ctx.squashBranch}:${base}`], 'Failed to push to origin');\n return true;\n }\n\n // Where the branch ended up, in the recap's own words. Three distinct outcomes, and \"deferred\" must\n // never read like the failure the other two could be mistaken for.\n private remoteRecapLine(feature: string, prNumber: string, recap: SyncRecap): string {\n if (recap.pushed) {\n return `landed back on ${feature} (== origin/${feature}${prNumber ? ` == PR #${prNumber}` : ''} — names match)`;\n }\n if (recap.pushDeferred) {\n return `landed back on ${feature} (local — by design; pnpm wp-finish-upsert-pr does the one push)`;\n }\n return `landed back on ${feature} (local only — no remote branch yet)`;\n }\n\n // The explicit, numbered \"here is exactly what I did\" recap the AI (and human) reads after a sync.\n private printSyncRecap(feature: string, backupBranch: string, prNumber: string, recap: SyncRecap): void {\n const backupKept = recap.backupKept;\n const remoteLine = this.remoteRecapLine(feature, prNumber, recap);\n const keptReason = recap.hadConflict ? 'this merge had conflicts' : 'not pushed yet — wp-finish-upsert-pr will push';\n const step1 = backupKept\n ? `snapshotted your pre-merge state → ${backupBranch} (kept — ${keptReason})`\n : `snapshotted your pre-merge state → ${backupBranch} (auto-removed — clean merge, no undo needed)`;\n const trailer = backupKept\n ? ` Pre-merge snapshot trail: git branch --list '${feature}PreMerge*'\\n` +\n ` Its conflict context lives in the paired merge-<n>/ folder under .webpieces/merge-info/\\n` +\n ` Prune this run's snapshot when safe: git branch -D ${backupBranch}\\n\\n`\n : '\\n';\n process.stdout.write(\n '\\n' + SEP + '✅ Sync complete — here is exactly what I did\\n' + SEP + '\\n' +\n ` 1. ${step1}\\n` +\n ` 2. pulled origin/main\\n` +\n ` 3. squash-merged your work onto main\\n` +\n ` 4. ${remoteLine}\\n\\n` +\n trailer,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"merge-end.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-end.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAGiC;AACjC,yCAA2D;AAC3D,mDAA+C;AAC/C,yCAAsC;AACtC,yCAAqC;AAErC,+CAA2C;AAE3C,MA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IAAI,CAAC;QACX,OAAO,CAAC,MAAM,CAAC,KAAK,CAChB,IAAI,GAAG,GAAG,GAAG,gDAAgD,GAAG,GAAG,GAAG,IAAI;YAC1E,SAAS,KAAK,IAAI;YAClB,4BAA4B;YAC5B,2CAA2C;YAC3C,SAAS,UAAU,MAAM;YACzB,OAAO,CACV,CAAC;IACN,CAAC;CACJ,CAAA;AAtMY,4BAAQ;mBAAR,QAAQ;IADpB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGF,4BAAY;QACT,mBAAQ;QAChB,kBAAO;QACJ,wBAAU;GALlC,QAAQ,CAsMpB","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n MERGE_EXPLANATION_FILE, stampCleanMainSyncStatus, CliExitError,\n MutationVerb, BranchMutationEvent, logBranchMutation,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BranchNaming } from './branch-naming';\nimport { CleanTmp } from './cleanTmp';\nimport { GitExec } from './git-exec';\nimport { MergeContext } from './merge-start';\nimport { MergeState } from './merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n// What finalizing actually did, for the recap. Data-only. `pushed` and `pushDeferred` are distinct on\n// purpose: \"we chose not to push yet\" must not be reported like \"there was no remote to push to\".\nclass SyncRecap {\n pushed: boolean;\n pushDeferred: boolean;\n hadConflict: boolean;\n backupKept: boolean;\n\n constructor(pushed: boolean, pushDeferred: boolean, hadConflict: boolean, backupKept: boolean) {\n this.pushed = pushed;\n this.pushDeferred = pushDeferred;\n this.hadConflict = hadConflict;\n this.backupKept = backupKept;\n }\n}\n\n// How a merge should be finalized. Data-only (per CLAUDE.md, classes for data) — bundled rather than\n// added as more positional params, which mergeEnd already has enough of.\nexport class MergeEndOptions {\n // Non-null means the AI resolved a conflict and it must be validated + committed before finalizing.\n // Null means merge-START already committed a clean merge, so finalize only.\n conflictedFiles: string[] | null;\n\n /**\n * Whether finalizing may push the squashed branch to origin.\n *\n * FALSE for the PR flow (`wp-start-upsert-pr` / `wp-finish-upsert-pr`), which pushes EXACTLY ONCE,\n * from GatedPrPublisher, after summary.json + every BLOCK checklist + the authoritative build gate\n * have passed and the gated PR body is already up. Code must not reach the remote ahead of its\n * review, and an early push here is also what fires `pull_request:synchronize` against a PR body\n * still carrying the previous run's gate token — the flap the whole gate redesign is removing.\n *\n * TRUE for the update-only flow (`wp-start-update` / `wp-finish-update`), which has no later push;\n * finalizing IS the end of that flow, so not pushing would silently strand the rewrite locally.\n */\n pushRemote: boolean;\n\n constructor(conflictedFiles: string[] | null, pushRemote: boolean) {\n this.conflictedFiles = conflictedFiles;\n this.pushRemote = pushRemote;\n }\n}\n\n// merge-END: the second half of the 3-point squash-merge lifecycle, symmetric with merge-START. Given\n// the branch context, it (optionally) validates + commits the AI's conflict resolution, then ALWAYS\n// finalizes — force-pushes `<branch>Squash` to the stable feature branch and renames it BACK to that\n// same feature name (local == remote == PR head), stamps a clean main-sync status, clears the marker,\n// and sweeps stale tmp. RunUpdate (clean path / validated resume), wp-finish-update, and\n// wp-finish-upsert-pr (conflict resolution) all call THIS, so finalization happens in exactly one place.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeEnd {\n constructor(\n private readonly branchNaming: BranchNaming,\n private readonly cleanTmpService: CleanTmp,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n ) {}\n\n /**\n * Complete a 3-point squash merge. See {@link MergeEndOptions} for what `conflictedFiles` and\n * `pushRemote` mean. Either way the merge ends fully finalized on the feature branch.\n */\n async mergeEnd(\n repoRoot: string, verb: MutationVerb, mergeDir: string, ctx: MergeContext, options: MergeEndOptions,\n ): Promise<void> {\n const conflictedFiles = options.conflictedFiles;\n if (conflictedFiles !== null) {\n process.stdout.write('\\n' + SEP + '🔎 Validating Merge Resolution\\n' + SEP + '\\n');\n this.validateResolution(repoRoot, verb, mergeDir, conflictedFiles);\n // Stage the AI's resolved conflicts, but NEVER sweep untracked files into the squash commit.\n // Fail on untracked so the AI commits or deletes them explicitly; then `git add -u` stages\n // tracked resolutions only.\n this.gitExec.assertNoUntracked(repoRoot);\n this.gitExec.runGitChecked(['add', '-u'], 'Failed to stage resolved files');\n\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (!nothingStaged) {\n this.gitExec.runGitChecked(\n ['commit', '-m', `Squash merge of ${ctx.currentBranch} (conflicts resolved)`],\n 'Failed to commit resolved merge',\n );\n }\n fs.writeFileSync(path.join(mergeDir, 'conflicts-resolved'), '');\n process.stdout.write('\\n✅ Merge validated and committed.\\n');\n }\n\n // A marker in THIS run dir means the sync hit conflicts (marker is written only on hand-back).\n // Read it BEFORE clearMergeMarker so finalize knows whether to keep the pre-merge snapshot.\n const hadConflict = this.mergeState.readMergeMarker(mergeDir) !== null;\n this.finalizeBranch(repoRoot, verb, ctx, hadConflict, options.pushRemote);\n this.mergeState.clearMergeMarker(mergeDir);\n await this.cleanTmpService.cleanTmp();\n }\n\n // Validate the AI's resolution of the conflicted files. Throws CliExitError with a fix instruction\n // on any failure; returns only when all three checks pass.\n // `verb` is the bin the AI actually ran (wp-finish-update or wp-finish-upsert-pr) — every \"re-run\"\n // instruction below is rendered from it. It used to be hardcoded to wp-finish-upsert-pr, which told\n // someone in the update-only flow to finish with the PR command: a pairing that does not exist.\n private validateResolution(repoRoot: string, verb: MutationVerb, mergeDir: string, conflictedFiles: string[]): void {\n const reRun = `pnpm ${verb}`;\n // 1. Scoped conflict-marker scan (only the conflicted files — O(conflicts), not O(repo)).\n const scan = this.mergeState.scanConflictMarkers(repoRoot, conflictedFiles);\n if (!scan.clean) {\n throw new CliExitError(1,\n '❌ Unresolved conflict markers (<<<<<<< / ======= / >>>>>>>) remain in:\\n' +\n scan.filesWithMarkers.map((file: string): string => ` - ${file}`).join('\\n') +\n `\\n\\nResolve them, then re-run: ${reRun}`,\n );\n }\n\n // 2. Ensure git itself has no remaining unmerged entries.\n const unmerged = execSync('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();\n if (unmerged !== '') {\n throw new CliExitError(1,\n '❌ Git still reports unmerged files:\\n' + unmerged +\n '\\n\\nResolve and `git add` them, then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ No conflict markers in resolved files.\\n');\n\n // 3. Explanation check — every conflicted file must have a non-empty merge-explanation.md in its\n // per-file context dir, proving the AI deliberately 3-point merged it (and recording how).\n const explanations = this.mergeState.scanMergeExplanations(mergeDir, conflictedFiles);\n if (!explanations.clean) {\n const missing = explanations.filesWithMarkers\n .map((file: string): string => ` - ${file}\\n → ${path.join(this.mergeState.perFileContextDir(mergeDir, file), MERGE_EXPLANATION_FILE)}`)\n .join('\\n');\n throw new CliExitError(1,\n `❌ Missing/empty merge explanation (${MERGE_EXPLANATION_FILE}) for:\\n` +\n missing +\n '\\n\\nWrite a few sentences on how you resolved each (which side, what you combined, why),\\n' +\n 'then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ Merge explanations present for all resolved files.\\n');\n }\n\n // Seam: overridden in the spec so the push/backup decisions are testable with no git and no repo.\n protected localBranchExists(name: string): boolean {\n return spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;\n }\n\n // Force-push the squash branch to the stable feature branch (where the single PR lives) — unless the\n // caller owns the push (see MergeEndOptions.pushRemote) — then RENAME the local squash branch back to\n // that SAME feature name. On a CLEAN sync the pre-merge snapshot is disposable, so it's deleted at the\n // very end; a CONFLICT sync — or a sync we did not push — keeps it.\n // eslint-disable-next-line @typescript-eslint/max-params\n private finalizeBranch(repoRoot: string, verb: MutationVerb, ctx: MergeContext, hadConflict: boolean, pushRemote: boolean): void {\n process.stdout.write('\\n' + SEP + '🗑️ Finalizing\\n' + SEP + '\\n');\n const base = this.branchNaming.baseBranchName(ctx.currentBranch);\n this.gitExec.runGitChecked(['branch', '-D', ctx.currentBranch], 'Failed to delete old feature branch');\n\n const pushed = pushRemote ? this.pushFinalized(ctx, base) : this.explainNoPush();\n this.gitExec.runGitChecked(['checkout', ctx.squashBranch], 'Failed to checkout squash branch');\n // Free the rename target: `base` is normally the branch we just deleted, but a backward-compat\n // sync from a leftover `…wpN` can leave a separate stale `base` lingering — drop it too.\n if (base !== ctx.currentBranch && this.localBranchExists(base)) {\n this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');\n }\n this.gitExec.runGitChecked(['branch', '-m', base], 'Failed to rename squash branch to the feature name');\n const renameEvent = new BranchMutationEvent(verb, 'RENAME');\n renameEvent.fromBranch = ctx.currentBranch;\n renameEvent.toBranch = base;\n logBranchMutation(repoRoot, renameEvent);\n\n // Branch now contains origin/main — stamp a clean main-sync status so the feature-branch-guard\n // unblocks edits immediately (no wait for the async refresher).\n stampCleanMainSyncStatus(repoRoot);\n\n // Clean sync → the pre-merge snapshot was never needed; delete it LAST. Conflict sync → keep it.\n // ALSO keep it when we did not push: the squash rewrite then exists ONLY in this working copy, so\n // deleting the snapshot would leave a history rewrite with no copy anywhere. It is disposable only\n // once origin has the result, and in the PR flow that does not happen until wp-finish-upsert-pr.\n const backupKept = hadConflict || !pushed;\n if (!backupKept && this.localBranchExists(ctx.backupBranch)) {\n this.gitExec.runGitChecked(['branch', '-D', ctx.backupBranch], 'Failed to delete clean-merge backup');\n }\n\n const finalizeEvent = new BranchMutationEvent(verb, 'FINALIZE');\n finalizeEvent.fromBranch = ctx.currentBranch;\n finalizeEvent.toBranch = base;\n finalizeEvent.outcome = 'finalized';\n finalizeEvent.artifacts = [backupKept ? `backup=${ctx.backupBranch}` : `backupDeleted=${ctx.backupBranch}`, `remotePR=${base}`];\n logBranchMutation(repoRoot, finalizeEvent);\n\n this.printSyncRecap(base, ctx.backupBranch, ctx.prNumber, new SyncRecap(pushed, !pushRemote, hadConflict, backupKept));\n }\n\n // Say WHY nothing was pushed, so an unpushed branch never looks like a failure. Always returns false\n // (nothing was pushed), which also keeps the pre-merge snapshot alive — see the backupKept comment.\n private explainNoPush(): boolean {\n process.stdout.write(\n 'Not pushing — the PR flow pushes exactly ONCE, from pnpm wp-finish-upsert-pr, after summary.json\\n' +\n 'and the build gate pass and the gated PR body is written. Your work stays local until then\\n' +\n '(the pre-merge snapshot below is kept as well, so nothing is only in one place).\\n',\n );\n return false;\n }\n\n // Push the finalized squash branch to the stable feature branch. Returns whether a push actually\n // happened — false when there is no remote branch yet (a brand-new branch is local until something\n // creates it, which in the PR flow is `gh pr create` after GatedPrPublisher's push).\n protected pushFinalized(ctx: MergeContext, base: string): boolean {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', base]).status === 0;\n if (!remoteExists) {\n process.stdout.write('No remote branch — local only.\\n');\n return false;\n }\n process.stdout.write(ctx.prNumber ? `Updating PR #${ctx.prNumber} (force-with-lease)...\\n` : 'Updating remote branch (force-with-lease)...\\n');\n this.gitExec.runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${ctx.squashBranch}:${base}`], 'Failed to push to origin');\n return true;\n }\n\n // Where the branch ended up, in the recap's own words. Three distinct outcomes, and \"deferred\" must\n // never read like the failure the other two could be mistaken for.\n private remoteRecapLine(feature: string, prNumber: string, recap: SyncRecap): string {\n if (recap.pushed) {\n return `landed back on ${feature} (== origin/${feature}${prNumber ? ` == PR #${prNumber}` : ''} — names match)`;\n }\n if (recap.pushDeferred) {\n return `landed back on ${feature} (local — by design; pnpm wp-finish-upsert-pr does the one push)`;\n }\n return `landed back on ${feature} (local only — no remote branch yet)`;\n }\n\n // The explicit, numbered \"here is exactly what I did\" recap the AI (and human) reads after a sync.\n private printSyncRecap(feature: string, backupBranch: string, prNumber: string, recap: SyncRecap): void {\n const backupKept = recap.backupKept;\n const remoteLine = this.remoteRecapLine(feature, prNumber, recap);\n const keptReason = recap.hadConflict ? 'this merge had conflicts' : 'not pushed yet — wp-finish-upsert-pr will push';\n const step1 = backupKept\n ? `snapshotted your pre-merge state → ${backupBranch} (kept — ${keptReason})`\n : `snapshotted your pre-merge state → ${backupBranch} (auto-removed — clean merge, no undo needed)`;\n const trailer = backupKept\n ? ` Pre-merge snapshot trail: git branch --list '${feature}PreMerge*'\\n` +\n ` Its conflict context lives in the paired merge-<n>/ folder under .webpieces/merge-info/\\n` +\n ` Prune this run's snapshot when safe: git branch -D ${backupBranch}\\n\\n`\n : '\\n';\n process.stdout.write(\n '\\n' + SEP + '✅ Sync complete — here is exactly what I did\\n' + SEP + '\\n' +\n ` 1. ${step1}\\n` +\n ` 2. pulled origin/main\\n` +\n ` 3. squash-merged your work onto main\\n` +\n ` 4. ${remoteLine}\\n\\n` +\n trailer,\n );\n }\n}\n"]}
|
|
@@ -28,7 +28,7 @@ let OpenPrCheck = class OpenPrCheck {
|
|
|
28
28
|
'PR already exists, wp-start-update would leave it pointing at the OLD branch. Fix gh first\n' +
|
|
29
29
|
'(install / `gh auth login` / restore network), then re-run — or, if a PR does exist, use\n' +
|
|
30
30
|
'the PR flow: pnpm wp-start-upsert-pr → /wp-merge (only on conflict) →\n' +
|
|
31
|
-
'pnpm wp-review-upsert-pr → write
|
|
31
|
+
'pnpm wp-review-upsert-pr → write summary.json → pnpm wp-finish-upsert-pr\n');
|
|
32
32
|
}
|
|
33
33
|
return (result.stdout ?? '').trim();
|
|
34
34
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"open-pr-check.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/open-pr-check.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuD;AACvD,yCAA2D;AAC3D,mDAA+C;AAE/C,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,+FAA+F;AAExF,IAAM,WAAW,GAAjB,MAAM,WAAW;IACS;IAA7B,YAA6B,YAA0B;QAA1B,iBAAY,GAAZ,YAAY,CAAc;IAAG,CAAC;IAE3D,qGAAqG;IACrG,+FAA+F;IAC/F,gGA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FAA+F;IAC/F,gGAAgG;IAChG,wGAAwG;IACxG,eAAe,CAAC,QAAgB,EAAE,aAAqB;QACnD,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC;QAC7D,MAAM,MAAM,GAAG,IAAA,yBAAS,EACpB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAClG,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CACtC,CAAC;QACF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,MAAM,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC;YAC5G,MAAM,IAAI,2BAAY,CAAC,CAAC,EACpB,IAAI,GAAG,GAAG,GAAG,oEAAoE,GAAG,GAAG,GAAG,IAAI;gBAC9F,8BAA8B,IAAI,MAAM,MAAM,MAAM;gBACpD,6FAA6F;gBAC7F,8FAA8F;gBAC9F,4FAA4F;gBAC5F,yEAAyE;gBACzE,4EAA4E,CAC/E,CAAC;QACN,CAAC;QACD,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,CAAC;CACJ,CAAA;AA3BY,kCAAW;sBAAX,WAAW;IADvB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEM,4BAAY;GAD9C,WAAW,CA2BvB","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BranchNaming } from './branch-naming';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/** Hard gate: whether an OPEN PR already tracks a feature branch (by its stable base name). */\n@injectable(bindingScopeValues.Singleton)\nexport class OpenPrCheck {\n constructor(private readonly branchNaming: BranchNaming) {}\n\n // The open PR (if any) tracking a feature branch, looked up by its STABLE base name. Returns '' ONLY\n // when GitHub answered and there is genuinely no open PR. HARD GATE: FAILS FAST if `gh` cannot\n // answer — we must NOT degrade \"couldn't ask GitHub\" into \"no PR\" (a 3-point update makes a new\n // branch generation and the existing PR would be stranded on the OLD branch). Refuse rather than guess.\n openPrForBranch(repoRoot: string, currentBranch: string): string {\n const base = this.branchNaming.baseBranchName(currentBranch);\n const result = spawnSync(\n 'gh', ['pr', 'list', '--head', base, '--state', 'open', '--json', 'number', '--jq', '.[0].number'],\n { cwd: repoRoot, encoding: 'utf8' },\n );\n if (result.status !== 0) {\n const detail = (result.stderr ?? '').trim() || (result.error ? result.error.message : 'gh exited non-zero');\n throw new CliExitError(2,\n '\\n' + SEP + '❌ Could not ask GitHub whether an open PR exists for this branch\\n' + SEP + '\\n' +\n `gh failed for base branch \"${base}\": ${detail}\\n\\n` +\n 'This check must NOT be skipped: a 3-point update creates a NEW branch generation, so if a\\n' +\n 'PR already exists, wp-start-update would leave it pointing at the OLD branch. Fix gh first\\n' +\n '(install / `gh auth login` / restore network), then re-run — or, if a PR does exist, use\\n' +\n 'the PR flow: pnpm wp-start-upsert-pr → /wp-merge (only on conflict) →\\n' +\n 'pnpm wp-review-upsert-pr → write summary.json → pnpm wp-finish-upsert-pr\\n',\n );\n }\n return (result.stdout ?? '').trim();\n }\n}\n"]}
|
|
@@ -30,7 +30,7 @@ export declare class ProvenanceEnforcer {
|
|
|
30
30
|
private readonly verdictProvenance;
|
|
31
31
|
constructor(aiBranchName: AiBranchName, provenance: SubagentProvenanceService, provenanceRecord: ReviewProvenanceService, reviewerInstructions: ReviewerInstructionsService, reviewJsonService: ReviewJsonService, verdictProvenance: VerdictProvenanceService);
|
|
32
32
|
/**
|
|
33
|
-
* Archive this round's provenance.json alongside the archived
|
|
33
|
+
* Archive this round's provenance.json alongside the archived summary.json, so an archived review keeps
|
|
34
34
|
* the transcript links belonging to the round that produced it — a record overwritten by the NEXT
|
|
35
35
|
* round audits nothing.
|
|
36
36
|
*
|
|
@@ -108,7 +108,7 @@ export declare class ProvenanceEnforcer {
|
|
|
108
108
|
* must be comparing a dash-form name against a slash-form git branch — see
|
|
109
109
|
* ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.
|
|
110
110
|
*
|
|
111
|
-
* A SEPARATE file rather than a field inside
|
|
111
|
+
* A SEPARATE file rather than a field inside summary.json / review-<id>.json, for two reasons. The
|
|
112
112
|
* reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no
|
|
113
113
|
* agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files
|
|
114
114
|
* byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about
|
|
@@ -50,7 +50,7 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
|
|
|
50
50
|
this.verdictProvenance = verdictProvenance;
|
|
51
51
|
}
|
|
52
52
|
/**
|
|
53
|
-
* Archive this round's provenance.json alongside the archived
|
|
53
|
+
* Archive this round's provenance.json alongside the archived summary.json, so an archived review keeps
|
|
54
54
|
* the transcript links belonging to the round that produced it — a record overwritten by the NEXT
|
|
55
55
|
* round audits nothing.
|
|
56
56
|
*
|
|
@@ -108,10 +108,10 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
|
|
|
108
108
|
* session and agent `wp-write-review` recorded. Read-counters stay at zero — the bin cannot know them.
|
|
109
109
|
*/
|
|
110
110
|
binEvidence(repoRoot, expected) {
|
|
111
|
-
const
|
|
111
|
+
const summaryPath = (0, rules_config_1.summaryJsonPath)(repoRoot, this.aiBranchName.getFeatureName());
|
|
112
112
|
const out = [];
|
|
113
113
|
for (const want of expected) {
|
|
114
|
-
const record = this.verdictProvenance.read(
|
|
114
|
+
const record = this.verdictProvenance.read(summaryPath, want.checklistId);
|
|
115
115
|
if (record === null)
|
|
116
116
|
continue;
|
|
117
117
|
out.push(new rules_config_1.ReviewerEvidence(want.checklistId, record.agentType === '' ? want.agentType : record.agentType, record.agentId));
|
|
@@ -224,7 +224,7 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
|
|
|
224
224
|
const verdictPaths = {};
|
|
225
225
|
for (const req of required) {
|
|
226
226
|
docPaths[req.id] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);
|
|
227
|
-
verdictPaths[req.id] = this.reviewJsonService.checklistResultPath((0, rules_config_1.
|
|
227
|
+
verdictPaths[req.id] = this.reviewJsonService.checklistResultPath((0, rules_config_1.summaryJsonPath)(repoRoot, featureName), req.id);
|
|
228
228
|
}
|
|
229
229
|
return new rules_config_1.ReviewerContext(branch, path.join((0, rules_config_1.prDirFor)(repoRoot, featureName), 'diff'), docPaths, verdictPaths);
|
|
230
230
|
}
|
|
@@ -237,7 +237,7 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
|
|
|
237
237
|
* must be comparing a dash-form name against a slash-form git branch — see
|
|
238
238
|
* ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.
|
|
239
239
|
*
|
|
240
|
-
* A SEPARATE file rather than a field inside
|
|
240
|
+
* A SEPARATE file rather than a field inside summary.json / review-<id>.json, for two reasons. The
|
|
241
241
|
* reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no
|
|
242
242
|
* agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files
|
|
243
243
|
* byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about
|
|
@@ -262,7 +262,7 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
|
|
|
262
262
|
reviewerPathsFor(repoRoot, featureName, required, checklistId) {
|
|
263
263
|
const req = required.find((r) => r.id === checklistId);
|
|
264
264
|
const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';
|
|
265
|
-
return new rules_config_1.ReviewerPaths(this.reviewJsonService.checklistResultPath((0, rules_config_1.
|
|
265
|
+
return new rules_config_1.ReviewerPaths(this.reviewJsonService.checklistResultPath((0, rules_config_1.summaryJsonPath)(repoRoot, featureName), checklistId), this.reviewerInstructions.pathFor(repoRoot, featureName, checklistId), doc);
|
|
266
266
|
}
|
|
267
267
|
/**
|
|
268
268
|
* The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provenance-enforcer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/provenance-enforcer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAOiC;AACjC,yCAA2D;AAC3D,iEAAsD;AACtD,6DAAgE;AAEhE;;;GAGG;AACH,MAAa,gBAAgB;IACzB,QAAQ,CAAU;IAClB,QAAQ,CAAqB;IAE7B,YAAY,QAAiB,EAAE,QAA4B;QACvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AARD,4CAQC;AAED;;;;;;;;;;GAUG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAGN;IACA;IACA;IACA;IACA;IACA;IAPrB,yDAAyD;IACzD,YACqB,YAA0B,EAC1B,UAAqC,EACrC,gBAAyC,EACzC,oBAAiD,EACjD,iBAAoC,EACpC,iBAA2C;QAL3C,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAA2B;QACrC,qBAAgB,GAAhB,gBAAgB,CAAyB;QACzC,yBAAoB,GAApB,oBAAoB,CAA6B;QACjD,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,sBAAiB,GAAjB,iBAAiB,CAA0B;IAC7D,CAAC;IAEJ;;;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S,KAAK,CAAC,MAAM,8EAA8E,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YACvH,yGAAyG,CAAC,CAAC;QAC/G,OAAO,EAAE,CAAC;IACd,CAAC;CACJ,CAAA;AAlQY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIF,mCAAY;QACd,wCAAyB;QACnB,sCAAuB;QACnB,0CAA2B;QAC9B,gCAAiB;QACjB,6CAAwB;GARvD,kBAAkB,CAkQ9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n prDirFor, reviewJsonPath, RequiredChecklist, PrGateConfig, ReviewJsonService,\n SubagentProvenanceService, PROVENANCE_OK, PROVENANCE_MISSING, PROVENANCE_SKIPPED,\n ProvenanceResult, ReviewerEvidence, ReviewerContext, ExpectedReviewer,\n ReviewProvenanceService, ProvenanceWriteRequest, ReviewerTranscript, ReviewerPaths, OfferedContext,\n ReviewerInstructionsService, InformAiError,\n claudeConfigDir, CLAUDE_CONFIG_DIR_ENV,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from './git-readAiBranchName';\nimport { VerdictProvenanceService } from './verdict-provenance';\n\n/**\n * The provenance outcome: whether each reviewer was VERIFIED to have run (the integrity check, which\n * blocks) plus what each one actually read (the quality signal, which is published). Data-only.\n */\nexport class ProvenanceReport {\n verified: boolean;\n evidence: ReviewerEvidence[];\n\n constructor(verified: boolean, evidence: ReviewerEvidence[]) {\n this.verified = verified;\n this.evidence = evidence;\n }\n}\n\n/**\n * Proves each checklist verdict came from an independently-run reviewer subagent, and records what\n * each one read.\n *\n * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam\n * twice over: this is a self-contained integrity check with its own spec\n * (`finish-provenance-record.spec.ts`), and that spec previously had to reach through\n * `command as unknown as { enforceProvenance(...) }` to get at it. Now `enforce` is simply public.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProvenanceEnforcer {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly aiBranchName: AiBranchName,\n private readonly provenance: SubagentProvenanceService,\n private readonly provenanceRecord: ReviewProvenanceService,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly verdictProvenance: VerdictProvenanceService,\n ) {}\n\n /**\n * Archive this round's provenance.json alongside the archived review.json, so an archived review keeps\n * the transcript links belonging to the round that produced it — a record overwritten by the NEXT\n * round audits nothing.\n *\n * Here rather than in the command because this class owns the record; the command only knows WHEN to\n * archive, not what the record is.\n */\n archiveRecord(prDir: string): void {\n this.provenanceRecord.archive(prDir);\n }\n\n // HEAD sha for the audit record. Failure-tolerant ('' rather than a throw): a missing sha degrades\n // the audit trail, and refusing a PR over it would be the wrong trade — see writeProvenanceRecord.\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Enforce that EACH matched checklist was reviewed by a real reviewer SUBAGENT — the coding agent may\n // not self-certify. Not by one of a particular NAME: see SubagentProvenanceService.isReviewerRun. One run may cover several checklists, because `reviewerAgents` is a\n // required CAP and grouping under it is what the repo configured. A verified set passes silently; any\n // missing reviewer throws so the PR does not open.\n //\n // No Claude session id (Codex, a plain terminal) is NOT a pass on integrity any more (issue #863): by\n // the time this runs the checklist scan has already REJECTED every verdict that `wp-write-review` did\n // not write for a reviewer subagent. What is skipped is only the transcript evidence, and the audit\n // record is filled from the bin's provenance instead — so a Codex reviewer's identity is recorded too.\n // eslint-disable-next-line @typescript-eslint/max-params\n enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): ProvenanceReport {\n const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified\n // Defense in depth: the scanner normally hands finish an empty set under this project policy, but\n // provenance must never resurrect a reviewer requirement if a caller still passes matched checklists.\n const enforced = config.reviewer.maxAgents === 0 ? [] : required;\n const expected = enforced\n .filter((r: RequiredChecklist): boolean => r.reviewer.agentName.trim() !== '')\n .map((r: RequiredChecklist): ExpectedReviewer => new ExpectedReviewer(r.id, r.reviewer.agentName.trim()));\n const context = this.contextFor(repoRoot, enforced, branch);\n // verifyReviewers short-circuits to OK on an empty set, so this runs unconditionally: a repo with no\n // checklists still gets a provenance record naming the session and the main agent's own transcript.\n const result = this.provenance.verifyReviewers(expected, context);\n report.verified = result.status === PROVENANCE_OK;\n if (result.status === PROVENANCE_SKIPPED) process.stderr.write(`⚠️ ${result.detail}\\n`);\n const skipped = result.status === PROVENANCE_SKIPPED;\n report.evidence = skipped\n ? this.binEvidence(repoRoot, expected)\n : this.provenance.evidenceFor(context, expected, result.agentIds);\n // Bin evidence says WHO submitted, not what they read, so it cannot be judged blind.\n const blind = skipped ? [] : this.blindReviewers(report.evidence, config);\n // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record\n // that only ever appeared on success could not answer what the reviewers did the time it was refused.\n this.writeProvenanceRecord(repoRoot, enforced, result, report.evidence);\n this.refuse(result, blind, context);\n return report;\n }\n\n /**\n * Evidence from `review-<id>.provenance.json` when there are no Claude transcripts to read: the harness,\n * session and agent `wp-write-review` recorded. Read-counters stay at zero — the bin cannot know them.\n */\n private binEvidence(repoRoot: string, expected: readonly ExpectedReviewer[]): ReviewerEvidence[] {\n const reviewPath = reviewJsonPath(repoRoot, this.aiBranchName.getFeatureName());\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const record = this.verdictProvenance.read(reviewPath, want.checklistId);\n if (record === null) continue;\n out.push(new ReviewerEvidence(\n want.checklistId, record.agentType === '' ? want.agentType : record.agentType, record.agentId));\n }\n return out;\n }\n\n /**\n * Refuse — with an instruction that matches WHICH failure this is.\n *\n * The count is the number of CHECKLISTS at fault, not the number of message paragraphs. It used to be\n * `errors.length`, which printed \"1 checklist(s) require …\" above a list of seven names.\n *\n * The split matters more than the count. A checklist with no verdict file needs a reviewer spawned. A\n * checklist WITH one needs the opposite: the reviewer already ran, the verdict is on disk, and only the\n * attribution failed — so telling an agent to \"spawn each as its OWN subagent\" makes it overwrite seven\n * verdicts with runs that are stamped identically and refused identically. That is a loop that destroys\n * evidence on every iteration, and it is what the previous single message guaranteed.\n *\n * The BLOCK decision is the STATUS, not the length of `missing`. Those agree today — but a\n * `PROVENANCE_MISSING` that arrived carrying no names would otherwise be a silent pass: reported\n * unverified and refused by nothing. Refusing on the status makes the unverified verdict block whatever\n * else is true, and `detail` carries the wording when there are no names to word it from.\n */\n private refuse(result: ProvenanceResult, blind: readonly string[], context: ReviewerContext): void {\n const missing = result.missing;\n const neverRan = missing.filter((t: string): boolean => !fs.existsSync(context.verdictPaths[t] ?? ''));\n const unattributed = missing.filter((t: string): boolean => fs.existsSync(context.verdictPaths[t] ?? ''));\n const paragraphs: string[] = [];\n if (result.status === PROVENANCE_MISSING && missing.length === 0) paragraphs.push(result.detail);\n if (neverRan.length > 0) {\n paragraphs.push(\n 'no reviewer subagent ran on this branch for these checklists (spawn the reviewer agent that ' +\n `pnpm wp-review-upsert-pr names — do not self-certify): ${neverRan.join(', ')}`);\n }\n if (unattributed.length > 0) paragraphs.push(this.unattributedMessage(unattributed, context));\n if (blind.length > 0) {\n paragraphs.push(`these reviewers wrote a verdict without opening the diff (pr-gate.requireDiffEvidence is on): ${blind.join(', ')}`);\n }\n if (paragraphs.length === 0) return;\n // The UNION, because one checklist can be both unattributed and blind, and counting the paragraphs\n // is what printed \"1 checklist(s) require …\" above a list of seven names. Floored at 1 so the\n // nameless-MISSING case above cannot announce \"0 checklist(s) failed\" and then refuse.\n const atFault = Math.max(new Set([...missing, ...blind]).size, 1);\n throw new InformAiError(\n `${atFault} checklist(s) failed the reviewer-provenance check — fix, then re-run pnpm wp-finish-upsert-pr:\\n\\n` +\n paragraphs.map((e: string): string => ` • ${e}`).join('\\n\\n'));\n }\n\n /**\n * The verdict exists but nothing can prove WHICH branch its reviewer looked at — or, in the one case\n * below, provenance never found the session's transcripts AT ALL and this is not about reviewers.\n *\n * The cwd paragraph is reachable when a session rooted in the PRIMARY CLONE spawns reviewers for a\n * branch that lives in a linked worktree: the harness stamps record 0 from the spawning session's cwd\n * (the Agent tool has no cwd parameter), so every respawn is stamped identically and re-spawning\n * cannot change the outcome. Saying so is the whole point of that message — the remedy is a session\n * rooted in the worktree, or a reviewer that names this branch's own files.\n *\n * It is GATED on having found the session, because it was printed for a completely different fault\n * and sent two debugging rounds in the wrong direction: see {@link transcriptRootProblem}.\n */\n private unattributedMessage(unattributed: readonly string[], context: ReviewerContext): string {\n const head = `these reviewers WROTE a verdict for this branch that provenance cannot attribute to them: ${unattributed.join(', ')}\\n` +\n ` Do NOT re-spawn them. A re-spawn overwrites the verdict file it already wrote, so that loop destroys\\n` +\n ` the verdicts and cannot change the outcome.\\n`;\n const rootProblem = this.transcriptRootProblem();\n if (rootProblem !== '') return head + rootProblem;\n return head +\n ` A reviewer is attributed when it names this branch's own files: its verdict\\n` +\n ` (${context.verdictPaths[unattributed[0]] ?? '<verdict path>'}) or the extracted diff (${context.diffDir}).\\n` +\n ` It is stamped with the cwd of the session that spawned it, so if the reviewers ran before\\n` +\n ` pnpm wp-review-upsert-pr materialized that diff, re-run this from a Claude Code session whose\\n` +\n ` cwd IS the worktree holding ${context.branch} — that is the only cwd the harness will stamp on them.`;\n }\n\n /**\n * The transcript ROOT is wrong — said so, instead of blaming the reviewers. '' when it is not.\n *\n * The test is exact rather than heuristic: the main agent's transcript is located by SESSION ID alone,\n * with no cwd, branch or stamping involved, so a known session id with no transcript anywhere can only\n * mean nothing was searched in the right place. That is a transcript-location problem, and it is not\n * something a reviewer did.\n *\n * It happened, and the cost was the whole point of gating the other message: on a machine with\n * `$CLAUDE_CONFIG_DIR` relocated, provenance searched a hardcoded `~/.claude`, found neither the\n * reviewers' transcripts nor the main agent's, and refused every PR with advice about cwd stamping,\n * worktrees and primary clones — none of which was involved. Two debugging rounds went into that\n * before `provenance.json`'s empty `mainTranscript` settled it.\n */\n private transcriptRootProblem(): string {\n const session = this.provenanceRecord.sessionId();\n if (session === '' || this.provenanceRecord.mainTranscript() !== '') return '';\n const configured = claudeConfigDir.configuredDir();\n return ` Provenance found NO transcripts at all for session ${session} — not even the main agent's own — under:\\n` +\n claudeConfigDir.projectsRoots().map((root: string): string => ` ${root}\\n`).join('') +\n ` $${CLAUDE_CONFIG_DIR_ENV}=${configured === '' ? '<unset>' : configured}. This is a transcript-LOCATION problem, not a\\n` +\n ` reviewer problem — your reviewers' verdicts are intact and must not be re-run. Point this command at the\\n` +\n ` config dir that session wrote to.`;\n }\n\n /**\n * WHERE this branch's review materials live — the paths BOTH provenance passes compare against.\n *\n * One object for crediting and for evidence: they ask different questions of the same files, and\n * building the paths twice is how the two could drift apart.\n */\n private contextFor(repoRoot: string, required: readonly RequiredChecklist[], branch: string): ReviewerContext {\n const featureName = this.aiBranchName.getFeatureName();\n const docPaths: Record<string, string> = {};\n const verdictPaths: Record<string, string> = {};\n for (const req of required) {\n docPaths[req.id] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n verdictPaths[req.id] = this.reviewJsonService.checklistResultPath(reviewJsonPath(repoRoot, featureName), req.id);\n }\n return new ReviewerContext(branch, path.join(prDirFor(repoRoot, featureName), 'diff'), docPaths, verdictPaths);\n }\n\n /**\n * Write this round's audit record: `.webpieces/pr-review/<featureSlug>/provenance.json`, linking each\n * verdict to the transcript of the subagent that produced it.\n *\n * `<featureSlug>`, not `<branch>`: the dir is named by `AiBranchName.getFeatureName()`, which\n * dash-sanitizes the branch. Calling it `<branch>` is what led a bug reporter to conclude the gate\n * must be comparing a dash-form name against a slash-form git branch — see\n * ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.\n *\n * A SEPARATE file rather than a field inside review.json / review-<id>.json, for two reasons. The\n * reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no\n * agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files\n * byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about\n * itself. Every path here is derived by the tooling from the harness's own artifacts.\n *\n * Never fatal: an unwritable record is a lost audit trail, not a reason to refuse a PR.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeProvenanceRecord(repoRoot: string, required: readonly RequiredChecklist[], result: ProvenanceResult, evidence: readonly ReviewerEvidence[]): void {\n const featureName = this.aiBranchName.getFeatureName();\n const prDir = prDirFor(repoRoot, featureName);\n const request = new ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);\n request.offered = new OfferedContext(\n path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));\n request.reviewers = evidence.map((e: ReviewerEvidence): ReviewerTranscript =>\n new ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.checklistId)));\n const written = this.provenanceRecord.write(request);\n if (written !== '') process.stdout.write(` transcript provenance → ${written}\\n`);\n }\n\n // Where ONE checklist's verdict, instructions and doc live — keyed by the checklist id, never by the\n // agent type, which every checklist now shares.\n // eslint-disable-next-line @typescript-eslint/max-params\n private reviewerPathsFor(repoRoot: string, featureName: string, required: readonly RequiredChecklist[], checklistId: string): ReviewerPaths {\n const req = required.find((r: RequiredChecklist): boolean => r.id === checklistId);\n const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';\n return new ReviewerPaths(\n this.reviewJsonService.checklistResultPath(reviewJsonPath(repoRoot, featureName), checklistId),\n this.reviewerInstructions.pathFor(repoRoot, featureName, checklistId),\n doc,\n );\n }\n\n /**\n * The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for\n * {@link refuse} to block on (opt-in).\n *\n * Default-warn because the signal is derived from undocumented Claude Code transcript internals: if the\n * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.\n * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.\n *\n * Returns the checklist ids rather than a finished sentence so the caller can count CHECKLISTS at fault —\n * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.\n */\n private blindReviewers(evidence: readonly ReviewerEvidence[], config: PrGateConfig): string[] {\n const blind = evidence.filter((e: ReviewerEvidence): boolean => !e.readDiff);\n if (blind.length === 0) return [];\n const names = blind.map((e: ReviewerEvidence): string => e.checklistId);\n if (config.requireDiffEvidence) return names;\n process.stderr.write(\n `\\n⚠️ ${blind.length} reviewer(s) wrote a verdict with no record of opening the extracted diff: ${names.join(', ')}\\n` +\n ' Published on the PR as a note. Not blocking — set pr-gate.requireDiffEvidence:true to make it one.\\n');\n return [];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provenance-enforcer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/provenance-enforcer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAOiC;AACjC,yCAA2D;AAC3D,iEAAsD;AACtD,6DAAgE;AAEhE;;;GAGG;AACH,MAAa,gBAAgB;IACzB,QAAQ,CAAU;IAClB,QAAQ,CAAqB;IAE7B,YAAY,QAAiB,EAAE,QAA4B;QACvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AARD,4CAQC;AAED;;;;;;;;;;GAUG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAGN;IACA;IACA;IACA;IACA;IACA;IAPrB,yDAAyD;IACzD,YACqB,YAA0B,EAC1B,UAAqC,EACrC,gBAAyC,EACzC,oBAAiD,EACjD,iBAAoC,EACpC,iBAA2C;QAL3C,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAA2B;QACrC,qBAAgB,GAAhB,gBAAgB,CAAyB;QACzC,yBAAoB,GAApB,oBAAoB,CAA6B;QACjD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I,MAAM,CAAC,mBAAmB;YAAE,OAAO,KAAK,CAAC;QAC7C,OAAO,CAAC,MAAM,CAAC,KAAK,CAChB,SAAS,KAAK,CAAC,MAAM,8EAA8E,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YACvH,yGAAyG,CAAC,CAAC;QAC/G,OAAO,EAAE,CAAC;IACd,CAAC;CACJ,CAAA;AAlQY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIF,mCAAY;QACd,wCAAyB;QACnB,sCAAuB;QACnB,0CAA2B;QAC9B,gCAAiB;QACjB,6CAAwB;GARvD,kBAAkB,CAkQ9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n prDirFor, summaryJsonPath, RequiredChecklist, PrGateConfig, ReviewJsonService,\n SubagentProvenanceService, PROVENANCE_OK, PROVENANCE_MISSING, PROVENANCE_SKIPPED,\n ProvenanceResult, ReviewerEvidence, ReviewerContext, ExpectedReviewer,\n ReviewProvenanceService, ProvenanceWriteRequest, ReviewerTranscript, ReviewerPaths, OfferedContext,\n ReviewerInstructionsService, InformAiError,\n claudeConfigDir, CLAUDE_CONFIG_DIR_ENV,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from './git-readAiBranchName';\nimport { VerdictProvenanceService } from './verdict-provenance';\n\n/**\n * The provenance outcome: whether each reviewer was VERIFIED to have run (the integrity check, which\n * blocks) plus what each one actually read (the quality signal, which is published). Data-only.\n */\nexport class ProvenanceReport {\n verified: boolean;\n evidence: ReviewerEvidence[];\n\n constructor(verified: boolean, evidence: ReviewerEvidence[]) {\n this.verified = verified;\n this.evidence = evidence;\n }\n}\n\n/**\n * Proves each checklist verdict came from an independently-run reviewer subagent, and records what\n * each one read.\n *\n * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam\n * twice over: this is a self-contained integrity check with its own spec\n * (`finish-provenance-record.spec.ts`), and that spec previously had to reach through\n * `command as unknown as { enforceProvenance(...) }` to get at it. Now `enforce` is simply public.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProvenanceEnforcer {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly aiBranchName: AiBranchName,\n private readonly provenance: SubagentProvenanceService,\n private readonly provenanceRecord: ReviewProvenanceService,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly verdictProvenance: VerdictProvenanceService,\n ) {}\n\n /**\n * Archive this round's provenance.json alongside the archived summary.json, so an archived review keeps\n * the transcript links belonging to the round that produced it — a record overwritten by the NEXT\n * round audits nothing.\n *\n * Here rather than in the command because this class owns the record; the command only knows WHEN to\n * archive, not what the record is.\n */\n archiveRecord(prDir: string): void {\n this.provenanceRecord.archive(prDir);\n }\n\n // HEAD sha for the audit record. Failure-tolerant ('' rather than a throw): a missing sha degrades\n // the audit trail, and refusing a PR over it would be the wrong trade — see writeProvenanceRecord.\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Enforce that EACH matched checklist was reviewed by a real reviewer SUBAGENT — the coding agent may\n // not self-certify. Not by one of a particular NAME: see SubagentProvenanceService.isReviewerRun. One run may cover several checklists, because `reviewerAgents` is a\n // required CAP and grouping under it is what the repo configured. A verified set passes silently; any\n // missing reviewer throws so the PR does not open.\n //\n // No Claude session id (Codex, a plain terminal) is NOT a pass on integrity any more (issue #863): by\n // the time this runs the checklist scan has already REJECTED every verdict that `wp-write-review` did\n // not write for a reviewer subagent. What is skipped is only the transcript evidence, and the audit\n // record is filled from the bin's provenance instead — so a Codex reviewer's identity is recorded too.\n // eslint-disable-next-line @typescript-eslint/max-params\n enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): ProvenanceReport {\n const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified\n // Defense in depth: the scanner normally hands finish an empty set under this project policy, but\n // provenance must never resurrect a reviewer requirement if a caller still passes matched checklists.\n const enforced = config.reviewer.maxAgents === 0 ? [] : required;\n const expected = enforced\n .filter((r: RequiredChecklist): boolean => r.reviewer.agentName.trim() !== '')\n .map((r: RequiredChecklist): ExpectedReviewer => new ExpectedReviewer(r.id, r.reviewer.agentName.trim()));\n const context = this.contextFor(repoRoot, enforced, branch);\n // verifyReviewers short-circuits to OK on an empty set, so this runs unconditionally: a repo with no\n // checklists still gets a provenance record naming the session and the main agent's own transcript.\n const result = this.provenance.verifyReviewers(expected, context);\n report.verified = result.status === PROVENANCE_OK;\n if (result.status === PROVENANCE_SKIPPED) process.stderr.write(`⚠️ ${result.detail}\\n`);\n const skipped = result.status === PROVENANCE_SKIPPED;\n report.evidence = skipped\n ? this.binEvidence(repoRoot, expected)\n : this.provenance.evidenceFor(context, expected, result.agentIds);\n // Bin evidence says WHO submitted, not what they read, so it cannot be judged blind.\n const blind = skipped ? [] : this.blindReviewers(report.evidence, config);\n // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record\n // that only ever appeared on success could not answer what the reviewers did the time it was refused.\n this.writeProvenanceRecord(repoRoot, enforced, result, report.evidence);\n this.refuse(result, blind, context);\n return report;\n }\n\n /**\n * Evidence from `review-<id>.provenance.json` when there are no Claude transcripts to read: the harness,\n * session and agent `wp-write-review` recorded. Read-counters stay at zero — the bin cannot know them.\n */\n private binEvidence(repoRoot: string, expected: readonly ExpectedReviewer[]): ReviewerEvidence[] {\n const summaryPath = summaryJsonPath(repoRoot, this.aiBranchName.getFeatureName());\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const record = this.verdictProvenance.read(summaryPath, want.checklistId);\n if (record === null) continue;\n out.push(new ReviewerEvidence(\n want.checklistId, record.agentType === '' ? want.agentType : record.agentType, record.agentId));\n }\n return out;\n }\n\n /**\n * Refuse — with an instruction that matches WHICH failure this is.\n *\n * The count is the number of CHECKLISTS at fault, not the number of message paragraphs. It used to be\n * `errors.length`, which printed \"1 checklist(s) require …\" above a list of seven names.\n *\n * The split matters more than the count. A checklist with no verdict file needs a reviewer spawned. A\n * checklist WITH one needs the opposite: the reviewer already ran, the verdict is on disk, and only the\n * attribution failed — so telling an agent to \"spawn each as its OWN subagent\" makes it overwrite seven\n * verdicts with runs that are stamped identically and refused identically. That is a loop that destroys\n * evidence on every iteration, and it is what the previous single message guaranteed.\n *\n * The BLOCK decision is the STATUS, not the length of `missing`. Those agree today — but a\n * `PROVENANCE_MISSING` that arrived carrying no names would otherwise be a silent pass: reported\n * unverified and refused by nothing. Refusing on the status makes the unverified verdict block whatever\n * else is true, and `detail` carries the wording when there are no names to word it from.\n */\n private refuse(result: ProvenanceResult, blind: readonly string[], context: ReviewerContext): void {\n const missing = result.missing;\n const neverRan = missing.filter((t: string): boolean => !fs.existsSync(context.verdictPaths[t] ?? ''));\n const unattributed = missing.filter((t: string): boolean => fs.existsSync(context.verdictPaths[t] ?? ''));\n const paragraphs: string[] = [];\n if (result.status === PROVENANCE_MISSING && missing.length === 0) paragraphs.push(result.detail);\n if (neverRan.length > 0) {\n paragraphs.push(\n 'no reviewer subagent ran on this branch for these checklists (spawn the reviewer agent that ' +\n `pnpm wp-review-upsert-pr names — do not self-certify): ${neverRan.join(', ')}`);\n }\n if (unattributed.length > 0) paragraphs.push(this.unattributedMessage(unattributed, context));\n if (blind.length > 0) {\n paragraphs.push(`these reviewers wrote a verdict without opening the diff (pr-gate.requireDiffEvidence is on): ${blind.join(', ')}`);\n }\n if (paragraphs.length === 0) return;\n // The UNION, because one checklist can be both unattributed and blind, and counting the paragraphs\n // is what printed \"1 checklist(s) require …\" above a list of seven names. Floored at 1 so the\n // nameless-MISSING case above cannot announce \"0 checklist(s) failed\" and then refuse.\n const atFault = Math.max(new Set([...missing, ...blind]).size, 1);\n throw new InformAiError(\n `${atFault} checklist(s) failed the reviewer-provenance check — fix, then re-run pnpm wp-finish-upsert-pr:\\n\\n` +\n paragraphs.map((e: string): string => ` • ${e}`).join('\\n\\n'));\n }\n\n /**\n * The verdict exists but nothing can prove WHICH branch its reviewer looked at — or, in the one case\n * below, provenance never found the session's transcripts AT ALL and this is not about reviewers.\n *\n * The cwd paragraph is reachable when a session rooted in the PRIMARY CLONE spawns reviewers for a\n * branch that lives in a linked worktree: the harness stamps record 0 from the spawning session's cwd\n * (the Agent tool has no cwd parameter), so every respawn is stamped identically and re-spawning\n * cannot change the outcome. Saying so is the whole point of that message — the remedy is a session\n * rooted in the worktree, or a reviewer that names this branch's own files.\n *\n * It is GATED on having found the session, because it was printed for a completely different fault\n * and sent two debugging rounds in the wrong direction: see {@link transcriptRootProblem}.\n */\n private unattributedMessage(unattributed: readonly string[], context: ReviewerContext): string {\n const head = `these reviewers WROTE a verdict for this branch that provenance cannot attribute to them: ${unattributed.join(', ')}\\n` +\n ` Do NOT re-spawn them. A re-spawn overwrites the verdict file it already wrote, so that loop destroys\\n` +\n ` the verdicts and cannot change the outcome.\\n`;\n const rootProblem = this.transcriptRootProblem();\n if (rootProblem !== '') return head + rootProblem;\n return head +\n ` A reviewer is attributed when it names this branch's own files: its verdict\\n` +\n ` (${context.verdictPaths[unattributed[0]] ?? '<verdict path>'}) or the extracted diff (${context.diffDir}).\\n` +\n ` It is stamped with the cwd of the session that spawned it, so if the reviewers ran before\\n` +\n ` pnpm wp-review-upsert-pr materialized that diff, re-run this from a Claude Code session whose\\n` +\n ` cwd IS the worktree holding ${context.branch} — that is the only cwd the harness will stamp on them.`;\n }\n\n /**\n * The transcript ROOT is wrong — said so, instead of blaming the reviewers. '' when it is not.\n *\n * The test is exact rather than heuristic: the main agent's transcript is located by SESSION ID alone,\n * with no cwd, branch or stamping involved, so a known session id with no transcript anywhere can only\n * mean nothing was searched in the right place. That is a transcript-location problem, and it is not\n * something a reviewer did.\n *\n * It happened, and the cost was the whole point of gating the other message: on a machine with\n * `$CLAUDE_CONFIG_DIR` relocated, provenance searched a hardcoded `~/.claude`, found neither the\n * reviewers' transcripts nor the main agent's, and refused every PR with advice about cwd stamping,\n * worktrees and primary clones — none of which was involved. Two debugging rounds went into that\n * before `provenance.json`'s empty `mainTranscript` settled it.\n */\n private transcriptRootProblem(): string {\n const session = this.provenanceRecord.sessionId();\n if (session === '' || this.provenanceRecord.mainTranscript() !== '') return '';\n const configured = claudeConfigDir.configuredDir();\n return ` Provenance found NO transcripts at all for session ${session} — not even the main agent's own — under:\\n` +\n claudeConfigDir.projectsRoots().map((root: string): string => ` ${root}\\n`).join('') +\n ` $${CLAUDE_CONFIG_DIR_ENV}=${configured === '' ? '<unset>' : configured}. This is a transcript-LOCATION problem, not a\\n` +\n ` reviewer problem — your reviewers' verdicts are intact and must not be re-run. Point this command at the\\n` +\n ` config dir that session wrote to.`;\n }\n\n /**\n * WHERE this branch's review materials live — the paths BOTH provenance passes compare against.\n *\n * One object for crediting and for evidence: they ask different questions of the same files, and\n * building the paths twice is how the two could drift apart.\n */\n private contextFor(repoRoot: string, required: readonly RequiredChecklist[], branch: string): ReviewerContext {\n const featureName = this.aiBranchName.getFeatureName();\n const docPaths: Record<string, string> = {};\n const verdictPaths: Record<string, string> = {};\n for (const req of required) {\n docPaths[req.id] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n verdictPaths[req.id] = this.reviewJsonService.checklistResultPath(summaryJsonPath(repoRoot, featureName), req.id);\n }\n return new ReviewerContext(branch, path.join(prDirFor(repoRoot, featureName), 'diff'), docPaths, verdictPaths);\n }\n\n /**\n * Write this round's audit record: `.webpieces/pr-review/<featureSlug>/provenance.json`, linking each\n * verdict to the transcript of the subagent that produced it.\n *\n * `<featureSlug>`, not `<branch>`: the dir is named by `AiBranchName.getFeatureName()`, which\n * dash-sanitizes the branch. Calling it `<branch>` is what led a bug reporter to conclude the gate\n * must be comparing a dash-form name against a slash-form git branch — see\n * ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.\n *\n * A SEPARATE file rather than a field inside summary.json / review-<id>.json, for two reasons. The\n * reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no\n * agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files\n * byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about\n * itself. Every path here is derived by the tooling from the harness's own artifacts.\n *\n * Never fatal: an unwritable record is a lost audit trail, not a reason to refuse a PR.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeProvenanceRecord(repoRoot: string, required: readonly RequiredChecklist[], result: ProvenanceResult, evidence: readonly ReviewerEvidence[]): void {\n const featureName = this.aiBranchName.getFeatureName();\n const prDir = prDirFor(repoRoot, featureName);\n const request = new ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);\n request.offered = new OfferedContext(\n path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));\n request.reviewers = evidence.map((e: ReviewerEvidence): ReviewerTranscript =>\n new ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.checklistId)));\n const written = this.provenanceRecord.write(request);\n if (written !== '') process.stdout.write(` transcript provenance → ${written}\\n`);\n }\n\n // Where ONE checklist's verdict, instructions and doc live — keyed by the checklist id, never by the\n // agent type, which every checklist now shares.\n // eslint-disable-next-line @typescript-eslint/max-params\n private reviewerPathsFor(repoRoot: string, featureName: string, required: readonly RequiredChecklist[], checklistId: string): ReviewerPaths {\n const req = required.find((r: RequiredChecklist): boolean => r.id === checklistId);\n const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';\n return new ReviewerPaths(\n this.reviewJsonService.checklistResultPath(summaryJsonPath(repoRoot, featureName), checklistId),\n this.reviewerInstructions.pathFor(repoRoot, featureName, checklistId),\n doc,\n );\n }\n\n /**\n * The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for\n * {@link refuse} to block on (opt-in).\n *\n * Default-warn because the signal is derived from undocumented Claude Code transcript internals: if the\n * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.\n * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.\n *\n * Returns the checklist ids rather than a finished sentence so the caller can count CHECKLISTS at fault —\n * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.\n */\n private blindReviewers(evidence: readonly ReviewerEvidence[], config: PrGateConfig): string[] {\n const blind = evidence.filter((e: ReviewerEvidence): boolean => !e.readDiff);\n if (blind.length === 0) return [];\n const names = blind.map((e: ReviewerEvidence): string => e.checklistId);\n if (config.requireDiffEvidence) return names;\n process.stderr.write(\n `\\n⚠️ ${blind.length} reviewer(s) wrote a verdict with no record of opening the extracted diff: ${names.join(', ')}\\n` +\n ' Published on the PR as a note. Not blocking — set pr-gate.requireDiffEvidence:true to make it one.\\n');\n return [];\n }\n}\n"]}
|
|
@@ -28,7 +28,7 @@ export declare class RefusedReviewer {
|
|
|
28
28
|
export declare class ReviewReportInput {
|
|
29
29
|
repoRoot: string;
|
|
30
30
|
featureName: string;
|
|
31
|
-
|
|
31
|
+
summaryPath: string;
|
|
32
32
|
definedCount: number;
|
|
33
33
|
applicableCount: number;
|
|
34
34
|
reviewed: RequiredChecklist[];
|
|
@@ -67,7 +67,7 @@ export declare class ReviewReportInput {
|
|
|
67
67
|
* CARRIED with its sha and the reason; a STALE or REJECTED one is printed with why it was re-briefed.
|
|
68
68
|
*/
|
|
69
69
|
standings: VerdictStanding[];
|
|
70
|
-
constructor(repoRoot: string, featureName: string,
|
|
70
|
+
constructor(repoRoot: string, featureName: string, summaryPath: string);
|
|
71
71
|
}
|
|
72
72
|
/**
|
|
73
73
|
* Renders the closing block of `wp-review-upsert-pr` — the checklist verdict, then EXACTLY ONE "what to do
|
|
@@ -75,14 +75,14 @@ export declare class ReviewReportInput {
|
|
|
75
75
|
*
|
|
76
76
|
* Extracted from the command so it can be asserted on as a rendered string, because the ordering IS the
|
|
77
77
|
* contract. The bug it was extracted to fix: the zero-checklist notice ended with "Carry on and run: pnpm
|
|
78
|
-
* wp-finish-upsert-pr", and the block printed directly beneath it said to write
|
|
78
|
+
* wp-finish-upsert-pr", and the block printed directly beneath it said to write summary.json first and
|
|
79
79
|
* finish afterwards. Two next-steps, in the wrong order, and an agent that follows instructions literally —
|
|
80
80
|
* which is the entire reason this command prints them — took the first one and opened a PR with no review.
|
|
81
81
|
* That is precisely the failure the three-stage flow exists to prevent (reported on PR #519).
|
|
82
82
|
*
|
|
83
83
|
* The invariants, enforced by review-report.spec.ts:
|
|
84
84
|
* 1. `wp-finish-upsert-pr` is named as a thing to run EXACTLY ONCE in the whole block.
|
|
85
|
-
* 2. The
|
|
85
|
+
* 2. The summary.json instruction comes BEFORE it — and BEFORE the spawn blocks (see nextSteps).
|
|
86
86
|
* 3. With zero checklists the all-clear precedes any configuration guidance.
|
|
87
87
|
* 4. REQUIRED reviewers are spawned unasked; OPTIONAL ones are only ever OFFERED, in one batched
|
|
88
88
|
* question. The two never share a step, because one instruction says "do it" and the other says
|
|
@@ -154,7 +154,7 @@ export declare class ReviewReport {
|
|
|
154
154
|
* then makes it, reasoning (correctly, on the facts) that the carried-forward verdicts judged an earlier
|
|
155
155
|
* tree. Reviews here are once per branch BY CONSTRUCTION: a passing review-<id>.json satisfies its
|
|
156
156
|
* checklist for the branch's whole life, and `wp-finish-upsert-pr` never archives one the way it archives
|
|
157
|
-
*
|
|
157
|
+
* summary.json. So the reuse is deliberate — it is what keeps post-PR iteration from re-paying for every
|
|
158
158
|
* matched reviewer — and the output has to say so, because the alternative reading is the expensive one.
|
|
159
159
|
*
|
|
160
160
|
* The overwrite warning is not decoration. A re-spawned reviewer writes to the SAME verdict path, so a
|
|
@@ -176,11 +176,11 @@ export declare class ReviewReport {
|
|
|
176
176
|
* ("Then… Finally…") so that skipping step 1 is visibly skipping a step, and worded so no earlier line
|
|
177
177
|
* can be mistaken for the real next action.
|
|
178
178
|
*
|
|
179
|
-
*
|
|
180
|
-
* This block used to print the spawn blocks first and then say to write
|
|
179
|
+
* summary.json is STEP 1 and the spawn blocks are STEP 2 — that ORDER is the contract, not a preference.
|
|
180
|
+
* This block used to print the spawn blocks first and then say to write summary.json "WHILE any reviewer
|
|
181
181
|
* subagents above are still running", which does not merely permit spawning first, it instructs it.
|
|
182
182
|
* Harmless for a reviewer that only reads the diff; wrong for one that judges the PR's stated INTENT —
|
|
183
|
-
* its title, summary or risk level — because
|
|
183
|
+
* its title, summary or risk level — because summary.json is the only place that intent lives. Such a
|
|
184
184
|
* reviewer either finds no file (a false RED and a wasted reviewer run) or, on a second run of this
|
|
185
185
|
* stage on the same branch, finds the PREVIOUS run's file and validates a title that no longer exists —
|
|
186
186
|
* a false GREEN, with nothing in the output saying which of the two happened. A consuming repo had to
|
|
@@ -192,7 +192,7 @@ export declare class ReviewReport {
|
|
|
192
192
|
* can never drift from the shape `wp-finish-upsert-pr` validates.
|
|
193
193
|
*/
|
|
194
194
|
private nextSteps;
|
|
195
|
-
private
|
|
195
|
+
private writeSummaryStep;
|
|
196
196
|
private singleRoundRepeatStep;
|
|
197
197
|
/**
|
|
198
198
|
* The REQUIRED reviewers — one copy-paste block each, and nothing at all when none is owed. The prompt is
|