@webpieces/pr-gate 0.4.801 → 0.4.802
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 +4 -3
- package/src/scripts/commands/await-reviews-command.d.ts +8 -2
- package/src/scripts/commands/await-reviews-command.js +27 -5
- package/src/scripts/commands/await-reviews-command.js.map +1 -1
- package/src/scripts/commands/review-upsert-pr-command.js +12 -2
- package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/write-review-command.d.ts +50 -0
- package/src/scripts/commands/write-review-command.js +175 -0
- package/src/scripts/commands/write-review-command.js.map +1 -0
- package/src/scripts/pr-gate-app.d.ts +8 -1
- package/src/scripts/pr-gate-app.js +12 -1
- package/src/scripts/pr-gate-app.js.map +1 -1
- package/src/scripts/workflow/checklist-scanner.d.ts +27 -1
- package/src/scripts/workflow/checklist-scanner.js +52 -4
- package/src/scripts/workflow/checklist-scanner.js.map +1 -1
- package/src/scripts/workflow/checklist-scope-hasher.d.ts +34 -0
- package/src/scripts/workflow/checklist-scope-hasher.js +67 -0
- package/src/scripts/workflow/checklist-scope-hasher.js.map +1 -0
- package/src/scripts/workflow/diff-materializer.d.ts +1 -1
- package/src/scripts/workflow/diff-materializer.js +2 -2
- package/src/scripts/workflow/diff-materializer.js.map +1 -1
- package/src/scripts/workflow/provenance-enforcer.d.ts +8 -1
- package/src/scripts/workflow/provenance-enforcer.js +34 -7
- package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
- package/src/scripts/workflow/review-report.d.ts +19 -0
- package/src/scripts/workflow/review-report.js +58 -12
- package/src/scripts/workflow/review-report.js.map +1 -1
- package/src/scripts/workflow/review-stage-receipt.d.ts +9 -0
- package/src/scripts/workflow/review-stage-receipt.js +29 -1
- package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
- package/src/scripts/workflow/reviewer-briefing-builder.d.ts +3 -2
- package/src/scripts/workflow/reviewer-briefing-builder.js +4 -2
- package/src/scripts/workflow/reviewer-briefing-builder.js.map +1 -1
- package/src/scripts/workflow/reviewer-identity.d.ts +39 -0
- package/src/scripts/workflow/reviewer-identity.js +90 -0
- package/src/scripts/workflow/reviewer-identity.js.map +1 -0
- package/src/scripts/workflow/reviewer-verdict-gate.d.ts +8 -0
- package/src/scripts/workflow/reviewer-verdict-gate.js +21 -1
- package/src/scripts/workflow/reviewer-verdict-gate.js.map +1 -1
- package/src/scripts/workflow/verdict-provenance.d.ts +90 -0
- package/src/scripts/workflow/verdict-provenance.js +214 -0
- package/src/scripts/workflow/verdict-provenance.js.map +1 -0
- package/src/scripts/wp-write-review.d.ts +2 -0
- package/src/scripts/wp-write-review.js +25 -0
- package/src/scripts/wp-write-review.js.map +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/pr-gate",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.802",
|
|
4
4
|
"description": "Gated PR system: 3-point squash-merge, merge validation gate, and red/yellow/green PR dashboard. Standalone scripts, no Nx dependency required.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@inversifyjs/binding-decorators": "1.1.5",
|
|
19
|
-
"@webpieces/ai-hook-rules": "0.4.
|
|
20
|
-
"@webpieces/rules-config": "0.4.
|
|
19
|
+
"@webpieces/ai-hook-rules": "0.4.802",
|
|
20
|
+
"@webpieces/rules-config": "0.4.802",
|
|
21
21
|
"inversify": "7.10.4",
|
|
22
22
|
"reflect-metadata": "0.2.2"
|
|
23
23
|
},
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"wp-push-dev": "./src/scripts/wp-push-dev.js",
|
|
40
40
|
"wp-finish-push-dev": "./src/scripts/wp-finish-push-dev.js",
|
|
41
41
|
"wp-await-reviews": "./src/scripts/wp-await-reviews.js",
|
|
42
|
+
"wp-write-review": "./src/scripts/wp-write-review.js",
|
|
42
43
|
"wp-await-checks": "./src/scripts/wp-await-checks.js"
|
|
43
44
|
}
|
|
44
45
|
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { RepoRootFinder, RequiredChecklist, ReviewJsonService } from '@webpieces/rules-config';
|
|
2
2
|
import { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';
|
|
3
3
|
import { ChecklistScanner } from '../workflow/checklist-scanner';
|
|
4
|
+
import { AiBranchName } from '../workflow/git-readAiBranchName';
|
|
5
|
+
import { ReviewStageReceiptService } from '../workflow/review-stage-receipt';
|
|
4
6
|
import { StageOutputLog } from '../workflow/stage-output-log';
|
|
5
7
|
/**
|
|
6
8
|
* `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its
|
|
@@ -34,7 +36,9 @@ export declare class AwaitReviewsCommand {
|
|
|
34
36
|
private readonly reviewJsonService;
|
|
35
37
|
private readonly awaitLoop;
|
|
36
38
|
private readonly stageConsole;
|
|
37
|
-
|
|
39
|
+
private readonly receipts;
|
|
40
|
+
private readonly aiBranchName;
|
|
41
|
+
constructor(repoRootFinder: RepoRootFinder, checklistScanner: ChecklistScanner, reviewJsonService: ReviewJsonService, awaitLoop: AwaitLoop, stageConsole: StageOutputLog, receipts: ReviewStageReceiptService, aiBranchName: AiBranchName);
|
|
38
42
|
run(): Promise<void>;
|
|
39
43
|
private reportNothingOwed;
|
|
40
44
|
private reportDisabled;
|
|
@@ -50,10 +54,11 @@ export declare class ReviewerWaitProbe implements WaitProbe {
|
|
|
50
54
|
private readonly reviewPath;
|
|
51
55
|
private readonly waitedOn;
|
|
52
56
|
private readonly applicable;
|
|
57
|
+
private readonly sinceMs;
|
|
53
58
|
readonly label = "reviewers";
|
|
54
59
|
readonly pollMs = 3000;
|
|
55
60
|
private results;
|
|
56
|
-
constructor(reviewJsonService: ReviewJsonService, reviewPath: string, waitedOn: readonly RequiredChecklist[], applicable: readonly RequiredChecklist[]);
|
|
61
|
+
constructor(reviewJsonService: ReviewJsonService, reviewPath: string, waitedOn: readonly RequiredChecklist[], applicable: readonly RequiredChecklist[], sinceMs: number);
|
|
57
62
|
/**
|
|
58
63
|
* Done when every awaited reviewer has ANSWERED — not when every answer is a pass.
|
|
59
64
|
*
|
|
@@ -81,5 +86,6 @@ export declare class ReviewerWaitProbe implements WaitProbe {
|
|
|
81
86
|
private icon;
|
|
82
87
|
private nextStep;
|
|
83
88
|
private pending;
|
|
89
|
+
private predates;
|
|
84
90
|
private reload;
|
|
85
91
|
}
|
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ReviewerWaitProbe = exports.AwaitReviewsCommand = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
|
+
const fs = tslib_1.__importStar(require("fs"));
|
|
5
6
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
6
7
|
const inversify_1 = require("inversify");
|
|
7
8
|
const await_loop_1 = require("../workflow/await-loop");
|
|
8
9
|
const checklist_scanner_1 = require("../workflow/checklist-scanner");
|
|
10
|
+
const git_readAiBranchName_1 = require("../workflow/git-readAiBranchName");
|
|
11
|
+
const review_stage_receipt_1 = require("../workflow/review-stage-receipt");
|
|
9
12
|
const stage_output_log_1 = require("../workflow/stage-output-log");
|
|
10
13
|
/**
|
|
11
14
|
* `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its
|
|
@@ -39,12 +42,16 @@ let AwaitReviewsCommand = class AwaitReviewsCommand {
|
|
|
39
42
|
reviewJsonService;
|
|
40
43
|
awaitLoop;
|
|
41
44
|
stageConsole;
|
|
42
|
-
|
|
45
|
+
receipts;
|
|
46
|
+
aiBranchName;
|
|
47
|
+
constructor(repoRootFinder, checklistScanner, reviewJsonService, awaitLoop, stageConsole, receipts, aiBranchName) {
|
|
43
48
|
this.repoRootFinder = repoRootFinder;
|
|
44
49
|
this.checklistScanner = checklistScanner;
|
|
45
50
|
this.reviewJsonService = reviewJsonService;
|
|
46
51
|
this.awaitLoop = awaitLoop;
|
|
47
52
|
this.stageConsole = stageConsole;
|
|
53
|
+
this.receipts = receipts;
|
|
54
|
+
this.aiBranchName = aiBranchName;
|
|
48
55
|
}
|
|
49
56
|
async run() {
|
|
50
57
|
const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());
|
|
@@ -62,7 +69,10 @@ let AwaitReviewsCommand = class AwaitReviewsCommand {
|
|
|
62
69
|
// not wait for them, and a wait that did would never end, because nothing is ever going to write
|
|
63
70
|
// a verdict for a reviewer that was deliberately never spawned. (The SET is shared with finish;
|
|
64
71
|
// the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)
|
|
65
|
-
|
|
72
|
+
// A verdict file older than the last stage ② is NOT an arrival: it is the stale green or rejected
|
|
73
|
+
// file that stage just re-briefed (issue #863), and counting it would end the wait on the spot.
|
|
74
|
+
const since = this.receipts.writtenAtMs(repoRoot, this.aiBranchName.getFeatureName());
|
|
75
|
+
const probe = new ReviewerWaitProbe(this.reviewJsonService, scan.reviewPath, scan.outstanding, scan.applicable, since);
|
|
66
76
|
const outcome = await this.awaitLoop.run(probe);
|
|
67
77
|
this.report(probe, outcome);
|
|
68
78
|
}
|
|
@@ -87,7 +97,9 @@ exports.AwaitReviewsCommand = AwaitReviewsCommand = tslib_1.__decorate([
|
|
|
87
97
|
checklist_scanner_1.ChecklistScanner,
|
|
88
98
|
rules_config_1.ReviewJsonService,
|
|
89
99
|
await_loop_1.AwaitLoop,
|
|
90
|
-
stage_output_log_1.StageOutputLog
|
|
100
|
+
stage_output_log_1.StageOutputLog,
|
|
101
|
+
review_stage_receipt_1.ReviewStageReceiptService,
|
|
102
|
+
git_readAiBranchName_1.AiBranchName])
|
|
91
103
|
], AwaitReviewsCommand);
|
|
92
104
|
/**
|
|
93
105
|
* The reviewer wait itself: which checklists are owed, and what the files on disk say about them right
|
|
@@ -99,16 +111,20 @@ class ReviewerWaitProbe {
|
|
|
99
111
|
reviewPath;
|
|
100
112
|
waitedOn;
|
|
101
113
|
applicable;
|
|
114
|
+
sinceMs;
|
|
102
115
|
label = 'reviewers';
|
|
103
116
|
// Verdict files are local reads, so polling them costs nothing worth economizing on. Fast enough
|
|
104
117
|
// that the command returns within seconds of the last reviewer finishing, which is the point.
|
|
105
118
|
pollMs = 3_000;
|
|
106
119
|
results = [];
|
|
107
|
-
constructor(reviewJsonService, reviewPath, waitedOn, applicable
|
|
120
|
+
constructor(reviewJsonService, reviewPath, waitedOn, applicable,
|
|
121
|
+
// Epoch ms of the last stage ② (0 = none): a verdict file last written before it is not an answer.
|
|
122
|
+
sinceMs) {
|
|
108
123
|
this.reviewJsonService = reviewJsonService;
|
|
109
124
|
this.reviewPath = reviewPath;
|
|
110
125
|
this.waitedOn = waitedOn;
|
|
111
126
|
this.applicable = applicable;
|
|
127
|
+
this.sinceMs = sinceMs;
|
|
112
128
|
this.reload();
|
|
113
129
|
}
|
|
114
130
|
/**
|
|
@@ -189,7 +205,13 @@ class ReviewerWaitProbe {
|
|
|
189
205
|
// The awaited checklists whose verdict file has not appeared yet — see `done()` for why this is
|
|
190
206
|
// arrival and not the gate's own "still owed".
|
|
191
207
|
pending() {
|
|
192
|
-
return this.waitedOn.filter((req) => this.reviewJsonService.resolveVerdict(req, this.results).status === rules_config_1.CK_MISSING);
|
|
208
|
+
return this.waitedOn.filter((req) => this.reviewJsonService.resolveVerdict(req, this.results).status === rules_config_1.CK_MISSING || this.predates(req));
|
|
209
|
+
}
|
|
210
|
+
predates(req) {
|
|
211
|
+
if (this.sinceMs === 0)
|
|
212
|
+
return false;
|
|
213
|
+
const file = this.reviewJsonService.checklistResultPath(this.reviewPath, req.id);
|
|
214
|
+
return fs.existsSync(file) && fs.statSync(file).mtimeMs < this.sinceMs;
|
|
193
215
|
}
|
|
194
216
|
reload() {
|
|
195
217
|
this.results = this.reviewJsonService.loadChecklistResults(this.reviewPath, this.applicable);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"await-reviews-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-reviews-command.ts"],"names":[],"mappings":";;;;AAAA,0DAGiC;AACjC,yCAA2D;AAE3D,uDAA2E;AAC3E,qEAAuF;AACvF,mEAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IACA;IACA;IACA;IALrB,YACqB,cAA8B,EAC9B,gBAAkC,EAClC,iBAAoC,EACpC,SAAoB,EACpB,YAA4B;QAJ5B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,cAAS,GAAT,SAAS,CAAW;QACpB,iBAAY,GAAZ,YAAY,CAAgB;IAC9C,CAAC;IAEJ,KAAK,CAAC,GAAG;QACL,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QACpE,MAAM,MAAM,GAAG,IAAA,8BAAe,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC;QAChD,+FAA+F;QAC/F,wFAAwF;QACxF,kCAAkC;QAClC,MAAM,IAAI,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,UAAU,EAAE,IAAI,wCAAoB,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;QACzG,IAAI,IAAI,CAAC,iBAAiB;YAAE,OAAO,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxE,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAClE,+FAA+F;QAC/F,kGAAkG;QAClG,iGAAiG;QACjG,gGAAgG;QAChG,2FAA2F;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U,CAAC,IAAI,CAAC,CAAC,GAAsB,EAAW,EAAE,CACpE,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,sBAAO,CAAC,CAAC;QACjF,OAAO,MAAM;YACT,CAAC,CAAC,+FAA+F;kBAC3F,kDAAkD;YACxD,CAAC,CAAC,6CAA6C,CAAC;IACxD,CAAC;IAED,gGAAgG;IAChG,+CAA+C;IACvC,OAAO;QACX,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAsB,EAAW,EAAE,CAC5D,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,yBAAU,CAAC,CAAC;IACxF,CAAC;IAEO,MAAM;QACV,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACjG,CAAC;CACJ;AA3GD,8CA2GC","sourcesContent":["import {\n ChecklistResult, ChecklistVerdict, CK_FAIL, CK_MISSING, CK_BAD_FORMAT, loadAndValidate,\n RepoRootFinder, RequiredChecklist, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/**\n * `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its\n * verdict, then print what each one said.\n *\n * ─── Why a command and not an instruction ──────────────────────────────────────────────────────────\n * An agent that has just spawned four reviewer subagents has nothing to do until they answer, and a\n * worktree-isolated subagent cannot simply wait: ending its turn ends its run. See {@link AwaitLoop}\n * for the full chain and the measurement (18.3% of all fleet tokens in one day spent on `echo .`).\n * A blocking Bash call is the only wait primitive it has, so webpieces provides one.\n *\n * ─── It INVENTS NO STATE ───────────────────────────────────────────────────────────────────────────\n * The set of reviewers a branch owes is `ChecklistScanner`'s answer — the SAME one `wp-review-upsert-pr`\n * lists and `wp-finish-upsert-pr` blocks on — and the verdicts are the `review-<id>.json` files those\n * two already read. Nothing here writes anything, and there is no third opinion about who is owed: a\n * waiter that computed its own set could finish while finish still refused, which is the one outcome\n * that would make waiting worse than not waiting.\n *\n * The scan runs ONCE. Its `applicable` set is a function of the diff, which does not change while the\n * agent sits still, so re-scanning per poll would re-run `git diff` every few seconds to re-derive an\n * unchanged answer. Only the verdict FILES are re-read, which is the only thing a reviewer changes.\n *\n * ─── What it does NOT do ───────────────────────────────────────────────────────────────────────────\n * It does not judge. A red verdict is a completed review, so this command RETURNS on it and prints it;\n * refusing the PR over it is `wp-finish-upsert-pr`'s job and stays there. It exits non-zero only when it\n * cannot do its own job at all.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitReviewsCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const config = loadAndValidate(repoRoot).prGate;\n // contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review\n // was briefed against, and rewriting it mid-review would restate the briefing under the\n // reviewers currently reading it.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(true, ''));\n if (scan.reviewersDisabled) return this.reportDisabled(scan.suppressed);\n if (scan.applicable.length === 0) return this.reportNothingOwed();\n // WAIT on the set finish blocks on (`outstanding`), REPORT on everything that applies. The two\n // sets differ by exactly the optional checklists nobody ran — `required: false` means the PR does\n // not wait for them, and a wait that did would never end, because nothing is ever going to write\n // a verdict for a reviewer that was deliberately never spawned. (The SET is shared with finish;\n // the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)\n const probe = new ReviewerWaitProbe(\n this.reviewJsonService, scan.reviewPath, scan.outstanding, scan.applicable);\n const outcome = await this.awaitLoop.run(probe);\n this.report(probe, outcome);\n }\n\n // Nothing to wait for, and saying so is the whole value: an agent that got no answer here would\n // otherwise assume the wait is still owed and start spinning again.\n private reportNothingOwed(): void {\n this.stageConsole.say('\\n✅ No reviewer was requested for this branch — nothing to wait for.\\n');\n }\n\n private reportDisabled(suppressed: readonly RequiredChecklist[]): void {\n this.stageConsole.say(\n `\\n⚫ Every reviewer is switched off on this machine (experimental.turnOffAllReviewers), so `\n + `${String(suppressed.length)} checklist(s) that would have run are not running. There is `\n + 'nothing to wait for.\\n');\n }\n\n private report(probe: ReviewerWaitProbe, outcome: WaitOutcome): void {\n this.stageConsole.say(outcome.done ? probe.verdictReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/**\n * The reviewer wait itself: which checklists are owed, and what the files on disk say about them right\n * now. It owns the reporting too, because every line it prints is derived from the same verdict read —\n * a report that re-read the files could disagree with the answer that ended the wait.\n */\nexport class ReviewerWaitProbe implements WaitProbe {\n readonly label = 'reviewers';\n // Verdict files are local reads, so polling them costs nothing worth economizing on. Fast enough\n // that the command returns within seconds of the last reviewer finishing, which is the point.\n readonly pollMs = 3_000;\n\n private results: ChecklistResult[] = [];\n\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly reviewPath: string,\n private readonly waitedOn: readonly RequiredChecklist[],\n private readonly applicable: readonly RequiredChecklist[],\n ) {\n this.reload();\n }\n\n /**\n * Done when every awaited reviewer has ANSWERED — not when every answer is a pass.\n *\n * That distinction is the whole contract of a wait, and getting it wrong makes the command useless\n * in the case it matters most. `ReviewJsonService.pendingChecklists` is finish's GATE predicate and\n * counts a RED verdict as still owed, correctly: the PR is refused until the finding is fixed. But\n * a red reviewer has finished; it will never write a different answer on its own, so waiting for it\n * to stop being red is waiting forever. The wait therefore ends on ARRIVAL — a verdict file that\n * exists, whatever it says — and `wp-finish-upsert-pr` keeps sole ownership of the gate.\n *\n * `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX\n * (four characters of JSON), not a thing to wait longer for.\n */\n done(): boolean {\n this.reload();\n return this.pending().length === 0;\n }\n\n describe(): string {\n const owed = this.pending().length;\n const total = this.waitedOn.length;\n return `${String(total - owed)} of ${String(total)} verdicts in`;\n }\n\n /** Every reviewer's answer, printed once the wait is over — the reason to wait rather than sleep. */\n verdictReport(outcome: WaitOutcome): string {\n // The headline counts what was WAITED ON; the list below covers everything that APPLIES, so an\n // optional checklist nobody ran shows as ❓ rather than being quietly dropped. Reporting only the\n // waited-on set would let a shorter list imply the others passed.\n const lines = [\n `\\n✅ All ${String(this.waitedOn.length)} awaited reviewer verdict(s) are in after `\n + `${String(outcome.waitedSeconds)}s:\\n`,\n ];\n for (const req of this.applicable) lines.push(this.oneVerdict(req));\n lines.push(this.nextStep());\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * The timeout report. It is a NORMAL exit and says so, because an agent that reads this as a failure\n * goes hunting for a broken reviewer instead of running one more plain command.\n */\n stillWaitingReport(outcome: WaitOutcome): string {\n const owed = this.pending();\n return `\\n⏳ Still waiting after ${String(outcome.waitedSeconds)}s — run me again: pnpm wp-await-reviews\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command, so a\\n'\n + ' long review costs a handful of calls instead of hundreds of keep-alive turns.)\\n\\n'\n + ` ${String(owed.length)} of ${String(this.waitedOn.length)} still owe a verdict: `\n + `${owed.map((r: RequiredChecklist): string => r.id).join(', ')}\\n`;\n }\n\n private oneVerdict(req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, this.results);\n return ` ${this.icon(verdict)} ${verdict.id} — ${verdict.status}${this.detail(verdict)}`;\n }\n\n // Only a NON-passing verdict's detail is printed. A green reviewer's output is already on the PR,\n // and reprinting four of them here would bury the one line that needs acting on.\n private detail(verdict: ChecklistVerdict): string {\n if (verdict.status !== CK_FAIL || verdict.detail === '') return '';\n return `\\n ${verdict.detail.split('\\n').join('\\n ')}`;\n }\n\n private icon(verdict: ChecklistVerdict): string {\n if (verdict.status === CK_FAIL) return '🔴';\n if (verdict.status === CK_MISSING || verdict.status === CK_BAD_FORMAT) return '❓';\n return '🟢';\n }\n\n // Named because a wait that ends without saying what it unblocked leaves the agent to guess, and\n // guessing here means spinning again. A red verdict changes the next move, so it is called out.\n private nextStep(): string {\n const anyRed = this.applicable.some((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_FAIL);\n return anyRed\n ? '\\n A reviewer REFUSED. Fix what it found — re-spawning it against unchanged code buys the\\n'\n + ' same answer — then re-run the review stage.\\n'\n : '\\n Nothing is owed on the review front.\\n';\n }\n\n // The awaited checklists whose verdict file has not appeared yet — see `done()` for why this is\n // arrival and not the gate's own \"still owed\".\n private pending(): RequiredChecklist[] {\n return this.waitedOn.filter((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_MISSING);\n }\n\n private reload(): void {\n this.results = this.reviewJsonService.loadChecklistResults(this.reviewPath, this.applicable);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"await-reviews-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-reviews-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAGiC;AACjC,yCAA2D;AAE3D,uDAA2E;AAC3E,qEAAuF;AACvF,2EAAgE;AAChE,2EAA6E;AAC7E,mEAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IACA;IACA;IACA;IACA;IACA;IAPrB,YACqB,cAA8B,EAC9B,gBAAkC,EAClC,iBAAoC,EACpC,SAAoB,EACpB,YAA4B,EAC5B,QAAmC,EACnC,YAA0B;QAN1B,mBAAc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,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,sBAAO,CAAC,CAAC;QACjF,OAAO,MAAM;YACT,CAAC,CAAC,+FAA+F;kBAC3F,kDAAkD;YACxD,CAAC,CAAC,6CAA6C,CAAC;IACxD,CAAC;IAED,gGAAgG;IAChG,+CAA+C;IACvC,OAAO;QACX,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAsB,EAAW,EAAE,CAC5D,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,yBAAU,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9G,CAAC;IAEO,QAAQ,CAAC,GAAsB;QACnC,IAAI,IAAI,CAAC,OAAO,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACrC,MAAM,IAAI,GAAG,IAAI,CAAC,iBAAiB,CAAC,mBAAmB,CAAC,IAAI,CAAC,UAAU,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QACjF,OAAO,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC3E,CAAC;IAEO,MAAM;QACV,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACjG,CAAC;CACJ;AAnHD,8CAmHC","sourcesContent":["import * as fs from 'fs';\nimport {\n ChecklistResult, ChecklistVerdict, CK_FAIL, CK_MISSING, CK_BAD_FORMAT, loadAndValidate,\n RepoRootFinder, RequiredChecklist, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/**\n * `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its\n * verdict, then print what each one said.\n *\n * ─── Why a command and not an instruction ──────────────────────────────────────────────────────────\n * An agent that has just spawned four reviewer subagents has nothing to do until they answer, and a\n * worktree-isolated subagent cannot simply wait: ending its turn ends its run. See {@link AwaitLoop}\n * for the full chain and the measurement (18.3% of all fleet tokens in one day spent on `echo .`).\n * A blocking Bash call is the only wait primitive it has, so webpieces provides one.\n *\n * ─── It INVENTS NO STATE ───────────────────────────────────────────────────────────────────────────\n * The set of reviewers a branch owes is `ChecklistScanner`'s answer — the SAME one `wp-review-upsert-pr`\n * lists and `wp-finish-upsert-pr` blocks on — and the verdicts are the `review-<id>.json` files those\n * two already read. Nothing here writes anything, and there is no third opinion about who is owed: a\n * waiter that computed its own set could finish while finish still refused, which is the one outcome\n * that would make waiting worse than not waiting.\n *\n * The scan runs ONCE. Its `applicable` set is a function of the diff, which does not change while the\n * agent sits still, so re-scanning per poll would re-run `git diff` every few seconds to re-derive an\n * unchanged answer. Only the verdict FILES are re-read, which is the only thing a reviewer changes.\n *\n * ─── What it does NOT do ───────────────────────────────────────────────────────────────────────────\n * It does not judge. A red verdict is a completed review, so this command RETURNS on it and prints it;\n * refusing the PR over it is `wp-finish-upsert-pr`'s job and stays there. It exits non-zero only when it\n * cannot do its own job at all.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitReviewsCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n private readonly receipts: ReviewStageReceiptService,\n private readonly aiBranchName: AiBranchName,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const config = loadAndValidate(repoRoot).prGate;\n // contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review\n // was briefed against, and rewriting it mid-review would restate the briefing under the\n // reviewers currently reading it.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(true, ''));\n if (scan.reviewersDisabled) return this.reportDisabled(scan.suppressed);\n if (scan.applicable.length === 0) return this.reportNothingOwed();\n // WAIT on the set finish blocks on (`outstanding`), REPORT on everything that applies. The two\n // sets differ by exactly the optional checklists nobody ran — `required: false` means the PR does\n // not wait for them, and a wait that did would never end, because nothing is ever going to write\n // a verdict for a reviewer that was deliberately never spawned. (The SET is shared with finish;\n // the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)\n // A verdict file older than the last stage ② is NOT an arrival: it is the stale green or rejected\n // file that stage just re-briefed (issue #863), and counting it would end the wait on the spot.\n const since = this.receipts.writtenAtMs(repoRoot, this.aiBranchName.getFeatureName());\n const probe = new ReviewerWaitProbe(\n this.reviewJsonService, scan.reviewPath, scan.outstanding, scan.applicable, since);\n const outcome = await this.awaitLoop.run(probe);\n this.report(probe, outcome);\n }\n\n // Nothing to wait for, and saying so is the whole value: an agent that got no answer here would\n // otherwise assume the wait is still owed and start spinning again.\n private reportNothingOwed(): void {\n this.stageConsole.say('\\n✅ No reviewer was requested for this branch — nothing to wait for.\\n');\n }\n\n private reportDisabled(suppressed: readonly RequiredChecklist[]): void {\n this.stageConsole.say(\n `\\n⚫ Every reviewer is switched off on this machine (experimental.turnOffAllReviewers), so `\n + `${String(suppressed.length)} checklist(s) that would have run are not running. There is `\n + 'nothing to wait for.\\n');\n }\n\n private report(probe: ReviewerWaitProbe, outcome: WaitOutcome): void {\n this.stageConsole.say(outcome.done ? probe.verdictReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/**\n * The reviewer wait itself: which checklists are owed, and what the files on disk say about them right\n * now. It owns the reporting too, because every line it prints is derived from the same verdict read —\n * a report that re-read the files could disagree with the answer that ended the wait.\n */\nexport class ReviewerWaitProbe implements WaitProbe {\n readonly label = 'reviewers';\n // Verdict files are local reads, so polling them costs nothing worth economizing on. Fast enough\n // that the command returns within seconds of the last reviewer finishing, which is the point.\n readonly pollMs = 3_000;\n\n private results: ChecklistResult[] = [];\n\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly reviewPath: string,\n private readonly waitedOn: readonly RequiredChecklist[],\n private readonly applicable: readonly RequiredChecklist[],\n // Epoch ms of the last stage ② (0 = none): a verdict file last written before it is not an answer.\n private readonly sinceMs: number,\n ) {\n this.reload();\n }\n\n /**\n * Done when every awaited reviewer has ANSWERED — not when every answer is a pass.\n *\n * That distinction is the whole contract of a wait, and getting it wrong makes the command useless\n * in the case it matters most. `ReviewJsonService.pendingChecklists` is finish's GATE predicate and\n * counts a RED verdict as still owed, correctly: the PR is refused until the finding is fixed. But\n * a red reviewer has finished; it will never write a different answer on its own, so waiting for it\n * to stop being red is waiting forever. The wait therefore ends on ARRIVAL — a verdict file that\n * exists, whatever it says — and `wp-finish-upsert-pr` keeps sole ownership of the gate.\n *\n * `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX\n * (four characters of JSON), not a thing to wait longer for.\n */\n done(): boolean {\n this.reload();\n return this.pending().length === 0;\n }\n\n describe(): string {\n const owed = this.pending().length;\n const total = this.waitedOn.length;\n return `${String(total - owed)} of ${String(total)} verdicts in`;\n }\n\n /** Every reviewer's answer, printed once the wait is over — the reason to wait rather than sleep. */\n verdictReport(outcome: WaitOutcome): string {\n // The headline counts what was WAITED ON; the list below covers everything that APPLIES, so an\n // optional checklist nobody ran shows as ❓ rather than being quietly dropped. Reporting only the\n // waited-on set would let a shorter list imply the others passed.\n const lines = [\n `\\n✅ All ${String(this.waitedOn.length)} awaited reviewer verdict(s) are in after `\n + `${String(outcome.waitedSeconds)}s:\\n`,\n ];\n for (const req of this.applicable) lines.push(this.oneVerdict(req));\n lines.push(this.nextStep());\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * The timeout report. It is a NORMAL exit and says so, because an agent that reads this as a failure\n * goes hunting for a broken reviewer instead of running one more plain command.\n */\n stillWaitingReport(outcome: WaitOutcome): string {\n const owed = this.pending();\n return `\\n⏳ Still waiting after ${String(outcome.waitedSeconds)}s — run me again: pnpm wp-await-reviews\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command, so a\\n'\n + ' long review costs a handful of calls instead of hundreds of keep-alive turns.)\\n\\n'\n + ` ${String(owed.length)} of ${String(this.waitedOn.length)} still owe a verdict: `\n + `${owed.map((r: RequiredChecklist): string => r.id).join(', ')}\\n`;\n }\n\n private oneVerdict(req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, this.results);\n return ` ${this.icon(verdict)} ${verdict.id} — ${verdict.status}${this.detail(verdict)}`;\n }\n\n // Only a NON-passing verdict's detail is printed. A green reviewer's output is already on the PR,\n // and reprinting four of them here would bury the one line that needs acting on.\n private detail(verdict: ChecklistVerdict): string {\n if (verdict.status !== CK_FAIL || verdict.detail === '') return '';\n return `\\n ${verdict.detail.split('\\n').join('\\n ')}`;\n }\n\n private icon(verdict: ChecklistVerdict): string {\n if (verdict.status === CK_FAIL) return '🔴';\n if (verdict.status === CK_MISSING || verdict.status === CK_BAD_FORMAT) return '❓';\n return '🟢';\n }\n\n // Named because a wait that ends without saying what it unblocked leaves the agent to guess, and\n // guessing here means spinning again. A red verdict changes the next move, so it is called out.\n private nextStep(): string {\n const anyRed = this.applicable.some((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_FAIL);\n return anyRed\n ? '\\n A reviewer REFUSED. Fix what it found — re-spawning it against unchanged code buys the\\n'\n + ' same answer — then re-run the review stage.\\n'\n : '\\n Nothing is owed on the review front.\\n';\n }\n\n // The awaited checklists whose verdict file has not appeared yet — see `done()` for why this is\n // arrival and not the gate's own \"still owed\".\n private pending(): RequiredChecklist[] {\n return this.waitedOn.filter((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_MISSING || this.predates(req));\n }\n\n private predates(req: RequiredChecklist): boolean {\n if (this.sinceMs === 0) return false;\n const file = this.reviewJsonService.checklistResultPath(this.reviewPath, req.id);\n return fs.existsSync(file) && fs.statSync(file).mtimeMs < this.sinceMs;\n }\n\n private reload(): void {\n this.results = this.reviewJsonService.loadChecklistResults(this.reviewPath, this.applicable);\n }\n}\n"]}
|
|
@@ -133,7 +133,11 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
|
|
|
133
133
|
const recordedReviewers = singleRoundRepeat
|
|
134
134
|
? singleRoundReviewers
|
|
135
135
|
: briefings.map((b) => b.checklistId);
|
|
136
|
-
|
|
136
|
+
const receipt = new review_stage_receipt_1.ReviewStageReceipt(scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt, recordedReviewers);
|
|
137
|
+
// The hashes `wp-write-review` stamps into each verdict's provenance — what its reviewer was briefed
|
|
138
|
+
// on. A single-round repeat briefs nobody, so it keeps the round's original hashes with its reviewers.
|
|
139
|
+
receipt.scopeHashes = singleRoundRepeat ? (previousReceipt?.scopeHashes ?? {}) : scan.scopeHashes;
|
|
140
|
+
this.receipts.write(repoRoot, featureName, receipt);
|
|
137
141
|
this.reportActiveHatches(repoRoot);
|
|
138
142
|
this.report(repoRoot, featureName, scan, briefings, opts, singleRoundRepeat, recordedReviewers, config);
|
|
139
143
|
}
|
|
@@ -202,7 +206,12 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
|
|
|
202
206
|
// to, which meant this command wrote the same file twice, the first time with an empty diffDir.
|
|
203
207
|
// `scan.changedFiles` is passed through so the context is not recomputed from a second git call.
|
|
204
208
|
scan.context = this.prContextWriter.ensure(repoRoot, featureName, scan.basis, 'stage2-review', scan.changedFiles, diffDir);
|
|
205
|
-
|
|
209
|
+
// ONLY the checklists still owed a verdict (issue #863). A green or yellow whose in-scope diff is
|
|
210
|
+
// unchanged since it was submitted CARRIES — the scan left it in `reviewed` — so briefing it again
|
|
211
|
+
// would pay a reviewer to re-read code it already judged. Red, stale and never-run are briefed.
|
|
212
|
+
const reviewedIds = new Set(scan.reviewed.map((r) => r.id));
|
|
213
|
+
const owed = scan.applicable.filter((r) => !reviewedIds.has(r.id));
|
|
214
|
+
const briefings = this.briefingBuilder.build(repoRoot, scan, owed, manifest, diffDir, config);
|
|
206
215
|
const dir = this.reviewerInstructions.instructionsDirFor(repoRoot, featureName);
|
|
207
216
|
fs.rmSync(dir, { recursive: true, force: true }); // stale instructions read as current are worse than none
|
|
208
217
|
fs.mkdirSync(dir, { recursive: true });
|
|
@@ -239,6 +248,7 @@ let ReviewUpsertPrCommand = class ReviewUpsertPrCommand {
|
|
|
239
248
|
input.singleRoundReview = scan.singleRoundReview;
|
|
240
249
|
input.singleRoundRepeat = singleRoundRepeat;
|
|
241
250
|
input.singleRoundReviewers = singleRoundReviewers.slice();
|
|
251
|
+
input.standings = scan.standings.slice();
|
|
242
252
|
// `say`: this block IS the next action — which reviewers to spawn, where review.json goes, and
|
|
243
253
|
// the command after that. Capturing it into the log would leave the terminal with a pointer and
|
|
244
254
|
// no instruction, which is the one thing this stage may never do.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/review-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAGiC;AACjC,yCAA2D;AAC3D,+DAA4E;AAC5E,2EAAgE;AAChE,+DAA6E;AAC7E,+DAA0D;AAC1D,yEAAoE;AACpE,qEAAsG;AACtG,qEAAiE;AACjE,mDAA+C;AAC/C,yDAAuD;AACvD,qDAAkE;AAClE,yDAAqD;AACrD,qEAAgE;AAChE,qFAAgF;AAChF,6DAA6F;AAC7F,2EAAiG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AC,KAAK,EAAE,CAAC;QAC1D,+FAA+F;QAC/F,gGAAgG;QAChG,kEAAkE;QAClE,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACK,QAAQ,CAAC,IAAmB;QAChC,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACxF,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,GAAsB,EAAmB,EAAE,CAAC,IAAI,+BAAe,CAC/E,GAAG,CAAC,EAAE,EACN,IAAI,CAAC,iBAAiB,CAAC,YAAY,CAC/B,GAAG,EAAE,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9F,CAAC;CACJ,CAAA;AA3NY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIA,6BAAc;QAChB,mCAAY;QACjB,kBAAO;QACD,8BAAa;QACT,uCAAiB;QACxB,wBAAU;QACZ,oBAAQ;QACA,oCAAgB;QACpB,4BAAY;QACZ,oCAAgB;QACb,mCAAe;QACf,mDAAuB;QAClB,0CAA2B;QACvC,gDAAyB;QAChB,kCAAiB;QAEjB,gCAAiB;QACtB,iCAAc;GApBxC,qBAAqB,CA2NjC","sourcesContent":["import * as fs from 'fs';\nimport {\n loadAndValidate, writeTemplate, PrGateConfig, RepoRootFinder, RequiredChecklist,\n ReviewerBriefing, ReviewerInstructionsService, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ActiveHatch, ActiveHatchReport } from '../workflow/active-hatches';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { BuildArtifactGate } from '../workflow/build-artifact-gate';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { DiffMaterializer } from '../workflow/diff-materializer';\nimport { GitExec } from '../workflow/git-exec';\nimport { MergeContext } from '../workflow/merge-start';\nimport { MergeEnd, MergeEndOptions } from '../workflow/merge-end';\nimport { MergeState } from '../workflow/merge-state';\nimport { PrContextWriter } from '../workflow/pr-context-writer';\nimport { ReviewerBriefingBuilder } from '../workflow/reviewer-briefing-builder';\nimport { RefusedReviewer, ReviewReport, ReviewReportInput } from '../workflow/review-report';\nimport { ReviewStageReceipt, ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog, REVIEW_CONSOLE_LOG } from '../workflow/stage-output-log';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/** The `--no-optional` decision, as data (per CLAUDE.md) rather than a bare boolean parameter. */\nexport class ReviewUpsertPrOptions {\n /**\n * true ⇒ the human ALREADY said to submit without the optional reviews, so stage ② must not print the\n * block telling the AI to offer them. It changes nothing about what BLOCKS: required checklists are\n * unaffected, and an optional checklist that already has a red verdict on this branch still refuses the\n * PR at finish. This only suppresses the offer.\n */\n skipOptional: boolean;\n\n constructor(skipOptional = false) {\n this.skipOptional = skipOptional;\n }\n}\n\n/**\n * `wp-review-upsert-pr` — STAGE ② of the three-stage PR flow, between `wp-start-upsert-pr` (sync from main)\n * and `wp-finish-upsert-pr` (post the PR).\n *\n * It exists because reviewing came before verifying. Under the old two-command flow the 3-point merge was\n * finalized and the build gate ran inside `wp-finish-upsert-pr` — i.e. AFTER the reviewers had already run.\n * A reviewer could therefore spend a full review on an unresolved merge, or on code that does not compile,\n * and only afterwards would the branch be checked. This command puts the verification first:\n *\n * 1. finalize + VALIDATE any in-progress 3-point merge (moved here from finish)\n * 2. assert a clean tree (meaningful now — step 1 committed the resolution)\n * 3. run the build gate (on the merged, committed tree)\n * 4. scan the checklists, EXTRACT the diff, BRIEF the reviewers\n * 5. write the stage receipt, then print what to spawn + the review.json schema\n *\n * Unlike the report-only command it replaces — which always exited 0, because reporting is not gating — this\n * command CAN FAIL, at steps 1, 2 and 3. That is the point: it fails BEFORE any reviewer is spawned, so a\n * branch with an unresolved merge or a broken build costs zero reviewer tokens.\n *\n * The ordering of 1 → 2 → 3 is load-bearing. MergeEnd stages and commits the conflict resolution, so the\n * tree is clean by the time the build runs; building first would either build a dirty tree (proving nothing\n * about what ships) or refuse a tree that is legitimately mid-resolution.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewUpsertPrCommand {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildArtifactGate: BuildArtifactGate,\n private readonly mergeState: MergeState,\n private readonly mergeEnd: MergeEnd,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewReport: ReviewReport,\n private readonly materializer: DiffMaterializer,\n private readonly prContextWriter: PrContextWriter,\n private readonly briefingBuilder: ReviewerBriefingBuilder,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly receipts: ReviewStageReceiptService,\n private readonly activeHatchReport: ActiveHatchReport,\n // Injected only to RESOLVE + RENDER refusals (see refusals()). This stage never archives a verdict.\n private readonly reviewJsonService: ReviewJsonService,\n private readonly stageConsole: StageOutputLog,\n ) {}\n\n /**\n * Everything below runs with this stage's console CAPTURED to a file (see StageOutputLog). Only the\n * lines an agent must act on before it can do anything else reach the terminal — the build heartbeat\n * and result, and the closing instruction block. The merge validation, the hatch report, the checklist\n * scan and the diff extraction are all in the file, one `grep` away.\n *\n * This is the FIRST half of the fix for the piped-command watchdog kill: an agent pipes a command it\n * expects to flood, a pipe withholds every byte until exit, and the harness kills a command that has\n * printed nothing for 600 seconds — after a full build. Guarding the pipe without first shrinking the\n * output would only have traded that kill for a flooded context.\n */\n async run(opts: ReviewUpsertPrOptions = new ReviewUpsertPrOptions()): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(\n repoRoot, REVIEW_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot, opts));\n }\n\n private async runStage(repoRoot: string, opts: ReviewUpsertPrOptions): Promise<void> {\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n writeTemplate(repoRoot, 'webpieces.review-checklists.md');\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n\n const mergeValidated = await this.finalizeAnyInProgressMerge(repoRoot);\n this.gitExec.assertCleanTree(repoRoot);\n const buildPassedAt = await this.runBuildGate(repoRoot);\n\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(false, '')); // '' — THIS command writes the context itself, after materializing\n const previousReceipt = this.receipts.read(repoRoot, featureName);\n const singleRoundReviewers = previousReceipt?.reviewersBriefed ?? [];\n const singleRoundRepeat = scan.singleRoundReview && singleRoundReviewers.length > 0;\n // A second stage-② invocation in single-round mode must not create a fresh launch surface. The\n // original generated instructions stay on disk; this run only refreshes the build receipt and gives\n // the caller one explicit next action: finish.\n const briefings = singleRoundRepeat ? [] : this.briefReviewers(repoRoot, featureName, scan, config);\n const recordedReviewers = singleRoundRepeat\n ? singleRoundReviewers\n : briefings.map((b: ReviewerBriefing): string => b.checklistId);\n this.receipts.write(repoRoot, featureName, new ReviewStageReceipt(\n scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt,\n recordedReviewers,\n ));\n this.reportActiveHatches(repoRoot);\n this.report(repoRoot, featureName, scan, briefings, opts, singleRoundRepeat, recordedReviewers, config);\n }\n\n /**\n * List every rule that is currently switched off in webpieces.config.json. NON-BLOCKING and printed\n * before the instruction block, because it is context for the review rather than a step in it.\n *\n * A hatch is the one config change that makes the build QUIETER, so no gate, reviewer or red check\n * will ever mention it — which is how a repo ends up with rules off for weeks that nobody chose to\n * leave off. This is the only place in the flow that says so out loud.\n */\n private reportActiveHatches(repoRoot: string): void {\n const hatches: ActiveHatch[] = this.activeHatchReport.scan(repoRoot);\n process.stdout.write(this.activeHatchReport.render(hatches));\n }\n\n /**\n * Validate + commit + finalize a conflict resolution, if one is in flight. MOVED here from\n * `wp-finish-upsert-pr` so that exactly one command owns merge finalization — two owners is the drift\n * failure `PrContextWriter`'s own docstring records having already happened once in this codebase.\n *\n * MergeEnd's three checks are what \"did the AI do the 3-point merge right?\" means concretely: no\n * conflict markers left in the scoped files, `git diff --diff-filter=U` empty, and a non-empty\n * merge-explanation.md beside every conflicted file.\n *\n * Returns true when a merge was finalized OR there was none to finalize; it throws rather than returning\n * false when validation fails, so the receipt can never record an unvalidated merge as validated.\n */\n private async finalizeAnyInProgressMerge(repoRoot: string): Promise<boolean> {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return true;\n process.stdout.write('\\n' + SEP + '① Validating your 3-point merge\\n' + SEP + '\\n');\n // pushRemote:false — finish still owns the single push.\n await this.mergeEnd.mergeEnd(\n repoRoot, 'wp-review-upsert-pr', activeDir,\n new MergeContext(marker.currentBranch, marker.squashBranch, marker.backupBranch, marker.prNumber),\n new MergeEndOptions(marker.conflictedFiles, false),\n );\n return true;\n }\n\n /**\n * The build gate, run BEFORE any reviewer is briefed. Returns the ISO time it passed, for the receipt —\n * which is what lets `wp-finish-upsert-pr` skip its own gate when HEAD has not moved, so moving the gate\n * earlier did not turn one build into two.\n */\n private async runBuildGate(repoRoot: string): Promise<string> {\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions(\n '🛠️ Build gate',\n 'pnpm wp-review-upsert-pr',\n 'Build failed — NO reviewer was briefed and no diff was extracted. Fix it, then re-run.',\n REVIEW_STAGE,\n ));\n // Repo-wide: the build must not have left anything uncommitted AND unstaged. Runs HERE, not in\n // finish, because this is the stage that ran buildCommand and is therefore holding the dirty\n // tree at the exact moment the question is answerable. Replaces the per-project\n // validate-di-graph-unchanged nx target — see BuildArtifactGate for why that one had to go.\n this.buildArtifactGate.assertBuildLeftNothingUncommitted(repoRoot);\n return new Date().toISOString();\n }\n\n /**\n * Extract the diff once, then write one instructions file per reviewer.\n *\n * The changed-file set and the basis both come off the SCAN rather than being recomputed, so the diff a\n * reviewer reads covers exactly the files its checklist matched against.\n */\n private briefReviewers(repoRoot: string, featureName: string, scan: ChecklistScan, config: PrGateConfig): ReviewerBriefing[] {\n if (scan.basis.unresolved) return [];\n const manifest = this.materializer.materialize(\n repoRoot, featureName, scan.basis, scan.changedFiles, config.reviewDiffExclude);\n const diffDir = this.materializer.diffDirFor(repoRoot, featureName);\n // Write pr-context.json ONCE, here — after materializing, so `diffDir` is populated on the first\n // write. The scan deliberately did not write it (ChecklistScanOptions.contextStage === ''); it used\n // to, which meant this command wrote the same file twice, the first time with an empty diffDir.\n // `scan.changedFiles` is passed through so the context is not recomputed from a second git call.\n scan.context = this.prContextWriter.ensure(\n repoRoot, featureName, scan.basis, 'stage2-review', scan.changedFiles, diffDir);\n const briefings = this.briefingBuilder.build(repoRoot, scan, manifest, diffDir, config);\n const dir = this.reviewerInstructions.instructionsDirFor(repoRoot, featureName);\n fs.rmSync(dir, { recursive: true, force: true }); // stale instructions read as current are worse than none\n fs.mkdirSync(dir, { recursive: true });\n for (const b of briefings) {\n fs.writeFileSync(this.reviewerInstructions.pathFor(repoRoot, featureName, b.checklistId),\n this.reviewerInstructions.render(b));\n }\n return briefings;\n }\n\n /**\n * What the AI must do next — rendered by `ReviewReport`, which owns the ordering.\n *\n * The rendering moved OUT of this command so the ordering could be asserted on as a string. It had a\n * real bug: the zero-checklist notice signed off with \"Carry on and run: pnpm wp-finish-upsert-pr\"\n * while the block right beneath it said to write review.json first. An agent that reads top to bottom\n * obeyed the first line and posted a PR with no review at all.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private report(\n repoRoot: string, featureName: string, scan: ChecklistScan, briefings: readonly ReviewerBriefing[],\n opts: ReviewUpsertPrOptions, singleRoundRepeat: boolean, singleRoundReviewers: readonly string[], config: PrGateConfig,\n ): void {\n const input = new ReviewReportInput(repoRoot, featureName, scan.reviewPath);\n input.definedCount = scan.defined.length;\n input.applicableCount = scan.applicable.length;\n input.reviewed = scan.reviewed.slice();\n input.formatErrors = scan.formatErrors.slice();\n input.briefings = briefings.slice();\n input.refused = this.refusals(scan);\n input.skipOptional = opts.skipOptional;\n input.reviewer = config.reviewer;\n // Straight off the SCAN — the one place `experimental.turnOffAllReviewers` is read. This command\n // deliberately does NOT consult the home config itself: a second read is a second answer, and the\n // command that lists and the command that blocks would be free to disagree about whether a branch\n // was reviewed. See ChecklistScanner.\n input.reviewersSuppressed = scan.reviewersDisabled;\n input.suppressed = scan.suppressed.slice();\n input.singleRoundReview = scan.singleRoundReview;\n input.singleRoundRepeat = singleRoundRepeat;\n input.singleRoundReviewers = singleRoundReviewers.slice();\n // `say`: this block IS the next action — which reviewers to spawn, where review.json goes, and\n // the command after that. Capturing it into the log would leave the terminal with a pointer and\n // no instruction, which is the one thing this stage may never do.\n this.stageConsole.say(this.reviewReport.render(input));\n }\n\n /**\n * The applicable checklists that ALREADY ANSWERED and refused, each with its refusal rendered by the ONE\n * renderer `wp-finish-upsert-pr` also uses.\n *\n * Stage ② had the identical defect finish did: a refused checklist has no passing verdict, so it is not\n * in `scan.reviewed`, so it was printed as an ordinary owed reviewer and re-instructed word for word —\n * and an agent that obeys spawns it against unchanged code, gets the same refusal, and loops one stage\n * earlier than the loop that was reported.\n *\n * NO archive path is passed, deliberately, and this stage moves nothing. Retiring a verdict is finish's\n * act on the refusal it is actually enforcing; doing it here would delete the live verdict of a branch\n * that has not even been asked to finish yet, and `refusalError`'s un-archived wording — \"fix it, then\n * re-run\" — is only correct while that verdict file is still there, which here it is.\n *\n * The review path IS passed, because the ship-anyway route the refusal prints is a command that writes\n * `override-<id>.json` beside it. That command is as correct at this stage as at finish: the override\n * is a separate file with its own writer, so nothing about it depends on the verdict having been moved.\n */\n private refusals(scan: ChecklistScan): RefusedReviewer[] {\n const refused = this.reviewJsonService.refusedChecklists(scan.applicable, scan.results);\n return refused.map((req: RequiredChecklist): RefusedReviewer => new RefusedReviewer(\n req.id,\n this.reviewJsonService.refusalError(\n req, this.reviewJsonService.resolveVerdict(req, scan.results), scan.reviewPath)));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"review-upsert-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/review-upsert-pr-command.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAGiC;AACjC,yCAA2D;AAC3D,+DAA4E;AAC5E,2EAAgE;AAChE,+DAA6E;AAC7E,+DAA0D;AAC1D,yEAAoE;AACpE,qEAAsG;AACtG,qEAAiE;AACjE,mDAA+C;AAC/C,yDAAuD;AACvD,qDAAkE;AAClE,yDAAqD;AACrD,qEAAgE;AAChE,qFAAgF;AAChF,6DAA6F;AAC7F,2EAAiG;AACjG,mEAAkF;AAElF,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,kGAAkG;AAClG,MAAa,qBAAqB;IAC9B;;;;;OAKG;IACH,YAAY,CAAU;IAEtB,YAAY,YAAY,GAAG,KAAK;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAZD,sDAYC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEI,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;IAGT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;I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CAAc;GApBxC,qBAAqB,CAqOjC","sourcesContent":["import * as fs from 'fs';\nimport {\n loadAndValidate, writeTemplate, PrGateConfig, RepoRootFinder, RequiredChecklist,\n ReviewerBriefing, ReviewerInstructionsService, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ActiveHatch, ActiveHatchReport } from '../workflow/active-hatches';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { REVIEW_STAGE } from '../workflow/build-gate-log';\nimport { BuildArtifactGate } from '../workflow/build-artifact-gate';\nimport { ChecklistScan, ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { DiffMaterializer } from '../workflow/diff-materializer';\nimport { GitExec } from '../workflow/git-exec';\nimport { MergeContext } from '../workflow/merge-start';\nimport { MergeEnd, MergeEndOptions } from '../workflow/merge-end';\nimport { MergeState } from '../workflow/merge-state';\nimport { PrContextWriter } from '../workflow/pr-context-writer';\nimport { ReviewerBriefingBuilder } from '../workflow/reviewer-briefing-builder';\nimport { RefusedReviewer, ReviewReport, ReviewReportInput } from '../workflow/review-report';\nimport { ReviewStageReceipt, ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog, REVIEW_CONSOLE_LOG } from '../workflow/stage-output-log';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/** The `--no-optional` decision, as data (per CLAUDE.md) rather than a bare boolean parameter. */\nexport class ReviewUpsertPrOptions {\n /**\n * true ⇒ the human ALREADY said to submit without the optional reviews, so stage ② must not print the\n * block telling the AI to offer them. It changes nothing about what BLOCKS: required checklists are\n * unaffected, and an optional checklist that already has a red verdict on this branch still refuses the\n * PR at finish. This only suppresses the offer.\n */\n skipOptional: boolean;\n\n constructor(skipOptional = false) {\n this.skipOptional = skipOptional;\n }\n}\n\n/**\n * `wp-review-upsert-pr` — STAGE ② of the three-stage PR flow, between `wp-start-upsert-pr` (sync from main)\n * and `wp-finish-upsert-pr` (post the PR).\n *\n * It exists because reviewing came before verifying. Under the old two-command flow the 3-point merge was\n * finalized and the build gate ran inside `wp-finish-upsert-pr` — i.e. AFTER the reviewers had already run.\n * A reviewer could therefore spend a full review on an unresolved merge, or on code that does not compile,\n * and only afterwards would the branch be checked. This command puts the verification first:\n *\n * 1. finalize + VALIDATE any in-progress 3-point merge (moved here from finish)\n * 2. assert a clean tree (meaningful now — step 1 committed the resolution)\n * 3. run the build gate (on the merged, committed tree)\n * 4. scan the checklists, EXTRACT the diff, BRIEF the reviewers\n * 5. write the stage receipt, then print what to spawn + the review.json schema\n *\n * Unlike the report-only command it replaces — which always exited 0, because reporting is not gating — this\n * command CAN FAIL, at steps 1, 2 and 3. That is the point: it fails BEFORE any reviewer is spawned, so a\n * branch with an unresolved merge or a broken build costs zero reviewer tokens.\n *\n * The ordering of 1 → 2 → 3 is load-bearing. MergeEnd stages and commits the conflict resolution, so the\n * tree is clean by the time the build runs; building first would either build a dirty tree (proving nothing\n * about what ships) or refuse a tree that is legitimately mid-resolution.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewUpsertPrCommand {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly aiBranchName: AiBranchName,\n private readonly gitExec: GitExec,\n private readonly buildAffected: BuildAffected,\n private readonly buildArtifactGate: BuildArtifactGate,\n private readonly mergeState: MergeState,\n private readonly mergeEnd: MergeEnd,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewReport: ReviewReport,\n private readonly materializer: DiffMaterializer,\n private readonly prContextWriter: PrContextWriter,\n private readonly briefingBuilder: ReviewerBriefingBuilder,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly receipts: ReviewStageReceiptService,\n private readonly activeHatchReport: ActiveHatchReport,\n // Injected only to RESOLVE + RENDER refusals (see refusals()). This stage never archives a verdict.\n private readonly reviewJsonService: ReviewJsonService,\n private readonly stageConsole: StageOutputLog,\n ) {}\n\n /**\n * Everything below runs with this stage's console CAPTURED to a file (see StageOutputLog). Only the\n * lines an agent must act on before it can do anything else reach the terminal — the build heartbeat\n * and result, and the closing instruction block. The merge validation, the hatch report, the checklist\n * scan and the diff extraction are all in the file, one `grep` away.\n *\n * This is the FIRST half of the fix for the piped-command watchdog kill: an agent pipes a command it\n * expects to flood, a pipe withholds every byte until exit, and the harness kills a command that has\n * printed nothing for 600 seconds — after a full build. Guarding the pipe without first shrinking the\n * output would only have traded that kill for a flooded context.\n */\n async run(opts: ReviewUpsertPrOptions = new ReviewUpsertPrOptions()): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n await this.stageConsole.withCapture(\n repoRoot, REVIEW_CONSOLE_LOG, (): Promise<void> => this.runStage(repoRoot, opts));\n }\n\n private async runStage(repoRoot: string, opts: ReviewUpsertPrOptions): Promise<void> {\n writeTemplate(repoRoot, 'webpieces.git-workflow.md');\n writeTemplate(repoRoot, 'webpieces.review-checklists.md');\n const featureName = this.aiBranchName.getFeatureName();\n const config = loadAndValidate(repoRoot).prGate;\n\n const mergeValidated = await this.finalizeAnyInProgressMerge(repoRoot);\n this.gitExec.assertCleanTree(repoRoot);\n const buildPassedAt = await this.runBuildGate(repoRoot);\n\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(false, '')); // '' — THIS command writes the context itself, after materializing\n const previousReceipt = this.receipts.read(repoRoot, featureName);\n const singleRoundReviewers = previousReceipt?.reviewersBriefed ?? [];\n const singleRoundRepeat = scan.singleRoundReview && singleRoundReviewers.length > 0;\n // A second stage-② invocation in single-round mode must not create a fresh launch surface. The\n // original generated instructions stay on disk; this run only refreshes the build receipt and gives\n // the caller one explicit next action: finish.\n const briefings = singleRoundRepeat ? [] : this.briefReviewers(repoRoot, featureName, scan, config);\n const recordedReviewers = singleRoundRepeat\n ? singleRoundReviewers\n : briefings.map((b: ReviewerBriefing): string => b.checklistId);\n const receipt = new ReviewStageReceipt(\n scan.basis.headSha, mergeValidated, this.buildAffected.resolveBuildCommand(repoRoot), buildPassedAt,\n recordedReviewers,\n );\n // The hashes `wp-write-review` stamps into each verdict's provenance — what its reviewer was briefed\n // on. A single-round repeat briefs nobody, so it keeps the round's original hashes with its reviewers.\n receipt.scopeHashes = singleRoundRepeat ? (previousReceipt?.scopeHashes ?? {}) : scan.scopeHashes;\n this.receipts.write(repoRoot, featureName, receipt);\n this.reportActiveHatches(repoRoot);\n this.report(repoRoot, featureName, scan, briefings, opts, singleRoundRepeat, recordedReviewers, config);\n }\n\n /**\n * List every rule that is currently switched off in webpieces.config.json. NON-BLOCKING and printed\n * before the instruction block, because it is context for the review rather than a step in it.\n *\n * A hatch is the one config change that makes the build QUIETER, so no gate, reviewer or red check\n * will ever mention it — which is how a repo ends up with rules off for weeks that nobody chose to\n * leave off. This is the only place in the flow that says so out loud.\n */\n private reportActiveHatches(repoRoot: string): void {\n const hatches: ActiveHatch[] = this.activeHatchReport.scan(repoRoot);\n process.stdout.write(this.activeHatchReport.render(hatches));\n }\n\n /**\n * Validate + commit + finalize a conflict resolution, if one is in flight. MOVED here from\n * `wp-finish-upsert-pr` so that exactly one command owns merge finalization — two owners is the drift\n * failure `PrContextWriter`'s own docstring records having already happened once in this codebase.\n *\n * MergeEnd's three checks are what \"did the AI do the 3-point merge right?\" means concretely: no\n * conflict markers left in the scoped files, `git diff --diff-filter=U` empty, and a non-empty\n * merge-explanation.md beside every conflicted file.\n *\n * Returns true when a merge was finalized OR there was none to finalize; it throws rather than returning\n * false when validation fails, so the receipt can never record an unvalidated merge as validated.\n */\n private async finalizeAnyInProgressMerge(repoRoot: string): Promise<boolean> {\n const home = this.mergeState.mergeDirFor(repoRoot, this.aiBranchName.getFeatureName());\n const activeDir = this.mergeState.findActiveMergeRunDir(home);\n const marker = activeDir ? this.mergeState.readMergeMarker(activeDir) : null;\n if (!activeDir || !marker || marker.validated) return true;\n process.stdout.write('\\n' + SEP + '① Validating your 3-point merge\\n' + SEP + '\\n');\n // pushRemote:false — finish still owns the single push.\n await this.mergeEnd.mergeEnd(\n repoRoot, 'wp-review-upsert-pr', activeDir,\n new MergeContext(marker.currentBranch, marker.squashBranch, marker.backupBranch, marker.prNumber),\n new MergeEndOptions(marker.conflictedFiles, false),\n );\n return true;\n }\n\n /**\n * The build gate, run BEFORE any reviewer is briefed. Returns the ISO time it passed, for the receipt —\n * which is what lets `wp-finish-upsert-pr` skip its own gate when HEAD has not moved, so moving the gate\n * earlier did not turn one build into two.\n */\n private async runBuildGate(repoRoot: string): Promise<string> {\n await this.buildAffected.runBuildGate(repoRoot, new BuildGateOptions(\n '🛠️ Build gate',\n 'pnpm wp-review-upsert-pr',\n 'Build failed — NO reviewer was briefed and no diff was extracted. Fix it, then re-run.',\n REVIEW_STAGE,\n ));\n // Repo-wide: the build must not have left anything uncommitted AND unstaged. Runs HERE, not in\n // finish, because this is the stage that ran buildCommand and is therefore holding the dirty\n // tree at the exact moment the question is answerable. Replaces the per-project\n // validate-di-graph-unchanged nx target — see BuildArtifactGate for why that one had to go.\n this.buildArtifactGate.assertBuildLeftNothingUncommitted(repoRoot);\n return new Date().toISOString();\n }\n\n /**\n * Extract the diff once, then write one instructions file per reviewer.\n *\n * The changed-file set and the basis both come off the SCAN rather than being recomputed, so the diff a\n * reviewer reads covers exactly the files its checklist matched against.\n */\n private briefReviewers(repoRoot: string, featureName: string, scan: ChecklistScan, config: PrGateConfig): ReviewerBriefing[] {\n if (scan.basis.unresolved) return [];\n const manifest = this.materializer.materialize(\n repoRoot, featureName, scan.basis, scan.changedFiles, config.reviewDiffExclude);\n const diffDir = this.materializer.diffDirFor(repoRoot, featureName);\n // Write pr-context.json ONCE, here — after materializing, so `diffDir` is populated on the first\n // write. The scan deliberately did not write it (ChecklistScanOptions.contextStage === ''); it used\n // to, which meant this command wrote the same file twice, the first time with an empty diffDir.\n // `scan.changedFiles` is passed through so the context is not recomputed from a second git call.\n scan.context = this.prContextWriter.ensure(\n repoRoot, featureName, scan.basis, 'stage2-review', scan.changedFiles, diffDir);\n // ONLY the checklists still owed a verdict (issue #863). A green or yellow whose in-scope diff is\n // unchanged since it was submitted CARRIES — the scan left it in `reviewed` — so briefing it again\n // would pay a reviewer to re-read code it already judged. Red, stale and never-run are briefed.\n const reviewedIds = new Set(scan.reviewed.map((r: RequiredChecklist): string => r.id));\n const owed = scan.applicable.filter((r: RequiredChecklist): boolean => !reviewedIds.has(r.id));\n const briefings = this.briefingBuilder.build(repoRoot, scan, owed, manifest, diffDir, config);\n const dir = this.reviewerInstructions.instructionsDirFor(repoRoot, featureName);\n fs.rmSync(dir, { recursive: true, force: true }); // stale instructions read as current are worse than none\n fs.mkdirSync(dir, { recursive: true });\n for (const b of briefings) {\n fs.writeFileSync(this.reviewerInstructions.pathFor(repoRoot, featureName, b.checklistId),\n this.reviewerInstructions.render(b));\n }\n return briefings;\n }\n\n /**\n * What the AI must do next — rendered by `ReviewReport`, which owns the ordering.\n *\n * The rendering moved OUT of this command so the ordering could be asserted on as a string. It had a\n * real bug: the zero-checklist notice signed off with \"Carry on and run: pnpm wp-finish-upsert-pr\"\n * while the block right beneath it said to write review.json first. An agent that reads top to bottom\n * obeyed the first line and posted a PR with no review at all.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private report(\n repoRoot: string, featureName: string, scan: ChecklistScan, briefings: readonly ReviewerBriefing[],\n opts: ReviewUpsertPrOptions, singleRoundRepeat: boolean, singleRoundReviewers: readonly string[], config: PrGateConfig,\n ): void {\n const input = new ReviewReportInput(repoRoot, featureName, scan.reviewPath);\n input.definedCount = scan.defined.length;\n input.applicableCount = scan.applicable.length;\n input.reviewed = scan.reviewed.slice();\n input.formatErrors = scan.formatErrors.slice();\n input.briefings = briefings.slice();\n input.refused = this.refusals(scan);\n input.skipOptional = opts.skipOptional;\n input.reviewer = config.reviewer;\n // Straight off the SCAN — the one place `experimental.turnOffAllReviewers` is read. This command\n // deliberately does NOT consult the home config itself: a second read is a second answer, and the\n // command that lists and the command that blocks would be free to disagree about whether a branch\n // was reviewed. See ChecklistScanner.\n input.reviewersSuppressed = scan.reviewersDisabled;\n input.suppressed = scan.suppressed.slice();\n input.singleRoundReview = scan.singleRoundReview;\n input.singleRoundRepeat = singleRoundRepeat;\n input.singleRoundReviewers = singleRoundReviewers.slice();\n input.standings = scan.standings.slice();\n // `say`: this block IS the next action — which reviewers to spawn, where review.json goes, and\n // the command after that. Capturing it into the log would leave the terminal with a pointer and\n // no instruction, which is the one thing this stage may never do.\n this.stageConsole.say(this.reviewReport.render(input));\n }\n\n /**\n * The applicable checklists that ALREADY ANSWERED and refused, each with its refusal rendered by the ONE\n * renderer `wp-finish-upsert-pr` also uses.\n *\n * Stage ② had the identical defect finish did: a refused checklist has no passing verdict, so it is not\n * in `scan.reviewed`, so it was printed as an ordinary owed reviewer and re-instructed word for word —\n * and an agent that obeys spawns it against unchanged code, gets the same refusal, and loops one stage\n * earlier than the loop that was reported.\n *\n * NO archive path is passed, deliberately, and this stage moves nothing. Retiring a verdict is finish's\n * act on the refusal it is actually enforcing; doing it here would delete the live verdict of a branch\n * that has not even been asked to finish yet, and `refusalError`'s un-archived wording — \"fix it, then\n * re-run\" — is only correct while that verdict file is still there, which here it is.\n *\n * The review path IS passed, because the ship-anyway route the refusal prints is a command that writes\n * `override-<id>.json` beside it. That command is as correct at this stage as at finish: the override\n * is a separate file with its own writer, so nothing about it depends on the verdict having been moved.\n */\n private refusals(scan: ChecklistScan): RefusedReviewer[] {\n const refused = this.reviewJsonService.refusedChecklists(scan.applicable, scan.results);\n return refused.map((req: RequiredChecklist): RefusedReviewer => new RefusedReviewer(\n req.id,\n this.reviewJsonService.refusalError(\n req, this.reviewJsonService.resolveVerdict(req, scan.results), scan.reviewPath)));\n }\n}\n"]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { RepoRootFinder } from '@webpieces/rules-config';
|
|
2
|
+
import { AiBranchName } from '../workflow/git-readAiBranchName';
|
|
3
|
+
import { ReviewStageReceiptService } from '../workflow/review-stage-receipt';
|
|
4
|
+
import { ReviewerIdentityResolver } from '../workflow/reviewer-identity';
|
|
5
|
+
import { VerdictProvenanceService } from '../workflow/verdict-provenance';
|
|
6
|
+
/** What `wp-write-review` was asked to do. Data-only. */
|
|
7
|
+
export declare class WriteReviewOptions {
|
|
8
|
+
checklistId: string;
|
|
9
|
+
json: string;
|
|
10
|
+
cwd: string;
|
|
11
|
+
constructor(checklistId: string, json: string, cwd: string);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* `wp-write-review` — the ONE way any reviewer, Claude or Codex, submits a checklist verdict (issue #863).
|
|
15
|
+
*
|
|
16
|
+
* Before it existed a verdict was "a file with the right shape at the right path", and that is exactly what
|
|
17
|
+
* a Codex coordinator produced on two merged PRs: the shared-tree guard blocked its reviewer's write, the
|
|
18
|
+
* guard's own cure said to hand the edit to the coordinator, the coordinator wrote all five verdicts, and
|
|
19
|
+
* `wp-finish-upsert-pr` accepted them. Now:
|
|
20
|
+
* 1. the caller is identified by the harness (ReviewerIdentityResolver) and the COORDINATOR is refused;
|
|
21
|
+
* 2. the checklist must be one stage ② briefed this round (its receipt), so a carried verdict cannot be
|
|
22
|
+
* overwritten and a checklist that does not apply cannot be invented;
|
|
23
|
+
* 3. the verdict is validated strictly — the five fields, nothing else;
|
|
24
|
+
* 4. it is written WITH `review-<id>.provenance.json`: who, which commit, which in-scope diff, and a hash
|
|
25
|
+
* of the verdict. `wp-finish-upsert-pr` rejects a verdict without one, or one edited since.
|
|
26
|
+
*
|
|
27
|
+
* `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.
|
|
28
|
+
*/
|
|
29
|
+
export declare class WriteReviewCommand {
|
|
30
|
+
private readonly repoRootFinder;
|
|
31
|
+
private readonly aiBranchName;
|
|
32
|
+
private readonly receipts;
|
|
33
|
+
private readonly identity;
|
|
34
|
+
private readonly provenance;
|
|
35
|
+
constructor(repoRootFinder: RepoRootFinder, aiBranchName: AiBranchName, receipts: ReviewStageReceiptService, identity: ReviewerIdentityResolver, provenance: VerdictProvenanceService);
|
|
36
|
+
run(opts: WriteReviewOptions): Promise<void>;
|
|
37
|
+
/** The stage-② receipt, provided it briefed THIS checklist this round. */
|
|
38
|
+
private briefedReceipt;
|
|
39
|
+
/** Strict: an object with exactly the verdict's five fields, every one a string, status one of three. */
|
|
40
|
+
private parse;
|
|
41
|
+
private text;
|
|
42
|
+
private parseObject;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Reads the verdict JSON for the composition root: `--file <path>`, else stdin. Separate from the command
|
|
46
|
+
* so the command stays a function of its inputs.
|
|
47
|
+
*/
|
|
48
|
+
export declare class WriteReviewInput {
|
|
49
|
+
read(filePath: string): string;
|
|
50
|
+
}
|