@operad-io/dev 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +795 -2
  3. package/dev.schema.json +602 -0
  4. package/flows/chat-worktree.flow.ts +18 -0
  5. package/flows/dev.flow.ts +7 -0
  6. package/package.json +29 -4
  7. package/src/actions.ts +591 -0
  8. package/src/announce.ts +225 -0
  9. package/src/chat.ts +234 -0
  10. package/src/check.ts +80 -0
  11. package/src/commands.ts +417 -0
  12. package/src/editor.ts +55 -0
  13. package/src/flaky.ts +716 -0
  14. package/src/flow-compiler.ts +858 -0
  15. package/src/followups.ts +223 -0
  16. package/src/gate.ts +2897 -0
  17. package/src/git.ts +138 -0
  18. package/src/index.ts +226 -0
  19. package/src/integrate.ts +1201 -0
  20. package/src/integration-queue.ts +393 -0
  21. package/src/lock.ts +36 -0
  22. package/src/mainclone.ts +102 -0
  23. package/src/marks.ts +126 -0
  24. package/src/model.ts +1165 -0
  25. package/src/notcode.ts +266 -0
  26. package/src/place-order.ts +161 -0
  27. package/src/place-wait.ts +64 -0
  28. package/src/places.ts +368 -0
  29. package/src/prepare.ts +106 -0
  30. package/src/progress.ts +115 -0
  31. package/src/project-flows.ts +160 -0
  32. package/src/project-settings.ts +185 -0
  33. package/src/refusals.ts +336 -0
  34. package/src/rerun.ts +378 -0
  35. package/src/reruns.ts +62 -0
  36. package/src/retry.ts +212 -0
  37. package/src/rework.ts +366 -0
  38. package/src/schedule.ts +1052 -0
  39. package/src/service.ts +2160 -0
  40. package/src/settings.ts +1463 -0
  41. package/src/standing.ts +87 -0
  42. package/src/stdin.ts +105 -0
  43. package/src/steps.ts +1775 -0
  44. package/src/stops.ts +103 -0
  45. package/src/throughput.ts +347 -0
  46. package/src/timeouts.ts +60 -0
  47. package/src/views.ts +1167 -0
  48. package/src/waits.ts +105 -0
