Repository navigation
Expand file tree
/
Copy pathrunner.ts
More file actions
530 lines (495 loc) · 19.7 KB
/
Copy pathrunner.ts
File metadata and controls
530 lines (495 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/**
* Phase runner — orchestrates template execution.
* Spawns CLI sessions per phase/round/role, writes prompts, watches for
* answers, handles reviewer consensus, and emits SSE events.
*
* Per-role drivers live in runner/{doer-driver,reviewer-driver,
* review-only-phase}.ts. Headless streaming hot paths live in
* runner/{doer,reviewer,stream-file-writer}.ts. Pure prompt-construction
* helpers live in runner/prompt-builder.ts.
*/
import fs from 'fs';
import os from 'os';
import path from 'path';
import { atomicWriteJsonSync } from '../lib/atomic-write.js';
import { chats } from '../lib/db/index.js';
import { logger } from '../lib/logger.js';
import { isReviewOnlyPhase, type StandardPhase, type Template } from '../lib/template-schema.js';
import type { ErrorDetector } from './error-detector.js';
import { runDoer } from './runner/doer-driver.js';
import { readPriorRoundFeedback } from './runner/prior-round.js';
import { runReviewers } from './runner/reviewer-driver.js';
import { runReviewOnlyPhase } from './runner/review-only-phase.js';
import { detectGitContext, runShipPhase } from './ship.js';
import type { TmuxManager } from './tmux-types.js';
export type { RunnerEvent } from './runner/types.js';
import type { RunnerEvent } from './runner/types.js';
export interface PhaseRunnerOptions {
chatId: string;
template: Template;
work: string;
/**
* Artifact text for review-only phases. When the template's first
* phase has `kind: review_only`, this MUST be supplied (the
* chat-create endpoint enforces it). The runner writes it into a
* synthetic doer-answer slot and emits synthetic doer phase events so
* reviewers see the same shape they always do.
*/
artifact?: string;
/**
* Optional absolute path to the user's repo. When set:
* - Doer cwd becomes this path (real edits land in the working tree)
* - Reviewers stay in scratch dirs (read-only, no writes to user's repo)
* - Ship phase (if template.ship.enabled) runs after consensus
* When unset: doer cwd is scratch dir as before; ship phase auto-skips.
*/
repoPath?: string;
/**
* Optional list of file paths to read and inline into doer + reviewer
* prompts. Paths are resolved relative to repoPath when set, else
* absolute. Missing files are skipped with a note. Each file is capped
* at 64 KB, total payload at 256 KB.
*/
attachedFiles?: string[];
onEvent: (e: RunnerEvent) => void;
abortSignal: AbortSignal;
tmuxMgr: TmuxManager;
errorDetector: ErrorDetector;
}
interface ChatMeta {
chatId: string;
work: string;
templateId: string;
createdAt: number;
}
/**
* Main runner. Iterates phases, spawns doers, waits for answers, runs
* reviewers, checks consensus, and emits events.
*/
export async function runChat(opts: PhaseRunnerOptions): Promise<void> {
const { chatId, template, work, artifact, repoPath, attachedFiles, onEvent, abortSignal, tmuxMgr, errorDetector } = opts;
const chatDir = path.join(os.homedir(), '.chorus', 'chats', chatId);
// Pack attached files into a single block once per chat. Both doer +
// every reviewer get the same block — they're auditing the same artifacts.
const filesBlock = packAttachedFiles(attachedFiles, repoPath);
if (!fs.existsSync(chatDir)) {
fs.mkdirSync(chatDir, { recursive: true });
}
// Freeze the template onto the chat row BEFORE any other durable run
// artifact. Ordering matters: if we wrote meta.json first and crashed
// before the snapshot, a daemon-restart-resume would re-enter runChat
// with whatever template the runner re-resolved at restart time — which
// could be a user-edited version, not the one this chat actually
// intended to run against. Writing the snapshot first means resume's
// IS-NULL guard finds it already there and the original is preserved.
// Write-once: a second call after a daemon-restart-resume is a no-op
// (helper guards on `template_snapshot IS NULL`). Failures are
// non-fatal — the cockpit falls back to the live template by id, same
// as legacy behaviour.
try {
await chats.setTemplateSnapshot(chatId, JSON.stringify(template));
} catch (err) {
logger.warn(
{ chatId, err: err instanceof Error ? err.message : String(err) },
'failed to persist template snapshot — cockpit will use live template fallback',
);
}
// Atomic temp+rename so a partial write (daemon crash, FS ENOSPC
// mid-fsync) can't leave a corrupt JSON the cockpit chokes on.
const meta: ChatMeta = {
chatId,
work,
templateId: template.id,
createdAt: Date.now(),
};
atomicWriteJsonSync(path.join(chatDir, 'meta.json'), meta);
// chat_done is a one-way latch. The abort listener and the normal
// terminal emission both try to fire it; whichever runs first wins.
// This closes a race where SSE-disconnect → abort → chat_done(cancelled),
// then the loop kept running and emitted chat_done(completed),
// overwriting 'cancelled' with 'approved' in the DB.
let chatDoneEmitted = false;
const emitChatDone = (payload: Record<string, unknown>): void => {
if (chatDoneEmitted) return;
chatDoneEmitted = true;
onEvent({ chatId, type: 'chat_done', payload, ts: Date.now() });
};
const abortListener = () => {
// TODO(H): send polite Escape to active session, flip status to cancelled
emitChatDone({ status: 'cancelled' });
};
abortSignal.addEventListener('abort', abortListener);
// Track whether any phase failed because every reviewer in it failed
// (timeout/quota/crash). If so, the chat ends in 'no_review' rather
// than 'approved' — there was no actual peer review to approve from.
let anyPhaseAllReviewersFailed = false;
// Track whether any doer failed all rounds (couldn't produce output).
// If so, the chat must NOT end approved — there was no real
// implementation to review.
let anyPhaseDoerFailed = false;
// Captures the consensus from the most recent review-only phase. Used
// to override the default 'approved' verdict in chat_done — review-only
// chats surface what the reviewers actually said rather than auto-
// approving. null when no review-only phase ran (standard templates).
let reviewOnlyConsensus: { agreed: boolean; summary: string } | null = null;
try {
for (let phaseIdx = 0; phaseIdx < template.phases.length; phaseIdx++) {
if (abortSignal.aborted) break;
const phase = template.phases[phaseIdx];
// Review-only phases skip the doer entirely. Single pass, no
// iterate loop, no ship — enforced here, not in the schema, so
// future hybrid templates can mix kinds without re-plumbing the
// validator.
if (isReviewOnlyPhase(phase)) {
const outcome = await runReviewOnlyPhase({
chatDir,
chatId,
phase,
phaseIdx,
artifact: artifact ?? '',
work,
filesBlock,
tmuxMgr,
errorDetector,
onEvent,
abortSignal,
templateFallbackReviewer: template.fallback?.reviewer,
});
if (outcome.allReviewersFailed) {
anyPhaseAllReviewersFailed = true;
}
if (!outcome.completed) {
// Aborted (Ctrl-C / cockpit cancel). DO NOT capture consensus
// here — emitChatDone is racing with the abort listener which
// fires status='cancelled', and surfacing 'request_changes'
// would collapse "user hit cancel" with "reviewers said no" if
// the abort listener loses the latch race.
break;
}
// Reviewers actually finished a pass. Capture so chat_done can
// surface the real verdict instead of always reporting 'approved'.
reviewOnlyConsensus = {
agreed: outcome.agreed,
summary: outcome.summary,
};
onEvent({
chatId,
type: 'phase_done',
payload: {
phaseId: phase.id,
phaseIdx,
kind: phase.kind,
},
ts: Date.now(),
});
continue;
}
// Standard phase from here on.
const stdPhase: StandardPhase = phase;
let doerSucceeded = false;
for (let round = 1; round <= stdPhase.iterate.maxRounds; round++) {
if (abortSignal.aborted) break;
onEvent({
chatId,
type: 'phase_start',
payload: {
phaseId: stdPhase.id,
phaseIdx,
kind: stdPhase.kind,
round,
role: 'doer',
agent: stdPhase.doer.lineage,
},
ts: Date.now(),
});
// Round 2+ feeds prior reviewer findings back into the doer prompt
// so disagreement → retry is a real revision loop, not "ask the same
// question again." Returns "" when round === 1.
const priorRoundFeedback = readPriorRoundFeedback(chatDir, round);
const doerAnswer = await runDoer(
chatDir,
chatId,
stdPhase,
phaseIdx,
round,
work,
filesBlock,
tmuxMgr,
errorDetector,
onEvent,
abortSignal,
repoPath,
template.fallback?.doer,
priorRoundFeedback,
);
// Treat null OR partial-stream as a doer failure — `!doerAnswer.full`
// means runDoerHeadless saw a mid-stream error and only captured a
// partial transcript. Passing that to reviewers leads to verdicts
// on a half-written answer (gemini caught this on the launch-eve
// runner review). The runner already retries via the round loop,
// so failing this round is the right move; reviewing garbage is not.
if (!doerAnswer || !doerAnswer.full) {
onEvent({
chatId,
type: 'phase_failed',
payload: {
phaseId: stdPhase.id,
phaseIdx,
kind: stdPhase.kind,
role: 'doer',
reason: doerAnswer ? 'doer_partial_stream' : 'doer_timeout',
},
ts: Date.now(),
});
break;
}
onEvent({
chatId,
type: 'phase_progress',
payload: {
phaseId: stdPhase.id,
round,
role: 'doer',
output: doerAnswer.content.slice(0, 500),
},
ts: Date.now(),
});
if (stdPhase.reviewer && stdPhase.reviewer.candidates.length > 0) {
const consensus = await runReviewers(
chatDir,
chatId,
stdPhase,
phaseIdx,
round,
doerAnswer.content,
work,
filesBlock,
tmuxMgr,
errorDetector,
onEvent,
abortSignal,
template.fallback?.reviewer,
);
if (consensus.allFailed) {
anyPhaseAllReviewersFailed = true;
}
if (consensus.agreed) {
doerSucceeded = true;
// Phase succeeded in this round — clear any
// all-reviewers-failed latch from prior rounds of THIS
// phase. Without this, a chat that had a flaky round 1 (one
// reviewer's CLI quota briefly exhausted, or a subprocess
// crashed) but recovered to consensus in round 2 was being
// terminally classified as `no_review`. The latch is meant
// to surface "we never got a real review", not "we briefly
// couldn't but eventually did". Subsequent phases set the
// flag again from their own round-1 outcomes, so cross-phase
// failure semantics are preserved.
anyPhaseAllReviewersFailed = false;
break;
}
if (round < stdPhase.iterate.maxRounds) {
onEvent({
chatId,
type: 'phase_progress',
payload: {
phaseId: stdPhase.id,
round,
role: 'reviewer',
disagreement: consensus.summary,
},
ts: Date.now(),
});
}
} else {
// No reviewers: doer succeeds immediately
doerSucceeded = true;
break;
}
}
if (!doerSucceeded) {
anyPhaseDoerFailed = true;
onEvent({
chatId,
type: 'phase_failed',
payload: {
phaseId: stdPhase.id,
phaseIdx,
kind: stdPhase.kind,
role: 'doer',
reason: 'max_rounds_exhausted',
},
ts: Date.now(),
});
// Don't continue to subsequent phases when a doer failed every
// round — there is no real implementation to feed forward, and
// the chat must not end 'approved'. The chat_done branch below
// handles the terminal status as 'failed' / 'no_review'.
break;
}
onEvent({
chatId,
type: 'phase_done',
payload: {
phaseId: stdPhase.id,
phaseIdx,
kind: stdPhase.kind,
},
ts: Date.now(),
});
}
// ─── Ship phase ────────────────────────────────────────────────
// Runs after all phases pass + reviewers agree, AND chat targets a
// real repo, AND template opted in. Failures are surfaced as
// status=blocked (chat ran fine, ship couldn't complete) rather
// than failed (chat broke).
let shipOutcome:
| { kind: 'skipped'; reason?: string }
| { kind: 'merged'; prUrl: string }
| { kind: 'blocked'; error: string }
= { kind: 'skipped' };
// Forcibly skipped when any phase is review_only — there's no doer
// diff to commit and a template author who set ship.enabled=true on
// a review-only template would otherwise hit gh-cli with an empty
// stage. The schema docs claim the runner enforces this.
const templateHasReviewOnly = template.phases.some(isReviewOnlyPhase);
if (
!anyPhaseAllReviewersFailed &&
!anyPhaseDoerFailed &&
!templateHasReviewOnly &&
template.ship?.enabled &&
repoPath
) {
const ctx = detectGitContext(repoPath, template.ship.baseBranch);
if (!ctx.ok) {
// Surface as a skip with reason — chat still ends approved
// (we didn't ship, but the review was real).
shipOutcome = { kind: 'skipped', reason: `${ctx.reason}: ${ctx.detail}` };
onEvent({
chatId,
type: 'phase_progress',
payload: { phaseId: 'ship', skipped: true, reason: ctx.reason, detail: ctx.detail },
ts: Date.now(),
});
} else {
// Read the most recent doer's output for the PR body. Fall back
// to the chat's `work` if we can't find it (shouldn't happen in
// practice — ship phase only runs after a successful doer).
const lastDoerOutput = readLastDoerAnswer(chatDir) ?? work;
onEvent({
chatId,
type: 'phase_start',
payload: { phaseId: 'ship', kind: 'ship' },
ts: Date.now(),
});
const result = runShipPhase({
context: ctx.context,
chatId,
templateId: template.id,
branchPattern: template.ship.branchPattern ?? 'chorus/{chatId}',
titleTemplate: template.ship.titleTemplate ?? 'chorus: {template} via #{chatId}',
summary: work,
doerOutput: lastDoerOutput,
});
if (result.ok) {
shipOutcome = { kind: 'merged', prUrl: result.prUrl };
onEvent({
chatId,
type: 'phase_done',
payload: { phaseId: 'ship', prUrl: result.prUrl, branch: result.branch },
ts: Date.now(),
});
} else {
shipOutcome = { kind: 'blocked', error: `${result.stage}: ${result.detail}` };
onEvent({
chatId,
type: 'phase_failed',
payload: { phaseId: 'ship', stage: result.stage, detail: result.detail },
ts: Date.now(),
});
}
}
}
// Final chat_done — encodes terminal status and ship-phase outcome.
// Routed through emitChatDone so an earlier abort (SSE close, user
// cancel) can't be overwritten by a later "completed" emission.
if (anyPhaseDoerFailed) {
// The doer never produced a real implementation. Don't pretend
// the chat was reviewed — surface as failed so the cockpit shows
// it red.
emitChatDone({ status: 'failed', verdict: 'failed', error: 'doer_failed_all_rounds' });
} else if (anyPhaseAllReviewersFailed) {
emitChatDone({ status: 'no_review', verdict: 'no_review' });
} else if (shipOutcome.kind === 'merged') {
emitChatDone({
status: 'merged',
verdict: 'approved',
prUrl: shipOutcome.prUrl,
});
} else if (shipOutcome.kind === 'blocked') {
emitChatDone({ status: 'blocked', verdict: 'approved', shipError: shipOutcome.error });
} else if (reviewOnlyConsensus !== null) {
// Review-only chats surface the actual reviewer consensus rather
// than auto-approving. The chat itself completed (artifact
// reviewed, findings written) regardless of agreement — verdict
// reflects what reviewers said so the cockpit/CLI can render a
// meaningful "agreed / requested changes" state.
emitChatDone({
status: 'completed',
verdict: reviewOnlyConsensus.agreed ? 'approved' : 'request_changes',
reviewerSummary: reviewOnlyConsensus.summary,
});
} else {
// Either no ship phase or ship was skipped — chat ends approved.
emitChatDone({
status: 'completed',
verdict: 'approved',
...(shipOutcome.kind === 'skipped' && shipOutcome.reason
? { shipSkipped: shipOutcome.reason }
: {}),
});
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
emitChatDone({ status: 'failed', error: message });
} finally {
abortSignal.removeEventListener('abort', abortListener);
}
}
/**
* Find and read the most recent doer's answer.md from the chat dir.
* Used by the ship phase to embed doer output in the PR body. Returns
* undefined if no doer output exists (shouldn't happen since ship runs
* after success).
*/
function readLastDoerAnswer(chatDir: string): string | undefined {
if (!fs.existsSync(chatDir)) return undefined;
// Walk rounds in reverse (highest first). Within each round pick the
// doer-* dir's answer.md. There's at most one doer per round.
const rounds = fs
.readdirSync(chatDir)
.filter((n) => /^round-\d+$/.test(n))
.map((n) => ({ name: n, num: parseInt(n.replace('round-', ''), 10) }))
.sort((a, b) => b.num - a.num);
for (const r of rounds) {
const roundDir = path.join(chatDir, r.name);
const doerSubdir = fs
.readdirSync(roundDir)
.find((n) => n.startsWith('doer-'));
if (!doerSubdir) continue;
const answerFile = path.join(roundDir, doerSubdir, 'answer.md');
if (fs.existsSync(answerFile)) {
const content = fs.readFileSync(answerFile, 'utf-8');
if (content.trim().length > 0) return content;
}
}
return undefined;
}
// Re-exports keep external import sites stable. Tests import some of
// these from `'../src/daemon/runner'`, the MCP layer imports verdict.
import { buildAsk, buildReviewerAsk, packAttachedFiles } from './runner/prompt-builder.js';
import { runDoerHeadless } from './runner/doer.js';
import { runReviewerHeadless } from './runner/reviewer.js';
import { StreamFileWriter } from './runner/stream-file-writer.js';
import { verdictFromReviewerText } from './runner/verdict.js';
export { buildAsk, buildReviewerAsk, packAttachedFiles, runDoerHeadless, runReviewerHeadless, StreamFileWriter, verdictFromReviewerText };