@webpieces/pr-gate 0.4.822 → 0.4.824
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -3
- package/src/dashboard/checklist-comment-renderer.js +6 -4
- package/src/dashboard/checklist-comment-renderer.js.map +1 -1
- package/src/dashboard/dashboard.js +6 -1
- package/src/dashboard/dashboard.js.map +1 -1
- package/src/index.d.ts +1 -1
- package/src/index.js +1 -1
- package/src/index.js.map +1 -1
- package/src/scripts/commands/build-command.d.ts +3 -0
- package/src/scripts/commands/build-command.js +29 -17
- package/src/scripts/commands/build-command.js.map +1 -1
- package/src/scripts/commands/check-pr-command.d.ts +10 -3
- package/src/scripts/commands/check-pr-command.js +31 -10
- package/src/scripts/commands/check-pr-command.js.map +1 -1
- package/src/scripts/commands/finish-upsert-pr-command.d.ts +4 -1
- package/src/scripts/commands/finish-upsert-pr-command.js +26 -5
- package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/human-post-pr-command.d.ts +52 -0
- package/src/scripts/commands/human-post-pr-command.js +260 -0
- package/src/scripts/commands/human-post-pr-command.js.map +1 -0
- package/src/scripts/commands/review-upsert-pr-command.d.ts +3 -1
- package/src/scripts/commands/review-upsert-pr-command.js +40 -23
- package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/write-review-command.d.ts +3 -1
- package/src/scripts/commands/write-review-command.js +9 -3
- package/src/scripts/commands/write-review-command.js.map +1 -1
- package/src/scripts/commands/write-review-fixes-command.d.ts +21 -0
- package/src/scripts/commands/write-review-fixes-command.js +68 -0
- package/src/scripts/commands/write-review-fixes-command.js.map +1 -0
- package/src/scripts/pr-gate-app.d.ts +9 -1
- package/src/scripts/pr-gate-app.js +18 -1
- package/src/scripts/pr-gate-app.js.map +1 -1
- package/src/scripts/workflow/build-affected.d.ts +3 -0
- package/src/scripts/workflow/build-affected.js +16 -3
- package/src/scripts/workflow/build-affected.js.map +1 -1
- package/src/scripts/workflow/build-gate-log.d.ts +4 -1
- package/src/scripts/workflow/build-gate-log.js +20 -5
- package/src/scripts/workflow/build-gate-log.js.map +1 -1
- package/src/scripts/workflow/build-log-follower.d.ts +13 -0
- package/src/scripts/workflow/build-log-follower.js +48 -0
- package/src/scripts/workflow/build-log-follower.js.map +1 -0
- package/src/scripts/workflow/checklist-scanner.d.ts +1 -3
- package/src/scripts/workflow/checklist-scanner.js +6 -9
- 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 +20 -7
- package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
- package/src/scripts/workflow/push-dev-state.js +30 -17
- package/src/scripts/workflow/push-dev-state.js.map +1 -1
- package/src/scripts/workflow/repo-config-testkit.js +2 -0
- package/src/scripts/workflow/repo-config-testkit.js.map +1 -1
- package/src/scripts/workflow/review-report.d.ts +7 -4
- package/src/scripts/workflow/review-report.js +44 -24
- package/src/scripts/workflow/review-report.js.map +1 -1
- package/src/scripts/workflow/review-round-state.d.ts +58 -0
- package/src/scripts/workflow/review-round-state.js +300 -0
- package/src/scripts/workflow/review-round-state.js.map +1 -0
- package/src/scripts/workflow/review-stage-receipt.d.ts +6 -0
- package/src/scripts/workflow/review-stage-receipt.js +13 -0
- package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
- package/src/scripts/workflow/reviewer-verdict-gate.js +6 -24
- package/src/scripts/workflow/reviewer-verdict-gate.js.map +1 -1
- package/src/scripts/workflow/verdict-provenance.d.ts +3 -8
- package/src/scripts/workflow/verdict-provenance.js +7 -17
- package/src/scripts/workflow/verdict-provenance.js.map +1 -1
- package/src/scripts/wp-human-post-pr.d.ts +2 -0
- package/src/scripts/wp-human-post-pr.js +15 -0
- package/src/scripts/wp-human-post-pr.js.map +1 -0
- package/src/scripts/wp-write-review-fixes.d.ts +2 -0
- package/src/scripts/wp-write-review-fixes.js +16 -0
- package/src/scripts/wp-write-review-fixes.js.map +1 -0
- package/src/scripts/workflow/git-validateUpToDate.d.ts +0 -1
- package/src/scripts/workflow/git-validateUpToDate.js +0 -70
- package/src/scripts/workflow/git-validateUpToDate.js.map +0 -1
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ReviewRoundStateService = exports.ReviewRemediation = exports.RemediationResponse = exports.ReviewRoundPlan = exports.ROUND_ACTION_FINISH = exports.ROUND_ACTION_RECORD = exports.ROUND_ACTION_FIX = exports.ROUND_ACTION_RESUME = exports.ROUND_ACTION_REVIEW = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const fs = tslib_1.__importStar(require("fs"));
|
|
6
|
+
const path = tslib_1.__importStar(require("path"));
|
|
7
|
+
const child_process_1 = require("child_process");
|
|
8
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
9
|
+
const inversify_1 = require("inversify");
|
|
10
|
+
const verdict_provenance_1 = require("./verdict-provenance");
|
|
11
|
+
const diff_basis_1 = require("./diff-basis");
|
|
12
|
+
exports.ROUND_ACTION_REVIEW = 'review';
|
|
13
|
+
exports.ROUND_ACTION_RESUME = 'resume';
|
|
14
|
+
exports.ROUND_ACTION_FIX = 'fix';
|
|
15
|
+
exports.ROUND_ACTION_RECORD = 'record';
|
|
16
|
+
exports.ROUND_ACTION_FINISH = 'finish';
|
|
17
|
+
class ReviewRoundPlan {
|
|
18
|
+
action;
|
|
19
|
+
round;
|
|
20
|
+
maxRounds;
|
|
21
|
+
basis;
|
|
22
|
+
changedFiles;
|
|
23
|
+
redChecklistIds;
|
|
24
|
+
constructor(action, round, maxRounds, basis, changedFiles = [], redChecklistIds = []) {
|
|
25
|
+
this.action = action;
|
|
26
|
+
this.round = round;
|
|
27
|
+
this.maxRounds = maxRounds;
|
|
28
|
+
this.basis = basis;
|
|
29
|
+
this.changedFiles = changedFiles;
|
|
30
|
+
this.redChecklistIds = redChecklistIds;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.ReviewRoundPlan = ReviewRoundPlan;
|
|
34
|
+
class RemediationResponse {
|
|
35
|
+
checklistId;
|
|
36
|
+
resolution;
|
|
37
|
+
files;
|
|
38
|
+
constructor(checklistId, resolution, files) {
|
|
39
|
+
this.checklistId = checklistId;
|
|
40
|
+
this.resolution = resolution;
|
|
41
|
+
this.files = files;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
exports.RemediationResponse = RemediationResponse;
|
|
45
|
+
class ReviewRemediation {
|
|
46
|
+
agent;
|
|
47
|
+
model;
|
|
48
|
+
fromHead;
|
|
49
|
+
toHead;
|
|
50
|
+
responses;
|
|
51
|
+
writtenAt;
|
|
52
|
+
constructor(agent, model, fromHead, toHead, responses) {
|
|
53
|
+
this.agent = agent;
|
|
54
|
+
this.model = model;
|
|
55
|
+
this.fromHead = fromHead;
|
|
56
|
+
this.toHead = toHead;
|
|
57
|
+
this.responses = responses;
|
|
58
|
+
this.writtenAt = new Date().toISOString();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
exports.ReviewRemediation = ReviewRemediation;
|
|
62
|
+
/** Immutable per-round verdict history plus the author-remediation records between rounds. */
|
|
63
|
+
let ReviewRoundStateService = class ReviewRoundStateService {
|
|
64
|
+
reviewJson;
|
|
65
|
+
provenance;
|
|
66
|
+
atomicFile;
|
|
67
|
+
constructor(reviewJson, provenance, atomicFile) {
|
|
68
|
+
this.reviewJson = reviewJson;
|
|
69
|
+
this.provenance = provenance;
|
|
70
|
+
this.atomicFile = atomicFile;
|
|
71
|
+
}
|
|
72
|
+
roundDir(summaryPath, round) {
|
|
73
|
+
return path.join(path.dirname(summaryPath), 'rounds', String(round));
|
|
74
|
+
}
|
|
75
|
+
archiveVerdict(summaryPath, checklistId, round) {
|
|
76
|
+
const dir = this.roundDir(summaryPath, round);
|
|
77
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
78
|
+
fs.copyFileSync(this.reviewJson.checklistResultPath(summaryPath, checklistId), path.join(dir, `review-${checklistId}.json`));
|
|
79
|
+
fs.copyFileSync(this.provenance.provenancePath(summaryPath, checklistId), path.join(dir, `review-${checklistId}.provenance.json`));
|
|
80
|
+
}
|
|
81
|
+
roundComplete(summaryPath, receipt) {
|
|
82
|
+
if (receipt.round < 1 || receipt.reviewersBriefed.length === 0)
|
|
83
|
+
return false;
|
|
84
|
+
return receipt.reviewersBriefed.every((id) => fs.existsSync(path.join(this.roundDir(summaryPath, receipt.round), `review-${id}.json`)));
|
|
85
|
+
}
|
|
86
|
+
redChecklistIds(summaryPath, receipt) {
|
|
87
|
+
if (!this.roundComplete(summaryPath, receipt))
|
|
88
|
+
return [];
|
|
89
|
+
return receipt.reviewersBriefed.filter((id) => {
|
|
90
|
+
const raw = this.readObject(path.join(this.roundDir(summaryPath, receipt.round), `review-${id}.json`));
|
|
91
|
+
return raw !== null && raw['status'] === rules_config_1.VERDICT_RED;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
remediationPath(summaryPath, round) {
|
|
95
|
+
return path.join(this.roundDir(summaryPath, round), 'review-fixes.json');
|
|
96
|
+
}
|
|
97
|
+
plan(repoRoot, summaryPath, receipt, maxRounds, fullBasis) {
|
|
98
|
+
if (receipt === null || receipt.round < 1) {
|
|
99
|
+
return new ReviewRoundPlan(exports.ROUND_ACTION_REVIEW, 1, maxRounds, fullBasis);
|
|
100
|
+
}
|
|
101
|
+
if (!this.roundComplete(summaryPath, receipt)) {
|
|
102
|
+
if (receipt.headSha !== fullBasis.headSha) {
|
|
103
|
+
throw new rules_config_1.InformAiError(`Global reviewer round ${receipt.round} of ${maxRounds} is still active at `
|
|
104
|
+
+ `${receipt.headSha.slice(0, 8)}. Finish that fixed roster before changing the reviewed HEAD.`);
|
|
105
|
+
}
|
|
106
|
+
return new ReviewRoundPlan(exports.ROUND_ACTION_RESUME, receipt.round, maxRounds, fullBasis);
|
|
107
|
+
}
|
|
108
|
+
const reds = this.redChecklistIds(summaryPath, receipt);
|
|
109
|
+
if (reds.length === 0)
|
|
110
|
+
return new ReviewRoundPlan(exports.ROUND_ACTION_FINISH, receipt.round, maxRounds, fullBasis);
|
|
111
|
+
if (receipt.headSha === fullBasis.headSha) {
|
|
112
|
+
return new ReviewRoundPlan(exports.ROUND_ACTION_FIX, receipt.round, maxRounds, fullBasis, [], reds);
|
|
113
|
+
}
|
|
114
|
+
const remediation = this.validRemediation(repoRoot, summaryPath, receipt);
|
|
115
|
+
if (remediation === null) {
|
|
116
|
+
return new ReviewRoundPlan(exports.ROUND_ACTION_RECORD, receipt.round, maxRounds, fullBasis, [], reds);
|
|
117
|
+
}
|
|
118
|
+
if (receipt.round >= maxRounds) {
|
|
119
|
+
return new ReviewRoundPlan(exports.ROUND_ACTION_FINISH, receipt.round, maxRounds, fullBasis, [], reds);
|
|
120
|
+
}
|
|
121
|
+
const basis = new diff_basis_1.DiffBasis(receipt.headSha, fullBasis.headSha, false, [], `git diff ${receipt.headSha} ${fullBasis.headSha}`, `git diff ${receipt.headSha} ${fullBasis.headSha} -- <file>`, fullBasis.hashMainHead);
|
|
122
|
+
const changed = this.git(repoRoot, ['diff', '--name-only', receipt.headSha, fullBasis.headSha])
|
|
123
|
+
.split('\n').filter((f) => f.trim() !== '');
|
|
124
|
+
return new ReviewRoundPlan(exports.ROUND_ACTION_REVIEW, receipt.round + 1, maxRounds, basis, changed, reds);
|
|
125
|
+
}
|
|
126
|
+
writeRemediation(repoRoot, summaryPath, receipt, json) {
|
|
127
|
+
if (!this.roundComplete(summaryPath, receipt)) {
|
|
128
|
+
throw new rules_config_1.InformAiError('wp-write-review-fixes: the active reviewer round is not complete yet.');
|
|
129
|
+
}
|
|
130
|
+
this.assertClean(repoRoot);
|
|
131
|
+
const currentHead = this.git(repoRoot, ['rev-parse', 'HEAD']);
|
|
132
|
+
const reds = this.redChecklistIds(summaryPath, receipt);
|
|
133
|
+
if (reds.length === 0)
|
|
134
|
+
throw new rules_config_1.InformAiError('wp-write-review-fixes: the completed round has no red verdict to remediate.');
|
|
135
|
+
if (currentHead === receipt.headSha || this.git(repoRoot, ['diff', '--name-only', receipt.headSha, currentHead]) === '') {
|
|
136
|
+
throw new rules_config_1.InformAiError('wp-write-review-fixes: remediation must contain a committed, non-empty delta after the reviewed HEAD.');
|
|
137
|
+
}
|
|
138
|
+
const raw = this.parseObject(json, 'wp-write-review-fixes: input must be one JSON object.');
|
|
139
|
+
const agent = this.requiredText(raw, 'agent');
|
|
140
|
+
const model = this.requiredText(raw, 'model');
|
|
141
|
+
const responses = this.responses(raw['responses']);
|
|
142
|
+
const ids = responses.map((r) => r.checklistId);
|
|
143
|
+
const unknown = ids.filter((id) => !reds.includes(id));
|
|
144
|
+
const missing = reds.filter((id) => !ids.includes(id));
|
|
145
|
+
if (unknown.length > 0 || missing.length > 0) {
|
|
146
|
+
throw new rules_config_1.InformAiError(`wp-write-review-fixes: responses must cover exactly the red checklist(s). `
|
|
147
|
+
+ `Unknown: ${unknown.join(', ') || '(none)'}. Missing: ${missing.join(', ') || '(none)'}.`);
|
|
148
|
+
}
|
|
149
|
+
const record = new ReviewRemediation(agent, model, receipt.headSha, currentHead, responses);
|
|
150
|
+
const out = this.remediationPath(summaryPath, receipt.round);
|
|
151
|
+
this.atomicFile.writeJsonAtomic(out, record);
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
validRemediation(repoRoot, summaryPath, receipt) {
|
|
155
|
+
const raw = this.readObject(this.remediationPath(summaryPath, receipt.round));
|
|
156
|
+
if (raw === null)
|
|
157
|
+
return null;
|
|
158
|
+
const currentHead = this.git(repoRoot, ['rev-parse', 'HEAD']);
|
|
159
|
+
const responses = this.responsesOrEmpty(raw['responses']);
|
|
160
|
+
const reds = this.redChecklistIds(summaryPath, receipt);
|
|
161
|
+
const ids = responses.map((r) => r.checklistId);
|
|
162
|
+
if (this.text(raw['agent']) === '' || this.text(raw['model']) === ''
|
|
163
|
+
|| raw['fromHead'] !== receipt.headSha || raw['toHead'] !== currentHead
|
|
164
|
+
|| currentHead === receipt.headSha || reds.some((id) => !ids.includes(id))
|
|
165
|
+
|| ids.some((id) => !reds.includes(id)))
|
|
166
|
+
return null;
|
|
167
|
+
return new ReviewRemediation(this.text(raw['agent']), this.text(raw['model']), receipt.headSha, currentHead, responses);
|
|
168
|
+
}
|
|
169
|
+
capRemediations(repoRoot, summaryPath, receipt, maxRounds) {
|
|
170
|
+
const out = {};
|
|
171
|
+
if (receipt === null || receipt.round < maxRounds)
|
|
172
|
+
return out;
|
|
173
|
+
const remediation = this.validRemediation(repoRoot, summaryPath, receipt);
|
|
174
|
+
if (remediation === null)
|
|
175
|
+
return out;
|
|
176
|
+
for (const response of remediation.responses) {
|
|
177
|
+
out[response.checklistId] = `Author-remediated after review cap; NOT re-reviewed. ${response.resolution} `
|
|
178
|
+
+ `(${remediation.fromHead.slice(0, 8)}..${remediation.toHead.slice(0, 8)})`;
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
auditTrail(summaryPath, checklistId, receipt) {
|
|
183
|
+
if (receipt === null || receipt.round < 1)
|
|
184
|
+
return '';
|
|
185
|
+
const lines = [];
|
|
186
|
+
for (let round = 1; round <= receipt.round; round++) {
|
|
187
|
+
const dir = this.roundDir(summaryPath, round);
|
|
188
|
+
const verdict = this.readObject(path.join(dir, `review-${checklistId}.json`));
|
|
189
|
+
const record = this.readObject(path.join(dir, `review-${checklistId}.provenance.json`));
|
|
190
|
+
if (verdict !== null) {
|
|
191
|
+
lines.push(`#### Reviewer round ${round} of ${receipt.maxReviewerRounds}`);
|
|
192
|
+
lines.push(`Reviewed SHA: ${this.text(record?.['headSha']) || '(unknown)'}`);
|
|
193
|
+
lines.push(`Status: ${this.text(verdict['status']).toUpperCase()}`);
|
|
194
|
+
lines.push('', this.text(verdict['output']), '');
|
|
195
|
+
}
|
|
196
|
+
const remediation = this.readObject(this.remediationPath(summaryPath, round));
|
|
197
|
+
if (remediation !== null && Array.isArray(remediation['responses'])) {
|
|
198
|
+
const response = remediation['responses'].find((entry) => typeof entry === 'object' && entry !== null && !Array.isArray(entry)
|
|
199
|
+
&& entry['checklistId'] === checklistId);
|
|
200
|
+
if (typeof response === 'object' && response !== null && !Array.isArray(response)) {
|
|
201
|
+
const raw = response;
|
|
202
|
+
lines.push(`#### Author remediation after round ${round}`);
|
|
203
|
+
lines.push(`Range: ${this.text(remediation['fromHead'])}..${this.text(remediation['toHead'])}`);
|
|
204
|
+
lines.push('', this.text(raw['resolution']), '');
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return lines.join('\n').trim();
|
|
209
|
+
}
|
|
210
|
+
responses(value) {
|
|
211
|
+
const responses = this.responsesOrEmpty(value);
|
|
212
|
+
if (responses.length === 0)
|
|
213
|
+
throw new rules_config_1.InformAiError('wp-write-review-fixes: "responses" must be a non-empty array.');
|
|
214
|
+
return responses;
|
|
215
|
+
}
|
|
216
|
+
responsesOrEmpty(value) {
|
|
217
|
+
if (!Array.isArray(value))
|
|
218
|
+
return [];
|
|
219
|
+
const out = [];
|
|
220
|
+
for (const entry of value) {
|
|
221
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry))
|
|
222
|
+
return [];
|
|
223
|
+
const raw = entry;
|
|
224
|
+
const id = this.text(raw['checklistId']);
|
|
225
|
+
const resolution = this.text(raw['resolution']);
|
|
226
|
+
const files = Array.isArray(raw['files']) ? raw['files'].filter((f) => typeof f === 'string' && f.trim() !== '') : [];
|
|
227
|
+
if (id === '' || resolution === '' || files.length === 0)
|
|
228
|
+
return [];
|
|
229
|
+
out.push(new RemediationResponse(id, resolution, files));
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
requiredText(raw, key) {
|
|
234
|
+
const value = this.text(raw[key]);
|
|
235
|
+
if (value === '')
|
|
236
|
+
throw new rules_config_1.InformAiError(`wp-write-review-fixes: "${key}" must be a non-empty string.`);
|
|
237
|
+
return value;
|
|
238
|
+
}
|
|
239
|
+
text(value) {
|
|
240
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
241
|
+
}
|
|
242
|
+
parseObject(json, message) {
|
|
243
|
+
// webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed author JSON becomes an actionable refusal
|
|
244
|
+
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
245
|
+
try {
|
|
246
|
+
const value = JSON.parse(json);
|
|
247
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value))
|
|
248
|
+
return value;
|
|
249
|
+
// webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
const error = (0, rules_config_1.toError)(err);
|
|
253
|
+
void error;
|
|
254
|
+
}
|
|
255
|
+
throw new rules_config_1.InformAiError(message);
|
|
256
|
+
}
|
|
257
|
+
readObject(file) {
|
|
258
|
+
if (!fs.existsSync(file))
|
|
259
|
+
return null;
|
|
260
|
+
// webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable durable state becomes an actionable refusal
|
|
261
|
+
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
262
|
+
try {
|
|
263
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
264
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value))
|
|
265
|
+
return value;
|
|
266
|
+
throw new rules_config_1.InformAiError(`Review state file must contain one JSON object: ${file}`);
|
|
267
|
+
// webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
const error = (0, rules_config_1.toError)(err);
|
|
271
|
+
if (error instanceof rules_config_1.InformAiError)
|
|
272
|
+
throw error;
|
|
273
|
+
throw new rules_config_1.InformAiError(`Could not read review state file ${file}: ${error.message}`, { cause: error });
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
assertClean(repoRoot) {
|
|
277
|
+
const status = this.git(repoRoot, ['status', '--porcelain', '--untracked-files=all']);
|
|
278
|
+
if (status !== '')
|
|
279
|
+
throw new rules_config_1.InformAiError('wp-write-review-fixes: commit every remediation and leave no staged, unstaged, or untracked files first.');
|
|
280
|
+
}
|
|
281
|
+
git(repoRoot, args) {
|
|
282
|
+
const result = (0, child_process_1.spawnSync)('git', args, { cwd: repoRoot, encoding: 'utf8' });
|
|
283
|
+
if (result.status === 0)
|
|
284
|
+
return (result.stdout ?? '').trim();
|
|
285
|
+
const command = `git ${args.join(' ')}`;
|
|
286
|
+
const detail = (result.stderr ?? '').trim() || result.error?.message || `exit ${result.status ?? 'unknown'}`;
|
|
287
|
+
const message = `Review-round Git command failed: ${command}\n${detail}`;
|
|
288
|
+
if (result.error !== undefined)
|
|
289
|
+
throw new rules_config_1.InformAiError(message, { cause: result.error });
|
|
290
|
+
throw new rules_config_1.InformAiError(message);
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
exports.ReviewRoundStateService = ReviewRoundStateService;
|
|
294
|
+
exports.ReviewRoundStateService = ReviewRoundStateService = tslib_1.__decorate([
|
|
295
|
+
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
296
|
+
tslib_1.__metadata("design:paramtypes", [rules_config_1.ReviewJsonService,
|
|
297
|
+
verdict_provenance_1.VerdictProvenanceService,
|
|
298
|
+
rules_config_1.AtomicFile])
|
|
299
|
+
], ReviewRoundStateService);
|
|
300
|
+
//# sourceMappingURL=review-round-state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"review-round-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-round-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,iDAA0C;AAC1C,0DAA6G;AAC7G,yCAA2D;AAE3D,6DAAgE;AAChE,6CAAyC;AAM5B,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC/B,QAAA,mBAA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,4BAAa,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;QAC1F,MAAM,IAAI,4BAAa,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACJ,CAAA;AAlOY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,gCAAiB;QACjB,6CAAwB;QACxB,yBAAU;GAJlC,uBAAuB,CAkOnC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { spawnSync } from 'child_process';\nimport { AtomicFile, InformAiError, ReviewJsonService, VERDICT_RED, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ReviewStageReceipt } from './review-stage-receipt';\nimport { VerdictProvenanceService } from './verdict-provenance';\nimport { DiffBasis } from './diff-basis';\n\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonValue[] | JsonObject;\ninterface JsonObject { [key: string]: JsonValue }\n\nexport const ROUND_ACTION_REVIEW = 'review';\nexport const ROUND_ACTION_RESUME = 'resume';\nexport const ROUND_ACTION_FIX = 'fix';\nexport const ROUND_ACTION_RECORD = 'record';\nexport const ROUND_ACTION_FINISH = 'finish';\n\nexport class ReviewRoundPlan {\n action: string;\n round: number;\n maxRounds: number;\n basis: DiffBasis;\n changedFiles: string[];\n redChecklistIds: string[];\n\n constructor(action: string, round: number, maxRounds: number, basis: DiffBasis, changedFiles: string[] = [], redChecklistIds: string[] = []) {\n this.action = action;\n this.round = round;\n this.maxRounds = maxRounds;\n this.basis = basis;\n this.changedFiles = changedFiles;\n this.redChecklistIds = redChecklistIds;\n }\n}\n\nexport class RemediationResponse {\n checklistId: string;\n resolution: string;\n files: string[];\n\n constructor(checklistId: string, resolution: string, files: string[]) {\n this.checklistId = checklistId;\n this.resolution = resolution;\n this.files = files;\n }\n}\n\nexport class ReviewRemediation {\n agent: string;\n model: string;\n fromHead: string;\n toHead: string;\n responses: RemediationResponse[];\n writtenAt: string;\n\n constructor(agent: string, model: string, fromHead: string, toHead: string, responses: RemediationResponse[]) {\n this.agent = agent;\n this.model = model;\n this.fromHead = fromHead;\n this.toHead = toHead;\n this.responses = responses;\n this.writtenAt = new Date().toISOString();\n }\n}\n\n/** Immutable per-round verdict history plus the author-remediation records between rounds. */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewRoundStateService {\n constructor(\n private readonly reviewJson: ReviewJsonService,\n private readonly provenance: VerdictProvenanceService,\n private readonly atomicFile: AtomicFile,\n ) {}\n\n roundDir(summaryPath: string, round: number): string {\n return path.join(path.dirname(summaryPath), 'rounds', String(round));\n }\n\n archiveVerdict(summaryPath: string, checklistId: string, round: number): void {\n const dir = this.roundDir(summaryPath, round);\n fs.mkdirSync(dir, { recursive: true });\n fs.copyFileSync(this.reviewJson.checklistResultPath(summaryPath, checklistId), path.join(dir, `review-${checklistId}.json`));\n fs.copyFileSync(this.provenance.provenancePath(summaryPath, checklistId), path.join(dir, `review-${checklistId}.provenance.json`));\n }\n\n roundComplete(summaryPath: string, receipt: ReviewStageReceipt): boolean {\n if (receipt.round < 1 || receipt.reviewersBriefed.length === 0) return false;\n return receipt.reviewersBriefed.every((id: string): boolean =>\n fs.existsSync(path.join(this.roundDir(summaryPath, receipt.round), `review-${id}.json`)));\n }\n\n redChecklistIds(summaryPath: string, receipt: ReviewStageReceipt): string[] {\n if (!this.roundComplete(summaryPath, receipt)) return [];\n return receipt.reviewersBriefed.filter((id: string): boolean => {\n const raw = this.readObject(path.join(this.roundDir(summaryPath, receipt.round), `review-${id}.json`));\n return raw !== null && raw['status'] === VERDICT_RED;\n });\n }\n\n remediationPath(summaryPath: string, round: number): string {\n return path.join(this.roundDir(summaryPath, round), 'review-fixes.json');\n }\n\n plan(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt | null, maxRounds: number, fullBasis: DiffBasis): ReviewRoundPlan {\n if (receipt === null || receipt.round < 1) {\n return new ReviewRoundPlan(ROUND_ACTION_REVIEW, 1, maxRounds, fullBasis);\n }\n if (!this.roundComplete(summaryPath, receipt)) {\n if (receipt.headSha !== fullBasis.headSha) {\n throw new InformAiError(`Global reviewer round ${receipt.round} of ${maxRounds} is still active at `\n + `${receipt.headSha.slice(0, 8)}. Finish that fixed roster before changing the reviewed HEAD.`);\n }\n return new ReviewRoundPlan(ROUND_ACTION_RESUME, receipt.round, maxRounds, fullBasis);\n }\n const reds = this.redChecklistIds(summaryPath, receipt);\n if (reds.length === 0) return new ReviewRoundPlan(ROUND_ACTION_FINISH, receipt.round, maxRounds, fullBasis);\n if (receipt.headSha === fullBasis.headSha) {\n return new ReviewRoundPlan(ROUND_ACTION_FIX, receipt.round, maxRounds, fullBasis, [], reds);\n }\n const remediation = this.validRemediation(repoRoot, summaryPath, receipt);\n if (remediation === null) {\n return new ReviewRoundPlan(ROUND_ACTION_RECORD, receipt.round, maxRounds, fullBasis, [], reds);\n }\n if (receipt.round >= maxRounds) {\n return new ReviewRoundPlan(ROUND_ACTION_FINISH, receipt.round, maxRounds, fullBasis, [], reds);\n }\n const basis = new DiffBasis(\n receipt.headSha, fullBasis.headSha, false, [],\n `git diff ${receipt.headSha} ${fullBasis.headSha}`,\n `git diff ${receipt.headSha} ${fullBasis.headSha} -- <file>`, fullBasis.hashMainHead);\n const changed = this.git(repoRoot, ['diff', '--name-only', receipt.headSha, fullBasis.headSha])\n .split('\\n').filter((f: string): boolean => f.trim() !== '');\n return new ReviewRoundPlan(ROUND_ACTION_REVIEW, receipt.round + 1, maxRounds, basis, changed, reds);\n }\n\n writeRemediation(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt, json: string): string {\n if (!this.roundComplete(summaryPath, receipt)) {\n throw new InformAiError('wp-write-review-fixes: the active reviewer round is not complete yet.');\n }\n this.assertClean(repoRoot);\n const currentHead = this.git(repoRoot, ['rev-parse', 'HEAD']);\n const reds = this.redChecklistIds(summaryPath, receipt);\n if (reds.length === 0) throw new InformAiError('wp-write-review-fixes: the completed round has no red verdict to remediate.');\n if (currentHead === receipt.headSha || this.git(repoRoot, ['diff', '--name-only', receipt.headSha, currentHead]) === '') {\n throw new InformAiError('wp-write-review-fixes: remediation must contain a committed, non-empty delta after the reviewed HEAD.');\n }\n const raw = this.parseObject(json, 'wp-write-review-fixes: input must be one JSON object.');\n const agent = this.requiredText(raw, 'agent');\n const model = this.requiredText(raw, 'model');\n const responses = this.responses(raw['responses']);\n const ids = responses.map((r: RemediationResponse): string => r.checklistId);\n const unknown = ids.filter((id: string): boolean => !reds.includes(id));\n const missing = reds.filter((id: string): boolean => !ids.includes(id));\n if (unknown.length > 0 || missing.length > 0) {\n throw new InformAiError(`wp-write-review-fixes: responses must cover exactly the red checklist(s). `\n + `Unknown: ${unknown.join(', ') || '(none)'}. Missing: ${missing.join(', ') || '(none)'}.`);\n }\n const record = new ReviewRemediation(agent, model, receipt.headSha, currentHead, responses);\n const out = this.remediationPath(summaryPath, receipt.round);\n this.atomicFile.writeJsonAtomic(out, record);\n return out;\n }\n\n validRemediation(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt): ReviewRemediation | null {\n const raw = this.readObject(this.remediationPath(summaryPath, receipt.round));\n if (raw === null) return null;\n const currentHead = this.git(repoRoot, ['rev-parse', 'HEAD']);\n const responses = this.responsesOrEmpty(raw['responses']);\n const reds = this.redChecklistIds(summaryPath, receipt);\n const ids = responses.map((r: RemediationResponse): string => r.checklistId);\n if (this.text(raw['agent']) === '' || this.text(raw['model']) === ''\n || raw['fromHead'] !== receipt.headSha || raw['toHead'] !== currentHead\n || currentHead === receipt.headSha || reds.some((id: string): boolean => !ids.includes(id))\n || ids.some((id: string): boolean => !reds.includes(id))) return null;\n return new ReviewRemediation(this.text(raw['agent']), this.text(raw['model']), receipt.headSha, currentHead, responses);\n }\n\n capRemediations(repoRoot: string, summaryPath: string, receipt: ReviewStageReceipt | null, maxRounds: number): Record<string, string> {\n const out: Record<string, string> = {};\n if (receipt === null || receipt.round < maxRounds) return out;\n const remediation = this.validRemediation(repoRoot, summaryPath, receipt);\n if (remediation === null) return out;\n for (const response of remediation.responses) {\n out[response.checklistId] = `Author-remediated after review cap; NOT re-reviewed. ${response.resolution} `\n + `(${remediation.fromHead.slice(0, 8)}..${remediation.toHead.slice(0, 8)})`;\n }\n return out;\n }\n\n auditTrail(summaryPath: string, checklistId: string, receipt: ReviewStageReceipt | null): string {\n if (receipt === null || receipt.round < 1) return '';\n const lines: string[] = [];\n for (let round = 1; round <= receipt.round; round++) {\n const dir = this.roundDir(summaryPath, round);\n const verdict = this.readObject(path.join(dir, `review-${checklistId}.json`));\n const record = this.readObject(path.join(dir, `review-${checklistId}.provenance.json`));\n if (verdict !== null) {\n lines.push(`#### Reviewer round ${round} of ${receipt.maxReviewerRounds}`);\n lines.push(`Reviewed SHA: ${this.text(record?.['headSha']) || '(unknown)'}`);\n lines.push(`Status: ${this.text(verdict['status']).toUpperCase()}`);\n lines.push('', this.text(verdict['output']), '');\n }\n const remediation = this.readObject(this.remediationPath(summaryPath, round));\n if (remediation !== null && Array.isArray(remediation['responses'])) {\n const response = (remediation['responses'] as JsonValue[]).find((entry: JsonValue): boolean =>\n typeof entry === 'object' && entry !== null && !Array.isArray(entry)\n && (entry as JsonObject)['checklistId'] === checklistId);\n if (typeof response === 'object' && response !== null && !Array.isArray(response)) {\n const raw = response as JsonObject;\n lines.push(`#### Author remediation after round ${round}`);\n lines.push(`Range: ${this.text(remediation['fromHead'])}..${this.text(remediation['toHead'])}`);\n lines.push('', this.text(raw['resolution']), '');\n }\n }\n }\n return lines.join('\\n').trim();\n }\n\n private responses(value: JsonValue | undefined): RemediationResponse[] {\n const responses = this.responsesOrEmpty(value);\n if (responses.length === 0) throw new InformAiError('wp-write-review-fixes: \"responses\" must be a non-empty array.');\n return responses;\n }\n\n private responsesOrEmpty(value: JsonValue | undefined): RemediationResponse[] {\n if (!Array.isArray(value)) return [];\n const out: RemediationResponse[] = [];\n for (const entry of value) {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return [];\n const raw = entry as JsonObject;\n const id = this.text(raw['checklistId']);\n const resolution = this.text(raw['resolution']);\n const files = Array.isArray(raw['files']) ? raw['files'].filter((f: JsonValue): f is string => typeof f === 'string' && f.trim() !== '') : [];\n if (id === '' || resolution === '' || files.length === 0) return [];\n out.push(new RemediationResponse(id, resolution, files));\n }\n return out;\n }\n\n private requiredText(raw: JsonObject, key: string): string {\n const value = this.text(raw[key]);\n if (value === '') throw new InformAiError(`wp-write-review-fixes: \"${key}\" must be a non-empty string.`);\n return value;\n }\n\n private text(value: JsonValue | undefined): string {\n return typeof value === 'string' ? value.trim() : '';\n }\n\n private parseObject(json: string, message: string): JsonObject {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: malformed author JSON becomes an actionable refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const value = JSON.parse(json) as JsonValue;\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value;\n // webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n throw new InformAiError(message);\n }\n\n private readObject(file: string): JsonObject | null {\n if (!fs.existsSync(file)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: unreadable durable state becomes an actionable refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const value = JSON.parse(fs.readFileSync(file, 'utf8')) as JsonValue;\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value;\n throw new InformAiError(`Review state file must contain one JSON object: ${file}`);\n // webpieces-disable no-any-unknown -- the language types caught JavaScript values as unknown\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError) throw error;\n throw new InformAiError(`Could not read review state file ${file}: ${error.message}`, { cause: error });\n }\n }\n\n private assertClean(repoRoot: string): void {\n const status = this.git(repoRoot, ['status', '--porcelain', '--untracked-files=all']);\n if (status !== '') throw new InformAiError('wp-write-review-fixes: commit every remediation and leave no staged, unstaged, or untracked files first.');\n }\n\n private git(repoRoot: string, args: string[]): string {\n const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8' });\n if (result.status === 0) return (result.stdout ?? '').trim();\n const command = `git ${args.join(' ')}`;\n const detail = (result.stderr ?? '').trim() || result.error?.message || `exit ${result.status ?? 'unknown'}`;\n const message = `Review-round Git command failed: ${command}\\n${detail}`;\n if (result.error !== undefined) throw new InformAiError(message, { cause: result.error });\n throw new InformAiError(message);\n }\n}\n"]}
|
|
@@ -15,6 +15,12 @@ export declare class ReviewStageReceipt {
|
|
|
15
15
|
* a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.
|
|
16
16
|
*/
|
|
17
17
|
scopeHashes: Record<string, string>;
|
|
18
|
+
/** Global reviewer round, owned by stage ②. Zero means no reviewer round has started. */
|
|
19
|
+
round: number;
|
|
20
|
+
/** Repository-owned cap copied from config so verdict provenance can audit the active budget. */
|
|
21
|
+
maxReviewerRounds: number;
|
|
22
|
+
/** Prior reviewed HEAD for remediation-only rounds; empty for the initial full review. */
|
|
23
|
+
remediationFromHead: string;
|
|
18
24
|
constructor(headSha?: string, mergeValidated?: boolean, buildCommand?: string, buildPassedAt?: string, reviewersBriefed?: string[]);
|
|
19
25
|
}
|
|
20
26
|
/**
|
|
@@ -22,6 +22,12 @@ class ReviewStageReceipt {
|
|
|
22
22
|
* a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.
|
|
23
23
|
*/
|
|
24
24
|
scopeHashes;
|
|
25
|
+
/** Global reviewer round, owned by stage ②. Zero means no reviewer round has started. */
|
|
26
|
+
round;
|
|
27
|
+
/** Repository-owned cap copied from config so verdict provenance can audit the active budget. */
|
|
28
|
+
maxReviewerRounds;
|
|
29
|
+
/** Prior reviewed HEAD for remediation-only rounds; empty for the initial full review. */
|
|
30
|
+
remediationFromHead;
|
|
25
31
|
// eslint-disable-next-line @typescript-eslint/max-params
|
|
26
32
|
constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed = []) {
|
|
27
33
|
this.headSha = headSha;
|
|
@@ -30,6 +36,9 @@ class ReviewStageReceipt {
|
|
|
30
36
|
this.buildPassedAt = buildPassedAt;
|
|
31
37
|
this.reviewersBriefed = reviewersBriefed;
|
|
32
38
|
this.scopeHashes = {};
|
|
39
|
+
this.round = 0;
|
|
40
|
+
this.maxReviewerRounds = 0;
|
|
41
|
+
this.remediationFromHead = '';
|
|
33
42
|
}
|
|
34
43
|
}
|
|
35
44
|
exports.ReviewStageReceipt = ReviewStageReceipt;
|
|
@@ -74,6 +83,10 @@ let ReviewStageReceiptService = class ReviewStageReceiptService {
|
|
|
74
83
|
const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
75
84
|
const receipt = new ReviewStageReceipt(typeof raw['headSha'] === 'string' ? raw['headSha'] : '', raw['mergeValidated'] === true, typeof raw['buildCommand'] === 'string' ? raw['buildCommand'] : '', typeof raw['buildPassedAt'] === 'string' ? raw['buildPassedAt'] : '', Array.isArray(raw['reviewersBriefed']) ? raw['reviewersBriefed'] : []);
|
|
76
85
|
receipt.scopeHashes = this.stringMap(raw['scopeHashes']);
|
|
86
|
+
receipt.round = typeof raw['round'] === 'number' && Number.isInteger(raw['round']) ? raw['round'] : 0;
|
|
87
|
+
receipt.maxReviewerRounds = typeof raw['maxReviewerRounds'] === 'number' && Number.isInteger(raw['maxReviewerRounds'])
|
|
88
|
+
? raw['maxReviewerRounds'] : 0;
|
|
89
|
+
receipt.remediationFromHead = typeof raw['remediationFromHead'] === 'string' ? raw['remediationFromHead'] : '';
|
|
77
90
|
return receipt;
|
|
78
91
|
}
|
|
79
92
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-stage-receipt.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-stage-receipt.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqE;AACrE,yCAA2D;AAE9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OAAO,CAAC;QACnB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,6EAA6E;YACzF,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IAED,wGAAwG;IACxG,WAAW,CAAC,QAAgB,EAAE,WAAmB;QAC7C,MAAM,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;QAClD,OAAO,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACzD,CAAC;IAED,uFAAuF;IAC/E,SAAS,CAAC,KAAc;QAC5B,MAAM,GAAG,GAA2B,EAAE,CAAC;QACvC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,OAAO,GAAG,CAAC;QACpF,4FAA4F;QAC5F,MAAM,GAAG,GAAG,KAAgC,CAAC;QAC7C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACjC,MAAM,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;YACnB,IAAI,OAAO,CAAC,KAAK,QAAQ;gBAAE,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,GAAG,CAAC;IACf,CAAC;CACJ,CAAA;AAzDY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEW,gCAAiB;GADxD,yBAAyB,CAyDrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { ReviewJsonService, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nexport const RECEIPT_FILE = 'review-stage.json';\n\n/**\n * Proof that stage ② (`wp-review-upsert-pr`) actually ran, and on WHICH commit. Data-only (per CLAUDE.md).\n */\nexport class ReviewStageReceipt {\n headSha: string; // the sha the merge was validated and the build was run against\n mergeValidated: boolean; // a 3-point merge was finalized here, or there was none to finalize\n buildCommand: string;\n buildPassedAt: string; // ISO; '' when the gate was skipped (mode OFF / no command)\n reviewersBriefed: string[];\n /**\n * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`\n * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and the next stage ② carries\n * a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.\n */\n scopeHashes: Record<string, string>;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed: string[] = []) {\n this.headSha = headSha;\n this.mergeValidated = mergeValidated;\n this.buildCommand = buildCommand;\n this.buildPassedAt = buildPassedAt;\n this.reviewersBriefed = reviewersBriefed;\n this.scopeHashes = {};\n }\n}\n\n/**\n * Reads/writes the stage-② receipt.\n *\n * WHY a receipt rather than relying on the artifacts that already exist: `wp-finish-upsert-pr` already\n * refuses when a reviewer has no verdict and when summary.json is absent, so a repo WITH checklists is\n * mostly interlocked already. A repo with NO checklists is not — summary.json is the only thing standing\n * between it and a PR, and the AI writes summary.json itself. Nothing stopped it from writing that file and\n * going straight to finish, skipping the merge validation and the build entirely.\n *\n * The receipt also pays for itself in the other direction: because it records the sha the build passed on,\n * finish can SKIP its own build when HEAD has not moved, so adding a gate in the middle did not cost a\n * second full `nx affected` run.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewStageReceiptService {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n receiptPath(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), RECEIPT_FILE);\n }\n\n write(repoRoot: string, featureName: string, receipt: ReviewStageReceipt): string {\n const p = this.receiptPath(repoRoot, featureName);\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(receipt, null, 2) + '\\n');\n return p;\n }\n\n /** The receipt, or null when stage ② never ran (or left something unreadable behind). */\n read(repoRoot: string, featureName: string): ReviewStageReceipt | null {\n const p = this.receiptPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable receipt is treated as absent, which re-runs stage ②\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n const receipt = new ReviewStageReceipt(\n typeof raw['headSha'] === 'string' ? (raw['headSha'] as string) : '',\n raw['mergeValidated'] === true,\n typeof raw['buildCommand'] === 'string' ? (raw['buildCommand'] as string) : '',\n typeof raw['buildPassedAt'] === 'string' ? (raw['buildPassedAt'] as string) : '',\n Array.isArray(raw['reviewersBriefed']) ? (raw['reviewersBriefed'] as string[]) : [],\n );\n receipt.scopeHashes = this.stringMap(raw['scopeHashes']);\n return receipt;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable ⇒ treated as absent, which re-runs stage ② (the safe direction)\n return null;\n }\n }\n\n /** The receipt file's mtime in epoch ms, or 0 when there is none — when stage ② last briefed anyone. */\n writtenAtMs(repoRoot: string, featureName: string): number {\n const p = this.receiptPath(repoRoot, featureName);\n return fs.existsSync(p) ? fs.statSync(p).mtimeMs : 0;\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSON value, narrowed to string→string\n private stringMap(value: unknown): Record<string, string> {\n const out: Record<string, string> = {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return out;\n // webpieces-disable no-any-unknown -- entries of an opaque JSON object, each narrowed below\n const obj = value as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n const v = obj[key];\n if (typeof v === 'string') out[key] = v;\n }\n return out;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"review-stage-receipt.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-stage-receipt.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqE;AACrE,yCAA2D;AAE9C,QAAA,YAAY,GAAG,mBAAmB,CAAC;AAEhD;;GAEG;AACH,MAAa,kBAAkB;IAC3B,OAAO,CAAS,CAAU,gEAAgE;IAC1F,cAAc,CAAU,CAAE,oEAAoE;IAC9F,YAAY,CAAS;IACrB,aAAa,CAAS,CAAI,4DAA4D;IACtF,gBAAgB,CAAW;IAC3B;;;;OAIG;IACH,WAAW,CAAyB;IACpC,yFAAyF;IACzF,KAAK,CAAS;IACd,iGAAiG;IACjG,iBAAiB,CAAS;IAC1B,0FAA0F;IAC1F,mBAAmB,CAAS;IAE5B,yDAAyD;IACzD,YAAY,OAAO,GAAG,EAAE,EAAE,cAAc,GAAG,KAAK,EAAE,YAAY,GAAG,EAAE,EAAE,aAAa,GAAG,EAAE,EAAE,mBAA6B,EAAE;QACpH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC;QACf,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,mBAAmB,GAAG,EAAE,CAAC;IAClC,CAAC;CACJ;AA/BD,gDA+BC;AAED;;;;;;;;;;;;;;GAcG;AAEI,IA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K,CAAC,CAAC,6EAA6E;YACzF,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IAED,wGAAwG;IACxG,WAAW,CAAC,QAAgB,EAAE,WAAmB;QAC7C,MAAM,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;QAClD,OAAO,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACzD,CAAC;IAED,uFAAuF;IAC/E,SAAS,CAAC,KAAc;QAC5B,MAAM,GAAG,GAA2B,EAAE,CAAC;QACvC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,OAAO,GAAG,CAAC;QACpF,4FAA4F;QAC5F,MAAM,GAAG,GAAG,KAAgC,CAAC;QAC7C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACjC,MAAM,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;YACnB,IAAI,OAAO,CAAC,KAAK,QAAQ;gBAAE,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,GAAG,CAAC;IACf,CAAC;CACJ,CAAA;AA7DY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEW,gCAAiB;GADxD,yBAAyB,CA6DrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { ReviewJsonService, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nexport const RECEIPT_FILE = 'review-stage.json';\n\n/**\n * Proof that stage ② (`wp-review-upsert-pr`) actually ran, and on WHICH commit. Data-only (per CLAUDE.md).\n */\nexport class ReviewStageReceipt {\n headSha: string; // the sha the merge was validated and the build was run against\n mergeValidated: boolean; // a 3-point merge was finalized here, or there was none to finalize\n buildCommand: string;\n buildPassedAt: string; // ISO; '' when the gate was skipped (mode OFF / no command)\n reviewersBriefed: string[];\n /**\n * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`\n * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and the next stage ② carries\n * a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.\n */\n scopeHashes: Record<string, string>;\n /** Global reviewer round, owned by stage ②. Zero means no reviewer round has started. */\n round: number;\n /** Repository-owned cap copied from config so verdict provenance can audit the active budget. */\n maxReviewerRounds: number;\n /** Prior reviewed HEAD for remediation-only rounds; empty for the initial full review. */\n remediationFromHead: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed: string[] = []) {\n this.headSha = headSha;\n this.mergeValidated = mergeValidated;\n this.buildCommand = buildCommand;\n this.buildPassedAt = buildPassedAt;\n this.reviewersBriefed = reviewersBriefed;\n this.scopeHashes = {};\n this.round = 0;\n this.maxReviewerRounds = 0;\n this.remediationFromHead = '';\n }\n}\n\n/**\n * Reads/writes the stage-② receipt.\n *\n * WHY a receipt rather than relying on the artifacts that already exist: `wp-finish-upsert-pr` already\n * refuses when a reviewer has no verdict and when summary.json is absent, so a repo WITH checklists is\n * mostly interlocked already. A repo with NO checklists is not — summary.json is the only thing standing\n * between it and a PR, and the AI writes summary.json itself. Nothing stopped it from writing that file and\n * going straight to finish, skipping the merge validation and the build entirely.\n *\n * The receipt also pays for itself in the other direction: because it records the sha the build passed on,\n * finish can SKIP its own build when HEAD has not moved, so adding a gate in the middle did not cost a\n * second full `nx affected` run.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewStageReceiptService {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n receiptPath(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), RECEIPT_FILE);\n }\n\n write(repoRoot: string, featureName: string, receipt: ReviewStageReceipt): string {\n const p = this.receiptPath(repoRoot, featureName);\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(receipt, null, 2) + '\\n');\n return p;\n }\n\n /** The receipt, or null when stage ② never ran (or left something unreadable behind). */\n read(repoRoot: string, featureName: string): ReviewStageReceipt | null {\n const p = this.receiptPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable receipt is treated as absent, which re-runs stage ②\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n const receipt = new ReviewStageReceipt(\n typeof raw['headSha'] === 'string' ? (raw['headSha'] as string) : '',\n raw['mergeValidated'] === true,\n typeof raw['buildCommand'] === 'string' ? (raw['buildCommand'] as string) : '',\n typeof raw['buildPassedAt'] === 'string' ? (raw['buildPassedAt'] as string) : '',\n Array.isArray(raw['reviewersBriefed']) ? (raw['reviewersBriefed'] as string[]) : [],\n );\n receipt.scopeHashes = this.stringMap(raw['scopeHashes']);\n receipt.round = typeof raw['round'] === 'number' && Number.isInteger(raw['round']) ? raw['round'] as number : 0;\n receipt.maxReviewerRounds = typeof raw['maxReviewerRounds'] === 'number' && Number.isInteger(raw['maxReviewerRounds'])\n ? raw['maxReviewerRounds'] as number : 0;\n receipt.remediationFromHead = typeof raw['remediationFromHead'] === 'string' ? raw['remediationFromHead'] as string : '';\n return receipt;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable ⇒ treated as absent, which re-runs stage ② (the safe direction)\n return null;\n }\n }\n\n /** The receipt file's mtime in epoch ms, or 0 when there is none — when stage ② last briefed anyone. */\n writtenAtMs(repoRoot: string, featureName: string): number {\n const p = this.receiptPath(repoRoot, featureName);\n return fs.existsSync(p) ? fs.statSync(p).mtimeMs : 0;\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSON value, narrowed to string→string\n private stringMap(value: unknown): Record<string, string> {\n const out: Record<string, string> = {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return out;\n // webpieces-disable no-any-unknown -- entries of an opaque JSON object, each narrowed below\n const obj = value as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n const v = obj[key];\n if (typeof v === 'string') out[key] = v;\n }\n return out;\n }\n}\n"]}
|
|
@@ -55,10 +55,10 @@ let ReviewerVerdictGate = class ReviewerVerdictGate {
|
|
|
55
55
|
const refusals = refused.map((req) => this.retireAndReport(scan, req));
|
|
56
56
|
throw new rules_config_1.InformAiError(this.headline(scan, refused, neverRan)
|
|
57
57
|
+ this.unreadableSection(scan)
|
|
58
|
-
+ this.refusedSection(refusals
|
|
58
|
+
+ this.refusedSection(refusals)
|
|
59
59
|
+ this.discountedSection(scan, neverRan)
|
|
60
60
|
+ this.neverRanSection(scan, neverRan)
|
|
61
|
-
+ this.footer(refused.length > 0
|
|
61
|
+
+ this.footer(refused.length > 0));
|
|
62
62
|
}
|
|
63
63
|
/**
|
|
64
64
|
* Say plainly how many REFUSED and how many never ran.
|
|
@@ -107,14 +107,9 @@ let ReviewerVerdictGate = class ReviewerVerdictGate {
|
|
|
107
107
|
* The refusals — SECOND, above anything that says to spawn a subagent, because a spawn instruction is the
|
|
108
108
|
* one line an agent acts on first, and acting on it here IS the loop.
|
|
109
109
|
*/
|
|
110
|
-
refusedSection(refusals
|
|
110
|
+
refusedSection(refusals) {
|
|
111
111
|
if (refusals.length === 0)
|
|
112
112
|
return '';
|
|
113
|
-
if (singleRoundReview) {
|
|
114
|
-
return '⛔ REFUSED — SINGLE-ROUND MODE. These reviewers ALREADY ANSWERED and MUST NOT be rerun.\n\n'
|
|
115
|
-
+ refusals.map((r) => ` • ${r}`).join('\n\n') + '\n\n'
|
|
116
|
-
+ ` main_agent_instructions: ${rules_config_1.SINGLE_ROUND_MAIN_AGENT_INSTRUCTIONS}\n\n`;
|
|
117
|
-
}
|
|
118
113
|
return '⛔ REFUSED — these reviewers ALREADY ANSWERED. Re-spawning one against unchanged code only buys\n'
|
|
119
114
|
+ ' the same answer: fix what it found (or get a HUMAN to authorize an override), THEN review again.\n\n'
|
|
120
115
|
+ refusals.map((r) => ` • ${r}`).join('\n\n') + '\n\n';
|
|
@@ -163,14 +158,6 @@ let ReviewerVerdictGate = class ReviewerVerdictGate {
|
|
|
163
158
|
*/
|
|
164
159
|
retireAndReport(scan, req) {
|
|
165
160
|
const verdict = this.reviewJsonService.resolveVerdict(req, scan.results);
|
|
166
|
-
if (scan.singleRoundReview) {
|
|
167
|
-
const live = this.reviewJsonService.checklistResultPath(scan.summaryPath, req.id);
|
|
168
|
-
return `Checklist "${req.id}" FAILED review (status:"red"). The reviewer wrote:\n`
|
|
169
|
-
+ ` ${verdict.detail}\n`
|
|
170
|
-
+ ` DO NOT RERUN this reviewer. After fixing every finding, edit ${live}.\n`
|
|
171
|
-
+ ' Change its addressed red status to "yellow". Yellow is accepted by the gate. If you genuinely\n'
|
|
172
|
-
+ ' disagree, leave it red and flag the human BEFORE posting the PR; red remains blocking.';
|
|
173
|
-
}
|
|
174
161
|
return this.reviewJsonService.refusalError(req, verdict, scan.summaryPath, this.archiveOrWarn(scan.summaryPath, req.id));
|
|
175
162
|
}
|
|
176
163
|
// The archive path, or '' when there was nothing to move or the move failed (see retireAndReport).
|
|
@@ -190,15 +177,10 @@ let ReviewerVerdictGate = class ReviewerVerdictGate {
|
|
|
190
177
|
// Re-running stage 2 is normally optional. It stops being optional after a refusal, because the only way
|
|
191
178
|
// past one is to CHANGE the code — which is exactly the condition that makes the extracted diff and every
|
|
192
179
|
// reviewer briefing stale.
|
|
193
|
-
footer(anyRefused
|
|
180
|
+
footer(anyRefused) {
|
|
194
181
|
if (anyRefused) {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
+ 'addressed red verdicts to yellow, then run: pnpm wp-finish-upsert-pr\n'
|
|
198
|
-
+ 'If any red remains because you disagree, STOP and ask the human before posting the PR.';
|
|
199
|
-
}
|
|
200
|
-
return 'Then re-run: pnpm wp-review-upsert-pr (the code changed, so the extracted diff and the reviewer\n'
|
|
201
|
-
+ 'briefings are stale), re-run the reviewer(s) above, and finally: pnpm wp-finish-upsert-pr';
|
|
182
|
+
return 'Fix every finding, commit the remediation, record it with pnpm wp-write-review-fixes, then re-run:\n'
|
|
183
|
+
+ 'pnpm wp-review-upsert-pr. The repository round budget decides whether a focused re-review remains.';
|
|
202
184
|
}
|
|
203
185
|
return 'Then re-run: pnpm wp-finish-upsert-pr\n'
|
|
204
186
|
+ '(Each reviewer\'s generated instructions file is already written — re-running pnpm wp-review-upsert-pr\n'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewer-verdict-gate.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/reviewer-verdict-gate.ts"],"names":[],"mappings":";;;;AAAA,0DAGiC;AACjC,yCAA2D;AAE3D,6DAA0F;AAE1F;;;;;;;;;;;;;;;;;;;;GAoBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IAFrB,YACqB,iBAAoC,EACpC,YAA0C;QAD1C,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,iBAAY,GAAZ,YAAY,CAA8B;IAC5D,CAAC;IAEJ;;;;;;;OAOG;IACH,sBAAsB,CAAC,IAAmB;QACtC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAC1C,qGAAqG;QACrG,kGAAkG;QAClG,gGAAgG;QAChG,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,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AAI,CAAC,CAAC;YAC7C,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;IAED,yGAAyG;IACzG,0GAA0G;IAC1G,2BAA2B;IACnB,MAAM,CAAC,UAAmB,EAAE,iBAA0B;QAC1D,IAAI,UAAU,EAAE,CAAC;YACb,IAAI,iBAAiB,EAAE,CAAC;gBACpB,OAAO,8FAA8F;sBAC/F,wEAAwE;sBACxE,wFAAwF,CAAC;YACnG,CAAC;YACD,OAAO,mGAAmG;kBACpG,2FAA2F,CAAC;QACtG,CAAC;QACD,OAAO,yCAAyC;cAC1C,0GAA0G;cAC1G,oDAAoD,CAAC;IAC/D,CAAC;CACJ,CAAA;AAvLY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGG,gCAAiB;QACtB,2CAA4B;GAHtD,mBAAmB,CAuL/B","sourcesContent":["import {\n ChecklistInstructionsService, InformAiError, RequiredChecklist, ReviewJsonService,\n SINGLE_ROUND_MAIN_AGENT_INSTRUCTIONS, toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ChecklistScan } from './checklist-scanner';\nimport { STANDING_REJECTED, STANDING_STALE, VerdictStanding } from './verdict-provenance';\n\n/**\n * The gate `wp-finish-upsert-pr` runs before it parses summary.json: REFUSE the PR while any applicable\n * checklist is not clear, and say — per checklist — which of three different things went wrong.\n *\n * It is its own class, not a private method on the command, for two reasons. It is the one piece of finish\n * that both MUTATES the branch (it retires red verdicts) and produces the text an AI acts on, so it is the\n * piece most worth asserting on directly; and the command it came out of is already the largest file in this\n * package, against a hard `@webpieces/max-file-lines` limit.\n *\n * THE BUG THIS EXISTS TO FIX. The message used to be one bucket and one imperative — \"You MUST run these N\n * reviewer subagent(s)\" — for three unrelated states. Handed to an agent, the literal, obedient response for\n * a checklist that had ALREADY REFUSED was to spawn the reviewer again; it re-read the same unchanged code,\n * refused again, and the loop cost a full subagent run per pass while the reviewer's actual finding was\n * never printed at all. Three states, three actions, in this order:\n *\n * 1. UNREADABLE (`scan.formatErrors`) -> fix four characters of JSON. Not a reviewer problem.\n * 2. REFUSED (CK_FAIL) -> fix the finding (or get a HUMAN override). Not a missing step.\n * 3. NEVER RAN (the rest) -> spawn the subagent. The ONLY case where that is the right move.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewerVerdictGate {\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly instructions: ChecklistInstructionsService,\n ) {}\n\n /**\n * Refuse the PR while ANY applicable checklist still owes a passing verdict — naming exactly what each\n * one needs. No-op for a repo with no applicable checklists.\n *\n * SIDE EFFECT, deliberately: every REFUSED checklist's verdict file is RETIRED to review-<id>.json.old on\n * the way out (see {@link retireAndReport}). Only red verdicts are ever moved — a green, yellow or\n * overridden one is reused across finish attempts and retiring it would force a needless subagent re-run.\n */\n assertEveryReviewerRan(scan: ChecklistScan): void {\n if (scan.outstanding.length === 0) return;\n // The split is computed from the verdicts the SCAN already loaded, never from a second read of disk:\n // a re-read here could disagree with the set that produced `outstanding`, and a checklist that is\n // \"outstanding\" per one read and \"clear\" per another belongs to neither section of the message.\n const refused = this.reviewJsonService.refusedChecklists(scan.outstanding, scan.results);\n const refusedIds = new Set(refused.map((r: RequiredChecklist): string => r.id));\n const neverRan = scan.outstanding.filter((r: RequiredChecklist): boolean => !refusedIds.has(r.id));\n // Rendered BEFORE the throw and, per checklist, with the verdict resolved before its file is moved —\n // the message quotes the reviewer's own words, so losing them to the move would defeat the point.\n const refusals = refused.map((req: RequiredChecklist): string => this.retireAndReport(scan, req));\n throw new InformAiError(\n this.headline(scan, refused, neverRan)\n + this.unreadableSection(scan)\n + this.refusedSection(refusals, scan.singleRoundReview)\n + this.discountedSection(scan, neverRan)\n + this.neverRanSection(scan, neverRan)\n + this.footer(refused.length > 0, scan.singleRoundReview),\n );\n }\n\n /**\n * Say plainly how many REFUSED and how many never ran.\n *\n * The old headline said all of them \"have no passing verdict yet\", which is technically true of a refusal\n * and reads as though nobody had looked. It is the sentence that framed a decision as an omission.\n */\n private headline(scan: ChecklistScan, refused: readonly RequiredChecklist[], neverRan: readonly RequiredChecklist[]): string {\n const lines = [\n `⛔ NO PR — ${scan.outstanding.length} of ${scan.applicable.length} review checklist(s) that apply to this branch are not clear:`,\n ];\n if (refused.length > 0) {\n lines.push(` • ${refused.length} REFUSED — a reviewer ran, judged this change, and said no: ${this.instructions.names(refused)}`);\n }\n if (neverRan.length > 0) {\n lines.push(` • ${neverRan.length} never ran — no verdict has been written yet: ${this.instructions.names(neverRan)}`);\n }\n return lines.join('\\n') + this.skippedNote(scan) + '\\n\\n';\n }\n\n /**\n * The optional checklists nobody ran, stated OUT LOUD on the refusal.\n *\n * They are not why the PR is being refused and this block says so — but a message that lists only what\n * blocked reads as \"everything else was reviewed\", and here that is false: those reviews were declined,\n * not passed. The one moment a human is looking at the review state is the moment to be honest about\n * which reviews did not happen, and it is also the prompt an AI needs to offer them again if the human\n * has changed their mind now that something else came back red.\n */\n private skippedNote(scan: ChecklistScan): string {\n if (scan.optionalNotRun.length === 0) return '';\n return `\\n (Not blocking: ${scan.optionalNotRun.length} OPTIONAL checklist(s) were not run — `\n + `${this.instructions.names(scan.optionalNotRun)}. They do not have to run; re-run\\n`\n + ' pnpm wp-review-upsert-pr if you now want to offer them.)';\n }\n\n // Unreadable verdict files come FIRST. A reviewer that wrote its verdict in the removed `success` format\n // is otherwise indistinguishable from one that never ran, and the AI would go re-run a subagent instead\n // of correcting four characters of JSON.\n private unreadableSection(scan: ChecklistScan): string {\n if (scan.formatErrors.length === 0) return '';\n return `${scan.formatErrors.length} verdict file(s) are in an UNREADABLE format:\\n\\n`\n + scan.formatErrors.map((e: string): string => ` • ${e}`).join('\\n') + '\\n\\n';\n }\n\n /**\n * The refusals — SECOND, above anything that says to spawn a subagent, because a spawn instruction is the\n * one line an agent acts on first, and acting on it here IS the loop.\n */\n private refusedSection(refusals: readonly string[], singleRoundReview: boolean): string {\n if (refusals.length === 0) return '';\n if (singleRoundReview) {\n return '⛔ REFUSED — SINGLE-ROUND MODE. These reviewers ALREADY ANSWERED and MUST NOT be rerun.\\n\\n'\n + refusals.map((r: string): string => ` • ${r}`).join('\\n\\n') + '\\n\\n'\n + ` main_agent_instructions: ${SINGLE_ROUND_MAIN_AGENT_INSTRUCTIONS}\\n\\n`;\n }\n return '⛔ REFUSED — these reviewers ALREADY ANSWERED. Re-spawning one against unchanged code only buys\\n'\n + ' the same answer: fix what it found (or get a HUMAN to authorize an override), THEN review again.\\n\\n'\n + refusals.map((r: string): string => ` • ${r}`).join('\\n\\n') + '\\n\\n';\n }\n\n /**\n * Verdict files that EXIST but do not count (issue #863), each with why — printed before the spawn\n * list so the reader does not mistake them for reviewers that never ran, and so a hand-written verdict\n * is named as what it is. REJECTED: no `wp-write-review` provenance, or edited after submission — a\n * coordinator writing a reviewer's verdict lands here, and that is the forgery this gate exists to\n * refuse. STALE: the checklist's in-scope files changed since it was submitted.\n */\n private discountedSection(scan: ChecklistScan, neverRan: readonly RequiredChecklist[]): string {\n const owed = new Set(neverRan.map((r: RequiredChecklist): string => r.id));\n const discounted = scan.standings.filter((s: VerdictStanding): boolean => owed.has(s.checklistId)\n && (s.standing === STANDING_REJECTED || s.standing === STANDING_STALE));\n if (discounted.length === 0) return '';\n return '🚫 NOT COUNTED — these verdict files exist, but they are not a current review:\\n\\n'\n + discounted.map((s: VerdictStanding): string => ` • ${s.checklistId} — ${s.standing.toUpperCase()}: ${s.reason}`).join('\\n')\n + '\\n A reviewer SUBAGENT must submit a fresh verdict with pnpm wp-write-review. Do NOT write or copy the\\n'\n + ' file yourself: the bin refuses the coordinating agent, and this gate rejects a verdict it did not write.\\n\\n';\n }\n\n /**\n * The reviewers that genuinely never ran — LAST, and listing ONLY these. When there are none this block\n * is absent entirely, which is the whole point: the \"You MUST run these N reviewer subagent(s)\"\n * imperative must not appear at all on a run whose only problem is a refusal.\n */\n private neverRanSection(scan: ChecklistScan, neverRan: readonly RequiredChecklist[]): string {\n if (neverRan.length === 0) return '';\n return '❓ NO VERDICT YET — nothing that counts has been submitted for these, so they must actually be run:\\n\\n'\n + `${this.instructions.render(neverRan, scan.summaryPath, scan.context)}\\n\\n`;\n }\n\n /**\n * Retire ONE refused checklist's verdict and render the refusal that reports it.\n *\n * ORDER IS LOAD-BEARING. The verdict is resolved from the already-loaded results, so the finding is in\n * hand before the file moves; the move then happens; and only then is the message rendered, because it\n * names the archive path and must not claim a move that did not happen.\n *\n * The move is NON-FATAL. A finish that died after retiring a verdict would leave the AI with a red\n * verdict gone from the live path and no message saying where it went or why the PR was refused — a\n * silent gap, and the worst possible outcome for a feature whose entire purpose is a durable record. So a\n * failed move warns and the refusal is reported without an archive path (the file is then still live,\n * which the un-archived wording of `refusalError` describes correctly).\n */\n private retireAndReport(scan: ChecklistScan, req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, scan.results);\n if (scan.singleRoundReview) {\n const live = this.reviewJsonService.checklistResultPath(scan.summaryPath, req.id);\n return `Checklist \"${req.id}\" FAILED review (status:\"red\"). The reviewer wrote:\\n`\n + ` ${verdict.detail}\\n`\n + ` DO NOT RERUN this reviewer. After fixing every finding, edit ${live}.\\n`\n + ' Change its addressed red status to \"yellow\". Yellow is accepted by the gate. If you genuinely\\n'\n + ' disagree, leave it red and flag the human BEFORE posting the PR; red remains blocking.';\n }\n return this.reviewJsonService.refusalError(\n req, verdict, scan.summaryPath, this.archiveOrWarn(scan.summaryPath, req.id));\n }\n\n // The archive path, or '' when there was nothing to move or the move failed (see retireAndReport).\n private archiveOrWarn(summaryPath: string, checklistId: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a failed archive must never swallow the refusal it belongs to\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return this.reviewJsonService.archiveChecklistResult(summaryPath, checklistId);\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(\n `⚠️ Could not retire the refused verdict for \"${checklistId}\" (non-fatal — the refusal is still `\n + `reported below): ${error.message}\\n`);\n return '';\n }\n }\n\n // Re-running stage 2 is normally optional. It stops being optional after a refusal, because the only way\n // past one is to CHANGE the code — which is exactly the condition that makes the extracted diff and every\n // reviewer briefing stale.\n private footer(anyRefused: boolean, singleRoundReview: boolean): string {\n if (anyRefused) {\n if (singleRoundReview) {\n return 'Do NOT run pnpm wp-review-upsert-pr and do NOT re-run a reviewer. Fix the findings, change\\n'\n + 'addressed red verdicts to yellow, then run: pnpm wp-finish-upsert-pr\\n'\n + 'If any red remains because you disagree, STOP and ask the human before posting the PR.';\n }\n return 'Then re-run: pnpm wp-review-upsert-pr (the code changed, so the extracted diff and the reviewer\\n'\n + 'briefings are stale), re-run the reviewer(s) above, and finally: pnpm wp-finish-upsert-pr';\n }\n return 'Then re-run: pnpm wp-finish-upsert-pr\\n'\n + '(Each reviewer\\'s generated instructions file is already written — re-running pnpm wp-review-upsert-pr\\n'\n + ' is only needed if the code changed since it ran.)';\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reviewer-verdict-gate.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/reviewer-verdict-gate.ts"],"names":[],"mappings":";;;;AAAA,0DAGiC;AACjC,yCAA2D;AAE3D,6DAA0F;AAE1F;;;;;;;;;;;;;;;;;;;;GAoBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IAFrB,YACqB,iBAAoC,EACpC,YAA0C;QAD1C,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,iBAAY,GAAZ,YAAY,CAA8B;IAC5D,CAAC;IAEJ;;;;;;;OAOG;IACH,sBAAsB,CAAC,IAAmB;QACtC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAC1C,qGAAqG;QACrG,kGAAkG;QAClG,gGAAgG;QAChG,MAAM,OAAO,G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B;QAC/D,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACzE,OAAO,IAAI,CAAC,iBAAiB,CAAC,YAAY,CACtC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACtF,CAAC;IAED,mGAAmG;IAC3F,aAAa,CAAC,WAAmB,EAAE,WAAmB;QAC1D,yHAAyH;QACzH,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,sBAAsB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;QACnF,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,MAAM,CAAC,KAAK,CAChB,iDAAiD,WAAW,sCAAsC;kBAChG,oBAAoB,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC;YAC7C,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;IAED,yGAAyG;IACzG,0GAA0G;IAC1G,2BAA2B;IACnB,MAAM,CAAC,UAAmB;QAC9B,IAAI,UAAU,EAAE,CAAC;YACb,OAAO,sGAAsG;kBACvG,oGAAoG,CAAC;QAC/G,CAAC;QACD,OAAO,yCAAyC;cAC1C,0GAA0G;cAC1G,oDAAoD,CAAC;IAC/D,CAAC;CACJ,CAAA;AArKY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGG,gCAAiB;QACtB,2CAA4B;GAHtD,mBAAmB,CAqK/B","sourcesContent":["import {\n ChecklistInstructionsService, InformAiError, RequiredChecklist, ReviewJsonService,\n toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ChecklistScan } from './checklist-scanner';\nimport { STANDING_REJECTED, STANDING_STALE, VerdictStanding } from './verdict-provenance';\n\n/**\n * The gate `wp-finish-upsert-pr` runs before it parses summary.json: REFUSE the PR while any applicable\n * checklist is not clear, and say — per checklist — which of three different things went wrong.\n *\n * It is its own class, not a private method on the command, for two reasons. It is the one piece of finish\n * that both MUTATES the branch (it retires red verdicts) and produces the text an AI acts on, so it is the\n * piece most worth asserting on directly; and the command it came out of is already the largest file in this\n * package, against a hard `@webpieces/max-file-lines` limit.\n *\n * THE BUG THIS EXISTS TO FIX. The message used to be one bucket and one imperative — \"You MUST run these N\n * reviewer subagent(s)\" — for three unrelated states. Handed to an agent, the literal, obedient response for\n * a checklist that had ALREADY REFUSED was to spawn the reviewer again; it re-read the same unchanged code,\n * refused again, and the loop cost a full subagent run per pass while the reviewer's actual finding was\n * never printed at all. Three states, three actions, in this order:\n *\n * 1. UNREADABLE (`scan.formatErrors`) -> fix four characters of JSON. Not a reviewer problem.\n * 2. REFUSED (CK_FAIL) -> fix the finding (or get a HUMAN override). Not a missing step.\n * 3. NEVER RAN (the rest) -> spawn the subagent. The ONLY case where that is the right move.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewerVerdictGate {\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly instructions: ChecklistInstructionsService,\n ) {}\n\n /**\n * Refuse the PR while ANY applicable checklist still owes a passing verdict — naming exactly what each\n * one needs. No-op for a repo with no applicable checklists.\n *\n * SIDE EFFECT, deliberately: every REFUSED checklist's verdict file is RETIRED to review-<id>.json.old on\n * the way out (see {@link retireAndReport}). Only red verdicts are ever moved — a green, yellow or\n * overridden one is reused across finish attempts and retiring it would force a needless subagent re-run.\n */\n assertEveryReviewerRan(scan: ChecklistScan): void {\n if (scan.outstanding.length === 0) return;\n // The split is computed from the verdicts the SCAN already loaded, never from a second read of disk:\n // a re-read here could disagree with the set that produced `outstanding`, and a checklist that is\n // \"outstanding\" per one read and \"clear\" per another belongs to neither section of the message.\n const refused = this.reviewJsonService.refusedChecklists(scan.outstanding, scan.results);\n const refusedIds = new Set(refused.map((r: RequiredChecklist): string => r.id));\n const neverRan = scan.outstanding.filter((r: RequiredChecklist): boolean => !refusedIds.has(r.id));\n // Rendered BEFORE the throw and, per checklist, with the verdict resolved before its file is moved —\n // the message quotes the reviewer's own words, so losing them to the move would defeat the point.\n const refusals = refused.map((req: RequiredChecklist): string => this.retireAndReport(scan, req));\n throw new InformAiError(\n this.headline(scan, refused, neverRan)\n + this.unreadableSection(scan)\n + this.refusedSection(refusals)\n + this.discountedSection(scan, neverRan)\n + this.neverRanSection(scan, neverRan)\n + this.footer(refused.length > 0),\n );\n }\n\n /**\n * Say plainly how many REFUSED and how many never ran.\n *\n * The old headline said all of them \"have no passing verdict yet\", which is technically true of a refusal\n * and reads as though nobody had looked. It is the sentence that framed a decision as an omission.\n */\n private headline(scan: ChecklistScan, refused: readonly RequiredChecklist[], neverRan: readonly RequiredChecklist[]): string {\n const lines = [\n `⛔ NO PR — ${scan.outstanding.length} of ${scan.applicable.length} review checklist(s) that apply to this branch are not clear:`,\n ];\n if (refused.length > 0) {\n lines.push(` • ${refused.length} REFUSED — a reviewer ran, judged this change, and said no: ${this.instructions.names(refused)}`);\n }\n if (neverRan.length > 0) {\n lines.push(` • ${neverRan.length} never ran — no verdict has been written yet: ${this.instructions.names(neverRan)}`);\n }\n return lines.join('\\n') + this.skippedNote(scan) + '\\n\\n';\n }\n\n /**\n * The optional checklists nobody ran, stated OUT LOUD on the refusal.\n *\n * They are not why the PR is being refused and this block says so — but a message that lists only what\n * blocked reads as \"everything else was reviewed\", and here that is false: those reviews were declined,\n * not passed. The one moment a human is looking at the review state is the moment to be honest about\n * which reviews did not happen, and it is also the prompt an AI needs to offer them again if the human\n * has changed their mind now that something else came back red.\n */\n private skippedNote(scan: ChecklistScan): string {\n if (scan.optionalNotRun.length === 0) return '';\n return `\\n (Not blocking: ${scan.optionalNotRun.length} OPTIONAL checklist(s) were not run — `\n + `${this.instructions.names(scan.optionalNotRun)}. They do not have to run; re-run\\n`\n + ' pnpm wp-review-upsert-pr if you now want to offer them.)';\n }\n\n // Unreadable verdict files come FIRST. A reviewer that wrote its verdict in the removed `success` format\n // is otherwise indistinguishable from one that never ran, and the AI would go re-run a subagent instead\n // of correcting four characters of JSON.\n private unreadableSection(scan: ChecklistScan): string {\n if (scan.formatErrors.length === 0) return '';\n return `${scan.formatErrors.length} verdict file(s) are in an UNREADABLE format:\\n\\n`\n + scan.formatErrors.map((e: string): string => ` • ${e}`).join('\\n') + '\\n\\n';\n }\n\n /**\n * The refusals — SECOND, above anything that says to spawn a subagent, because a spawn instruction is the\n * one line an agent acts on first, and acting on it here IS the loop.\n */\n private refusedSection(refusals: readonly string[]): string {\n if (refusals.length === 0) return '';\n return '⛔ REFUSED — these reviewers ALREADY ANSWERED. Re-spawning one against unchanged code only buys\\n'\n + ' the same answer: fix what it found (or get a HUMAN to authorize an override), THEN review again.\\n\\n'\n + refusals.map((r: string): string => ` • ${r}`).join('\\n\\n') + '\\n\\n';\n }\n\n /**\n * Verdict files that EXIST but do not count (issue #863), each with why — printed before the spawn\n * list so the reader does not mistake them for reviewers that never ran, and so a hand-written verdict\n * is named as what it is. REJECTED: no `wp-write-review` provenance, or edited after submission — a\n * coordinator writing a reviewer's verdict lands here, and that is the forgery this gate exists to\n * refuse. STALE: the checklist's in-scope files changed since it was submitted.\n */\n private discountedSection(scan: ChecklistScan, neverRan: readonly RequiredChecklist[]): string {\n const owed = new Set(neverRan.map((r: RequiredChecklist): string => r.id));\n const discounted = scan.standings.filter((s: VerdictStanding): boolean => owed.has(s.checklistId)\n && (s.standing === STANDING_REJECTED || s.standing === STANDING_STALE));\n if (discounted.length === 0) return '';\n return '🚫 NOT COUNTED — these verdict files exist, but they are not a current review:\\n\\n'\n + discounted.map((s: VerdictStanding): string => ` • ${s.checklistId} — ${s.standing.toUpperCase()}: ${s.reason}`).join('\\n')\n + '\\n A reviewer SUBAGENT must submit a fresh verdict with pnpm wp-write-review. Do NOT write or copy the\\n'\n + ' file yourself: the bin refuses the coordinating agent, and this gate rejects a verdict it did not write.\\n\\n';\n }\n\n /**\n * The reviewers that genuinely never ran — LAST, and listing ONLY these. When there are none this block\n * is absent entirely, which is the whole point: the \"You MUST run these N reviewer subagent(s)\"\n * imperative must not appear at all on a run whose only problem is a refusal.\n */\n private neverRanSection(scan: ChecklistScan, neverRan: readonly RequiredChecklist[]): string {\n if (neverRan.length === 0) return '';\n return '❓ NO VERDICT YET — nothing that counts has been submitted for these, so they must actually be run:\\n\\n'\n + `${this.instructions.render(neverRan, scan.summaryPath, scan.context)}\\n\\n`;\n }\n\n /**\n * Retire ONE refused checklist's verdict and render the refusal that reports it.\n *\n * ORDER IS LOAD-BEARING. The verdict is resolved from the already-loaded results, so the finding is in\n * hand before the file moves; the move then happens; and only then is the message rendered, because it\n * names the archive path and must not claim a move that did not happen.\n *\n * The move is NON-FATAL. A finish that died after retiring a verdict would leave the AI with a red\n * verdict gone from the live path and no message saying where it went or why the PR was refused — a\n * silent gap, and the worst possible outcome for a feature whose entire purpose is a durable record. So a\n * failed move warns and the refusal is reported without an archive path (the file is then still live,\n * which the un-archived wording of `refusalError` describes correctly).\n */\n private retireAndReport(scan: ChecklistScan, req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, scan.results);\n return this.reviewJsonService.refusalError(\n req, verdict, scan.summaryPath, this.archiveOrWarn(scan.summaryPath, req.id));\n }\n\n // The archive path, or '' when there was nothing to move or the move failed (see retireAndReport).\n private archiveOrWarn(summaryPath: string, checklistId: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a failed archive must never swallow the refusal it belongs to\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return this.reviewJsonService.archiveChecklistResult(summaryPath, checklistId);\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(\n `⚠️ Could not retire the refused verdict for \"${checklistId}\" (non-fatal — the refusal is still `\n + `reported below): ${error.message}\\n`);\n return '';\n }\n }\n\n // Re-running stage 2 is normally optional. It stops being optional after a refusal, because the only way\n // past one is to CHANGE the code — which is exactly the condition that makes the extracted diff and every\n // reviewer briefing stale.\n private footer(anyRefused: boolean): string {\n if (anyRefused) {\n return 'Fix every finding, commit the remediation, record it with pnpm wp-write-review-fixes, then re-run:\\n'\n + 'pnpm wp-review-upsert-pr. The repository round budget decides whether a focused re-review remains.';\n }\n return 'Then re-run: pnpm wp-finish-upsert-pr\\n'\n + '(Each reviewer\\'s generated instructions file is already written — re-running pnpm wp-review-upsert-pr\\n'\n + ' is only needed if the code changed since it ran.)';\n }\n}\n"]}
|