@farmslot/review-dispatch 0.11.1 → 0.13.0

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.
@@ -0,0 +1,722 @@
1
+ import { deriveChecklistStepDurations, digestRecipeDocument, extractRunArtifactManifest, isTerminalRunStatus, observedReviewSessionContinuity, reviewChainForRun, reviewResultForRun, } from '@farmslot/protocol';
2
+ import { reviewHistoryTimeline } from './review-history-timeline.js';
3
+ import { runActivityView, runReviewActivityContext } from './run-activity.js';
4
+ import { reviewAttemptFailureReason } from './run-review-failures.js';
5
+ /** Transport generations invalidate requests, not facts already read from the same owner. */
6
+ export function reviewHistoryCacheScope(runId, authority) {
7
+ return JSON.stringify([
8
+ authority.gatewayUrl,
9
+ authority.profileId ?? null,
10
+ authority.principalId,
11
+ runId,
12
+ ]);
13
+ }
14
+ function reviewUsageLabel(usage) {
15
+ if (!usage)
16
+ return null;
17
+ if (usage.source === 'unavailable')
18
+ return 'Usage unavailable';
19
+ const parts = [
20
+ usage.turns != null ? `${usage.turns} turns` : null,
21
+ usage.totalTokens != null ? `${usage.totalTokens.toLocaleString()} tokens` : null,
22
+ usage.costUsd != null ? `$${usage.costUsd.toFixed(4)}` : null,
23
+ ].filter(Boolean);
24
+ return parts.length ? parts.join(' · ') : 'Usage measured';
25
+ }
26
+ /** Keep recorded history readable during a refresh outage, while exposing the failed read. */
27
+ export function mergeReviewHistoryArtifacts(previous, next) {
28
+ return {
29
+ ...previous,
30
+ ...Object.fromEntries(Object.entries(next).map(([path, value]) => [
31
+ path,
32
+ value.error && previous[path]?.content !== undefined
33
+ ? { ...previous[path], error: value.error }
34
+ : value,
35
+ ])),
36
+ };
37
+ }
38
+ function isRecord(value) {
39
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
40
+ }
41
+ function record(value) {
42
+ return isRecord(value) ? value : null;
43
+ }
44
+ function text(value) {
45
+ return typeof value === 'string' && value.trim() ? value : null;
46
+ }
47
+ function number(value) {
48
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
49
+ }
50
+ function artifact(artifacts, path) {
51
+ const content = artifacts[path]?.content;
52
+ if (!content)
53
+ return null;
54
+ try {
55
+ return record(JSON.parse(content));
56
+ }
57
+ catch {
58
+ // A partial/legacy artifact cannot supply facts; its round remains visible as not recorded.
59
+ return null;
60
+ }
61
+ }
62
+ function duration(start, end) {
63
+ if (!start || !end)
64
+ return null;
65
+ const ms = Date.parse(end) - Date.parse(start);
66
+ return Number.isFinite(ms) && ms >= 0 ? ms : null;
67
+ }
68
+ function range(base, head) {
69
+ const left = text(base), right = text(head);
70
+ return left || right ? `${left?.slice(0, 7) ?? '?'} → ${right?.slice(0, 7) ?? '?'}` : null;
71
+ }
72
+ function fixStat(value) {
73
+ const delta = record(value), diff = record(delta?.diffStat);
74
+ if (!diff)
75
+ return null;
76
+ const files = number(diff.files);
77
+ const untracked = Array.isArray(delta?.untrackedFiles) ? delta.untrackedFiles.length : 0;
78
+ const paths = untracked && files !== null
79
+ ? `${Math.max(0, files - untracked)} tracked + ${untracked} untracked`
80
+ : `${files ?? '?'} file${files === 1 ? '' : 's'}`;
81
+ return `${paths} · +${number(diff.additions) ?? '?'} −${number(diff.deletions) ?? '?'}`;
82
+ }
83
+ function findings(value) {
84
+ if (!Array.isArray(value))
85
+ return [];
86
+ return value.flatMap((entry) => {
87
+ const issue = record(entry);
88
+ const description = text(issue?.description) ?? text(issue?.body);
89
+ if (!issue || !description)
90
+ return [];
91
+ const priority = /^\[(P[0-3])\]\s*/.exec(description);
92
+ const body = priority ? description.slice(priority[0].length) : description;
93
+ const firstLine = body.split('\n')[0];
94
+ const title = text(issue.title) ?? firstLine.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? firstLine;
95
+ return [
96
+ {
97
+ id: text(issue.id) ?? digestRecipeDocument({ file: issue.file ?? issue.path, title }),
98
+ title,
99
+ details: body.startsWith(title) ? body.slice(title.length).trim() : body,
100
+ severity: text(issue.severity) ?? priority?.[1] ?? 'Severity not recorded',
101
+ file: text(issue.file) ?? text(issue.path) ?? 'General finding',
102
+ line: number(issue.line),
103
+ status: 'new',
104
+ statusLabel: 'New',
105
+ resolvedBy: null,
106
+ },
107
+ ];
108
+ });
109
+ }
110
+ /** Shared with snapshot capture: clients must request the artifact the engine actually wrote. */
111
+ export function reviewArtifactDir(loopNumber, artifactScope) {
112
+ const scope = artifactScope?.trim().replace(/^\/+|\/+$/g, '');
113
+ if (!scope)
114
+ return `artifacts/pipeline-review-loop-${loopNumber}`;
115
+ if (scope.includes('..'))
116
+ throw new Error(`Invalid review artifact scope: ${artifactScope}`);
117
+ return `artifacts/${scope}/review-loop-${loopNumber}`;
118
+ }
119
+ export function reviewHistoryArtifactPaths(run) {
120
+ return [
121
+ ...new Set((run.agentContexts ?? [])
122
+ .filter((context) => context.role === 'review')
123
+ .flatMap(reviewHistoryArtifactPathsForActor)),
124
+ ];
125
+ }
126
+ function recoveredSnapshotKey(actor) {
127
+ return `history:${actor.id}:${actor.reviewLoopNumber ?? 0}:${actor.deliveryBaselineRef ?? actor.pipelineVisualReviewInput?.headSha ?? ''}:snapshot`;
128
+ }
129
+ function readyReviews(run) {
130
+ const live = run.engineState?.publishGate?.reviews;
131
+ if (live?.length)
132
+ return live;
133
+ for (const decision of [...run.decisions].reverse())
134
+ if (decision.payload?.kind === 'ready')
135
+ return decision.payload.reviews ?? [];
136
+ return [];
137
+ }
138
+ export function reviewHistoryView(run, artifacts = {}, chain = reviewChainForRun(run)) {
139
+ const result = reviewResultForRun(run);
140
+ const staticActors = new Set((run.agentContexts ?? [])
141
+ .filter((context) => context.role === 'review' && !context.reviewLoopNumber && run.flowType === 'review-pr')
142
+ .map((context) => context.id));
143
+ const contexts = (run.agentContexts ?? [])
144
+ .filter((context) => context.role === 'review')
145
+ .flatMap((context) => staticActors.has(context.id)
146
+ ? [
147
+ {
148
+ ...context,
149
+ reviewId: context.reviewId ?? `workspace-review-${run.id}`,
150
+ reviewLoopNumber: 1,
151
+ },
152
+ ]
153
+ : context.reviewId && context.reviewLoopNumber
154
+ ? [context]
155
+ : []);
156
+ const reviews = readyReviews(run);
157
+ const useGit = artifacts['history:git']?.content === 'enabled';
158
+ const retainedPaths = new Set(extractRunArtifactManifest(run).map((entry) => entry.path));
159
+ const currentActor = runActivityView(run)?.kind === 'worker-fix' ? runReviewActivityContext(run) : null;
160
+ const fixingActor = currentActor?.role === 'review-fix' ? currentActor : null;
161
+ const latestReviewActor = [...contexts]
162
+ .sort((left, right) => (left.attemptStartedAt ?? left.startedAt ?? '').localeCompare(right.attemptStartedAt ?? right.startedAt ?? ''))
163
+ .at(-1);
164
+ const steps = run.steps.filter((step) => step.name.includes('review') && Array.isArray(step.outputs?.attempts));
165
+ const stepId = (step) => text(step.outputs?.reviewId) ?? `pipeline-review-${run.id}`;
166
+ const segments = run.steps
167
+ .filter((step) => step.name.includes('review'))
168
+ .flatMap((step) => Array.isArray(step.outputs?.timeline)
169
+ ? step.outputs.timeline.map(record).filter(isRecord)
170
+ : []);
171
+ const checks = [];
172
+ const ids = [
173
+ ...new Set([
174
+ ...reviews.map((review) => review.id),
175
+ ...contexts.map((context) => context.reviewId),
176
+ ...steps.map(stepId),
177
+ ]),
178
+ ];
179
+ for (const id of ids) {
180
+ const review = reviews.find((entry) => entry.id === id);
181
+ const actors = contexts.filter((context) => context.reviewId === id);
182
+ const step = steps.find((entry) => stepId(entry) === id);
183
+ const stepAttempts = Array.isArray(step?.outputs?.attempts)
184
+ ? step.outputs.attempts.map(record).filter(isRecord)
185
+ : [];
186
+ const attempts = review
187
+ ? review.attempts?.length
188
+ ? review.attempts
189
+ : [review]
190
+ : [];
191
+ const loops = [
192
+ ...new Set([
193
+ ...attempts.map((attempt) => attempt.loopNumber),
194
+ ...actors.map((context) => context.reviewLoopNumber),
195
+ ...stepAttempts.map((entry, index) => number(entry.loopNumber) ?? index + 1),
196
+ ]),
197
+ ].sort((a, b) => a - b);
198
+ // Replays can restart the loop counter. A context is an attempt, not another copy of loop 1.
199
+ const sources = loops
200
+ .flatMap((loop) => {
201
+ const matching = actors.filter((context) => context.reviewLoopNumber === loop);
202
+ return matching.length
203
+ ? matching.map((actor) => ({ loop, actor }))
204
+ : [{ loop, actor: undefined }];
205
+ })
206
+ .sort((left, right) => (left.actor?.startedAt ?? '').localeCompare(right.actor?.startedAt ?? '') ||
207
+ left.loop - right.loop);
208
+ let roundNumber = 0;
209
+ const rounds = sources.map(({ loop, actor }) => {
210
+ roundNumber = Math.max(roundNumber + 1, loop);
211
+ const sameLoop = actors.filter((context) => context.reviewLoopNumber === loop);
212
+ const ownsAttempt = (entry, entryLoop) => {
213
+ if (!actor)
214
+ return entryLoop === loop;
215
+ if (actor.status === 'failed' && entry.verdict !== 'failed')
216
+ return false;
217
+ if (entry.startedAt && actor.completedAt && entry.startedAt > actor.completedAt)
218
+ return false;
219
+ if (entry.completedAt && actor.startedAt && entry.completedAt < actor.startedAt)
220
+ return false;
221
+ if (entry.headSha &&
222
+ actor.deliveryBaselineRef &&
223
+ entry.headSha !== actor.deliveryBaselineRef)
224
+ return false;
225
+ const sameHead = entry.headSha && entry.headSha === actor.deliveryBaselineRef;
226
+ if (entryLoop !== loop && !sameHead)
227
+ return false;
228
+ return (sameLoop.length === 1 ||
229
+ (entry.startedAt
230
+ ? entry.startedAt >= (actor.startedAt ?? '') &&
231
+ (!actor.completedAt || entry.startedAt <= actor.completedAt)
232
+ : sameLoop.at(-1)?.id === actor.id));
233
+ };
234
+ const recordedAttempt = attempts
235
+ .filter((entry) => ownsAttempt({ ...entry, headSha: entry.reviewSnapshot?.headSha ?? undefined }, entry.loopNumber))
236
+ .at(-1);
237
+ const recordedRaw = stepAttempts
238
+ .filter((entry, index) => ownsAttempt({
239
+ startedAt: text(entry.startedAt) ?? undefined,
240
+ completedAt: text(entry.completedAt) ?? undefined,
241
+ verdict: text(entry.verdict) ?? undefined,
242
+ headSha: text(record(entry.reviewSnapshot)?.headSha) ?? undefined,
243
+ }, number(entry.loopNumber) ?? index + 1))
244
+ .at(-1);
245
+ const newerActive = actor &&
246
+ ['working', 'launching', 'waiting'].includes(actor.status) &&
247
+ (!(recordedAttempt?.completedAt ?? text(recordedRaw?.completedAt)) ||
248
+ Date.parse(actor.attemptStartedAt ?? actor.startedAt ?? '') >=
249
+ Date.parse(recordedAttempt?.completedAt ?? text(recordedRaw?.completedAt) ?? ''));
250
+ const attempt = newerActive ? undefined : recordedAttempt;
251
+ const raw = newerActive ? undefined : recordedRaw;
252
+ const dir = reviewArtifactDir(loop, actor?.artifactScope);
253
+ const saved = actor?.reviewResultFile && (!newerActive || actor.reviewResultValidatedAt)
254
+ ? artifact(artifacts, actor.reviewResultFile)
255
+ : null;
256
+ const staticResult = actor && staticActors.has(actor.id) ? result : null;
257
+ const storedSnapshot = attempt?.reviewSnapshot ?? record(raw?.reviewSnapshot) ?? staticResult?.reviewSnapshot;
258
+ const recordedSnapshot = storedSnapshot ?? artifact(artifacts, `${dir}/review-diff-stat.json`);
259
+ const expectedHead = actor?.deliveryBaselineRef ?? actor?.pipelineVisualReviewInput?.headSha;
260
+ const overwritten = !storedSnapshot &&
261
+ actor?.completedAt &&
262
+ text(recordedSnapshot?.capturedAt) &&
263
+ String(recordedSnapshot?.capturedAt) > actor.completedAt;
264
+ const snapshot = (overwritten || (expectedHead && recordedSnapshot?.headSha !== expectedHead)
265
+ ? null
266
+ : recordedSnapshot) ?? (actor ? artifact(artifacts, recoveredSnapshotKey(actor)) : null);
267
+ const storedFix = attempt?.fixDelta ?? record(raw?.fixDelta);
268
+ const candidateFix = storedFix ?? artifact(artifacts, `${dir}/fix-delta-stat.json`);
269
+ const fix = (!storedFix &&
270
+ actor?.completedAt &&
271
+ text(candidateFix?.capturedAt) &&
272
+ String(candidateFix?.capturedAt) > actor.completedAt) ||
273
+ (expectedHead &&
274
+ candidateFix &&
275
+ (candidateFix.fixHeadSha ?? candidateFix.headSha) !== expectedHead)
276
+ ? null
277
+ : candidateFix;
278
+ const issueValue = attempt?.issues ?? raw?.issues ?? saved?.issues ?? staticResult?.lineComments;
279
+ const issueRows = findings(issueValue);
280
+ const startedAt = attempt?.startedAt ??
281
+ text(raw?.startedAt) ??
282
+ actor?.startedAt ??
283
+ actor?.attemptStartedAt ??
284
+ null;
285
+ const completedAt = attempt?.completedAt ??
286
+ text(raw?.completedAt) ??
287
+ actor?.completedAt ??
288
+ (staticResult ? run.steps.find((entry) => entry.name === 'monitor')?.completedAt : null) ??
289
+ null;
290
+ const previousCompletedAt = actors
291
+ .filter((candidate) => candidate.id !== actor?.id &&
292
+ candidate.completedAt &&
293
+ startedAt &&
294
+ candidate.completedAt <= startedAt)
295
+ .map((candidate) => candidate.completedAt)
296
+ .filter((value) => Boolean(value))
297
+ .sort()
298
+ .at(-1);
299
+ const previousActor = actors
300
+ .filter((candidate) => candidate.id !== actor?.id &&
301
+ candidate.completedAt &&
302
+ startedAt &&
303
+ candidate.completedAt <= startedAt)
304
+ .sort((left, right) => (left.completedAt ?? '').localeCompare(right.completedAt ?? ''))
305
+ .at(-1);
306
+ const previousHead = previousActor?.deliveryBaselineRef ?? previousActor?.pipelineVisualReviewInput?.headSha;
307
+ const headSha = text(snapshot?.headSha) ?? expectedHead ?? null;
308
+ const reconstructedFix = !fix && previousHead && headSha && previousHead !== headSha;
309
+ const fixBaseSha = text(fix?.fixBaseSha ?? fix?.baseSha) ?? (reconstructedFix ? previousHead : null);
310
+ const fixHeadSha = text(fix?.fixHeadSha ?? fix?.headSha) ?? (reconstructedFix ? headSha : null);
311
+ const fixDiffPath = useGit && fixBaseSha && fixHeadSha
312
+ ? `history:git:${fixBaseSha}:${fixHeadSha}.diff`
313
+ : (text(fix?.diffPath) ??
314
+ (reconstructedFix && actor ? `history:${actor.id}:fix.diff` : null));
315
+ const reviewBaseSha = text(snapshot?.baseSha);
316
+ const diffPath = useGit && reviewBaseSha && headSha
317
+ ? `history:git:${reviewBaseSha}:${headSha}.diff`
318
+ : text(snapshot?.diffPath);
319
+ const completedFix = previousCompletedAt && startedAt
320
+ ? (run.agentContexts ?? [])
321
+ .filter((candidate) => candidate.role === 'review-fix' &&
322
+ (candidate.completedAt ?? text(fix?.capturedAt)) &&
323
+ (candidate.promptDeliveryStartedAt ?? candidate.startedAt ?? '') >
324
+ previousCompletedAt &&
325
+ (candidate.completedAt ?? text(fix?.capturedAt) ?? '') <= startedAt)
326
+ .sort((left, right) => (left.completedAt ?? '').localeCompare(right.completedAt ?? ''))
327
+ .at(-1)
328
+ : undefined;
329
+ const firstFix = previousCompletedAt && startedAt
330
+ ? run.agentContexts?.find((candidate) => candidate.role === 'review-fix' &&
331
+ candidate.startedAt &&
332
+ candidate.startedAt > previousCompletedAt &&
333
+ candidate.startedAt <= startedAt)
334
+ : undefined;
335
+ const segment = attempt?.timeline?.find((entry) => entry.kind === 'worker-fix');
336
+ const rawSegment = (Array.isArray(raw?.timeline) ? raw.timeline.map(record).filter(isRecord) : segments).find((entry) => entry.kind === 'worker-fix' && (number(entry.loopNumber) ?? loop) === loop);
337
+ const fixing = fixingActor &&
338
+ (fixingActor.artifactScope
339
+ ? fixingActor.artifactScope === actor?.artifactScope || fixingActor.artifactScope === id
340
+ : latestReviewActor?.reviewId === id)
341
+ ? fixingActor
342
+ : null;
343
+ const initialMode = loop === 1 && id === `pipeline-review-${run.id}`
344
+ ? record(run.steps.find((step) => step.name === 'review')?.inputs?.reviewSelection)?.mode
345
+ : null;
346
+ const mode = attempt?.mode ??
347
+ text(raw?.mode) ??
348
+ text(saved?.mode) ??
349
+ staticResult?.session?.mode ??
350
+ (actor?.reviewFallback
351
+ ? 'cold'
352
+ : actor?.nativeSession?.handoffFrom
353
+ ? 'warm'
354
+ : actor?.nativeSession
355
+ ? 'cold'
356
+ : null) ??
357
+ (actor && staticActors.has(actor.id)
358
+ ? (run.reviewMode ?? run.repeatReviewContext?.mode)
359
+ : null) ??
360
+ initialMode;
361
+ const recorded = Array.isArray(issueValue);
362
+ const verdict = attempt?.verdict ??
363
+ text(raw?.verdict) ??
364
+ staticResult?.recommendation ??
365
+ (actor?.status === 'failed' ? 'failed' : text(saved?.verdict)) ??
366
+ (actor?.status === 'complete' ? 'Result not recorded' : 'pending');
367
+ const failureReason = verdict === 'failed'
368
+ ? (attempt?.reason ??
369
+ text(raw?.reason) ??
370
+ (actor ? reviewAttemptFailureReason(run, actor) : null))
371
+ : null;
372
+ const unresolved = attempt?.unresolvedCount ??
373
+ number(raw?.unresolvedCount) ??
374
+ (recorded ? issueRows.length : null);
375
+ return {
376
+ key: actor?.id ?? `${id}:${loop}`,
377
+ reviewId: id,
378
+ loopNumber: loop,
379
+ roundNumber,
380
+ runner: actor?.runner ?? review?.runner ?? text(step?.outputs?.runner) ?? 'Unknown runner',
381
+ model: actor?.model ?? review?.model ?? text(step?.outputs?.model) ?? 'default',
382
+ mode: mode === 'warm' || mode === 'cold' ? mode : null,
383
+ modeLabel: mode === 'warm' || mode === 'cold' ? mode.toUpperCase() : 'Mode unavailable',
384
+ verdict,
385
+ verdictTone: ['pass', 'APPROVE'].includes(verdict)
386
+ ? 'ok'
387
+ : verdict === 'failed'
388
+ ? 'fail'
389
+ : verdict === 'pending'
390
+ ? 'running'
391
+ : 'warn',
392
+ failureReason,
393
+ startedAt,
394
+ completedAt,
395
+ durationMs: duration(startedAt, completedAt),
396
+ usageLabel: reviewUsageLabel(attempt?.usage ??
397
+ (review &&
398
+ ownsAttempt({ ...review, headSha: review.reviewSnapshot?.headSha ?? undefined }, review.loopNumber)
399
+ ? review.usage
400
+ : undefined)),
401
+ headSha,
402
+ reviewBaseSha,
403
+ resultRecorded: recorded,
404
+ unresolvedCount: unresolved,
405
+ unresolvedLabel: unresolved !== null
406
+ ? `${unresolved} unresolved`
407
+ : verdict === 'pending'
408
+ ? 'Findings pending'
409
+ : 'Finding count not recorded',
410
+ findingsLabel: recorded
411
+ ? issueRows.length
412
+ ? `${issueRows.length} finding${issueRows.length === 1 ? '' : 's'} recorded.`
413
+ : 'No findings recorded in this round.'
414
+ : verdict === 'pending'
415
+ ? 'Review is running. Findings appear when it finishes.'
416
+ : verdict === 'failed'
417
+ ? 'Review failed before producing findings.'
418
+ : 'Findings unavailable',
419
+ findings: issueRows,
420
+ earlierAttempts: [],
421
+ reviewRange: range(snapshot?.baseSha, snapshot?.headSha) ??
422
+ actor?.deliveryBaselineRef?.slice(0, 7) ??
423
+ 'Head pending',
424
+ fixRange: range(fixBaseSha, fixHeadSha),
425
+ fixStat: fixStat(fix),
426
+ fixDurationMs: segment?.durationMs ??
427
+ number(rawSegment?.durationMs) ??
428
+ duration(segment?.startedAt ?? text(rawSegment?.startedAt), segment?.completedAt ?? text(rawSegment?.completedAt)) ??
429
+ duration(completedFix?.promptDeliveryStartedAt ??
430
+ completedFix?.startedAt ??
431
+ completedFix?.attemptStartedAt ??
432
+ null, completedFix?.completedAt ?? text(fix?.capturedAt)),
433
+ fixStartedAt: segment?.startedAt ??
434
+ text(rawSegment?.startedAt) ??
435
+ completedFix?.promptDeliveryStartedAt ??
436
+ completedFix?.startedAt ??
437
+ firstFix?.startedAt ??
438
+ null,
439
+ fixCompletedAt: segment?.completedAt ??
440
+ text(rawSegment?.completedAt) ??
441
+ completedFix?.completedAt ??
442
+ text(fix?.capturedAt),
443
+ fixFiles: [
444
+ ...(artifacts[String(fixDiffPath)]?.content ?? '').matchAll(/^diff --git a\/.+ b\/(.+)$/gm),
445
+ ].map((match) => match[1]),
446
+ fixRunning: Boolean(actor?.id === latestReviewActor?.id && fixing),
447
+ activeFixStartedAt: actor?.id === latestReviewActor?.id
448
+ ? (fixing?.promptDeliveryStartedAt ??
449
+ fixing?.attemptStartedAt ??
450
+ fixing?.startedAt ??
451
+ null)
452
+ : null,
453
+ hasFix: Boolean(fix || reconstructedFix || segment || rawSegment || completedFix),
454
+ diffPath,
455
+ diffReconstructed: useGit || record(snapshot)?.reconstructed === true,
456
+ diffText: diffPath ? (artifacts[String(diffPath)]?.content ?? null) : null,
457
+ reviewDiffRetained: retainedPaths.has(String(snapshot?.diffPath)),
458
+ fixDiffPath,
459
+ fixDiffText: fixDiffPath ? (artifacts[String(fixDiffPath)]?.content ?? null) : null,
460
+ fixDiffError: fixDiffPath ? (artifacts[String(fixDiffPath)]?.error ?? null) : null,
461
+ fixBaseSha,
462
+ fixHeadSha,
463
+ fixReconstructed: Boolean(reconstructedFix || (useGit && fixBaseSha && fixHeadSha)),
464
+ validationDepth: attempt?.validationDepth ??
465
+ text(raw?.validationDepth) ??
466
+ review?.validationDepth ??
467
+ 'static-code',
468
+ timing: deriveChecklistStepDurations(attempt?.checklistTiming, startedAt ?? undefined),
469
+ unavailable: [
470
+ ...reviewHistoryArtifactPathsForActor(actor),
471
+ ...(actor ? [recoveredSnapshotKey(actor)] : []),
472
+ ...(fixDiffPath ? [fixDiffPath] : []),
473
+ ...(diffPath ? [diffPath] : []),
474
+ ].flatMap((path) => (artifacts[path]?.error ? [artifacts[path].error] : [])),
475
+ };
476
+ });
477
+ if (!rounds.length)
478
+ continue;
479
+ const latest = rounds.at(-1);
480
+ const reviewerActive = actors.some((context) => ['launching', 'working', 'waiting'].includes(context.status));
481
+ const pendingContinuation = review?.recoveryContinuationPending === true && (latest.unresolvedCount ?? 0) > 0;
482
+ const continuation = pendingContinuation
483
+ ? reviewerActive
484
+ ? 'The worker fix is complete; the next review round is running.'
485
+ : latest.fixRunning
486
+ ? `Worker is fixing the latest ${latest.unresolvedCount} findings.`
487
+ : `Stopped after the retry limit: the latest ${latest.unresolvedCount} findings still need delivery to the worker.`
488
+ : latest.fixRunning
489
+ ? 'Worker is fixing the latest findings.'
490
+ : null;
491
+ checks.push({
492
+ id,
493
+ checkNumber: checks.length + 1,
494
+ findingCount: rounds.reduce((sum, round) => sum + round.findings.length, 0),
495
+ runner: review?.runner ?? latest.runner,
496
+ model: review?.model ?? latest.model,
497
+ source: review?.source === 'human-gate' ? 'Requested review' : 'Review',
498
+ verdict: latest.verdict,
499
+ unresolvedCount: latest.unresolvedCount,
500
+ stale: review?.stale === true,
501
+ continuation,
502
+ rounds,
503
+ });
504
+ }
505
+ const roundCount = checks.reduce((sum, check) => sum + check.rounds.length, 0);
506
+ const replayStep = run.steps.find((step) => step.name === 'review' && step.status === 'running');
507
+ const activeReplay = run.status === 'reviewing' &&
508
+ (run.engineState?.generation ?? 0) > 0 &&
509
+ replayStep?.startedAt &&
510
+ latestReviewActor?.completedAt &&
511
+ replayStep.startedAt > latestReviewActor.completedAt &&
512
+ !contexts.some((context) => ['launching', 'working', 'waiting'].includes(context.status))
513
+ ? {
514
+ roundNumber: Math.max(...checks.flatMap((check) => check.rounds.map((round) => round.roundNumber))) +
515
+ 1,
516
+ startedAt: replayStep.startedAt,
517
+ }
518
+ : null;
519
+ const summary = [
520
+ chain.length ? `${chain.length} diff generation${chain.length === 1 ? '' : 's'}` : '',
521
+ `${checks.length} review check${checks.length === 1 ? '' : 's'}`,
522
+ `${roundCount} round${roundCount === 1 ? '' : 's'}`,
523
+ ]
524
+ .filter(Boolean)
525
+ .join(' · ');
526
+ return {
527
+ checks,
528
+ segments,
529
+ roundCount,
530
+ activeReplay,
531
+ summary,
532
+ chain: chain.map((entry) => ({
533
+ ...entry,
534
+ continuity: observedReviewSessionContinuity(entry),
535
+ range: range(entry.baseSha, entry.headSha) ?? 'SHA unavailable',
536
+ diffPath: entry.artifactRefs.find((artifact) => artifact.path.endsWith('.diff'))?.path ?? null,
537
+ })),
538
+ events: reviewHistoryTimeline(run, checks.flatMap((check) => check.rounds)),
539
+ };
540
+ }
541
+ function reviewHistoryArtifactPathsForActor(actor) {
542
+ if (!actor?.reviewLoopNumber)
543
+ return actor?.reviewResultFile ? [actor.reviewResultFile] : [];
544
+ const dir = reviewArtifactDir(actor.reviewLoopNumber, actor.artifactScope);
545
+ return [
546
+ actor.reviewResultValidatedAt || !['working', 'launching', 'waiting'].includes(actor.status)
547
+ ? actor.reviewResultFile
548
+ : null,
549
+ `${dir}/review-diff-stat.json`,
550
+ ...(actor.reviewLoopNumber > 1 ? [`${dir}/fix-delta-stat.json`] : []),
551
+ ].filter((path) => Boolean(path));
552
+ }
553
+ function historyAttemptIdentity(value) {
554
+ const attempt = record(value);
555
+ return [
556
+ attempt?.loopNumber,
557
+ attempt?.mode,
558
+ attempt?.verdict,
559
+ attempt?.unresolvedCount,
560
+ attempt?.startedAt,
561
+ attempt?.completedAt,
562
+ attempt?.reviewSnapshot,
563
+ attempt?.fixDelta,
564
+ attempt?.artifactPaths,
565
+ ];
566
+ }
567
+ /** Refresh on retained round changes, without rereading files for unrelated run heartbeats. */
568
+ export function reviewHistoryIdentity(run) {
569
+ return JSON.stringify([
570
+ run.id,
571
+ run.reviewResult,
572
+ run.reviewMode,
573
+ run.reviewRoundSettlements,
574
+ readyReviews(run).map((review) => [
575
+ review.id,
576
+ review.runner,
577
+ review.model,
578
+ review.source,
579
+ review.stale,
580
+ historyAttemptIdentity(review),
581
+ review.attempts?.map(historyAttemptIdentity),
582
+ ]),
583
+ run.steps
584
+ .filter((step) => step.name.includes('review'))
585
+ .map((step) => [
586
+ step.status,
587
+ step.startedAt,
588
+ step.completedAt,
589
+ Array.isArray(step.outputs?.attempts)
590
+ ? step.outputs.attempts.map(historyAttemptIdentity)
591
+ : undefined,
592
+ step.outputs?.timeline,
593
+ step.outputs?.reviewId,
594
+ step.outputs?.runner,
595
+ step.outputs?.model,
596
+ ]),
597
+ (run.agentContexts ?? [])
598
+ .filter((context) => ['review', 'review-fix'].includes(context.role))
599
+ .map((context) => [
600
+ context.id,
601
+ context.status,
602
+ context.reviewLoopNumber,
603
+ context.reviewResultValidatedAt,
604
+ context.reviewResultFile,
605
+ context.artifactScope,
606
+ context.attemptStartedAt,
607
+ context.startedAt,
608
+ context.completedAt,
609
+ context.deliveryBaselineRef,
610
+ context.nativeSession?.handoffFrom,
611
+ ]),
612
+ ]);
613
+ }
614
+ /** One loader for both clients; the transport owns authentication and checks farm identity. */
615
+ export async function loadReviewHistoryArtifacts(run, read, readLive, readDiff) {
616
+ const readPaths = async (paths) => {
617
+ const settled = await Promise.allSettled(paths.map(async (path) => {
618
+ const retained = await read(path);
619
+ if (retained !== null)
620
+ return retained;
621
+ // A completed live round can precede its bundle capture. Its recorded task owns the read.
622
+ const actor = !isTerminalRunStatus(run.status)
623
+ ? run.agentContexts?.find((context) => context.role === 'review' &&
624
+ context.runId === run.id &&
625
+ context.slotId === run.slotId &&
626
+ context.taskFile &&
627
+ (reviewHistoryArtifactPathsForActor(context).includes(path) ||
628
+ (context.reviewLoopNumber &&
629
+ path.startsWith(`${reviewArtifactDir(context.reviewLoopNumber, context.artifactScope)}/`))))
630
+ : undefined;
631
+ if (!readLive || !actor?.slotId || !actor.taskFile)
632
+ throw new Error('Not recorded in the retained run');
633
+ const taskDir = actor.taskFile.slice(0, actor.taskFile.lastIndexOf('/'));
634
+ if (!taskDir || taskDir.split('/').includes('..') || path.split('/').includes('..'))
635
+ throw new Error('Recorded review task is unavailable');
636
+ return readLive({ slotId: actor.slotId, path: `${taskDir}/${path}` });
637
+ }));
638
+ return Object.fromEntries(paths.map((path, index) => {
639
+ const value = settled[index];
640
+ return [
641
+ path,
642
+ value.status === 'fulfilled'
643
+ ? { content: value.value }
644
+ : {
645
+ error: `${path}: ${value.reason instanceof Error ? value.reason.message : String(value.reason)}`,
646
+ },
647
+ ];
648
+ }));
649
+ };
650
+ const metadata = await readPaths(reviewHistoryArtifactPaths(run));
651
+ if (readDiff && !isTerminalRunStatus(run.status))
652
+ metadata['history:git'] = { content: 'enabled' };
653
+ if (readLive && readDiff && !isTerminalRunStatus(run.status)) {
654
+ const rounds = reviewHistoryView(run, metadata).checks.flatMap((check) => check.rounds);
655
+ const recoveryRounds = rounds.filter((round) => !round.diffPath);
656
+ const recoveries = await Promise.allSettled(recoveryRounds.map(async (round) => {
657
+ const actor = run.agentContexts?.find((context) => context.id === round.key &&
658
+ context.runId === run.id &&
659
+ context.slotId === run.slotId &&
660
+ context.taskFile &&
661
+ !['working', 'launching'].includes(context.status));
662
+ if (!actor?.slotId || !actor.taskFile)
663
+ return;
664
+ const task = await readLive({ slotId: actor.slotId, path: actor.taskFile });
665
+ // These are engine-written frozen input headers, not reviewer transcript/output.
666
+ const match = /## COLD review range\s+Review the complete PR diff ([a-f0-9]{40})\.\.([a-f0-9]{40}) in /.exec(task) ?? /- Exact review range: `([a-f0-9]{40})\.\.([a-f0-9]{40})`/.exec(task);
667
+ if (!match || (round.headSha && match[2] !== round.headSha))
668
+ return;
669
+ metadata[recoveredSnapshotKey(actor)] = {
670
+ content: JSON.stringify({
671
+ source: 'local-git',
672
+ baseSha: match[1],
673
+ headSha: match[2],
674
+ reconstructed: true,
675
+ }),
676
+ };
677
+ }));
678
+ recoveries.forEach((result, index) => {
679
+ if (result.status === 'rejected') {
680
+ const actor = run.agentContexts?.find((context) => context.id === recoveryRounds[index].key);
681
+ if (actor)
682
+ metadata[recoveredSnapshotKey(actor)] = {
683
+ error: result.reason instanceof Error ? result.reason.message : String(result.reason),
684
+ };
685
+ }
686
+ });
687
+ }
688
+ if (readDiff && metadata['history:git']) {
689
+ const requests = new Map();
690
+ for (const round of reviewHistoryView(run, metadata).checks.flatMap((check) => check.rounds)) {
691
+ for (const [path, base, head] of [
692
+ [round.diffPath, round.reviewBaseSha, round.headSha],
693
+ [round.fixDiffPath, round.fixBaseSha, round.fixHeadSha],
694
+ ]) {
695
+ if (path?.startsWith('history:git:') && base && head)
696
+ requests.set(path, {
697
+ slotId: run.slotId ?? '',
698
+ ...(run.slotId ? {} : { runId: run.id }),
699
+ base,
700
+ head,
701
+ });
702
+ }
703
+ }
704
+ const entries = [...requests];
705
+ const results = await Promise.allSettled(entries.map(([, params]) => readDiff(params)));
706
+ entries.forEach(([path], index) => {
707
+ const value = results[index];
708
+ metadata[path] =
709
+ value.status === 'fulfilled'
710
+ ? { content: value.value }
711
+ : { error: value.reason instanceof Error ? value.reason.message : String(value.reason) };
712
+ });
713
+ }
714
+ // Reuse each platform's existing diff viewer for changed files, instead of another diff parser.
715
+ const diffs = [
716
+ ...new Set(reviewHistoryView(run, metadata).checks.flatMap((check) => check.rounds.flatMap((round) => [round.fixDiffPath, round.diffPath]
717
+ .filter((path) => !path?.startsWith('history:'))
718
+ .filter((path) => Boolean(path))))),
719
+ ];
720
+ return { ...metadata, ...(await readPaths(diffs)) };
721
+ }
722
+ //# sourceMappingURL=review-history.js.map