package/src/gate.ts ADDED
@@ -0,0 +1,2897 @@
1
+ /**
2
+ * The gate: verify a task's commit with the repository's commands, review its
3
+ * diff with a harness step, and turn a failure into another rework pass. Both
4
+ * steps run git here; the kernel never runs a command or a harness itself.
5
+ */
6
+
7
+ import {
8
+ closeSync,
9
+ constants as fsConstants,
10
+ existsSync,
11
+ readFileSync,
12
+ fstatSync,
13
+ lstatSync,
14
+ mkdirSync,
15
+ openSync,
16
+ readSync,
17
+ rmSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import { dirname, join, resolve } from "node:path";
21
+ import { checkPlaces } from "./places.ts";
22
+ import { runPrepare, stepOptions } from "./prepare.ts";
23
+ import { runCheckCommands } from "./rerun.ts";
24
+ import { runCheckSteadily } from "./notcode.ts";
25
+ import { reportFlakyTests } from "./flaky.ts";
26
+ import { recordRerunPasses } from "./reruns.ts";
27
+ import {
28
+ ReviewGradingError,
29
+ readReviewGrading,
30
+ strictestFixLevel,
31
+ type Grading,
32
+ } from "@operad-io/review-grading";
33
+ import { isRecord, messageOf, type PluginStepResult, type StepContext, type StepRunOptions } from "@operad-io/engine";
34
+ import { appendRework, DevError, type PendingReviewRun, type ReviewFinding, type ReviewNote, type ReviewNotes, type ReviewRecord, type ReviewResult, type ReviewRunRecord, type ReviewRunReason, type ReviewRunRole, type ReworkRecord, type TaskAttempt, type TaskData, type VerifyRecord, type VerifyResult } from "./model.ts";
35
+ import {
36
+ assertInsideRepository,
37
+ type CheckCommand,
38
+ type DevSettings,
39
+ type FixLevel,
40
+ type ReviewerFallback,
41
+ type ReviewerSettings,
42
+ } from "./settings.ts";
43
+ import { reviewWaitKind } from "./waits.ts";
44
+ import { appendChange } from "./model.ts";
45
+ import {
46
+ briefText,
47
+ cancelledStep,
48
+ claimAllows,
49
+ git,
50
+ headOf,
51
+ isRegistered,
52
+ saveTaskGuarded,
53
+ taskContext,
54
+ workBranch,
55
+ type TaskContext,
56
+ } from "./steps.ts";
57
+ import {
58
+ addedLinesOf,
59
+ filePatches,
60
+ incrementOf,
61
+ type Increment,
62
+ fixedCount,
63
+ movesIn,
64
+ type ReviewKind,
65
+ type ReviewSettingsUsed,
66
+ reviewSettingsOf,
67
+ previousLine,
68
+ previousReview,
69
+ type LineMap,
70
+ type PreviousFinding,
71
+ type ReviewHistoryEntry,
72
+ } from "./rework.ts";
73
+ import {
74
+ MAX_REVIEW_WAITS,
75
+ reviewWaitMs,
76
+ REVIEW_WAIT_CHUNK_MS,
77
+ STEP_TIMEOUT_SECS,
78
+ } from "./timeouts.ts";
79
+
80
+ /** The gate worktree of a task: `<worktreeRoot>/<task id>-gate`. */
81
+ export function gateWorktreePath(
82
+ repositoryPath: string,
83
+ settings: DevSettings,
84
+ taskId: string,
85
+ ): string {
86
+ const path = resolve(repositoryPath, settings.worktreeRoot, `${taskId}-gate`);
87
+ assertInsideRepository(repositoryPath, path, "worktreeRoot");
88
+ return path;
89
+ }
90
+
91
+ /** The commit a task's branch points at, local first and then the remote. */
92
+ export function branchHead(
93
+ repositoryPath: string,
94
+ settings: DevSettings,
95
+ workName: string,
96
+ ): string | undefined {
97
+ const branch = workBranch(workName);
98
+ const local = git(repositoryPath, [
99
+ "rev-parse",
100
+ "--verify",
101
+ "--quiet",
102
+ `${branch}^{commit}`,
103
+ ]);
104
+ if (local.ok && local.out.length > 0) return local.out;
105
+ const remote = git(repositoryPath, [
106
+ "rev-parse",
107
+ "--verify",
108
+ "--quiet",
109
+ `refs/remotes/${settings.remote}/${branch}^{commit}`,
110
+ ]);
111
+ return remote.ok && remote.out.length > 0 ? remote.out : undefined;
112
+ }
113
+
114
+ /** The commit the task branched from: the merge base of main and the commit. */
115
+ function mergeBase(
116
+ repositoryPath: string,
117
+ settings: DevSettings,
118
+ sha: string,
119
+ ): string | undefined {
120
+ const main = `${settings.remote}/${settings.mainBranch}`;
121
+ const result = git(repositoryPath, ["merge-base", main, sha]);
122
+ return result.ok && result.out.length > 0 ? result.out : undefined;
123
+ }
124
+
125
+ /** Removes whatever is at the gate path and checks a commit out detached. */
126
+ export function recreateGateWorktree(
127
+ repositoryPath: string,
128
+ path: string,
129
+ sha: string,
130
+ settings: DevSettings,
131
+ ): string | undefined {
132
+ if (existsSync(path)) {
133
+ if (isRegistered(repositoryPath, path)) {
134
+ const removed = git(repositoryPath, [
135
+ "worktree",
136
+ "remove",
137
+ "--force",
138
+ path,
139
+ ]);
140
+ if (!removed.ok) {
141
+ rmSync(path, { recursive: true, force: true });
142
+ git(repositoryPath, ["worktree", "prune"]);
143
+ }
144
+ } else {
145
+ rmSync(path, { recursive: true, force: true });
146
+ }
147
+ }
148
+ git(repositoryPath, ["worktree", "prune"]);
149
+ mkdirSync(dirname(path), { recursive: true });
150
+ const add = git(repositoryPath, [
151
+ "worktree",
152
+ "add",
153
+ "--detach",
154
+ path,
155
+ sha,
156
+ ]);
157
+ if (add.ok) return undefined;
158
+ return `cannot check out ${sha} at ${path}: ${add.err || add.out}`;
159
+ }
160
+
161
+ function attemptOf(ctx: StepContext, task: TaskData): TaskAttempt {
162
+ return (
163
+ task.attempt ?? {
164
+ number: Math.max(task.attempts, 0) + 1,
165
+ run: ctx.runId,
166
+ }
167
+ );
168
+ }
169
+
170
+ function verifyData(record: VerifyRecord, extra: Readonly<Record<string, unknown>>): Record<string, unknown> {
171
+ return { ...record, ...extra };
172
+ }
173
+
174
+ function recordVerify(
175
+ attempt: TaskAttempt,
176
+ record: VerifyRecord,
177
+ ): TaskAttempt {
178
+ return { ...attempt, verify: record };
179
+ }
180
+
181
+ /** Step `dev/verify`: run the gate commands on the task's branch head. */
182
+ export async function runVerify(
183
+ ctx: StepContext,
184
+ ): Promise<PluginStepResult> {
185
+ const context = await taskContext(ctx);
186
+ if (!claimAllows(ctx, context.task)) return cancelledStep();
187
+ const task = context.task;
188
+ const attempt = attemptOf(ctx, task);
189
+ const previous = attempt.verify;
190
+ git(context.repository.path, [
191
+ "fetch",
192
+ "--prune",
193
+ context.settings.remote,
194
+ ]);
195
+ const sha = branchHead(
196
+ context.repository.path,
197
+ context.settings,
198
+ context.workName,
199
+ );
200
+ // A replay of the same run reads the result it already recorded, but only
201
+ // while the branch is still at the commit that result is for: a commit that
202
+ // landed since (T-0290: the worker's last commit, the merge of main) has no
203
+ // result, and review must not see it without a check.
204
+ if (
205
+ previous !== undefined &&
206
+ previous !== null &&
207
+ previous.run === ctx.runId &&
208
+ sha !== undefined &&
209
+ attempt.verified === sha
210
+ ) {
211
+ return {
212
+ result: typeof previous.notCode === "string" ? "not_code" : previous.result,
213
+ data: verifyData(previous, {
214
+ attempt: attempt.number,
215
+ verified: attempt.verified,
216
+ replayed: true,
217
+ }),
218
+ };
219
+ }
220
+ const path = gateWorktreePath(
221
+ context.repository.path,
222
+ context.settings,
223
+ context.taskId,
224
+ );
225
+
226
+ const failed = async (
227
+ message: string,
228
+ extra: Readonly<Record<string, unknown>> = {},
229
+ ): Promise<PluginStepResult> => {
230
+ const record: VerifyRecord = {
231
+ result: "fail",
232
+ run: ctx.runId,
233
+ message,
234
+ };
235
+ const written = await saveTaskGuarded(
236
+ ctx,
237
+ context.taskKey,
238
+ {
239
+ ...task,
240
+ phase: "review",
241
+ run: ctx.runId,
242
+ attempts: Math.max(task.attempts, attempt.number),
243
+ attempt: recordVerify(
244
+ { ...attempt, run: ctx.runId, verified: sha ?? null },
245
+ record,
246
+ ),
247
+ },
248
+ "dev:verify",
249
+ );
250
+ if (!written) return cancelledStep();
251
+ return {
252
+ result: "fail",
253
+ data: verifyData(record, {
254
+ attempt: attempt.number,
255
+ verified: sha ?? null,
256
+ worktree: path,
257
+ ...extra,
258
+ }),
259
+ };
260
+ };
261
+
262
+ if (sha === undefined) {
263
+ return failed(
264
+ `no branch "${workBranch(context.workName)}" or "${context.settings.remote}/${workBranch(context.workName)}" to verify`,
265
+ );
266
+ }
267
+ const prepared = recreateGateWorktree(
268
+ context.repository.path,
269
+ path,
270
+ sha,
271
+ context.settings,
272
+ );
273
+ if (prepared !== undefined) return failed(prepared, { sha, verified: sha });
274
+ const prepareFailure = await runPrepare(ctx, context.settings, path);
275
+ if (prepareFailure !== undefined) {
276
+ return failed(prepareFailure.message, {
277
+ sha,
278
+ verified: sha,
279
+ reason: prepareFailure.reason,
280
+ ...(prepareFailure.log === undefined ? {} : { log: prepareFailure.log }),
281
+ });
282
+ }
283
+
284
+ const commands = (() => {
285
+ const given = ((ctx.params ?? {}) as { readonly commands?: unknown }).commands;
286
+ return Array.isArray(given)
287
+ ? (given as readonly CheckCommand[])
288
+ : context.settings.gate.commands;
289
+ })();
290
+ const rerun = (() => {
291
+ const given = ((ctx.params ?? {}) as { readonly rerun?: unknown }).rerun;
292
+ return typeof given === "number" ? given : context.settings.check.rerun;
293
+ })();
294
+ const runStep = ctx.runStep;
295
+ if (runStep === undefined) {
296
+ return failed(
297
+ "the kernel did not offer a way to run the gate commands",
298
+ { sha, verified: sha },
299
+ );
300
+ }
301
+
302
+ const steady = await runCheckSteadily({
303
+ run: () =>
304
+ runCheckCommands(
305
+ runStep,
306
+ { cwd: path, timeoutSecs: context.settings.gate.commandTimeoutSecs },
307
+ commands,
308
+ stepOptions(ctx, path),
309
+ rerun,
310
+ checkPlaces(ctx, context.repository, context.settings.gate.places, context.taskKey),
311
+ ),
312
+ limit: context.settings.check.loadLimit,
313
+ signal: ctx.signal,
314
+ log: (text) => ctx.logger.write(text),
315
+ });
316
+ if (steady.cancelled === true) return cancelledStep();
317
+ const { checked } = steady;
318
+ await recordRerunPasses(ctx.store, checked.passedOnRerun);
319
+ const flakyNotice = await reportFlakyTests({
320
+ ctx,
321
+ repository: context.repository,
322
+ taskId: context.taskId,
323
+ threshold: context.settings.check.flakyTask,
324
+ flakyPlan: context.settings.check.flakyPlan,
325
+ check: checked,
326
+ loads: steady.loads,
327
+ loadLimit: context.settings.check.flakyLoadLimit,
328
+ });
329
+ const { outcome, hostError } = checked;
330
+ // A notice joins the check's own note, so the task's Changes and the step's history say it.
331
+ const note =
332
+ flakyNotice === undefined
333
+ ? checked.note
334
+ : [checked.note, flakyNotice].filter((part) => part !== undefined).join("; ");
335
+
336
+ const outcomeData =
337
+ outcome !== undefined && isRecord(outcome.data) ? outcome.data : {};
338
+ const result: VerifyResult =
339
+ hostError === undefined && outcome?.result === "pass" ? "pass" : "fail";
340
+ const command =
341
+ typeof outcomeData.line === "string" ? outcomeData.line : undefined;
342
+ const log = typeof outcomeData.log === "string" ? outcomeData.log : undefined;
343
+ const failureText =
344
+ hostError ??
345
+ (typeof outcomeData.message === "string" ? outcomeData.message : undefined) ??
346
+ (result === "fail"
347
+ ? `the gate commands failed (${outcome?.result ?? "unknown"})`
348
+ : undefined);
349
+ const failure =
350
+ steady.notCode === undefined
351
+ ? failureText
352
+ : [steady.notCode.cause, failureText].filter((part) => part !== undefined).join("; ");
353
+ // History shows the message before the reason, so a failure carries the notice.
354
+ const message =
355
+ failure !== undefined && flakyNotice !== undefined
356
+ ? `${failure}; ${flakyNotice}`
357
+ : failure;
358
+ const lineNumber =
359
+ typeof outcomeData.lineNumber === "number"
360
+ ? outcomeData.lineNumber
361
+ : undefined;
362
+
363
+ const record: VerifyRecord = {
364
+ result,
365
+ run: ctx.runId,
366
+ commands: commands.map((line) => (typeof line === "string" ? line : line.run)),
367
+ ...(command === undefined ? {} : { command }),
368
+ ...(log === undefined ? {} : { log }),
369
+ ...(message === undefined ? {} : { message }),
370
+ ...(lineNumber === undefined ? {} : { lineNumber }),
371
+ ...(steady.notCode === undefined ? {} : { notCode: steady.notCode.cause }),
372
+ };
373
+ const nextAttempt: TaskAttempt = {
374
+ ...recordVerify(attempt, record),
375
+ run: ctx.runId,
376
+ verified: sha,
377
+ };
378
+ const written = await saveTaskGuarded(
379
+ ctx,
380
+ context.taskKey,
381
+ {
382
+ ...task,
383
+ // A check that was not the code waits for a person, not for the worker.
384
+ phase: steady.notCode === undefined ? "review" : "waiting",
385
+ run: ctx.runId,
386
+ attempts: Math.max(task.attempts, attempt.number),
387
+ attempt: nextAttempt,
388
+ ...(note === undefined
389
+ ? {}
390
+ : { brief: appendChange(task.brief, note) }),
391
+ },
392
+ "dev:verify",
393
+ );
394
+ if (!written) return cancelledStep();
395
+ return {
396
+ result: steady.notCode === undefined ? result : "not_code",
397
+ data: verifyData(record, {
398
+ ...(note === undefined ? {} : { note }),
399
+ ...(flakyNotice === undefined ? {} : { reason: flakyNotice }),
400
+ ...(checked.rerun ? { rerun: true } : {}),
401
+ attempt: attempt.number,
402
+ verified: sha,
403
+ worktree: path,
404
+ ...(outcomeData.tail === undefined ? {} : { tail: outcomeData.tail }),
405
+ }),
406
+ };
407
+ }
408
+
409
+ /** The gate commands the attempt's verify ran, from its record. */
410
+ function verifiedCommands(verify: VerifyRecord | undefined | null): readonly string[] {
411
+ const named = verify?.commands;
412
+ return Array.isArray(named)
413
+ ? named.filter((line): line is string => typeof line === "string")
414
+ : [];
415
+ }
416
+
417
+ interface FileDiff {
418
+ readonly path: string;
419
+ readonly added: number;
420
+ readonly removed: number;
421
+ /** The patch as text, used for its size and its content when included. */
422
+ readonly patch: string;
423
+ readonly bytes: number;
424
+ /** Why the file is left out of the prompt, or undefined when it is in it. */
425
+ readonly leftOut: string | undefined;
426
+ readonly binary: boolean;
427
+ }
428
+
429
+ interface Attributes {
430
+ readonly vendored: boolean;
431
+ readonly generated: boolean;
432
+ readonly diffable: boolean;
433
+ readonly binary: boolean;
434
+ }
435
+
436
+ const NO_ATTRIBUTES: Attributes = {
437
+ vendored: false,
438
+ generated: false,
439
+ diffable: true,
440
+ binary: false,
441
+ };
442
+
443
+ /** Reads the attributes that decide whether a file belongs in a review diff. */
444
+ function attributesOf(
445
+ repositoryPath: string,
446
+ paths: readonly string[],
447
+ ): ReadonlyMap<string, Attributes> {
448
+ const map = new Map<string, Attributes>();
449
+ if (paths.length === 0) return map;
450
+ const result = git(
451
+ repositoryPath,
452
+ [
453
+ "check-attr",
454
+ "--stdin",
455
+ "-z",
456
+ "linguist-vendored",
457
+ "linguist-generated",
458
+ "diff",
459
+ "binary",
460
+ ],
461
+ { raw: true, input: `${paths.join("\0")}\0` },
462
+ );
463
+ if (!result.ok) return map;
464
+ const parts = result.out.split("\0");
465
+ for (let index = 0; index + 2 < parts.length; index += 3) {
466
+ const path = parts[index] ?? "";
467
+ const attribute = parts[index + 1] ?? "";
468
+ const value = parts[index + 2] ?? "";
469
+ const current = map.get(path) ?? NO_ATTRIBUTES;
470
+ const set = value !== "unspecified" && value !== "unset";
471
+ if (attribute === "linguist-vendored") {
472
+ map.set(path, { ...current, vendored: set });
473
+ } else if (attribute === "linguist-generated") {
474
+ map.set(path, { ...current, generated: set });
475
+ } else if (attribute === "diff") {
476
+ map.set(path, {
477
+ ...current,
478
+ diffable: value !== "unset" && value !== "binary",
479
+ });
480
+ } else if (attribute === "binary") {
481
+ map.set(path, { ...current, binary: set });
482
+ }
483
+ }
484
+ return map;
485
+ }
486
+
487
+ /** How a file changed, from `git diff --name-status`. */
488
+ interface Change {
489
+ readonly status: "added" | "deleted" | "renamed" | "other";
490
+ /** The old path of a renamed file. */
491
+ readonly from: string | undefined;
492
+ }
493
+
494
+ /** The status of every changed file, keyed by its new path. */
495
+ function changesOf(
496
+ repositoryPath: string,
497
+ base: string,
498
+ sha: string,
499
+ ): ReadonlyMap<string, Change> {
500
+ const map = new Map<string, Change>();
501
+ const result = git(
502
+ repositoryPath,
503
+ ["diff", "--name-status", "-M", "-z", base, sha],
504
+ { raw: true },
505
+ );
506
+ if (!result.ok) return map;
507
+ const parts = result.out.split("\0");
508
+ for (let index = 0; index < parts.length; ) {
509
+ const status = parts[index] ?? "";
510
+ if (status.length === 0) {
511
+ index += 1;
512
+ continue;
513
+ }
514
+ if (status.startsWith("R") || status.startsWith("C")) {
515
+ const from = parts[index + 1] ?? "";
516
+ const to = parts[index + 2] ?? "";
517
+ map.set(to, {
518
+ status: status.startsWith("R") ? "renamed" : "other",
519
+ from,
520
+ });
521
+ index += 3;
522
+ continue;
523
+ }
524
+ const path = parts[index + 1] ?? "";
525
+ map.set(path, {
526
+ status: status === "D" ? "deleted" : status === "A" ? "added" : "other",
527
+ from: undefined,
528
+ });
529
+ index += 2;
530
+ }
531
+ return map;
532
+ }
533
+
534
+ /**
535
+ * The changed files with line counts and what the prompt carries for each. A
536
+ * renamed file carries only its edits (one line when it has none); a deleted
537
+ * file carries one line, not its removed lines. The reviewer reads a deleted
538
+ * file with `git show <base>:<path>`.
539
+ */
540
+ function diffsOf(
541
+ repositoryPath: string,
542
+ base: string,
543
+ sha: string,
544
+ ): readonly FileDiff[] {
545
+ const numstat = git(
546
+ repositoryPath,
547
+ ["diff", "--numstat", "-M", "-z", base, sha],
548
+ { raw: true },
549
+ );
550
+ if (!numstat.ok) return [];
551
+ const changes = changesOf(repositoryPath, base, sha);
552
+ const files: FileDiff[] = [];
553
+ const parts = numstat.out.split("\0");
554
+ for (let index = 0; index < parts.length; index += 1) {
555
+ const record = parts[index] ?? "";
556
+ if (record.length === 0) continue;
557
+ const first = record.indexOf("\t");
558
+ const second = record.indexOf("\t", first + 1);
559
+ if (first < 0 || second < 0) continue;
560
+ const addedText = record.slice(0, first);
561
+ const removedText = record.slice(first + 1, second);
562
+ let path = record.slice(second + 1);
563
+ let from: string | undefined;
564
+ if (path.length === 0) {
565
+ // A rename: the two paths follow as records of their own.
566
+ from = parts[index + 1] ?? "";
567
+ path = parts[index + 2] ?? "";
568
+ index += 2;
569
+ }
570
+ if (path.length === 0) continue;
571
+ const binary = addedText === "-" || removedText === "-";
572
+ const added = binary ? 0 : Number(addedText) || 0;
573
+ const removed = binary ? 0 : Number(removedText) || 0;
574
+ const change = changes.get(path);
575
+ let patch = "";
576
+ if (binary) {
577
+ patch = "";
578
+ } else if (from !== undefined && added === 0 && removed === 0) {
579
+ patch = `renamed ${from} → ${path}, unchanged\n`;
580
+ } else if (change?.status === "deleted") {
581
+ patch = `${path}: deleted, ${removed} lines (read it with \`git show ${base}:${path}\`)\n`;
582
+ } else {
583
+ patch = git(repositoryPath, [
584
+ "diff",
585
+ "--no-color",
586
+ "--no-ext-diff",
587
+ "-M",
588
+ base,
589
+ sha,
590
+ "--",
591
+ ...(from === undefined ? [path] : [from, path]),
592
+ ]).out;
593
+ }
594
+ files.push({
595
+ path,
596
+ added,
597
+ removed,
598
+ patch,
599
+ bytes: Buffer.byteLength(patch, "utf8"),
600
+ leftOut: undefined,
601
+ binary,
602
+ });
603
+ }
604
+ return files;
605
+ }
606
+
607
+ interface PreparedDiff {
608
+ readonly files: readonly FileDiff[];
609
+ /** The files that go into the prompt, in path order. */
610
+ readonly included: readonly FileDiff[];
611
+ /** The files left out, with the reason, in path order. */
612
+ readonly leftOut: readonly FileDiff[];
613
+ /** The bytes of every diff the review could carry, not only the included ones. */
614
+ readonly bytes: number;
615
+ /** The bytes of the diff text that goes into the prompt. */
616
+ readonly includedBytes: number;
617
+ }
618
+
619
+ function reasonFor(
620
+ attributes: Attributes,
621
+ diff: FileDiff,
622
+ maxFileDiffBytes: number,
623
+ ): string | undefined {
624
+ if (attributes.vendored) return "vendored";
625
+ if (attributes.generated) return "generated";
626
+ if (attributes.binary || diff.binary) return "binary";
627
+ if (!attributes.diffable) return "not diffable";
628
+ if (diff.bytes > maxFileDiffBytes) return "too large";
629
+ return undefined;
630
+ }
631
+
632
+ /** True when a file is left out because of an attribute, not its size. */
633
+ function excludedByAttribute(
634
+ attributes: Attributes,
635
+ diff: FileDiff,
636
+ ): boolean {
637
+ return (
638
+ attributes.vendored ||
639
+ attributes.generated ||
640
+ attributes.binary ||
641
+ diff.binary ||
642
+ !attributes.diffable
643
+ );
644
+ }
645
+
646
+ /**
647
+ * Prepares the diff for a review prompt. Vendored and non-diffable files never
648
+ * enter the prompt, and neither does a file whose own diff is over the limit;
649
+ * every one of them is listed so the reviewer knows it exists.
650
+ */
651
+ export function normalizePath(path: string): string {
652
+ return path.startsWith("./") ? path.slice(2) : path;
653
+ }
654
+
655
+ function prepareDiff(
656
+ repositoryPath: string,
657
+ base: string,
658
+ sha: string,
659
+ reviewer: ReviewerSettings,
660
+ attributesCwd: string = repositoryPath,
661
+ ): PreparedDiff {
662
+ const diffs = diffsOf(repositoryPath, base, sha);
663
+ const attributes = attributesOf(
664
+ attributesCwd,
665
+ diffs.map((diff) => diff.path),
666
+ );
667
+ const files = diffs.map((diff) => {
668
+ const reason = reasonFor(
669
+ attributes.get(diff.path) ?? NO_ATTRIBUTES,
670
+ diff,
671
+ reviewer.maxFileDiffBytes,
672
+ );
673
+ return { ...diff, leftOut: reason };
674
+ });
675
+ // The size check counts every file that is not vendored or not diffable:
676
+ // leaving a huge real-code file out of the prompt must not hide it.
677
+ const bytes = files
678
+ .filter(
679
+ (file) =>
680
+ !excludedByAttribute(
681
+ attributes.get(file.path) ?? NO_ATTRIBUTES,
682
+ file,
683
+ ),
684
+ )
685
+ .reduce((sum, file) => sum + file.bytes, 0);
686
+ const included = files.filter((file) => file.leftOut === undefined);
687
+ const leftOut = files.filter((file) => file.leftOut !== undefined);
688
+ return {
689
+ files,
690
+ included,
691
+ leftOut,
692
+ bytes,
693
+ includedBytes: included.reduce((sum, file) => sum + file.bytes, 0),
694
+ };
695
+ }
696
+
697
+ /** The line that tells the reviewer a file was left out and why. */
698
+ export function leftOutLine(file: FileDiff): string {
699
+ return `- ${file.path} (+${file.added}/-${file.removed}) — ${file.leftOut ?? "left out"}`;
700
+ }
701
+
702
+ function severityRank(severity: string): number {
703
+ if (severity === "critical") return 3;
704
+ if (severity === "major") return 2;
705
+ if (severity === "minor") return 1;
706
+ return 0;
707
+ }
708
+
709
+ function levelRank(level: FixLevel): number {
710
+ return severityRank(level);
711
+ }
712
+
713
+ function atOrAbove(severity: string, level: FixLevel): boolean {
714
+ return severityRank(severity) >= levelRank(level);
715
+ }
716
+
717
+ interface FindingShape {
718
+ readonly file: string;
719
+ readonly line: number;
720
+ readonly severity: string;
721
+ readonly summary: string;
722
+ readonly trigger: string;
723
+ }
724
+
725
+ function parseFinding(value: unknown): FindingShape | undefined {
726
+ if (!isRecord(value)) return undefined;
727
+ if (typeof value.file !== "string" || value.file.length === 0) return undefined;
728
+ const severity = value.severity;
729
+ if (
730
+ severity !== "critical" &&
731
+ severity !== "major" &&
732
+ severity !== "minor"
733
+ ) {
734
+ return undefined;
735
+ }
736
+ // Every field the prompt asks for is required: a finding without them is a
737
+ // malformed report, and the step retries instead of recording a blank one.
738
+ const line = value.line;
739
+ if (typeof line !== "number" || !Number.isFinite(line)) return undefined;
740
+ if (typeof value.summary !== "string") return undefined;
741
+ if (typeof value.trigger !== "string") return undefined;
742
+ return {
743
+ file: value.file,
744
+ line,
745
+ severity,
746
+ summary: value.summary,
747
+ trigger: value.trigger,
748
+ };
749
+ }
750
+
751
+ interface Report {
752
+ readonly findings: readonly FindingShape[];
753
+ readonly verified: readonly string[];
754
+ /** The commit the reviewer says it read; absent when it did not say, which dev refuses. */
755
+ readonly sha?: string;
756
+ }
757
+
758
+ function parseReport(text: string): Report | undefined {
759
+ let value: unknown;
760
+ try {
761
+ value = JSON.parse(text);
762
+ } catch {
763
+ return undefined;
764
+ }
765
+ if (!isRecord(value)) return undefined;
766
+ if (!Array.isArray(value.findings)) return undefined;
767
+ if (!Array.isArray(value.verified)) return undefined;
768
+ if (!value.verified.every((item) => typeof item === "string")) return undefined;
769
+ const findings: FindingShape[] = [];
770
+ for (const item of value.findings) {
771
+ const finding = parseFinding(item);
772
+ if (finding === undefined) return undefined;
773
+ findings.push(finding);
774
+ }
775
+ if (value.sha !== undefined && typeof value.sha !== "string") return undefined;
776
+ return {
777
+ findings,
778
+ verified: value.verified as readonly string[],
779
+ ...(typeof value.sha === "string" ? { sha: value.sha } : {}),
780
+ };
781
+ }
782
+
783
+ /** The flow whose grading the review reads when a stage names none. */
784
+ const REVIEW_FLOW = "dev";
785
+
786
+ /**
787
+ * The repository's grading for this flow. An invalid review.json fails the
788
+ * step the way an invalid dev.json does. A review stage may name its entry.
789
+ */
790
+ function gradingOf(context: TaskContext, params: unknown): Grading {
791
+ const given = ((params ?? {}) as { readonly grading?: unknown }).grading;
792
+ const flow = typeof given === "string" && given.length > 0 ? given : REVIEW_FLOW;
793
+ try {
794
+ return readReviewGrading(context.repository.path, flow);
795
+ } catch (error) {
796
+ if (error instanceof ReviewGradingError) {
797
+ throw new DevError(
798
+ "review.json",
799
+ error.message.slice("review.json: ".length),
800
+ );
801
+ }
802
+ throw error;
803
+ }
804
+ }
805
+
806
+ /**
807
+ * When this flow's grading sets no fixLevel, the strictest of dev.json's and
808
+ * every level review.json sets for any flow, so a run never reviews with a
809
+ * weaker level than the repository configures anywhere. Undefined when
810
+ * review.json sets none, which leaves dev.json's.
811
+ */
812
+ function strictestElsewhere(context: TaskContext): FixLevel | undefined {
813
+ try {
814
+ const other = strictestFixLevel(context.repository.path);
815
+ if (other === undefined) return undefined;
816
+ return levelRank(other) < levelRank(context.settings.reviewer.fixLevel)
817
+ ? other
818
+ : context.settings.reviewer.fixLevel;
819
+ } catch (error) {
820
+ if (error instanceof ReviewGradingError) {
821
+ throw new DevError("review.json", error.message.slice("review.json: ".length));
822
+ }
823
+ throw error;
824
+ }
825
+ }
826
+
827
+ /** The context with review.json's fixLevel, when set, over dev.json's. */
828
+ function gradedContext(
829
+ context: TaskContext,
830
+ params: unknown,
831
+ ): {
832
+ readonly context: TaskContext;
833
+ readonly grading: Grading;
834
+ } {
835
+ const grading = gradingOf(context, params);
836
+ const fixLevel = grading.fixLevel ?? strictestElsewhere(context);
837
+ if (fixLevel === undefined) return { context, grading };
838
+ return {
839
+ grading,
840
+ context: {
841
+ ...context,
842
+ settings: {
843
+ ...context.settings,
844
+ reviewer: { ...context.settings.reviewer, fixLevel },
845
+ },
846
+ },
847
+ };
848
+ }
849
+
850
+ /** The "## Grading" section's lines: the levels and rules, verbatim. */
851
+ function gradingLines(grading: Grading): string[] {
852
+ const lines: string[] = [];
853
+ for (const level of ["critical", "major", "minor"] as const) {
854
+ const text = grading.levels?.[level];
855
+ if (text !== undefined) lines.push(`- ${level}: ${text}`);
856
+ }
857
+ for (const rule of grading.rules ?? []) lines.push(`- ${rule}`);
858
+ return lines;
859
+ }
860
+
861
+ /** What a rework round's prompt holds beside the brief. */
862
+ interface ReworkPrompt {
863
+ readonly previousSha: string;
864
+ readonly previous: readonly PreviousFinding[];
865
+ readonly commits: string;
866
+ readonly increment: Increment;
867
+ }
868
+
869
+ function reviewPrompt(
870
+ task: TaskData,
871
+ sha: string,
872
+ base: string,
873
+ prepared: PreparedDiff,
874
+ resultPath: string,
875
+ grading: Grading,
876
+ prepare: readonly string[] = [],
877
+ rework?: ReworkPrompt,
878
+ checks: readonly string[] = [],
879
+ ): string {
880
+ const pieces: string[] = [
881
+ `Review the changes of task ${task.title}.`,
882
+ "## Brief",
883
+ briefText(task).trim(),
884
+ ];
885
+ const graded = gradingLines(grading);
886
+ if (graded.length > 0) pieces.push("## Grading", graded.join("\n"));
887
+ if (rework !== undefined) {
888
+ pieces.push(
889
+ "## Previous review",
890
+ `This is a rework round. The previous review looked at ${rework.previousSha} and found these blocking problems:`,
891
+ rework.previous.length === 0
892
+ ? "(none)"
893
+ : rework.previous.map(previousLine).join("\n"),
894
+ "## Commits since the previous review",
895
+ rework.commits.length === 0 ? "(none)" : rework.commits,
896
+ "## Increment",
897
+ `The task's own diff, restricted to the hunks that changed since ${rework.previousSha}. The full diff is not here; read any file you need.`,
898
+ rework.increment.added.length === 0
899
+ ? "No hunk of the task's own diff changed since the previous review."
900
+ : rework.increment.added,
901
+ ...(rework.increment.removed.length === 0
902
+ ? []
903
+ : [
904
+ "## Removed since the previous review",
905
+ "These hunks of the previous review's diff are gone or changed; this is their old content:",
906
+ rework.increment.removed,
907
+ ]),
908
+ );
909
+ } else if (prepared.included.length === 0) {
910
+ pieces.push("## Diff", "The change has no diff to review.");
911
+ } else {
912
+ pieces.push(
913
+ "## Diff",
914
+ `The diff from the merge base ${base} to the verified commit ${sha}:`,
915
+ prepared.included.map((file) => file.patch).join(""),
916
+ );
917
+ }
918
+ if (prepared.leftOut.length > 0) {
919
+ pieces.push(
920
+ "## Files left out of the diff",
921
+ "These files changed but their content is not in the diff:",
922
+ prepared.leftOut.map(leftOutLine).join("\n"),
923
+ );
924
+ }
925
+ if (prepare.length > 0) {
926
+ pieces.push(
927
+ "## The checkout",
928
+ [
929
+ "The checkout you are in is prepared: these commands already ran in it, so do not install anything. Packages of this repository resolve to the code in this checkout.",
930
+ ...prepare.map((line) => `- \`${line}\``),
931
+ ].join("\n"),
932
+ );
933
+ }
934
+ pieces.push(
935
+ "## Checks already run",
936
+ [
937
+ checks.length === 0
938
+ ? "No checks ran on this commit: the repository has none configured."
939
+ : `These checks already passed on this commit:\n${checks.map((line) => `- \`${line}\``).join("\n")}`,
940
+ checks.length === 0
941
+ ? "Do not run the repository's full test suite, nor anything that starts a simulator, a browser or a server. You may run one focused test file to confirm a suspicion, inside this checkout only. Do not copy the checkout elsewhere."
942
+ : "Do not run them again, nor the repository's full test suite, nor anything that starts a simulator, a browser or a server. You may run one focused test file to confirm a suspicion, inside this checkout only. Do not copy the checkout elsewhere.",
943
+ ].join("\n"),
944
+ "## What to write",
945
+ [
946
+ `Write a JSON object to ${resultPath} (inside the worktree you are in). The file must contain exactly (\`sha\` is the commit you reviewed, ${sha}):`,
947
+ `{ "findings": [{ "file": "<path>", "line": <number>, "severity": "critical|major|minor", "summary": "<one line>", "trigger": "<what causes it>" }], "verified": ["<what you checked>"], "sha": "${sha}" }`,
948
+ "List every problem you find; the gate decides which of them are old, not you.",
949
+ ...(rework === undefined
950
+ ? []
951
+ : [
952
+ "Check each previous problem above: in `verified`, write one entry per previous problem that says whether it is fixed or not fixed. Then review the increment.",
953
+ ]),
954
+ "Write only the JSON file. Do not change anything else in the worktree.",
955
+ ].join("\n"),
956
+ );
957
+ return pieces.join("\n\n");
958
+ }
959
+
960
+ /** What one call to a reviewer harness step produced. */
961
+ interface ReviewerCall {
962
+ readonly outcome:
963
+ | "report"
964
+ | "invalid"
965
+ | "no_report"
966
+ | "unavailable"
967
+ | "timed_out"
968
+ | "failed";
969
+ readonly report?: Report | undefined;
970
+ readonly message: string;
971
+ }
972
+
973
+ /** The largest review report the gate reads; anything bigger is not a report. */
974
+ const MAX_REPORT_BYTES = 1_000_000;
975
+
976
+ interface ReportRead {
977
+ readonly text?: string;
978
+ readonly message?: string;
979
+ /** The review folders were not plain directories, or changed during the read. */
980
+ readonly unsafe?: boolean;
981
+ }
982
+
983
+ /**
984
+ * Reads a reviewer report without trusting the path. The reviewer owns the
985
+ * gate worktree and can leave a FIFO or a link at the report path; the file is
986
+ * opened non-blocking without following a link, and the descriptor must still
987
+ * be a bounded regular file before anything is read.
988
+ */
989
+ function readReport(
990
+ resultPath: string,
991
+ guard?: () => string | undefined,
992
+ ): ReportRead {
993
+ const before = guard?.();
994
+ if (guard !== undefined && before === undefined) {
995
+ return {
996
+ message: `the review folders of ${resultPath} are not plain directories`,
997
+ unsafe: true,
998
+ };
999
+ }
1000
+ let details;
1001
+ try {
1002
+ details = lstatSync(resultPath);
1003
+ } catch {
1004
+ return { message: `the reviewer wrote no report at ${resultPath}` };
1005
+ }
1006
+ if (!details.isFile()) {
1007
+ return {
1008
+ message: `the review report at ${resultPath} is not a regular file`,
1009
+ };
1010
+ }
1011
+ if (details.size > MAX_REPORT_BYTES) {
1012
+ return {
1013
+ message: `the review report at ${resultPath} is over ${MAX_REPORT_BYTES} bytes`,
1014
+ };
1015
+ }
1016
+ let fd: number;
1017
+ try {
1018
+ fd = openSync(
1019
+ resultPath,
1020
+ fsConstants.O_RDONLY | fsConstants.O_NONBLOCK | fsConstants.O_NOFOLLOW,
1021
+ );
1022
+ } catch (error) {
1023
+ return { message: `cannot read ${resultPath}: ${String(error)}` };
1024
+ }
1025
+ try {
1026
+ // The path may have changed between `lstat` and `open`; the descriptor is
1027
+ // what is read, so a swap to a FIFO is caught here and cannot block.
1028
+ const opened = fstatSync(fd);
1029
+ if (!opened.isFile()) {
1030
+ return {
1031
+ message: `the review report at ${resultPath} is not a regular file`,
1032
+ };
1033
+ }
1034
+ if (opened.size > MAX_REPORT_BYTES) {
1035
+ return {
1036
+ message: `the review report at ${resultPath} is over ${MAX_REPORT_BYTES} bytes`,
1037
+ };
1038
+ }
1039
+ const buffer = Buffer.alloc(opened.size);
1040
+ let offset = 0;
1041
+ while (offset < buffer.length) {
1042
+ let count: number;
1043
+ try {
1044
+ count = readSync(fd, buffer, offset, buffer.length - offset, offset);
1045
+ } catch (error) {
1046
+ return { message: `cannot read ${resultPath}: ${String(error)}` };
1047
+ }
1048
+ if (count === 0) break;
1049
+ offset += count;
1050
+ }
1051
+ if (guard !== undefined) {
1052
+ reviewTestHooks.afterOpen?.();
1053
+ // The same plain directories must still be there after the read.
1054
+ if (guard() !== before) {
1055
+ return {
1056
+ message: `the review folders of ${resultPath} changed while the report was read`,
1057
+ unsafe: true,
1058
+ };
1059
+ }
1060
+ }
1061
+ return { text: buffer.subarray(0, offset).toString("utf8") };
1062
+ } finally {
1063
+ closeSync(fd);
1064
+ }
1065
+ }
1066
+
1067
+ /** The model a harness step names, or its step name when it names none. */
1068
+ function modelOf(use: string, args: readonly string[]): string {
1069
+ for (let index = 0; index < args.length; index += 1) {
1070
+ const arg = args[index] ?? "";
1071
+ if (arg === "--model") {
1072
+ const value = args[index + 1];
1073
+ return typeof value === "string" && value.length > 0 ? value : use;
1074
+ }
1075
+ if (arg.startsWith("--model=")) {
1076
+ const value = arg.slice("--model=".length);
1077
+ return value.length > 0 ? value : use;
1078
+ }
1079
+ }
1080
+ return use;
1081
+ }
1082
+
1083
+ /** The `kind` of the `modelError` a harness reports, when it reports one. */
1084
+ function modelErrorKind(data: Record<string, unknown>): string | undefined {
1085
+ const value = data.modelError;
1086
+ if (isRecord(value) && typeof value.kind === "string") return value.kind;
1087
+ return undefined;
1088
+ }
1089
+
1090
+ /** What a provider prints when it refuses a request for rate or load. */
1091
+ const UNAVAILABLE_STDERR =
1092
+ /\b(?:HTTP|status(?: code)?)[ :=]+429\b|\btoo many requests\b/i;
1093
+
1094
+ /** True when the tail of the harness's own error output names a 429. */
1095
+ function stderrSaysUnavailable(data: Record<string, unknown>): boolean {
1096
+ const tail = data.stderr;
1097
+ if (!Array.isArray(tail)) return false;
1098
+ return tail.some(
1099
+ (line) => typeof line === "string" && UNAVAILABLE_STDERR.test(line),
1100
+ );
1101
+ }
1102
+
1103
+ /**
1104
+ * Why a reviewer run failed: unavailable, timed out, or anything else. Only
1105
+ * the harness's `modelError` (and, when a harness reports none, an anchored
1106
+ * phrase in the tail of its error output) says unavailable; a number or a
1107
+ * word elsewhere in the data never does.
1108
+ */
1109
+ function failureOutcome(
1110
+ data: Record<string, unknown>,
1111
+ _message: string,
1112
+ ): "unavailable" | "timed_out" | "failed" {
1113
+ const kind = modelErrorKind(data);
1114
+ if (kind === "unavailable" || kind === "usage_limit") return "unavailable";
1115
+ const reason = typeof data.reason === "string" ? data.reason : undefined;
1116
+ if (reason === "wall" || reason === "stall" || reason === "timeout") {
1117
+ return "timed_out";
1118
+ }
1119
+ if (stderrSaysUnavailable(data)) return "unavailable";
1120
+ return "failed";
1121
+ }
1122
+
1123
+ /** Where one reviewer call leaves its outcome beside the report it wrote. */
1124
+ function reviewOutcomePath(resultPath: string): string {
1125
+ return resultPath.endsWith(".json")
1126
+ ? `${resultPath.slice(0, -".json".length)}.run.json`
1127
+ : `${resultPath}.run.json`;
1128
+ }
1129
+
1130
+ function writeReviewOutcome(path: string, call: ReviewerCall): void {
1131
+ try {
1132
+ writeFileSync(
1133
+ path,
1134
+ JSON.stringify({
1135
+ outcome: call.outcome,
1136
+ message: call.message,
1137
+ ...(call.report === undefined ? {} : { report: call.report }),
1138
+ }),
1139
+ );
1140
+ } catch {
1141
+ // A sidecar that cannot be written only costs one repeated run after a
1142
+ // crash; the review itself still continues.
1143
+ }
1144
+ }
1145
+
1146
+ const REVIEW_OUTCOMES: readonly ReviewerCall["outcome"][] = [
1147
+ "report",
1148
+ "invalid",
1149
+ "no_report",
1150
+ "unavailable",
1151
+ "timed_out",
1152
+ "failed",
1153
+ ];
1154
+
1155
+ /** The call a crashed review recorded, or undefined when it never answered. */
1156
+ function readReviewOutcome(resultPath: string): ReviewerCall | undefined {
1157
+ const read = readReport(reviewOutcomePath(resultPath));
1158
+ if (read.text === undefined) return undefined;
1159
+ let value: unknown;
1160
+ try {
1161
+ value = JSON.parse(read.text);
1162
+ } catch {
1163
+ return undefined;
1164
+ }
1165
+ if (!isRecord(value)) return undefined;
1166
+ const outcome = value.outcome;
1167
+ if (
1168
+ typeof outcome !== "string" ||
1169
+ !REVIEW_OUTCOMES.includes(outcome as ReviewerCall["outcome"])
1170
+ ) {
1171
+ return undefined;
1172
+ }
1173
+ const message = typeof value.message === "string" ? value.message : "";
1174
+ if (outcome !== "report") {
1175
+ return { outcome: outcome as ReviewerCall["outcome"], message };
1176
+ }
1177
+ const report = parseReport(JSON.stringify(value.report));
1178
+ if (report === undefined) return undefined;
1179
+ return { outcome: "report", report, message };
1180
+ }
1181
+
1182
+ /** The report path of one reviewer call, relative to the gate worktree. */
1183
+ function workspaceReportPath(
1184
+ gatePath: string,
1185
+ runId: string,
1186
+ attempt: number,
1187
+ round: number,
1188
+ tryNo: number,
1189
+ ): string {
1190
+ return join(
1191
+ gatePath,
1192
+ ".operad",
1193
+ "review",
1194
+ `${runId}-attempt-${attempt}-review-${round}-try-${tryNo}.json`,
1195
+ );
1196
+ }
1197
+
1198
+ /**
1199
+ * Makes sure `.operad/review` exists in the gate worktree as plain
1200
+ * directories, looking at every component with `lstat` and never following a
1201
+ * link. Returns the reason when it cannot, so no report is written there. It
1202
+ * creates folders and removes nothing.
1203
+ */
1204
+ function prepareReportFolder(
1205
+ gatePath: string,
1206
+ create = true,
1207
+ ): string | undefined {
1208
+ let folder = gatePath;
1209
+ for (const name of [".operad", "review"]) {
1210
+ folder = join(folder, name);
1211
+ let details = lstatOrUndefined(folder);
1212
+ if (details === undefined && create) {
1213
+ try {
1214
+ mkdirSync(folder);
1215
+ } catch {
1216
+ // Another process may have made it; look again below.
1217
+ }
1218
+ details = lstatOrUndefined(folder);
1219
+ }
1220
+ // Checking only: a folder that is not there holds no report to follow.
1221
+ if (details === undefined) return create ? `cannot create ${folder}` : undefined;
1222
+ if (!details.isDirectory()) {
1223
+ return `${folder} is not a plain directory (a link or a file), so the review report cannot be written under it`;
1224
+ }
1225
+ }
1226
+ return undefined;
1227
+ }
1228
+
1229
+ /**
1230
+ * The identity of `.operad` and `.operad/review` when both exist as plain
1231
+ * directories, otherwise undefined. Two equal identities mean the same
1232
+ * directories were there both times.
1233
+ */
1234
+ function folderIdentity(gatePath: string): string | undefined {
1235
+ const parts: string[] = [];
1236
+ let folder = gatePath;
1237
+ for (const name of [".operad", "review"]) {
1238
+ folder = join(folder, name);
1239
+ const details = lstatOrUndefined(folder);
1240
+ if (details === undefined || !details.isDirectory()) return undefined;
1241
+ parts.push(`${details.dev}:${details.ino}`);
1242
+ }
1243
+ return parts.join("/");
1244
+ }
1245
+
1246
+ function lstatOrUndefined(path: string): ReturnType<typeof lstatSync> | undefined {
1247
+ try {
1248
+ return lstatSync(path);
1249
+ } catch {
1250
+ return undefined;
1251
+ }
1252
+ }
1253
+
1254
+ /** The valid report at a path with its text, otherwise undefined. */
1255
+ function readValidReportText(
1256
+ path: string,
1257
+ gatePath: string,
1258
+ ): { readonly report: Report; readonly text: string } | undefined {
1259
+ const read = readReport(
1260
+ path,
1261
+ () => folderIdentity(gatePath),
1262
+ );
1263
+ if (read.text === undefined) return undefined;
1264
+ const report = parseReport(read.text);
1265
+ return report === undefined ? undefined : { report, text: read.text };
1266
+ }
1267
+
1268
+ /** Copies a valid report to the store record. Returns the failure, if any. */
1269
+ function copyToStore(storePath: string, text: string): string | undefined {
1270
+ try {
1271
+ reviewTestHooks.beforeCopy?.();
1272
+ writeFileSync(storePath, text);
1273
+ return undefined;
1274
+ } catch (error) {
1275
+ return `cannot write the review record at ${storePath}: ${messageOf(error)} (the report is still in the review workspace)`;
1276
+ }
1277
+ }
1278
+
1279
+ /**
1280
+ * One call to the reviewer, with its outcome written to disk before it
1281
+ * returns. A crash after the model answered therefore reads the outcome back
1282
+ * instead of asking the same model again.
1283
+ */
1284
+ async function callReviewer(
1285
+ ctx: StepContext,
1286
+ context: TaskContext,
1287
+ gatePath: string,
1288
+ prompt: string,
1289
+ reportPath: string,
1290
+ storePath: string,
1291
+ reviewer: { readonly use: string; readonly args: readonly string[] },
1292
+ limits: ReviewSettingsUsed,
1293
+ resuming: boolean,
1294
+ ): Promise<ReviewerCall> {
1295
+ const call = await callReviewerOnce(
1296
+ ctx,
1297
+ context,
1298
+ gatePath,
1299
+ prompt,
1300
+ reportPath,
1301
+ storePath,
1302
+ reviewer,
1303
+ limits,
1304
+ resuming,
1305
+ );
1306
+ writeReviewOutcome(reviewOutcomePath(storePath), call);
1307
+ return call;
1308
+ }
1309
+
1310
+ /** The reviewer's last words, from what its harness step reported. */
1311
+ function lastMessageOf(outcome: PluginStepResult): string {
1312
+ const data = isRecord(outcome.data) ? outcome.data : {};
1313
+ if (typeof data.finalMessage === "string") return data.finalMessage;
1314
+ if (typeof data.message === "string") return data.message;
1315
+ return "";
1316
+ }
1317
+
1318
+ async function callReviewerOnce(
1319
+ ctx: StepContext,
1320
+ context: TaskContext,
1321
+ gatePath: string,
1322
+ prompt: string,
1323
+ reportPath: string,
1324
+ storePath: string,
1325
+ reviewer: { readonly use: string; readonly args: readonly string[] },
1326
+ limits: ReviewSettingsUsed,
1327
+ resuming: boolean,
1328
+ ): Promise<ReviewerCall> {
1329
+ const runStep = ctx.runStep;
1330
+ if (runStep === undefined) {
1331
+ return {
1332
+ outcome: "failed",
1333
+ message: "the kernel did not offer a way to run the reviewer",
1334
+ };
1335
+ }
1336
+ const settings = context.settings.reviewer;
1337
+ if (resuming && prepareReportFolder(gatePath, false) === undefined) {
1338
+ // A valid report already on disk is the answer: a crash between the
1339
+ // report and its recorded outcome must not ask the model again. The
1340
+ // workspace path comes first; a run whose older prompt named the store
1341
+ // path left its report there.
1342
+ const inWorkspace = readValidReportText(reportPath, gatePath);
1343
+ if (inWorkspace !== undefined) {
1344
+ const failure = copyToStore(storePath, inWorkspace.text);
1345
+ if (failure !== undefined) return { outcome: "failed", message: failure };
1346
+ return { outcome: "report", report: inWorkspace.report, message: "" };
1347
+ }
1348
+ if (lstatOrUndefined(reportPath) === undefined) {
1349
+ const inStore = readValidReport(storePath);
1350
+ if (inStore !== undefined) {
1351
+ return { outcome: "report", report: inStore, message: "" };
1352
+ }
1353
+ }
1354
+ }
1355
+ // The store copy and its sidecar belong to dev; the review workspace is
1356
+ // never cleaned.
1357
+ for (const stale of [storePath, reviewOutcomePath(storePath)]) {
1358
+ try {
1359
+ rmSync(stale, { force: true });
1360
+ } catch {
1361
+ // A record that cannot be removed is overwritten when a report is copied.
1362
+ }
1363
+ }
1364
+ const folderFailure = prepareReportFolder(gatePath);
1365
+ if (folderFailure !== undefined) {
1366
+ return { outcome: "failed", message: folderFailure };
1367
+ }
1368
+ if (lstatOrUndefined(reportPath) !== undefined) {
1369
+ return {
1370
+ outcome: "failed",
1371
+ message: `a file already exists at the report path ${reportPath}; it is left as it is and no report is written there`,
1372
+ };
1373
+ }
1374
+ let outcome: PluginStepResult | undefined;
1375
+ let thrown: string | undefined;
1376
+ try {
1377
+ outcome = await runStep(
1378
+ reviewer.use,
1379
+ {
1380
+ prompt,
1381
+ cwd: gatePath,
1382
+ args: reviewer.args,
1383
+ wallTimeSecs: limits.timeoutSecs,
1384
+ ...(limits.stallSecs === undefined
1385
+ ? {}
1386
+ : { stallSecs: limits.stallSecs }),
1387
+ resultPath: reportPath,
1388
+ },
1389
+ stepOptions(ctx, gatePath),
1390
+ );
1391
+ } catch (error) {
1392
+ thrown = messageOf(error);
1393
+ }
1394
+ // The reviewer owned the worktree during the call. The folders must still be
1395
+ // plain directories (a missing one is a failure too) before anything is read.
1396
+ const folders = (): string | undefined => folderIdentity(gatePath);
1397
+ if (folders() === undefined) {
1398
+ return {
1399
+ outcome: "failed",
1400
+ message: `${join(gatePath, ".operad", "review")} is not a plain directory any more, so the review report is not read`,
1401
+ };
1402
+ }
1403
+ // How the round is named: a valid report is used whatever the harness
1404
+ // result; a file that fails validation is invalid; with no file a timeout or
1405
+ // an unavailable model keeps its own rule, and anything else is a report
1406
+ // the reviewer could not write.
1407
+ const read = readReport(reportPath, folders);
1408
+ if (read.unsafe === true) {
1409
+ return { outcome: "failed", message: read.message ?? "unsafe report" };
1410
+ }
1411
+ if (read.text !== undefined) {
1412
+ const report = parseReport(read.text);
1413
+ if (report === undefined) {
1414
+ return {
1415
+ outcome: "invalid",
1416
+ message: `the review report at ${reportPath} is not the expected JSON`,
1417
+ };
1418
+ }
1419
+ const failure = copyToStore(storePath, read.text);
1420
+ if (failure !== undefined) return { outcome: "failed", message: failure };
1421
+ return { outcome: "report", report, message: "" };
1422
+ }
1423
+ if (lstatOrUndefined(reportPath) !== undefined) {
1424
+ return {
1425
+ outcome: "invalid",
1426
+ message: read.message ?? `cannot read ${reportPath}`,
1427
+ };
1428
+ }
1429
+ if (outcome === undefined) {
1430
+ const message = thrown ?? "the reviewer did not run";
1431
+ return { outcome: failureOutcome({}, message), message };
1432
+ }
1433
+ const data = isRecord(outcome.data) ? outcome.data : {};
1434
+ if (outcome.result !== "done") {
1435
+ const message =
1436
+ typeof data.message === "string"
1437
+ ? data.message
1438
+ : `the reviewer ended "${outcome.result}"`;
1439
+ const kind = failureOutcome(data, message);
1440
+ if (kind === "timed_out" || kind === "unavailable") {
1441
+ return { outcome: kind, message };
1442
+ }
1443
+ }
1444
+ return { outcome: "no_report", message: lastMessageOf(outcome) };
1445
+ }
1446
+
1447
+ /** The report at a path when it reads and parses, otherwise undefined. */
1448
+ function readValidReport(resultPath: string): Report | undefined {
1449
+ const read = readReport(resultPath);
1450
+ if (read.text === undefined) return undefined;
1451
+ return parseReport(read.text);
1452
+ }
1453
+
1454
+ function reviewData(
1455
+ result: string,
1456
+ sha: string,
1457
+ extra: Readonly<Record<string, unknown>>,
1458
+ ): Record<string, unknown> {
1459
+ return { result, sha, ...extra };
1460
+ }
1461
+
1462
+ /** The step result a finished review record stands for. */
1463
+ function stepResultOf(record: ReviewRecord): string {
1464
+ if (record.reason === "exhausted") return "exhausted";
1465
+ if (record.reason === "out_of_time") return "out_of_time";
1466
+ if (record.decision === "passed") return "pass";
1467
+ if (record.decision === "findings") return "fail";
1468
+ if (record.decision === "unavailable") return "unavailable";
1469
+ if (record.decision === "timed_out") return "timed_out";
1470
+ if (record.result === "pass" || record.result === "passed") return "pass";
1471
+ if (record.result === "fail" || record.result === "findings") return "fail";
1472
+ return "failed";
1473
+ }
1474
+
1475
+ /** A review step that runs again after a crash reads the round it recorded. */
1476
+ function replayReview(
1477
+ record: ReviewRecord,
1478
+ attempt: TaskAttempt,
1479
+ ): PluginStepResult {
1480
+ const stepResult = stepResultOf(record);
1481
+ return {
1482
+ result: stepResult,
1483
+ data: reviewData(stepResult, record.sha ?? "", {
1484
+ attempt: attempt.number,
1485
+ ...(record.decision === undefined || record.decision === null
1486
+ ? {}
1487
+ : { decision: record.decision }),
1488
+ ...(record.round === undefined || record.round === null
1489
+ ? {}
1490
+ : { round: record.round }),
1491
+ ...(record.model === undefined || record.model === null
1492
+ ? {}
1493
+ : { model: record.model }),
1494
+ ...(record.retryAt === undefined || record.retryAt === null
1495
+ ? {}
1496
+ : { retryAt: record.retryAt }),
1497
+ ...(record.runs === undefined ? {} : { runs: record.runs }),
1498
+ ...(record.findings === undefined ? {} : { findings: record.findings }),
1499
+ ...(record.verified === undefined ? {} : { verified: record.verified }),
1500
+ ...(record.message === undefined || record.message === null
1501
+ ? {}
1502
+ : { message: record.message }),
1503
+ ...(record.reviewSettings === undefined || record.reviewSettings === null
1504
+ ? {}
1505
+ : { reviewSettings: record.reviewSettings }),
1506
+ replayed: true,
1507
+ }),
1508
+ };
1509
+ }
1510
+
1511
+ interface ReviewAction {
1512
+ readonly role: ReviewRunRole;
1513
+ readonly reason: ReviewRunReason;
1514
+ }
1515
+
1516
+ type ReviewNext =
1517
+ | ReviewAction
1518
+ | "done"
1519
+ | "wait-unavailable"
1520
+ | "wait-timed-out"
1521
+ | "wait-exhausted"
1522
+ | "out-of-time"
1523
+ | "failed";
1524
+
1525
+ /**
1526
+ * What the next run of a review round is. A report ends the round; an
1527
+ * unavailable primary goes to the fallback once; a timeout is retried once on
1528
+ * the same model; an invalid report is retried once. Every other state ends
1529
+ * the round for a person or for a wait.
1530
+ */
1531
+ function nextReviewAction(
1532
+ runs: readonly ReviewRunRecord[],
1533
+ fallback: ReviewerFallback | undefined,
1534
+ ): ReviewNext {
1535
+ const last = runs[runs.length - 1];
1536
+ if (last === undefined) return { role: "primary", reason: "initial" };
1537
+ switch (last.outcome) {
1538
+ case "report":
1539
+ return "done";
1540
+ case "unavailable":
1541
+ // A round uses its fallback exactly once, even when it runs again after
1542
+ // `retryAt`: a later primary failure waits instead of trying it again.
1543
+ if (
1544
+ last.role === "primary" &&
1545
+ fallback !== undefined &&
1546
+ !runs.some((run) => run.role === "fallback")
1547
+ ) {
1548
+ return { role: "fallback", reason: "fallback" };
1549
+ }
1550
+ return "wait-unavailable";
1551
+ case "timed_out": {
1552
+ const before = runs[runs.length - 2];
1553
+ if (
1554
+ before !== undefined &&
1555
+ before.outcome === "timed_out" &&
1556
+ before.role === last.role
1557
+ ) {
1558
+ return "wait-timed-out";
1559
+ }
1560
+ return { role: last.role, reason: "retry" };
1561
+ }
1562
+ case "invalid":
1563
+ case "no_report": {
1564
+ const before = runs[runs.length - 2];
1565
+ if (
1566
+ before !== undefined &&
1567
+ (before.outcome === "invalid" || before.outcome === "no_report") &&
1568
+ before.role === last.role
1569
+ ) {
1570
+ return "failed";
1571
+ }
1572
+ return { role: last.role, reason: "retry" };
1573
+ }
1574
+ case "failed":
1575
+ return "failed";
1576
+ }
1577
+ }
1578
+
1579
+ /** One run in words a person can read. */
1580
+ function runPhrase(run: ReviewRunRecord): string {
1581
+ const who = run.role === "fallback" ? `fallback ${run.model}` : run.model;
1582
+ switch (run.outcome) {
1583
+ case "report":
1584
+ return `${who} reviewed`;
1585
+ case "unavailable":
1586
+ return `${who} was unavailable${run.message === undefined || run.message === null ? "" : ` (${run.message})`}`;
1587
+ case "timed_out":
1588
+ return `${who} timed out`;
1589
+ case "invalid":
1590
+ return `${who} wrote an invalid report`;
1591
+ case "no_report":
1592
+ return `${who} could not write the report${run.message === undefined || run.message === null || run.message.length === 0 ? "" : ` (last message: ${run.message})`}`;
1593
+ case "failed":
1594
+ return `${who} failed${run.message === undefined || run.message === null ? "" : ` (${run.message})`}`;
1595
+ }
1596
+ }
1597
+
1598
+ /** Why a round ended the way it did, as the history line shows it. */
1599
+ function reviewMessage(
1600
+ decision: "passed" | "findings" | "unavailable" | "timed_out",
1601
+ runs: readonly ReviewRunRecord[],
1602
+ retryAt?: number,
1603
+ ): string {
1604
+ if (decision === "timed_out") return "review timed out twice";
1605
+ const parts = runs.map(runPhrase);
1606
+ if (decision === "unavailable" && retryAt !== undefined) {
1607
+ parts.push(`it runs again at ${new Date(retryAt).toISOString()}`);
1608
+ }
1609
+ return parts.join("; ");
1610
+ }
1611
+
1612
+ /** Test-only hooks: a child process crashes at a named point in a review. */
1613
+ export const reviewTestHooks: {
1614
+ now?: (() => number) | undefined;
1615
+ /** Waits instead of the real timer, so a test can move the clock. */
1616
+ wait?:
1617
+ | ((ms: number, signal: AbortSignal | undefined) => Promise<boolean>)
1618
+ | undefined;
1619
+ beforeRun?:
1620
+ | ((run: { readonly role: ReviewRunRole; readonly reason: ReviewRunReason }) => void)
1621
+ | undefined;
1622
+ /** Runs after the reviewer answered and before its run is written. */
1623
+ afterCall?:
1624
+ | ((run: { readonly role: ReviewRunRole; readonly reason: ReviewRunReason }) => void)
1625
+ | undefined;
1626
+ afterRunSaved?: ((run: ReviewRunRecord) => void) | undefined;
1627
+ /** Runs after the reviewer wrote a valid report, before the store copy. */
1628
+ beforeCopy?: (() => void) | undefined;
1629
+ /** Runs while a workspace report is open, before the folders are checked again. */
1630
+ afterOpen?: (() => void) | undefined;
1631
+ } = {};
1632
+
1633
+ /** The task's notes with this round's findings that did not fail it. */
1634
+ function notesOf(
1635
+ task: TaskData,
1636
+ record: ReviewRecord,
1637
+ attempt: number,
1638
+ round: number,
1639
+ fixLevel: FixLevel,
1640
+ ): { readonly reviewNotes?: readonly ReviewNotes[] } {
1641
+ const findings: ReviewNote[] = (record.findings ?? [])
1642
+ .filter(
1643
+ (finding) =>
1644
+ finding.preExisting === true ||
1645
+ finding.pre_existing === true ||
1646
+ !atOrAbove(finding.severity, fixLevel),
1647
+ )
1648
+ .map((finding) => ({
1649
+ severity: finding.severity,
1650
+ file: finding.file,
1651
+ line: typeof finding.line === "number" ? finding.line : null,
1652
+ summary: finding.summary,
1653
+ }));
1654
+ if (findings.length === 0) return {};
1655
+ const old = Array.isArray(task.reviewNotes) ? task.reviewNotes : [];
1656
+ return { reviewNotes: [...old, { attempt, round, findings }] };
1657
+ }
1658
+
1659
+ /** The task's review history with this record added, when it holds a report. */
1660
+ function historyOf(
1661
+ task: TaskData,
1662
+ record: ReviewRecord,
1663
+ attempt: number,
1664
+ fixLevel: FixLevel,
1665
+ ): { readonly reviewHistory?: readonly ReviewHistoryEntry[] } {
1666
+ if (
1667
+ (record.decision !== "passed" && record.decision !== "findings") ||
1668
+ typeof record.sha !== "string" ||
1669
+ record.sha.length === 0
1670
+ ) {
1671
+ return {};
1672
+ }
1673
+ const blocking: PreviousFinding[] = (record.findings ?? [])
1674
+ .filter(
1675
+ (finding) =>
1676
+ finding.preExisting !== true &&
1677
+ finding.pre_existing !== true &&
1678
+ atOrAbove(finding.severity, fixLevel),
1679
+ )
1680
+ .map((finding) => ({
1681
+ severity: finding.severity,
1682
+ file: finding.file,
1683
+ line: typeof finding.line === "number" ? finding.line : null,
1684
+ summary: finding.summary,
1685
+ }));
1686
+ const old = Array.isArray(task.reviewHistory) ? task.reviewHistory : [];
1687
+ return {
1688
+ reviewHistory: [
1689
+ ...old,
1690
+ {
1691
+ ...(typeof record.base === "string" ? { base: record.base } : {}),
1692
+ attempt,
1693
+ round: typeof record.round === "number" ? record.round : 1,
1694
+ sha: record.sha,
1695
+ blocking,
1696
+ },
1697
+ ].slice(-10),
1698
+ };
1699
+ }
1700
+
1701
+ function reworkPromptOf(
1702
+ repositoryPath: string,
1703
+ settings: DevSettings,
1704
+ followed: ReviewHistoryEntry,
1705
+ sha: string,
1706
+ prepared: PreparedDiff,
1707
+ gatePath: string,
1708
+ ): ReworkPrompt {
1709
+ const reviewer = settings.reviewer;
1710
+ // The previous review's own diff: its recorded merge base, or the merge base
1711
+ // of the remote main and the previous commit when none was recorded.
1712
+ const recorded =
1713
+ followed.base !== undefined &&
1714
+ git(repositoryPath, ["cat-file", "-e", `${followed.base}^{commit}`]).ok
1715
+ ? followed.base
1716
+ : mergeBase(repositoryPath, settings, followed.sha);
1717
+ // Both sides are prepared the same way, so a file the review diff leaves out
1718
+ // (or shows as a one-line placeholder) is the same on both.
1719
+ const before =
1720
+ recorded === undefined
1721
+ ? []
1722
+ : prepareDiff(repositoryPath, recorded, followed.sha, reviewer, gatePath)
1723
+ .included;
1724
+ const leftOutNow = new Set(prepared.leftOut.map((file) => file.path));
1725
+ const previousPatches = new Map(
1726
+ before
1727
+ .filter((file) => !leftOutNow.has(file.path))
1728
+ .map((file) => [file.path, file.patch]),
1729
+ );
1730
+ const now = new Map(prepared.included.map((file) => [file.path, file.patch]));
1731
+ return {
1732
+ previousSha: followed.sha,
1733
+ previous: followed.blocking,
1734
+ commits: git(repositoryPath, [
1735
+ "log",
1736
+ "--oneline",
1737
+ `${followed.sha}..${sha}`,
1738
+ ]).out,
1739
+ increment: incrementOf(previousPatches, now),
1740
+ };
1741
+ }
1742
+
1743
+ /** The string list a stage parameter holds, when it holds one. */
1744
+ function stringsOf(value: unknown): readonly string[] | undefined {
1745
+ if (!Array.isArray(value)) return undefined;
1746
+ return value.every((item): item is string => typeof item === "string")
1747
+ ? value
1748
+ : undefined;
1749
+ }
1750
+
1751
+ /**
1752
+ * A reviewer overlaid with its stage's parameters. `use` and `args` apply to
1753
+ * every review of the stage; `later` replaces the arguments after the first
1754
+ * review of an attempt.
1755
+ */
1756
+ function stageReviewerOf(
1757
+ base: ReviewerSettings,
1758
+ params: unknown,
1759
+ laterRound: boolean,
1760
+ ): ReviewerSettings {
1761
+ const given = (params ?? {}) as {
1762
+ readonly use?: unknown;
1763
+ readonly args?: unknown;
1764
+ readonly later?: unknown;
1765
+ };
1766
+ const use = typeof given.use === "string" ? given.use : undefined;
1767
+ const args = stringsOf(given.args);
1768
+ const later = stringsOf(given.later);
1769
+ const first = base.first;
1770
+ const stage: ReviewerSettings = {
1771
+ ...base,
1772
+ ...(use === undefined ? {} : { use }),
1773
+ ...(args === undefined
1774
+ ? {}
1775
+ : {
1776
+ args,
1777
+ firstArgs: args,
1778
+ ...(first === undefined ? {} : { first: { ...first, args } }),
1779
+ }),
1780
+ ...(first !== undefined && use !== undefined
1781
+ ? { first: { ...first, use, ...(args === undefined ? {} : { args }) } }
1782
+ : {}),
1783
+ };
1784
+ if (!laterRound || later === undefined) return stage;
1785
+ // `later` is the task's second round on: it replaces the first-review
1786
+ // arguments too, which a rework's first review of an attempt would keep.
1787
+ const { firstArgs: _firstArgs, first: _first, ...rest } = stage;
1788
+ return { ...rest, args: later };
1789
+ }
1790
+
1791
+ /** Step `dev/review`: have the reviewer read the verified commit's diff. */
1792
+ export async function runReview(
1793
+ ctx: StepContext,
1794
+ ): Promise<PluginStepResult> {
1795
+ const { context, grading } = gradedContext(await taskContext(ctx), ctx.params);
1796
+ if (!claimAllows(ctx, context.task)) return cancelledStep();
1797
+ const task = context.task;
1798
+ const attempt = attemptOf(ctx, task);
1799
+ const reviews =
1800
+ typeof attempt.reviews === "number" ? attempt.reviews : 0;
1801
+ const round = reviews + 1;
1802
+ const now = reviewTestHooks.now?.() ?? Date.now();
1803
+ const previous = attempt.review;
1804
+
1805
+ // A record without a decision came from before review rounds existed; a
1806
+ // record with one is read back when the same round already ended.
1807
+ if (
1808
+ previous !== undefined &&
1809
+ previous !== null &&
1810
+ previous.decision === undefined &&
1811
+ previous.run === ctx.runId
1812
+ ) {
1813
+ return replayReview(previous, attempt);
1814
+ }
1815
+ if (previous !== undefined && previous !== null) {
1816
+ const finished =
1817
+ previous.decision === "passed" ||
1818
+ previous.decision === "findings" ||
1819
+ previous.decision === "timed_out" ||
1820
+ previous.reason === "exhausted" ||
1821
+ previous.reason === "out_of_time";
1822
+ // A round recorded for another commit is not this commit's review.
1823
+ const sameCommit =
1824
+ typeof previous.sha !== "string" ||
1825
+ typeof attempt.verified !== "string" ||
1826
+ previous.sha === attempt.verified;
1827
+ if (
1828
+ finished &&
1829
+ sameCommit &&
1830
+ (previous.round === round || previous.run === ctx.runId)
1831
+ ) {
1832
+ return replayReview(previous, attempt);
1833
+ }
1834
+ if (previous.round === round && previous.decision === "unavailable") {
1835
+ const retryAt =
1836
+ typeof previous.retryAt === "number" ? previous.retryAt : 0;
1837
+ // Wait until the recorded time; a recovered step asks no model again.
1838
+ if (now < retryAt) return replayReview(previous, attempt);
1839
+ }
1840
+ }
1841
+
1842
+ const sha = attempt.verified;
1843
+ let current: TaskAttempt = attempt;
1844
+ // The settings the round ran with; set once the round's kind is known.
1845
+ let used: ReviewSettingsUsed | undefined;
1846
+ const finish = async (
1847
+ recorded: ReviewRecord,
1848
+ stepResult: string,
1849
+ extra: Readonly<Record<string, unknown>> = {},
1850
+ ): Promise<PluginStepResult> => {
1851
+ // A report from the fallback harness ran with the fallback's harness and
1852
+ // arguments; only the limits carried over from the round.
1853
+ const lastRun = recorded.runs?.[recorded.runs.length - 1];
1854
+ const fallback = context.settings.reviewer.fallback;
1855
+ if (used !== undefined && lastRun?.role === "fallback" && fallback !== undefined) {
1856
+ used = {
1857
+ ...used,
1858
+ use: fallback.use,
1859
+ args: fallback.args ?? [],
1860
+ sources: { ...used.sources, use: "fallback", args: "fallback" },
1861
+ };
1862
+ }
1863
+ // The report names the commit it reviewed; one that is not the checked
1864
+ // commit is refused, not recorded as a review of it.
1865
+ if (
1866
+ typeof sha === "string" &&
1867
+ typeof recorded.sha === "string" &&
1868
+ recorded.sha !== sha
1869
+ ) {
1870
+ const message = `the review report is for ${recorded.sha}, not the checked commit ${sha}`;
1871
+ return finish(
1872
+ { result: "failed", run: ctx.runId, sha, round, reason: "wrong_commit", message },
1873
+ "failed",
1874
+ { reason: "wrong_commit", message },
1875
+ );
1876
+ }
1877
+ const stamped: ReviewRecord =
1878
+ typeof sha === "string" && recorded.sha === undefined
1879
+ ? { ...recorded, sha }
1880
+ : recorded;
1881
+ const record: ReviewRecord =
1882
+ used === undefined ? stamped : { ...stamped, reviewSettings: used };
1883
+ const waiting =
1884
+ record.decision !== "findings" && record.result !== "fail";
1885
+ const written = await saveTaskGuarded(
1886
+ ctx,
1887
+ context.taskKey,
1888
+ {
1889
+ ...task,
1890
+ // A findings review continues to the rework step; every other ending
1891
+ // is a wait, either for a person or for the next review time.
1892
+ phase: waiting ? "waiting" : "review",
1893
+ waitKind: waiting ? reviewWaitKind(record) : undefined,
1894
+ run: ctx.runId,
1895
+ attempts: Math.max(task.attempts, attempt.number),
1896
+ attempt: {
1897
+ ...current,
1898
+ run: ctx.runId,
1899
+ review: record,
1900
+ // An unavailable round is not finished: the same round runs again.
1901
+ reviews:
1902
+ record.decision === "unavailable" &&
1903
+ record.reason !== "exhausted" &&
1904
+ record.reason !== "out_of_time"
1905
+ ? round - 1
1906
+ : round,
1907
+ },
1908
+ ...(record.decision === "passed" ? { reworkStreak: 0 } : {}),
1909
+ ...(record.decision === "passed" ? { reviewFailed: undefined } : {}),
1910
+ ...(typeof record.reworkLine === "string" && record.reworkLine.length > 0
1911
+ ? { brief: appendChange(task.brief, record.reworkLine) }
1912
+ : {}),
1913
+ ...historyOf(task, record, attempt.number, context.settings.reviewer.fixLevel),
1914
+ ...notesOf(task, record, attempt.number, round, context.settings.reviewer.fixLevel),
1915
+ retryAt:
1916
+ record.decision === "unavailable" && typeof record.retryAt === "number"
1917
+ ? record.retryAt
1918
+ : null,
1919
+ },
1920
+ "dev:review",
1921
+ );
1922
+ if (!written) return cancelledStep();
1923
+ return {
1924
+ result: stepResult,
1925
+ data: reviewData(stepResult, typeof sha === "string" ? sha : "", {
1926
+ attempt: attempt.number,
1927
+ round,
1928
+ ...(record.decision === undefined || record.decision === null
1929
+ ? {}
1930
+ : { decision: record.decision }),
1931
+ ...(record.model === undefined || record.model === null
1932
+ ? {}
1933
+ : { model: record.model }),
1934
+ ...(record.retryAt === undefined || record.retryAt === null
1935
+ ? {}
1936
+ : { retryAt: record.retryAt }),
1937
+ ...(record.runs === undefined ? {} : { runs: record.runs }),
1938
+ ...(record.findings === undefined ? {} : { findings: record.findings }),
1939
+ ...(record.verified === undefined ? {} : { verified: record.verified }),
1940
+ ...(record.message === undefined || record.message === null
1941
+ ? {}
1942
+ : { message: record.message }),
1943
+ ...(used === undefined ? {} : { reviewSettings: used }),
1944
+ ...extra,
1945
+ }),
1946
+ };
1947
+ };
1948
+
1949
+ if (typeof sha !== "string" || sha.length === 0) {
1950
+ const record: ReviewRecord = {
1951
+ result: "failed",
1952
+ run: ctx.runId,
1953
+ round,
1954
+ reason: "no_verified_commit",
1955
+ message: "the verify step recorded no commit to review",
1956
+ };
1957
+ return finish(record, "failed", {
1958
+ reason: "no_verified_commit",
1959
+ message: record.message,
1960
+ });
1961
+ }
1962
+
1963
+ git(context.repository.path, [
1964
+ "fetch",
1965
+ "--prune",
1966
+ context.settings.remote,
1967
+ ]);
1968
+ const base = mergeBase(context.repository.path, context.settings, sha);
1969
+ if (base === undefined) {
1970
+ const record: ReviewRecord = {
1971
+ result: "failed",
1972
+ run: ctx.runId,
1973
+ sha,
1974
+ round,
1975
+ reason: "no_merge_base",
1976
+ message: `cannot find the merge base of ${context.settings.remote}/${context.settings.mainBranch} and ${sha}`,
1977
+ };
1978
+ return finish(record, "failed", {
1979
+ reason: "no_merge_base",
1980
+ message: record.message,
1981
+ });
1982
+ }
1983
+
1984
+ const path = gateWorktreePath(
1985
+ context.repository.path,
1986
+ context.settings,
1987
+ context.taskId,
1988
+ );
1989
+ // A crash after the reviewer wrote its report and before the store copy
1990
+ // left the report in the old gate worktree, which is about to be replaced:
1991
+ // copy it first, so the resumed round reads it instead of asking again.
1992
+ const pendingReport = attempt.reviewPending;
1993
+ if (
1994
+ pendingReport !== undefined &&
1995
+ pendingReport !== null &&
1996
+ pendingReport.round === round &&
1997
+ typeof pendingReport.report === "string" &&
1998
+ pendingReport.report.startsWith(path) &&
1999
+ prepareReportFolder(path, false) === undefined
2000
+ ) {
2001
+ const old = readValidReportText(pendingReport.report, path);
2002
+ if (old !== undefined) {
2003
+ const savedDir = join(ctx.store.root, "dev", "reviews", ctx.runId);
2004
+ mkdirSync(savedDir, { recursive: true });
2005
+ const failure = copyToStore(
2006
+ join(
2007
+ savedDir,
2008
+ `${context.taskId}-attempt-${attempt.number}-review-${round}.json`,
2009
+ ),
2010
+ old.text,
2011
+ );
2012
+ if (failure !== undefined) {
2013
+ return finish(
2014
+ {
2015
+ result: "failed",
2016
+ run: ctx.runId,
2017
+ sha,
2018
+ round,
2019
+ reason: "review_failed",
2020
+ message: failure,
2021
+ },
2022
+ "failed",
2023
+ { reason: "review_failed", message: failure },
2024
+ );
2025
+ }
2026
+ }
2027
+ }
2028
+ const preparedWorktree = recreateGateWorktree(
2029
+ context.repository.path,
2030
+ path,
2031
+ sha,
2032
+ context.settings,
2033
+ );
2034
+ if (preparedWorktree !== undefined) {
2035
+ const record: ReviewRecord = {
2036
+ result: "failed",
2037
+ run: ctx.runId,
2038
+ sha,
2039
+ round,
2040
+ reason: "worktree",
2041
+ message: preparedWorktree,
2042
+ };
2043
+ return finish(record, "failed", {
2044
+ reason: "worktree",
2045
+ message: preparedWorktree,
2046
+ });
2047
+ }
2048
+
2049
+ const prepareFailure = await runPrepare(ctx, context.settings, path);
2050
+ if (prepareFailure !== undefined) {
2051
+ const record: ReviewRecord = {
2052
+ result: "failed",
2053
+ run: ctx.runId,
2054
+ sha,
2055
+ round,
2056
+ reason: prepareFailure.reason,
2057
+ message: prepareFailure.message,
2058
+ ...(prepareFailure.log === undefined ? {} : { log: prepareFailure.log }),
2059
+ };
2060
+ return finish(record, "failed", {
2061
+ reason: prepareFailure.reason,
2062
+ message: prepareFailure.message,
2063
+ ...(prepareFailure.log === undefined ? {} : { log: prepareFailure.log }),
2064
+ });
2065
+ }
2066
+
2067
+ // The gate worktree is at the verified commit, so its `.gitattributes` are
2068
+ // the ones that decide which changed files belong in the review diff.
2069
+ const prepared = prepareDiff(
2070
+ context.repository.path,
2071
+ base,
2072
+ sha,
2073
+ context.settings.reviewer,
2074
+ path,
2075
+ );
2076
+
2077
+ // The previous review is the newest report of the task for another commit,
2078
+ // in any attempt; none, or a commit the checkout lacks, is a first review.
2079
+ const history: readonly ReviewHistoryEntry[] = Array.isArray(task.reviewHistory)
2080
+ ? task.reviewHistory
2081
+ : [];
2082
+ const followed = previousReview(history, sha);
2083
+ const rework =
2084
+ followed !== undefined &&
2085
+ git(context.repository.path, [
2086
+ "cat-file",
2087
+ "-e",
2088
+ `${followed.sha}^{commit}`,
2089
+ ]).ok
2090
+ ? followed
2091
+ : undefined;
2092
+ // A rework round applies the line rules; a first review only the per-file
2093
+ // rule; a review of the same commit as an earlier one moves nothing.
2094
+ const kind: ReviewKind =
2095
+ rework !== undefined
2096
+ ? "rework"
2097
+ : followed === undefined && history.length > 0
2098
+ ? "reverify"
2099
+ : "first";
2100
+ // A review of a task that already had one is a later review for its
2101
+ // settings, even when the followed commit is missing and it reads like a first.
2102
+ used = reviewSettingsOf(
2103
+ kind === "first" && history.length > 0 ? "rework" : kind,
2104
+ stageReviewerOf(
2105
+ context.settings.reviewer,
2106
+ ctx.params,
2107
+ kind !== "first" || history.length > 0,
2108
+ ),
2109
+ reviews === 0,
2110
+ );
2111
+ // The lines the task's own change added, for the pre-existing rules.
2112
+ const own: LineMap = addedLinesOf(
2113
+ git(
2114
+ context.repository.path,
2115
+ [
2116
+ "-c",
2117
+ "core.quotepath=false",
2118
+ "diff",
2119
+ "-U0",
2120
+ "--no-color",
2121
+ "--no-ext-diff",
2122
+ "-M",
2123
+ base,
2124
+ sha,
2125
+ ],
2126
+ { raw: true },
2127
+ ).out,
2128
+ );
2129
+ const reworkPrompt: ReworkPrompt | undefined =
2130
+ rework === undefined
2131
+ ? undefined
2132
+ : reworkPromptOf(
2133
+ context.repository.path,
2134
+ context.settings,
2135
+ rework,
2136
+ sha,
2137
+ prepared,
2138
+ path,
2139
+ );
2140
+
2141
+ if (prepared.bytes > context.settings.reviewer.maxDiffBytes) {
2142
+ const largest = [...prepared.files]
2143
+ .sort((left, right) => right.bytes - left.bytes)
2144
+ .slice(0, 5)
2145
+ .map((file) => ({
2146
+ path: file.path,
2147
+ bytes: file.bytes,
2148
+ added: file.added,
2149
+ removed: file.removed,
2150
+ }));
2151
+ const message = `the diff is ${prepared.bytes} bytes, over the ${context.settings.reviewer.maxDiffBytes}-byte review limit`;
2152
+ await ctx.facts.append({
2153
+ type: "dev/review_too_large",
2154
+ ...(ctx.object === undefined
2155
+ ? {}
2156
+ : { object: { type: ctx.object.type, id: ctx.object.id } }),
2157
+ cause: "dev:review",
2158
+ data: {
2159
+ bytes: prepared.bytes,
2160
+ limit: context.settings.reviewer.maxDiffBytes,
2161
+ largest,
2162
+ },
2163
+ });
2164
+ const record: ReviewRecord = {
2165
+ result: "failed",
2166
+ run: ctx.runId,
2167
+ sha,
2168
+ round,
2169
+ reason: "diff_size",
2170
+ message,
2171
+ };
2172
+ return finish(record, "failed", {
2173
+ reason: "diff_size",
2174
+ message,
2175
+ bytes: prepared.bytes,
2176
+ limit: context.settings.reviewer.maxDiffBytes,
2177
+ largest,
2178
+ });
2179
+ }
2180
+
2181
+ // Nothing changed between the base and the verified commit: there is no
2182
+ // review to ask a model for. A change made only of left-out files still runs
2183
+ // the reviewer: the list is what tells it those files exist.
2184
+ if (prepared.files.length === 0) {
2185
+ const record: ReviewRecord = {
2186
+ result: "passed",
2187
+ decision: "passed",
2188
+ run: ctx.runId,
2189
+ sha,
2190
+ round,
2191
+ runs: [],
2192
+ findings: [],
2193
+ verified: [],
2194
+ reason: "empty",
2195
+ };
2196
+ return finish(record, "pass", {
2197
+ reason: "empty",
2198
+ leftOut: prepared.leftOut.map(leftOutLine),
2199
+ });
2200
+ }
2201
+
2202
+ const reviewDir = join(ctx.store.root, "dev", "reviews", ctx.runId);
2203
+ mkdirSync(reviewDir, { recursive: true });
2204
+ const resultPath = join(
2205
+ reviewDir,
2206
+ `${context.taskId}-attempt-${attempt.number}-review-${round}.json`,
2207
+ );
2208
+ const promptPath = join(
2209
+ reviewDir,
2210
+ `${context.taskId}-attempt-${attempt.number}-review-${round}.prompt.md`,
2211
+ );
2212
+
2213
+ const settings = context.settings.reviewer;
2214
+ // The retry is the same review round, so it keeps the round's settings:
2215
+ // the first review still gets the first block on its retry.
2216
+ const roundSettings = used;
2217
+ const roundArgs = roundSettings.args;
2218
+ // The runs of this round survive a crash; a fresh round starts with none.
2219
+ const runs: ReviewRunRecord[] = (attempt.reviewRuns ?? []).filter(
2220
+ (run) =>
2221
+ run.round === round &&
2222
+ (run.attempt === undefined ||
2223
+ run.attempt === null ||
2224
+ run.attempt === attempt.number),
2225
+ );
2226
+ // The recorded unavailable round holds the runs it had when it waited. Once
2227
+ // the time has passed, a primary run starts the round again; a run saved
2228
+ // after that point is resumed instead of started twice.
2229
+ const recordedRuns = (previous?.runs ?? []).filter(
2230
+ (run) =>
2231
+ run.round === round &&
2232
+ (run.attempt === undefined ||
2233
+ run.attempt === null ||
2234
+ run.attempt === attempt.number),
2235
+ );
2236
+ const retryAfterWait =
2237
+ previous !== undefined &&
2238
+ previous !== null &&
2239
+ previous.round === round &&
2240
+ previous.decision === "unavailable" &&
2241
+ now >= (typeof previous.retryAt === "number" ? previous.retryAt : 0) &&
2242
+ runs.length <= recordedRuns.length;
2243
+ let next: ReviewNext = retryAfterWait
2244
+ ? { role: "primary", reason: "retry" }
2245
+ : nextReviewAction(runs, settings.fallback);
2246
+
2247
+ // A run that crashed after its model answered left this pending record and
2248
+ // its outcome beside the report path. Resuming reads that outcome instead of
2249
+ // asking the same model a second time.
2250
+ let pendingReview: PendingReviewRun | undefined =
2251
+ attempt.reviewPending !== undefined &&
2252
+ attempt.reviewPending !== null &&
2253
+ attempt.reviewPending.round === round &&
2254
+ (attempt.reviewPending.attempt === undefined ||
2255
+ attempt.reviewPending.attempt === null ||
2256
+ attempt.reviewPending.attempt === attempt.number)
2257
+ ? attempt.reviewPending
2258
+ : undefined;
2259
+
2260
+ // Every run of this step must end before the step's own timeout: a run that
2261
+ // cannot fit in what is left is skipped and the round waits for a person.
2262
+ const clock = (): number => reviewTestHooks.now?.() ?? Date.now();
2263
+ const deadline = clock() + (STEP_TIMEOUT_SECS - 60) * 1000;
2264
+ let ranHere = 0;
2265
+
2266
+ while (typeof next === "object") {
2267
+ const action = next;
2268
+ const resume =
2269
+ pendingReview !== undefined &&
2270
+ pendingReview.role === action.role &&
2271
+ pendingReview.reason === action.reason
2272
+ ? pendingReview
2273
+ : undefined;
2274
+ pendingReview = undefined;
2275
+ const use =
2276
+ resume?.use ??
2277
+ (action.role === "fallback"
2278
+ ? settings.fallback?.use ?? roundSettings.use
2279
+ : roundSettings.use);
2280
+ const args =
2281
+ resume?.args ??
2282
+ (action.role === "fallback" ? settings.fallback?.args ?? [] : roundArgs);
2283
+ const model = resume?.model ?? modelOf(use, args);
2284
+ // One path per call: the calls before it in this round are the try number,
2285
+ // so a stale report of an earlier call is never read and never removed.
2286
+ const reportPath = workspaceReportPath(
2287
+ path,
2288
+ ctx.runId,
2289
+ attempt.number,
2290
+ round,
2291
+ runs.length,
2292
+ );
2293
+ const built = reviewPrompt(
2294
+ task,
2295
+ sha,
2296
+ base,
2297
+ prepared,
2298
+ reportPath,
2299
+ grading,
2300
+ context.settings.prepare,
2301
+ reworkPrompt,
2302
+ verifiedCommands(attempt.verify),
2303
+ );
2304
+ // A resumed call asks with the prompt it recorded, not one built again.
2305
+ const recorded =
2306
+ resume === undefined || !existsSync(promptPath)
2307
+ ? undefined
2308
+ : readFileSync(promptPath, "utf8");
2309
+ const prompt = recorded !== undefined && recorded.includes(reportPath) ? recorded : built;
2310
+ let call =
2311
+ resume === undefined ? undefined : readReviewOutcome(resultPath);
2312
+ if (
2313
+ call === undefined &&
2314
+ ranHere > 0 &&
2315
+ clock() + roundSettings.timeoutSecs * 1000 > deadline
2316
+ ) {
2317
+ next = "out-of-time";
2318
+ break;
2319
+ }
2320
+ if (call === undefined) {
2321
+ ranHere += 1;
2322
+ // Keep the prompt for a person to read without putting its bytes in a fact.
2323
+ try {
2324
+ writeFileSync(promptPath, prompt);
2325
+ } catch {
2326
+ // A prompt file is a convenience; the reviewer still gets the text.
2327
+ }
2328
+ // Record the run before the model is asked: a crash after it answers
2329
+ // finds the run and its outcome on disk instead of repeating the call.
2330
+ current = {
2331
+ ...current,
2332
+ run: ctx.runId,
2333
+ reviewPending: {
2334
+ attempt: attempt.number,
2335
+ round,
2336
+ role: action.role,
2337
+ use,
2338
+ args,
2339
+ model,
2340
+ reason: action.reason,
2341
+ run: ctx.runId,
2342
+ report: reportPath,
2343
+ },
2344
+ };
2345
+ const pendingWritten = await saveTaskGuarded(
2346
+ ctx,
2347
+ context.taskKey,
2348
+ {
2349
+ ...task,
2350
+ run: ctx.runId,
2351
+ attempts: Math.max(task.attempts, attempt.number),
2352
+ attempt: current,
2353
+ },
2354
+ "dev:review",
2355
+ );
2356
+ if (!pendingWritten) return cancelledStep();
2357
+ reviewTestHooks.beforeRun?.({ role: action.role, reason: action.reason });
2358
+ call = await callReviewer(
2359
+ ctx,
2360
+ context,
2361
+ path,
2362
+ prompt,
2363
+ reportPath,
2364
+ resultPath,
2365
+ { use, args },
2366
+ roundSettings,
2367
+ resume !== undefined,
2368
+ );
2369
+ }
2370
+ reviewTestHooks.afterCall?.({ role: action.role, reason: action.reason });
2371
+ let runRecord: ReviewRunRecord;
2372
+ // A report for another commit is refused, not recorded as this commit's.
2373
+ if (call.outcome === "report" && call.report?.sha !== sha) {
2374
+ const message =
2375
+ call.report?.sha === undefined
2376
+ ? `the review report does not name the commit it reviewed; the checked commit is ${sha}`
2377
+ : `the review report is for ${call.report.sha}, not the checked commit ${sha}`;
2378
+ return finish(
2379
+ { result: "failed", run: ctx.runId, sha, round, reason: "wrong_commit", message },
2380
+ "failed",
2381
+ { reason: "wrong_commit", message },
2382
+ );
2383
+ }
2384
+ if (call.outcome === "report" && call.report !== undefined) {
2385
+ // Dev decides what is pre-existing; a mark the model wrote is dropped.
2386
+ const findings: ReviewFinding[] = call.report.findings.map((reported) => {
2387
+ const finding: ReviewFinding = { ...reported };
2388
+ delete (finding as { preExisting?: unknown }).preExisting;
2389
+ delete (finding as { pre_existing?: unknown }).pre_existing;
2390
+ const moved =
2391
+ atOrAbove(finding.severity, settings.fixLevel) &&
2392
+ movesIn(
2393
+ kind,
2394
+ {
2395
+ severity: finding.severity,
2396
+ file: finding.file,
2397
+ line: finding.line,
2398
+ },
2399
+ own,
2400
+ rework?.blocking ?? [],
2401
+ normalizePath,
2402
+ );
2403
+ return moved
2404
+ ? { ...finding, preExisting: true, pre_existing: true }
2405
+ : finding;
2406
+ });
2407
+ const counted = findings.filter(
2408
+ (finding) =>
2409
+ finding.preExisting !== true &&
2410
+ finding.pre_existing !== true &&
2411
+ atOrAbove(finding.severity, settings.fixLevel),
2412
+ ).length;
2413
+ runRecord = {
2414
+ attempt: attempt.number,
2415
+ round,
2416
+ role: action.role,
2417
+ use,
2418
+ args,
2419
+ model,
2420
+ reason: action.reason,
2421
+ outcome: "report",
2422
+ run: ctx.runId,
2423
+ findings,
2424
+ verified: call.report.verified,
2425
+ counted,
2426
+ };
2427
+ } else {
2428
+ runRecord = {
2429
+ attempt: attempt.number,
2430
+ round,
2431
+ role: action.role,
2432
+ use,
2433
+ args,
2434
+ model,
2435
+ reason: action.reason,
2436
+ outcome: call.outcome,
2437
+ run: ctx.runId,
2438
+ ...(call.message.length === 0 ? {} : { message: call.message }),
2439
+ };
2440
+ }
2441
+ runs.push(runRecord);
2442
+ current = {
2443
+ ...current,
2444
+ run: ctx.runId,
2445
+ reviewPending: null,
2446
+ reviewRuns: [...(current.reviewRuns ?? []), runRecord],
2447
+ };
2448
+ const written = await saveTaskGuarded(
2449
+ ctx,
2450
+ context.taskKey,
2451
+ {
2452
+ ...task,
2453
+ run: ctx.runId,
2454
+ attempts: Math.max(task.attempts, attempt.number),
2455
+ attempt: current,
2456
+ },
2457
+ "dev:review",
2458
+ );
2459
+ if (!written) return cancelledStep();
2460
+ reviewTestHooks.afterRunSaved?.(runRecord);
2461
+ next = nextReviewAction(runs, settings.fallback);
2462
+ }
2463
+
2464
+ const last = runs[runs.length - 1];
2465
+ if (next === "done" && last !== undefined) {
2466
+ const counted = last.counted ?? 0;
2467
+ const decision = counted === 0 ? "passed" : "findings";
2468
+ const stepResult = decision === "passed" ? "pass" : "fail";
2469
+ const result: ReviewResult = decision;
2470
+ const findings = last.findings ?? [];
2471
+ const countedFindings = findings.filter(
2472
+ (finding) =>
2473
+ finding.preExisting !== true &&
2474
+ finding.pre_existing !== true &&
2475
+ atOrAbove(finding.severity, settings.fixLevel),
2476
+ );
2477
+ const preExistingCount = findings.filter(
2478
+ (finding) =>
2479
+ finding.preExisting === true || finding.pre_existing === true,
2480
+ ).length;
2481
+ const findingsMessage = countedFindings
2482
+ .map(
2483
+ (finding) =>
2484
+ `${finding.file}:${finding.line} ${finding.severity}: ${finding.summary}`,
2485
+ )
2486
+ .join("; ");
2487
+ const reworkLine =
2488
+ rework === undefined
2489
+ ? ""
2490
+ : `rework round: ${rework.blocking.length} previous findings, ${fixedCount(
2491
+ rework.blocking,
2492
+ countedFindings.map((finding) => ({
2493
+ severity: finding.severity,
2494
+ file: finding.file,
2495
+ line: finding.line,
2496
+ })),
2497
+ normalizePath,
2498
+ )} fixed, ${preExistingCount} moved as pre-existing`;
2499
+ const message = [reviewMessage(decision, runs), reworkLine, findingsMessage]
2500
+ .filter((piece) => piece.length > 0)
2501
+ .join("; ");
2502
+ const record: ReviewRecord = {
2503
+ result,
2504
+ decision,
2505
+ run: ctx.runId,
2506
+ sha,
2507
+ round,
2508
+ model: last.model,
2509
+ runs,
2510
+ findings,
2511
+ verified: last.verified ?? [],
2512
+ log: resultPath,
2513
+ message,
2514
+ base,
2515
+ ...(reworkLine.length === 0 ? {} : { reworkLine }),
2516
+ ...(decision === "findings" ? { reason: "findings" } : {}),
2517
+ };
2518
+ return finish(record, stepResult, {
2519
+ counted,
2520
+ preExisting: preExistingCount,
2521
+ pre_existing: preExistingCount,
2522
+ moved: preExistingCount,
2523
+ ...(rework === undefined ? {} : { reworkRound: true }),
2524
+ leftOut: prepared.leftOut.map(leftOutLine),
2525
+ log: resultPath,
2526
+ prompt: promptPath,
2527
+ });
2528
+ }
2529
+
2530
+ if (
2531
+ next === "wait-unavailable" &&
2532
+ runs.filter((run) => run.role === "primary" && run.outcome === "unavailable")
2533
+ .length > MAX_REVIEW_WAITS
2534
+ ) {
2535
+ next = "wait-exhausted";
2536
+ }
2537
+
2538
+ if (next === "wait-exhausted" || next === "out-of-time") {
2539
+ const exhausted = next === "wait-exhausted";
2540
+ const reason = exhausted ? "exhausted" : "out_of_time";
2541
+ const why = exhausted
2542
+ ? "review did not finish (model unavailable)"
2543
+ : "review did not finish (out of time)";
2544
+ const message = [reviewMessage("passed", runs), why]
2545
+ .filter((piece) => piece.length > 0)
2546
+ .join("; ");
2547
+ const timedOut = !exhausted && last?.outcome === "timed_out";
2548
+ const record: ReviewRecord = {
2549
+ result: timedOut ? "timed_out" : "unavailable",
2550
+ decision: timedOut ? "timed_out" : "unavailable",
2551
+ run: ctx.runId,
2552
+ sha,
2553
+ round,
2554
+ ...(last === undefined ? {} : { model: last.model }),
2555
+ runs,
2556
+ message,
2557
+ reason,
2558
+ log: resultPath,
2559
+ };
2560
+ return finish(record, reason, {
2561
+ reason,
2562
+ message,
2563
+ log: resultPath,
2564
+ prompt: promptPath,
2565
+ });
2566
+ }
2567
+
2568
+ if (next === "wait-unavailable") {
2569
+ const waits = runs.filter(
2570
+ (run) => run.role === "primary" && run.outcome === "unavailable",
2571
+ ).length;
2572
+ const retryAt =
2573
+ (reviewTestHooks.now?.() ?? Date.now()) +
2574
+ reviewWaitMs(settings.retrySecs, waits);
2575
+ const message = reviewMessage("unavailable", runs, retryAt);
2576
+ const record: ReviewRecord = {
2577
+ result: "unavailable",
2578
+ decision: "unavailable",
2579
+ run: ctx.runId,
2580
+ sha,
2581
+ round,
2582
+ ...(last === undefined ? {} : { model: last.model }),
2583
+ runs,
2584
+ retryAt,
2585
+ message,
2586
+ reason: "unavailable",
2587
+ log: resultPath,
2588
+ };
2589
+ return finish(record, "unavailable", {
2590
+ reason: "unavailable",
2591
+ message,
2592
+ retryAt,
2593
+ log: resultPath,
2594
+ prompt: promptPath,
2595
+ });
2596
+ }
2597
+
2598
+ if (next === "wait-timed-out") {
2599
+ const message = "review timed out twice";
2600
+ const record: ReviewRecord = {
2601
+ result: "timed_out",
2602
+ decision: "timed_out",
2603
+ run: ctx.runId,
2604
+ sha,
2605
+ round,
2606
+ ...(last === undefined ? {} : { model: last.model }),
2607
+ runs,
2608
+ message,
2609
+ reason: "timed_out",
2610
+ log: resultPath,
2611
+ };
2612
+ return finish(record, "timed_out", {
2613
+ reason: "timed_out",
2614
+ message,
2615
+ log: resultPath,
2616
+ prompt: promptPath,
2617
+ });
2618
+ }
2619
+
2620
+ const message =
2621
+ last?.message === undefined || last.message === null
2622
+ ? reviewMessage("passed", runs)
2623
+ : [reviewMessage("passed", runs), last.message]
2624
+ .filter((piece) => piece.length > 0)
2625
+ .join("; ");
2626
+ const record: ReviewRecord = {
2627
+ result: "failed",
2628
+ run: ctx.runId,
2629
+ sha,
2630
+ round,
2631
+ ...(last === undefined ? {} : { model: last.model }),
2632
+ runs,
2633
+ message,
2634
+ reason: last?.outcome === "invalid" ? "invalid_json" : "review_failed",
2635
+ log: resultPath,
2636
+ };
2637
+ return finish(record, "failed", {
2638
+ reason: record.reason,
2639
+ message,
2640
+ log: resultPath,
2641
+ prompt: promptPath,
2642
+ });
2643
+ }
2644
+
2645
+ /** Waits for a timer, or returns false when the run is cancelled. */
2646
+ export function waitFor(ms: number, signal: AbortSignal | undefined): Promise<boolean> {
2647
+ return new Promise((resolve) => {
2648
+ if (signal?.aborted === true) {
2649
+ resolve(false);
2650
+ return;
2651
+ }
2652
+ const cleanup = (): void => {
2653
+ clearTimeout(timer);
2654
+ signal?.removeEventListener("abort", onAbort);
2655
+ };
2656
+ const timer = setTimeout(() => {
2657
+ cleanup();
2658
+ resolve(true);
2659
+ }, ms);
2660
+ const onAbort = (): void => {
2661
+ cleanup();
2662
+ resolve(false);
2663
+ };
2664
+ signal?.addEventListener("abort", onAbort, { once: true });
2665
+ });
2666
+ }
2667
+
2668
+ /**
2669
+ * Step `dev/review_due`: the wait a review enters when its model was
2670
+ * unavailable. It holds until the recorded `retryAt`, then lets the flow run
2671
+ * the same review round again without polling. A wait longer than one step run
2672
+ * is split into pieces below the step timeout.
2673
+ */
2674
+ export async function runReviewDue(
2675
+ ctx: StepContext,
2676
+ ): Promise<PluginStepResult> {
2677
+ const context = await taskContext(ctx);
2678
+ if (!claimAllows(ctx, context.task)) {
2679
+ return { result: "interrupted", data: { reason: "cancelled" } };
2680
+ }
2681
+ const review = context.task.attempt?.review;
2682
+ const retryAt =
2683
+ typeof context.task.retryAt === "number"
2684
+ ? context.task.retryAt
2685
+ : review !== undefined &&
2686
+ review !== null &&
2687
+ review.decision === "unavailable" &&
2688
+ typeof review.retryAt === "number"
2689
+ ? review.retryAt
2690
+ : undefined;
2691
+ return holdUntil(ctx, retryAt);
2692
+ }
2693
+
2694
+ /**
2695
+ * Step `dev/work_due`: the work step found its model unavailable. It holds
2696
+ * until the recorded `workRetryAt`, then lets the flow run the work again.
2697
+ */
2698
+ export async function runWorkDue(ctx: StepContext): Promise<PluginStepResult> {
2699
+ const context = await taskContext(ctx);
2700
+ if (!claimAllows(ctx, context.task)) {
2701
+ return { result: "interrupted", data: { reason: "cancelled" } };
2702
+ }
2703
+ const retryAt = context.task.attempt?.workRetryAt;
2704
+ return holdUntil(ctx, typeof retryAt === "number" ? retryAt : undefined);
2705
+ }
2706
+
2707
+ /** Waits (in pieces below the step timeout) until `retryAt`, or until cancelled. */
2708
+ async function holdUntil(
2709
+ ctx: StepContext,
2710
+ retryAt: number | undefined,
2711
+ ): Promise<PluginStepResult> {
2712
+ const now = reviewTestHooks.now?.() ?? Date.now();
2713
+ if (retryAt === undefined || retryAt <= now) {
2714
+ return { result: "ready", data: { at: now } };
2715
+ }
2716
+ const waitMs = Math.min(retryAt - now, REVIEW_WAIT_CHUNK_MS);
2717
+ const wait = reviewTestHooks.wait ?? waitFor;
2718
+ const waited = await wait(waitMs, ctx.signal);
2719
+ if (!waited) return { result: "interrupted", data: { reason: "cancelled" } };
2720
+ const after = reviewTestHooks.now?.() ?? Date.now();
2721
+ if (after < retryAt) {
2722
+ // The piece ended early: the review step replays its unavailable round and
2723
+ // the flow enters this wait again for the next piece.
2724
+ return { result: "ready", data: { at: after, retryAt, waitedMs: waitMs } };
2725
+ }
2726
+ return {
2727
+ result: "ready",
2728
+ data: { at: retryAt, waitedMs: retryAt - now },
2729
+ };
2730
+ }
2731
+
2732
+ function gateSource(task: TaskData): "verify" | "review" {
2733
+ const review = task.attempt?.review;
2734
+ if (review !== undefined && review !== null) {
2735
+ if (review.decision === "findings") return "review";
2736
+ if (
2737
+ review.result === "fail" ||
2738
+ review.result === "findings" ||
2739
+ review.result === "failed"
2740
+ ) {
2741
+ return "review";
2742
+ }
2743
+ }
2744
+ return "verify";
2745
+ }
2746
+
2747
+ function findingText(finding: ReviewFinding): string {
2748
+ const place = `${finding.file}:${finding.line}`;
2749
+ const trigger =
2750
+ finding.trigger.length === 0 ? "" : ` — ${finding.trigger}`;
2751
+ return `- \`${place}\` ${finding.severity}: ${finding.summary}${trigger}`;
2752
+ }
2753
+
2754
+ /** The instruction every rework section ends with. */
2755
+ export const REWORK_INSTRUCTION =
2756
+ "Fix them and nothing else, append commits to the branch, and do not rebase.";
2757
+
2758
+ /** Step `dev/rework`: add the gate failure to the brief and decide who fixes it. */
2759
+ export async function runRework(
2760
+ ctx: StepContext,
2761
+ ): Promise<PluginStepResult> {
2762
+ const context = await taskContext(ctx);
2763
+ if (!claimAllows(ctx, context.task)) return cancelledStep();
2764
+ const task = context.task;
2765
+ const attempt = attemptOf(ctx, task);
2766
+ // A rework that saved its task but lost its step result is replayed by the
2767
+ // runner; the section and the streak are already recorded, so reuse them.
2768
+ const previous = attempt.rework;
2769
+ if (
2770
+ previous !== undefined &&
2771
+ previous !== null &&
2772
+ previous.run === ctx.runId
2773
+ ) {
2774
+ return {
2775
+ result: previous.result,
2776
+ data: {
2777
+ attempt: attempt.number,
2778
+ source: previous.source,
2779
+ rework: previous.streak,
2780
+ streak: previous.streak,
2781
+ maxAutoRework: context.settings.maxAutoRework,
2782
+ brief: task.brief,
2783
+ replayed: true,
2784
+ },
2785
+ };
2786
+ }
2787
+ const source = gateSource(task);
2788
+ const pieces: string[] = [];
2789
+ let reason: string | undefined;
2790
+
2791
+ if (source === "review") {
2792
+ const review = attempt?.review;
2793
+ const level = gradedContext(context, ctx.params).context.settings.reviewer.fixLevel;
2794
+ const findings = (review?.findings ?? []).filter(
2795
+ (finding) =>
2796
+ finding.preExisting !== true &&
2797
+ finding.pre_existing !== true &&
2798
+ atOrAbove(finding.severity, level),
2799
+ );
2800
+ const first = findings[0];
2801
+ if (first !== undefined) {
2802
+ reason = findingText(first).replace(/^- /, "").replaceAll("`", "");
2803
+ pieces.push(
2804
+ "The review failed with these findings:",
2805
+ findings.map(findingText).join("\n"),
2806
+ );
2807
+ } else {
2808
+ reason = `the review failed: ${review?.message ?? "no review report was produced"}`;
2809
+ pieces.push(
2810
+ `The review failed: ${review?.message ?? "no review report was produced"}`,
2811
+ );
2812
+ }
2813
+ } else {
2814
+ const verify = attempt?.verify;
2815
+ if (
2816
+ typeof verify?.command === "string" &&
2817
+ verify.command.length > 0
2818
+ ) {
2819
+ reason = `the verify command failed: ${verify.command}`;
2820
+ pieces.push(
2821
+ `The verify command failed: \`${verify.command}\``,
2822
+ ...(typeof verify.log === "string" && verify.log.length > 0
2823
+ ? [`Log: \`${verify.log}\``]
2824
+ : []),
2825
+ );
2826
+ } else {
2827
+ reason = `the gate failed: ${verify?.message ?? "verify recorded no reason"}`;
2828
+ pieces.push(
2829
+ `The gate failed: ${verify?.message ?? "verify recorded no reason"}`,
2830
+ );
2831
+ }
2832
+ }
2833
+ const failedText = pieces.slice(0, 2).join("\n\n");
2834
+ const streak = (task.reworkStreak ?? 0) + 1;
2835
+ const twice =
2836
+ source === "review" &&
2837
+ task.reviewFailed !== undefined &&
2838
+ streak <= context.settings.maxAutoRework;
2839
+ if (twice) {
2840
+ pieces.push(
2841
+ "The review failed twice in a row. The previous round's findings:",
2842
+ task.reviewFailed ?? "",
2843
+ );
2844
+ }
2845
+ pieces.push(REWORK_INSTRUCTION);
2846
+
2847
+ const withRework = appendRework(
2848
+ task,
2849
+ source,
2850
+ pieces.join("\n\n"),
2851
+ reason,
2852
+ );
2853
+ const again = !twice && streak <= context.settings.maxAutoRework;
2854
+ const record: ReworkRecord = {
2855
+ run: ctx.runId,
2856
+ source,
2857
+ streak,
2858
+ limit: context.settings.maxAutoRework,
2859
+ result: again ? "again" : "ask",
2860
+ ...(twice ? { twice: true } : {}),
2861
+ };
2862
+ const next: TaskData = {
2863
+ ...withRework,
2864
+ reviewFailed: source === "review" ? failedText : undefined,
2865
+ phase: again ? "review" : "waiting",
2866
+ run: ctx.runId,
2867
+ attempts: Math.max(task.attempts, attempt.number),
2868
+ reworkStreak: streak,
2869
+ attempt: { ...attempt, run: ctx.runId, rework: record },
2870
+ };
2871
+ if (!(await saveTaskGuarded(ctx, context.taskKey, next, "dev:rework"))) {
2872
+ return cancelledStep();
2873
+ }
2874
+ return {
2875
+ result: again ? "again" : "ask",
2876
+ data: {
2877
+ attempt: attempt.number,
2878
+ source,
2879
+ rework: streak,
2880
+ streak,
2881
+ maxAutoRework: context.settings.maxAutoRework,
2882
+ brief: next.brief,
2883
+ },
2884
+ };
2885
+ }
2886
+
2887
+ /** The recorded verified commit of a task, for a caller that wants to look. */
2888
+ export function verifiedCommitOf(task: TaskData): string | undefined {
2889
+ const sha = task.attempt?.verified;
2890
+ return typeof sha === "string" && sha.length > 0 ? sha : undefined;
2891
+ }
2892
+
2893
+ /** The branch head a task's worktree is on, for tests and views. */
2894
+ export function taskHead(path: string): string | undefined {
2895
+ return headOf(path);
2896
+ }
2897
+