zelio-cli 0.1.0-beta.1 → 0.1.0-beta.3

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 (98) hide show
  1. package/README.md +9 -2
  2. package/dist/cli.js +34 -7
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cloud/command.js +23 -2
  5. package/dist/cloud/command.js.map +1 -1
  6. package/dist/cloud/push-nudge.js +5 -3
  7. package/dist/cloud/push-nudge.js.map +1 -1
  8. package/dist/cloud/relay.js +5 -0
  9. package/dist/cloud/relay.js.map +1 -1
  10. package/dist/cloud/tunnel.js +65 -1
  11. package/dist/cloud/tunnel.js.map +1 -1
  12. package/dist/db/db.js +273 -146
  13. package/dist/db/db.js.map +1 -1
  14. package/dist/db/lifecycle.js +18 -5
  15. package/dist/db/lifecycle.js.map +1 -1
  16. package/dist/orchestrator/contract.js +22 -19
  17. package/dist/orchestrator/contract.js.map +1 -1
  18. package/dist/orchestrator/research.js +1 -1
  19. package/dist/orchestrator/research.js.map +1 -1
  20. package/dist/orchestrator/runtime.js +180 -27
  21. package/dist/orchestrator/runtime.js.map +1 -1
  22. package/dist/repo/instructions.js +9 -3
  23. package/dist/repo/instructions.js.map +1 -1
  24. package/dist/repo/linked-boards.js +8 -123
  25. package/dist/repo/linked-boards.js.map +1 -1
  26. package/dist/repo/project-repos.js +78 -0
  27. package/dist/repo/project-repos.js.map +1 -0
  28. package/dist/run/actions.js +24 -0
  29. package/dist/run/actions.js.map +1 -1
  30. package/dist/run/auto-review.js +102 -0
  31. package/dist/run/auto-review.js.map +1 -0
  32. package/dist/run/claude-runtime.js +37 -9
  33. package/dist/run/claude-runtime.js.map +1 -1
  34. package/dist/run/codex-client.js +3 -1
  35. package/dist/run/codex-client.js.map +1 -1
  36. package/dist/run/codex-runtime.js +190 -96
  37. package/dist/run/codex-runtime.js.map +1 -1
  38. package/dist/run/consult.js +105 -0
  39. package/dist/run/consult.js.map +1 -0
  40. package/dist/run/diff.js +42 -0
  41. package/dist/run/diff.js.map +1 -1
  42. package/dist/run/finish.js +22 -7
  43. package/dist/run/finish.js.map +1 -1
  44. package/dist/run/handoff.js +51 -0
  45. package/dist/run/handoff.js.map +1 -0
  46. package/dist/run/harness-runtime.js +4 -1
  47. package/dist/run/harness-runtime.js.map +1 -1
  48. package/dist/run/lead.js +42 -83
  49. package/dist/run/lead.js.map +1 -1
  50. package/dist/run/manager.js +896 -59
  51. package/dist/run/manager.js.map +1 -1
  52. package/dist/run/merge-watch.js +48 -17
  53. package/dist/run/merge-watch.js.map +1 -1
  54. package/dist/run/pi-rpc.js +32 -5
  55. package/dist/run/pi-rpc.js.map +1 -1
  56. package/dist/run/piped-check.js +56 -0
  57. package/dist/run/piped-check.js.map +1 -0
  58. package/dist/run/pr-checks.js +67 -0
  59. package/dist/run/pr-checks.js.map +1 -0
  60. package/dist/run/prompt.js +45 -2
  61. package/dist/run/prompt.js.map +1 -1
  62. package/dist/run/red-check.js +130 -0
  63. package/dist/run/red-check.js.map +1 -0
  64. package/dist/run/retro.js +2 -2
  65. package/dist/run/retro.js.map +1 -1
  66. package/dist/run/settings.js +4 -2
  67. package/dist/run/settings.js.map +1 -1
  68. package/dist/run/skills.js +146 -0
  69. package/dist/run/skills.js.map +1 -0
  70. package/dist/run/tests-first.js +146 -0
  71. package/dist/run/tests-first.js.map +1 -0
  72. package/dist/run/watchdog.js +259 -0
  73. package/dist/run/watchdog.js.map +1 -0
  74. package/dist/run/workflow.js +17 -6
  75. package/dist/run/workflow.js.map +1 -1
  76. package/dist/server/app.js +644 -201
  77. package/dist/server/app.js.map +1 -1
  78. package/dist/server/principal.js +5 -2
  79. package/dist/server/principal.js.map +1 -1
  80. package/dist/server/repo-picker.js +18 -0
  81. package/dist/server/repo-picker.js.map +1 -0
  82. package/dist/setup/ink-ui.js +1 -0
  83. package/dist/setup/ink-ui.js.map +1 -1
  84. package/dist/setup/onboarding.js +0 -16
  85. package/dist/setup/onboarding.js.map +1 -1
  86. package/dist/skills.js +151 -0
  87. package/dist/skills.js.map +1 -0
  88. package/dist/ticket-cli.js +41 -0
  89. package/dist/ticket-cli.js.map +1 -1
  90. package/dist/version.js +13 -0
  91. package/dist/version.js.map +1 -0
  92. package/dist/web/assets/index-CCQMrUIF.js +255 -0
  93. package/dist/web/assets/index-lzGSgTRQ.css +1 -0
  94. package/dist/web/index.html +2 -2
  95. package/dist/web/sw.js +3 -1
  96. package/package.json +1 -1
  97. package/dist/web/assets/index-ChuS3qKc.js +0 -254
  98. package/dist/web/assets/index-DR6WkmzI.css +0 -1
@@ -4,21 +4,45 @@ import { mkdirSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { absoluteAttachments } from "../attachments.js";
7
- import { actionDetail, actionPath, closeActions, finishAction, MAX_ACTION_OUTPUT, startAction, } from "./actions.js";
7
+ import { actionDetail, actionPath, checkActions, closeActions, finishAction, MAX_ACTION_OUTPUT, startAction, } from "./actions.js";
8
8
  import { bashGuardBlockedReader } from "./bash-guard.js";
9
- import { captureRunFacts, captureWorktree, commitAttempt, worktreeHead, } from "./diff.js";
10
- import { buildTicketPrompt, CODING_AGENT_PROMPT, RESUME_PROMPT, VERIFIED_CODING_AGENT_PROMPT, VERIFIED_RESUME_PROMPT, withExtraInstructions, } from "./prompt.js";
9
+ import { captureRunFacts, captureWorktree, commitAttempt, worktreeHead, worktreeTree, } from "./diff.js";
10
+ import { buildTicketPrompt, CODING_AGENT_PROMPT, commandTimingsSection, RESUME_PROMPT, VERIFIED_CODING_AGENT_PROMPT, VERIFIED_RESUME_PROMPT, withExtraInstructions, } from "./prompt.js";
11
11
  import { readRepoInstructions } from "../repo/instructions.js";
12
12
  import { buildDeveloperContextPack } from "./context.js";
13
13
  import { profileFor } from "./profiles.js";
14
+ import { chosenSkills, readSkills, skillStoreOf } from "./skills.js";
14
15
  import { commentActionsFor, wasteSignalDetails } from "./retro.js";
15
16
  import { phaseForTool } from "./phases.js";
16
17
  import { buildRunSystemPrompt, emptyWorkflow, hasWorkflow, workflowSummary, } from "./workflow.js";
17
18
  import { evidenceRevision } from "./evidence.js";
18
19
  import { resultComment } from "./result.js";
19
20
  import { stripWorktreeCd } from "./actions.js";
21
+ import { pipedEvidence, unpipedCommand } from "./piped-check.js";
20
22
  import { commitTicketWork, failureReport, hasTicketChanges, publishBranch, runChecks, ticketDiff, worktreeFingerprint, } from "./finish.js";
23
+ import { MAX_WATCHDOG_CHECKS, MAX_WATCHDOG_STEERS, STEER_HEADING, WATCHDOG_BACKSTOP_MS, WATCHDOG_COOLDOWN_TICKS, WATCHDOG_TICK_MS, callLines, lookLabel, watchdogSignals, watchdogSummary, } from "./watchdog.js";
24
+ import { MAX_AUTO_REVIEWS } from "./auto-review.js";
25
+ import { isTestPath, redCheck, ticketChanges } from "./red-check.js";
26
+ import { MAX_TEST_REVIEWS, TEST_REVIEW_CHANGES_PROMPT, TEST_REVIEW_HEADING, TESTS_FIRST_PROMPT, TESTS_MISSING_PROMPT, TESTS_PASS_ALREADY_PROMPT, approvalComment, approvedTests, implementPrompt, testsChangedPrompt, testsDiff, testsOnlyPrompt, weakenedTests, } from "./tests-first.js";
21
27
  const execFileAsync = promisify(execFile);
28
+ /** How a review that sent the work back starts its board comment; the count reads it. */
29
+ export const REVIEW_CHANGES_HEADING = "Automatic review: changes needed before Review.";
30
+ /** Sent to the developer with the reviewer's findings, the way a failed check's output is. */
31
+ export const REVIEW_CHANGES_PROMPT = `The board's checks pass, but the automatic review found that the work does not yet give the person what they asked for. The checks are the minimum; done means the person gets what they asked for. Read the findings below, open the ticket's screenshots if it has any, make the change, and end your turn when it is done. Do not argue with a finding by restating the acceptance: if a finding is wrong, say why in your reply and change nothing for it.`;
32
+ /** Sent when the ticket's checks also pass on the code before the change; the test files it copied are named after it. */
33
+ export const RED_CHECK_PROMPT = "The board's checks pass, but they also pass on the code before your change, with your test changes copied in. So they do not test what the ticket asks for. Add or extend tests that fail without your change and pass with it, one for each acceptance criterion including its failure case, then end your turn. Do not weaken or delete existing assertions. If the ticket is a refactor that must not change behaviour, say so in your reply and end your turn without new tests.";
34
+ /** Sent when a run that was asked for a change ends without changing the worktree. */
35
+ export const IDLE_RUN_PROMPT = "Your turn ended without changing anything in the worktree since this run started. The ticket's earlier work is still there, but you were asked for a change: make it now, run the checks it needs, and end your turn when it is done. If what you were asked was only a question that needs no change, say so in your reply and end your turn again.";
36
+ /** Said on the ticket when the tests still pass without the change after the one send-back. */
37
+ export const RED_CHECK_STILL_PASSES = "The ticket's checks still pass on the code before the change, so they do not prove it. That is expected for a refactor; otherwise, check the tests in review.";
38
+ /** Whether this run's latest completed command proves a check on the current tree. */
39
+ export function developerCheckPassed(command, evidence, inFlightCommands, currentRevision) {
40
+ const normalized = stripWorktreeCd(command);
41
+ if (inFlightCommands.includes(normalized) || !currentRevision)
42
+ return false;
43
+ const latest = evidence.findLast((item) => item.command === normalized);
44
+ return latest?.outcome === "passed" && latest.revision === currentRevision;
45
+ }
22
46
  export class RunAlreadyActiveError extends Error {
23
47
  constructor(ticketId) {
24
48
  super(`${ticketId} is already running`);
@@ -132,6 +156,13 @@ export class RunManager {
132
156
  retro;
133
157
  defaults;
134
158
  lead;
159
+ rootFor;
160
+ reviewer;
161
+ redCheckEnabled;
162
+ testsFirstEnabled;
163
+ skills;
164
+ listModels;
165
+ watchdog;
135
166
  active = new Map();
136
167
  statuses = new Map();
137
168
  /**
@@ -152,7 +183,45 @@ export class RunManager {
152
183
  */
153
184
  retro, defaults = () => ({ harness: "pi", model: "" }),
154
185
  /** The stronger model a stuck verified ticket is sent to before the person. */
155
- lead) {
186
+ lead,
187
+ /**
188
+ * The checkout root a ticket works in. Absent means every ticket works in
189
+ * `repoRoot`; a card for an added repository has its own root.
190
+ */
191
+ rootFor,
192
+ /**
193
+ * The read-only reviewer asked, once a verified ticket's checks pass,
194
+ * whether the work gives the person what they asked for. Absent, the board
195
+ * publishes on passing checks alone.
196
+ */
197
+ reviewer,
198
+ /**
199
+ * Once a verified ticket's checks pass, they must also fail on the code
200
+ * before the change, with only the developer's test files copied in.
201
+ * Off, the board trusts the checks as written.
202
+ */
203
+ redCheckEnabled = false,
204
+ /**
205
+ * A verified ticket's first runs write only the tests, which must fail and
206
+ * pass a test review before the developer implements against them.
207
+ */
208
+ testsFirstEnabled = () => false,
209
+ /**
210
+ * Where the skills a ticket chose are read from. Absent, the board's own
211
+ * database once it keeps skills, and no skills until then.
212
+ */
213
+ skills = skillStoreOf(db),
214
+ /**
215
+ * The models a harness lists. A card's model is kept only if the harness
216
+ * that runs it lists it; a list that cannot be read is empty, so the card
217
+ * runs on the default model instead of an unknown one.
218
+ */
219
+ listModels = async () => [],
220
+ /**
221
+ * Looks over a live developer run and may steer it or stop it for the lead.
222
+ * Absent, a run is only looked at once it has stopped.
223
+ */
224
+ watchdog) {
156
225
  this.db = db;
157
226
  this.runtime = runtime;
158
227
  this.onStatus = onStatus;
@@ -165,6 +234,13 @@ export class RunManager {
165
234
  this.retro = retro;
166
235
  this.defaults = defaults;
167
236
  this.lead = lead;
237
+ this.rootFor = rootFor;
238
+ this.reviewer = reviewer;
239
+ this.redCheckEnabled = redCheckEnabled;
240
+ this.testsFirstEnabled = testsFirstEnabled;
241
+ this.skills = skills;
242
+ this.listModels = listModels;
243
+ this.watchdog = watchdog;
168
244
  this.retry = { ...DEFAULT_RETRY, ...retry };
169
245
  }
170
246
  /** Where the harness keeps session files: with the board's own state. */
@@ -309,7 +385,7 @@ export class RunManager {
309
385
  text: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Resuming it from its last turn.`,
310
386
  });
311
387
  try {
312
- this.start(ticket, worktree, latest.attempt, {
388
+ await this.begin(ticket, worktree, latest.attempt, {
313
389
  prompt: (ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT,
314
390
  profile: latest.profile ?? ticket.profile ?? "developer",
315
391
  label: "Resumed",
@@ -346,9 +422,34 @@ export class RunManager {
346
422
  });
347
423
  return started ? (this.statuses.get(ticket.id) ?? null) : null;
348
424
  }
349
- start(ticket, worktree, attempt = 1, job) {
425
+ /**
426
+ * Starts a run once the model list it needs is read. Only a developer run on
427
+ * the harness that names the card's model needs the list; every other run
428
+ * starts at once with `start`.
429
+ */
430
+ async begin(ticket, worktree, attempt = 1, job) {
431
+ const profileName = job?.profile ?? ticket.profile ?? "developer";
432
+ const profile = this.db.getProfile(profileName) ?? profileFor(profileName);
433
+ const defaults = this.defaults();
434
+ const command = job?.command?.trim() || profile.harness.trim() || defaults.harness;
435
+ const profileHarness = profile.harness.trim() || defaults.harness;
436
+ const cardOnHarness = profileName === "developer" && command === profileHarness && Boolean(ticket.model?.trim());
437
+ const models = cardOnHarness ? await this.modelsOf(command) : undefined;
438
+ return this.start(ticket, worktree, attempt, job, models);
439
+ }
440
+ async modelsOf(command) {
441
+ return Promise.resolve()
442
+ .then(() => this.listModels(command))
443
+ .catch(() => []);
444
+ }
445
+ /**
446
+ * `models` is the list of the run's harness when the card's model needs one;
447
+ * absent means it is unknown, so the card's model is not used.
448
+ */
449
+ start(ticket, worktree, attempt = 1, job, models) {
350
450
  if (this.active.has(ticket.id))
351
451
  throw new RunAlreadyActiveError(ticket.id);
452
+ const testsFirstEnabled = this.testsFirstEnabled();
352
453
  const resolvedJob = job ?? {
353
454
  prompt: buildTicketPrompt(ticket, {
354
455
  number: attempt,
@@ -365,7 +466,20 @@ export class RunManager {
365
466
  const profile = this.db.getProfile(resolvedJob.profile) ?? profileFor(resolvedJob.profile);
366
467
  const defaults = this.defaults();
367
468
  const command = resolvedJob.command?.trim() || profile.harness.trim() || defaults.harness;
368
- const model = profile.model.trim() || (command === defaults.harness ? defaults.model : "");
469
+ // A profile's model is named by its own harness, so it applies only on that
470
+ // harness: a send-back pinned to an earlier one never gets the new model.
471
+ const profileHarness = profile.harness.trim() || defaults.harness;
472
+ // A card's model is named by the developer harness, so it applies only to a
473
+ // developer run on that harness, and only if that harness lists it. Anything
474
+ // else runs on the default model, which is the one the board records.
475
+ const cardModel = resolvedJob.profile === "developer" &&
476
+ command === profileHarness &&
477
+ models?.includes(ticket.model?.trim() ?? "")
478
+ ? (ticket.model?.trim() ?? "")
479
+ : "";
480
+ const model = cardModel ||
481
+ (command === profileHarness ? profile.model.trim() : "") ||
482
+ (command === defaults.harness ? defaults.model : "");
369
483
  // A pi run can seed its own session id before the process starts. Codex
370
484
  // returns a thread id instead, so its row stays open until that arrives.
371
485
  const seedId = !this.runtime.sessionIdFromHarness?.(command);
@@ -375,7 +489,9 @@ export class RunManager {
375
489
  // different list: no checks, and board rules that forbid editing. A conflict
376
490
  // repair started from Review is neither, and takes no workflow.
377
491
  const stage = resolvedJob.stage ?? "in_progress";
378
- const takesWorkflow = !resolvedJob.outsideStage && (profile.touchesRepo || stage === "review");
492
+ // A card for an added repo runs only its own verify commands: the board's
493
+ // stage checks were written for the home repo and would fail there.
494
+ const takesWorkflow = !resolvedJob.outsideStage && !ticket.repo && (profile.touchesRepo || stage === "review");
379
495
  const workflow = takesWorkflow
380
496
  ? this.db.getStageWorkflow(stage)
381
497
  : emptyWorkflow();
@@ -388,6 +504,7 @@ export class RunManager {
388
504
  resumeCount: resolvedJob.resumes ?? 0,
389
505
  profile: resolvedJob.profile,
390
506
  harness: command,
507
+ model: model || null,
391
508
  source: resolvedJob.source,
392
509
  prompt: resolvedJob.originalPrompt ?? resolvedJob.prompt,
393
510
  systemPrompt: resolvedJob.systemPrompt ?? null,
@@ -405,21 +522,40 @@ export class RunManager {
405
522
  // Empty extra prompt must leave the prompt untouched, including "undefined"
406
523
  // so the runtime applies its own default exactly as before. A verified run
407
524
  // always names its prompt, because the runtime default is the unverified one.
408
- const profilePrompt = profile.extraPrompt.trim()
525
+ const extraPrompt = profile.extraPrompt.trim()
409
526
  ? withExtraInstructions(basePrompt, profile.extraPrompt)
410
527
  : (resolvedJob.systemPrompt ?? (verified ? VERIFIED_CODING_AGENT_PROMPT : undefined));
528
+ // A developer in In Progress is told how long each of its checks took the
529
+ // last time the board ran them, so a slow one is run once and waited out.
530
+ // A command the board has never timed adds nothing.
531
+ const timedCommands = resolvedJob.profile === "developer" && stage === "in_progress" && !resolvedJob.outsideStage
532
+ ? [...(ticket.verify ?? []), ...workflow.checks].map((check) => check.command)
533
+ : [];
534
+ const timings = timedCommands.length
535
+ ? commandTimingsSection(timedCommands, this.db.commandDurations(ticket.repo ?? null, timedCommands))
536
+ : "";
537
+ const profilePrompt = timings ? `${extraPrompt ?? defaultPrompt}\n\n${timings}` : extraPrompt;
411
538
  // The repository's own AGENTS.md/CLAUDE.md comes before the workflow: it is
412
539
  // the person's standing word on this repo, and it is read at run time, so a
413
540
  // change to it takes effect on the next run without touching the board.
414
541
  const instructions = profile.touchesRepo
415
- ? readRepoInstructions(this.repoRoot)
542
+ ? readRepoInstructions(this.rootFor ? this.rootFor(ticket) : this.repoRoot, undefined, this.runtime.instructionFilesFromHarness?.(command) ?? [])
416
543
  : { files: [], text: "" };
544
+ // The skills the planner chose for the card, read now so a skill disabled or
545
+ // deleted since is simply absent. The harness loads none of its own.
546
+ const skills = resolvedJob.profile === "developer" && (ticket.skills ?? []).length > 0
547
+ ? chosenSkills(ticket.skills, readSkills(this.skills))
548
+ : [];
417
549
  // The workflow section goes last: it closes by restating the board rules no
418
550
  // standing instruction may override, so it has to be the final thing the run
419
551
  // reads. With nothing configured it is a no-op and the prompt is untouched.
420
- const systemPrompt = hasWorkflow(workflow) || instructions.text
552
+ const systemPrompt = hasWorkflow(workflow) ||
553
+ instructions.text ||
554
+ instructions.loadedByHarness?.length ||
555
+ skills.length > 0
421
556
  ? buildRunSystemPrompt(profilePrompt ?? defaultPrompt, stage, workflow, instructions, {
422
557
  verified,
558
+ skills,
423
559
  })
424
560
  : profilePrompt;
425
561
  const status = {
@@ -438,6 +574,26 @@ export class RunManager {
438
574
  actions: [],
439
575
  ...(snapshot ? { workflow: workflowSummary(stage, workflow) } : {}),
440
576
  };
577
+ // Tests first applies to the ticket's own brief, not to a person's send-back:
578
+ // a follow-up may change what the tests should say. The phase is read back
579
+ // from the board's approval comment, so a restart or a retry picks it up.
580
+ const approved = testsFirstEnabled &&
581
+ resolvedJob.profile === "developer" &&
582
+ resolvedJob.source === "ticket" &&
583
+ !resolvedJob.outsideStage &&
584
+ ticket.verify.length > 0
585
+ ? { tests: approvedTests(this.db.listComments(ticket.id)) }
586
+ : null;
587
+ const testsPhase = !approved ? null : approved.tests ? "implement" : "tests";
588
+ const phaseBrief = resolvedJob.sessionId || !testsPhase
589
+ ? ""
590
+ : testsPhase === "tests"
591
+ ? TESTS_FIRST_PROMPT
592
+ : implementPrompt(approved.tests.sha, approved.tests.files);
593
+ // Read before the harness starts, so no edit of the run can land in it.
594
+ const startTree = resolvedJob.profile === "developer" && resolvedJob.expectsChange
595
+ ? worktreeTree(worktree.path)
596
+ : null;
441
597
  let run;
442
598
  try {
443
599
  const boardUrl = this.statusBaseUrl.replace(/\/$/, "");
@@ -457,7 +613,7 @@ export class RunManager {
457
613
  const prompt = resolvedJob.profile === "developer" &&
458
614
  resolvedJob.source === "ticket" &&
459
615
  !resolvedJob.sessionId
460
- ? `${resolvedJob.prompt}\n\n${buildDeveloperContextPack(worktree.path, ticket)}`
616
+ ? `${resolvedJob.prompt}\n\n${buildDeveloperContextPack(worktree.path, ticket)}${phaseBrief ? `\n\n${phaseBrief}` : ""}`
461
617
  : resolvedJob.prompt;
462
618
  run = this.runtime.spawn(worktree.path, prompt, {
463
619
  env,
@@ -499,6 +655,7 @@ export class RunManager {
499
655
  command,
500
656
  status,
501
657
  statusToken,
658
+ testsFirstEnabled,
502
659
  startHead: worktreeHead(worktree.path),
503
660
  cancelled: false,
504
661
  settled: false,
@@ -510,18 +667,47 @@ export class RunManager {
510
667
  actions: [],
511
668
  toolCalls: new Map(),
512
669
  commandEvidence: [...(resolvedJob.resumeEvidence ?? [])],
670
+ developerCommandEvidence: [],
513
671
  checks: stage === "in_progress" && !resolvedJob.outsideStage
514
672
  ? workflow.checks.map((check) => ({ label: check.label, command: check.command }))
515
673
  : [],
516
674
  verifyRounds: 0,
675
+ handoffRounds: 0,
517
676
  verified: ticket.verify.length > 0,
518
677
  repeat: { key: "", count: 0 },
519
678
  nudged: false,
679
+ redSentBack: false,
680
+ startTree,
681
+ idleSentBack: false,
682
+ testsPhase,
683
+ approved: testsPhase === "implement" ? (approved?.tests ?? null) : null,
520
684
  gating: false,
521
685
  gateAbort: new AbortController(),
522
686
  worktreePath: worktree.path,
523
687
  tokens: null,
524
688
  ...(resolvedJob.profile === "developer" ? { executionPhase: "inspect" } : {}),
689
+ ...(this.watchdog &&
690
+ run.sendMessage &&
691
+ resolvedJob.profile === "developer" &&
692
+ stage === "in_progress" &&
693
+ !resolvedJob.outsideStage
694
+ ? {
695
+ watchdog: {
696
+ tick: 0,
697
+ busy: false,
698
+ checks: 0,
699
+ steers: 0,
700
+ quietUntil: 0,
701
+ lastCheckAt: Date.now(),
702
+ lastSeq: 0,
703
+ edited: false,
704
+ fingerprint: null,
705
+ unchangedTicks: 0,
706
+ offPlan: new Set(),
707
+ looks: [],
708
+ },
709
+ }
710
+ : {}),
525
711
  };
526
712
  if (active.commandEvidence.length)
527
713
  this.db.recordCommandEvidence(record.id, active.commandEvidence);
@@ -532,6 +718,7 @@ export class RunManager {
532
718
  return status;
533
719
  }
534
720
  async continuationPrompt(ticketId, runId) {
721
+ await this.evidenceCaughtUp(ticketId, runId);
535
722
  const gate = await this.completionGate(ticketId, runId, false);
536
723
  if (gate.kind === "completed" || gate.kind === "escalated")
537
724
  return undefined;
@@ -539,7 +726,7 @@ export class RunManager {
539
726
  const current = this.active.get(ticketId);
540
727
  if (current?.status.runId === runId) {
541
728
  this.update(ticketId, current, {
542
- label: `Fixing checks (round ${current.verifyRounds}/${MAX_VERIFY_ROUNDS})`,
729
+ label: gate.label ?? `Fixing checks (round ${current.verifyRounds}/${MAX_VERIFY_ROUNDS})`,
543
730
  tool: null,
544
731
  });
545
732
  }
@@ -560,6 +747,23 @@ export class RunManager {
560
747
  });
561
748
  return CONTINUATION_PROMPT;
562
749
  }
750
+ /**
751
+ * A harness asks "keep going?" the moment it reads its own settle, which can
752
+ * be before the event loop has recorded the command that just finished: the
753
+ * loop hashes the worktree for that evidence asynchronously. Wait until every
754
+ * queued event has been handled, so the gate never misses a passing check
755
+ * the developer just ran.
756
+ */
757
+ async evidenceCaughtUp(ticketId, runId) {
758
+ for (;;) {
759
+ // Queued events reach the loop as microtasks; this runs after them.
760
+ await new Promise((resolve) => setImmediate(resolve));
761
+ const active = this.active.get(ticketId);
762
+ if (!active || active.status.runId !== runId || !active.evidencePending)
763
+ return;
764
+ await active.evidencePending.catch(() => null);
765
+ }
766
+ }
563
767
  /**
564
768
  * The board's own completion check for a verified In Progress ticket. The
565
769
  * ticket's verify commands and the stage checks run in the worktree; when they
@@ -605,6 +809,8 @@ export class RunManager {
605
809
  async verifyTicket(ticketId, runId, active, ticket, final) {
606
810
  const cwd = active.worktreePath;
607
811
  const max = MAX_VERIFY_ROUNDS;
812
+ if (active.testsPhase === "tests")
813
+ return this.testsGate(ticketId, runId, active, ticket, final);
608
814
  const changed = await hasTicketChanges(cwd);
609
815
  if (!this.isLive(ticketId, active))
610
816
  return { kind: "skip" };
@@ -620,6 +826,83 @@ export class RunManager {
620
826
  },
621
827
  });
622
828
  }
829
+ // The ticket has work, but this run may have added none: a run told to make
830
+ // a change that ends after reading files is not done because an earlier
831
+ // run's work still passes. It is sent back once; a second time it goes on,
832
+ // because a question needs no edit. Only a run asked for a change has a
833
+ // start tree to compare with.
834
+ const nowTree = active.startTree === null ? null : worktreeTree(cwd);
835
+ const idle = nowTree !== null && nowTree === active.startTree;
836
+ if (idle && !active.idleSentBack) {
837
+ active.idleSentBack = true;
838
+ const nowPrint = await worktreeFingerprint(cwd);
839
+ if (!this.isLive(ticketId, active))
840
+ return { kind: "skip" };
841
+ return this.failRound(ticketId, runId, active, final, {
842
+ prompt: IDLE_RUN_PROMPT,
843
+ summary: "the run changed nothing",
844
+ check: "the run changed nothing",
845
+ fingerprint: nowPrint,
846
+ blocked: {
847
+ summary: `The run still changed nothing after ${max} rounds.`,
848
+ reason: `the run ended without changing the worktree after ${max} verification rounds`,
849
+ unblock: "Make the requested change, then mention @developer to continue.",
850
+ detail: "",
851
+ },
852
+ });
853
+ }
854
+ // Requiring a local pass before this stage makes the handoff meaningful:
855
+ // otherwise the board would be the first actor to discover a known failure.
856
+ // Evidence is tied to both a completed bash call and the exact worktree
857
+ // content at its end; edits after the pass make it stale.
858
+ const currentRevision = await evidenceRevision(cwd);
859
+ if (!this.isLive(ticketId, active))
860
+ return { kind: "skip" };
861
+ const inFlightCommands = [...active.toolCalls.values()]
862
+ .filter((call) => call.tool === "bash" && call.command)
863
+ .flatMap((call) => {
864
+ const base = unpipedCommand(call.command);
865
+ return base ? [call.command, base] : [call.command];
866
+ });
867
+ const missingDeveloperChecks = ticket.verify.filter((check) => !developerCheckPassed(check.command, active.developerCommandEvidence, inFlightCommands, currentRevision));
868
+ if (missingDeveloperChecks.length) {
869
+ const commands = missingDeveloperChecks.map((check) => `\`${check.command}\``).join(", ");
870
+ return this.failRound(ticketId, runId, active, final, {
871
+ handoffOnly: true,
872
+ prompt: `Before handing this ticket to the board, run and finish these Verify commands yourself, each in its own shell call and exactly as written, without piping the output through tail, head or grep: ${commands}. The board will wait for your checks before its next verification. A command that is still running, failed, or passed before your latest edits does not count. If the shell returns a session id, keep reading that same session until it exits, then fix any failure and run the command again.`,
873
+ summary: `the developer did not finish Verify: ${missingDeveloperChecks.map((check) => check.label).join(", ")}`,
874
+ blocked: {
875
+ summary: `The developer did not finish the ticket's Verify command after ${MAX_VERIFY_ROUNDS} handoff attempts.`,
876
+ reason: `the developer did not record completed passing runs of ${commands} against the current worktree after ${MAX_VERIFY_ROUNDS} handoff attempts`,
877
+ unblock: `Run ${commands} in the ticket worktree, fix any failure, and continue the ticket.`,
878
+ detail: "",
879
+ },
880
+ });
881
+ }
882
+ // Implementing against approved tests: they may be fixed and may grow, but
883
+ // no approved check may go.
884
+ if (active.testsPhase === "implement" && active.approved) {
885
+ const weakened = await weakenedTests(cwd, active.approved.sha, active.approved.files);
886
+ if (!this.isLive(ticketId, active))
887
+ return { kind: "skip" };
888
+ if (weakened.length > 0) {
889
+ const fingerprint = await worktreeFingerprint(cwd);
890
+ if (!this.isLive(ticketId, active))
891
+ return { kind: "skip" };
892
+ return this.failRound(ticketId, runId, active, final, {
893
+ prompt: testsChangedPrompt(weakened),
894
+ summary: "an approved check was removed",
895
+ check: "approved tests kept",
896
+ fingerprint,
897
+ blocked: {
898
+ summary: `The approved tests were still changed after ${max} rounds.`,
899
+ reason: `approved checks in ${weakened.map((item) => item.file).join(", ")} were removed or changed after ${max} verification rounds`,
900
+ unblock: "Restore the approved tests, or mention @developer with the change you want to the tests.",
901
+ detail: "",
902
+ },
903
+ });
904
+ }
905
+ }
623
906
  const checks = [...ticket.verify, ...active.checks];
624
907
  const env = this.agentPath
625
908
  ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
@@ -631,6 +914,13 @@ export class RunManager {
631
914
  });
632
915
  if (!this.isLive(ticketId, active))
633
916
  return { kind: "skip" };
917
+ // A check that exited or hit its timeout ran for a real duration; one that
918
+ // never started or was aborted did not, and leaves the last one in place.
919
+ for (const result of results) {
920
+ if (result.exitCode === null && !result.timedOut)
921
+ continue;
922
+ this.db.recordCommandDuration(ticket.repo ?? null, result.command, result.durationMs);
923
+ }
634
924
  for (const result of results.filter((item) => item.flaky)) {
635
925
  this.db.addComment({
636
926
  ticket_id: ticketId,
@@ -649,6 +939,10 @@ export class RunManager {
649
939
  }
650
940
  active.commandEvidence = active.commandEvidence.slice(-64);
651
941
  this.db.recordCommandEvidence(runId, active.commandEvidence);
942
+ // The board's checks land in the trace, so a timeout reads as a timeout
943
+ // there rather than hiding behind the agent's own passing run.
944
+ active.actions = checkActions(active.actions, results);
945
+ this.update(ticketId, active, { actions: active.actions });
652
946
  const failed = results.find((result) => !result.passed);
653
947
  if (failed) {
654
948
  const detail = failureReport(results);
@@ -657,7 +951,8 @@ export class RunManager {
657
951
  return { kind: "skip" };
658
952
  return this.failRound(ticketId, runId, active, final, {
659
953
  prompt: `${VERIFY_FAILED_PROMPT}\n\n${detail}`,
660
- summary: failed.label,
954
+ summary: failed.timedOut ? `${failed.label} timed out` : failed.label,
955
+ outcome: failed.timedOut ? "Check timed out" : "Check failed",
661
956
  check: failed.label,
662
957
  fingerprint,
663
958
  blocked: {
@@ -668,6 +963,58 @@ export class RunManager {
668
963
  },
669
964
  });
670
965
  }
966
+ // Passing checks must also fail on the code before the change; otherwise
967
+ // they prove nothing, and the developer is asked for tests that do.
968
+ if (this.redCheckEnabled) {
969
+ this.update(ticketId, active, {
970
+ label: "Checking the tests fail without the change",
971
+ tool: null,
972
+ });
973
+ const red = await redCheck(cwd, ticket.verify, { env, signal: active.gateAbort.signal });
974
+ if (!this.isLive(ticketId, active))
975
+ return { kind: "skip" };
976
+ if (red.kind === "proves-nothing" && active.redSentBack) {
977
+ this.db.addComment({
978
+ ticket_id: ticketId,
979
+ type: "system",
980
+ author: "zelio",
981
+ text: RED_CHECK_STILL_PASSES,
982
+ });
983
+ }
984
+ else if (red.kind === "proves-nothing") {
985
+ active.redSentBack = true;
986
+ const fingerprint = await worktreeFingerprint(cwd);
987
+ if (!this.isLive(ticketId, active))
988
+ return { kind: "skip" };
989
+ return this.failRound(ticketId, runId, active, final, {
990
+ prompt: `${RED_CHECK_PROMPT}\n\nTest files the board copied onto the old code: ${red.testFiles.join(", ") || "none"}`,
991
+ summary: "the tests pass without the change",
992
+ check: "tests fail without the change",
993
+ fingerprint,
994
+ blocked: {
995
+ summary: `The ticket's tests still pass without the change after ${max} rounds.`,
996
+ reason: `The Verify commands pass on the code before the change after ${max} verification rounds, so they do not test the ticket`,
997
+ unblock: "Add tests that fail without the change, or correct the ticket's verify commands, then mention @developer to continue.",
998
+ detail: "",
999
+ },
1000
+ });
1001
+ }
1002
+ if (red.kind === "unavailable") {
1003
+ this.db.addComment({
1004
+ ticket_id: ticketId,
1005
+ type: "system",
1006
+ author: "zelio",
1007
+ text: `The board could not check that the tests fail without the change: ${red.reason}`,
1008
+ });
1009
+ }
1010
+ }
1011
+ // Checks prove what they test; the review asks whether the person got what
1012
+ // they asked for, before anything is committed or published.
1013
+ const review = await this.autoReview(ticketId, active, ticket);
1014
+ if (review)
1015
+ return review;
1016
+ if (!this.isLive(ticketId, active))
1017
+ return { kind: "skip" };
671
1018
  const branch = ticket.branch?.trim() || (await currentBranch(cwd));
672
1019
  if (!this.isLive(ticketId, active))
673
1020
  return { kind: "skip" };
@@ -728,9 +1075,246 @@ export class RunManager {
728
1075
  this.update(ticketId, active, { label: "Finishing", tool: null });
729
1076
  return { kind: "completed" };
730
1077
  }
1078
+ /**
1079
+ * The end of a tests-only turn. The tests must be the only change, must fail
1080
+ * on the code as it is, and must pass the test review; then the board commits
1081
+ * them and the same session goes on to implement against them. Anything else
1082
+ * sends the turn back the way a failed check does.
1083
+ */
1084
+ async testsGate(ticketId, runId, active, ticket, final) {
1085
+ const cwd = active.worktreePath;
1086
+ const max = MAX_VERIFY_ROUNDS;
1087
+ const sendBack = async (prompt, summary, reason) => {
1088
+ const fingerprint = await worktreeFingerprint(cwd);
1089
+ if (!this.isLive(ticketId, active))
1090
+ return { kind: "skip" };
1091
+ return this.failRound(ticketId, runId, active, final, {
1092
+ prompt,
1093
+ summary,
1094
+ check: summary,
1095
+ fingerprint,
1096
+ blocked: {
1097
+ summary: `The tests were still not ready after ${max} rounds: ${summary}.`,
1098
+ reason: `${reason} after ${max} verification rounds`,
1099
+ unblock: "Write tests that fail on the current code and check what was asked, then mention @developer to continue.",
1100
+ detail: "",
1101
+ },
1102
+ });
1103
+ };
1104
+ const changes = await ticketChanges(cwd);
1105
+ if (!this.isLive(ticketId, active))
1106
+ return { kind: "skip" };
1107
+ if (!changes) {
1108
+ // Without a base the board cannot tell tests from code; it does not hold
1109
+ // the ticket for that, and the run implements without the test phase.
1110
+ this.db.addComment({
1111
+ ticket_id: ticketId,
1112
+ type: "system",
1113
+ author: "zelio",
1114
+ text: "The board could not find the base to check the tests against, so this ticket skips the test phase.",
1115
+ });
1116
+ active.testsPhase = null;
1117
+ return this.verifyTicket(ticketId, runId, active, ticket, final);
1118
+ }
1119
+ const tests = changes.files.filter(isTestPath);
1120
+ const others = changes.files.filter((file) => !isTestPath(file));
1121
+ if (tests.length === 0) {
1122
+ return sendBack(TESTS_MISSING_PROMPT, "no tests were written", "no test file changed");
1123
+ }
1124
+ if (others.length > 0) {
1125
+ return sendBack(testsOnlyPrompt(others), "files outside tests changed", `files outside tests changed in the test phase (${others.join(", ")})`);
1126
+ }
1127
+ // The code is untouched, so the ticket's checks run here exactly as they
1128
+ // would on the old code: one of them has to fail.
1129
+ this.update(ticketId, active, { label: "Checking the tests fail", tool: null });
1130
+ const env = this.agentPath
1131
+ ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
1132
+ : process.env;
1133
+ const results = await runChecks(cwd, ticket.verify, { env, signal: active.gateAbort.signal });
1134
+ if (!this.isLive(ticketId, active))
1135
+ return { kind: "skip" };
1136
+ if (results.length === ticket.verify.length && results.every((result) => result.passed)) {
1137
+ return sendBack(TESTS_PASS_ALREADY_PROMPT, "the tests pass without the change", "the tests pass on the code before the change");
1138
+ }
1139
+ const diff = await testsDiff(cwd, changes.mergeBase, tests);
1140
+ if (!this.isLive(ticketId, active))
1141
+ return { kind: "skip" };
1142
+ const review = await this.testReview(ticketId, active, ticket, diff);
1143
+ if (review)
1144
+ return review;
1145
+ if (!this.isLive(ticketId, active))
1146
+ return { kind: "skip" };
1147
+ const commit = await commitTicketWork(cwd, `test: ${ticket.title}`);
1148
+ if (!this.isLive(ticketId, active))
1149
+ return { kind: "skip" };
1150
+ if (commit.error || !commit.head) {
1151
+ const hook = commit.error
1152
+ ? `The commit hook failed:\n\n\`\`\`text\n${commit.error}\n\`\`\``
1153
+ : "The board could not commit the tests.";
1154
+ return sendBack(`${VERIFY_FAILED_PROMPT}\n\n${hook}`, "the tests could not be committed", "the tests could not be committed");
1155
+ }
1156
+ this.db.addComment({
1157
+ ticket_id: ticketId,
1158
+ type: "system",
1159
+ author: "zelio",
1160
+ text: approvalComment(commit.head, tests),
1161
+ });
1162
+ active.testsPhase = "implement";
1163
+ active.approved = { sha: commit.head, files: tests };
1164
+ // The test phase's rounds were spent on the tests; implementing starts fresh.
1165
+ active.verifyRounds = 0;
1166
+ active.lastFailure = undefined;
1167
+ return {
1168
+ kind: "continue",
1169
+ prompt: implementPrompt(commit.head, tests),
1170
+ summary: "the tests were approved",
1171
+ label: "Implementing against the approved tests",
1172
+ };
1173
+ }
1174
+ /**
1175
+ * The reviewer reads the tests alone against the person's request. Null means
1176
+ * approve them: they passed, the review gave no usable answer or is not
1177
+ * configured, or it has sent them back as often as it may.
1178
+ */
1179
+ async testReview(ticketId, active, ticket, diff) {
1180
+ const reviewer = this.reviewer;
1181
+ if (!reviewer)
1182
+ return null;
1183
+ const note = (text) => this.db.addComment({ ticket_id: ticketId, type: "system", author: "zelio", text });
1184
+ const earlier = this.db
1185
+ .listComments(ticketId)
1186
+ .filter((comment) => comment.author === "reviewer" &&
1187
+ comment.type === "review" &&
1188
+ comment.text.startsWith(TEST_REVIEW_HEADING))
1189
+ .map((comment) => comment.text.slice(TEST_REVIEW_HEADING.length).trim());
1190
+ if (earlier.length >= MAX_TEST_REVIEWS) {
1191
+ note(`The test review sent the tests back ${MAX_TEST_REVIEWS} times; the board approves them as they are, with the last findings above for Review.`);
1192
+ return null;
1193
+ }
1194
+ const round = earlier.length + 1;
1195
+ this.update(ticketId, active, { label: "Reviewing the tests", tool: null });
1196
+ let verdict = null;
1197
+ try {
1198
+ verdict = await reviewer({
1199
+ ticketId,
1200
+ title: ticket.title,
1201
+ goal: ticket.goal,
1202
+ outOfScope: ticket.out_of_scope,
1203
+ acceptance: ticket.acceptance,
1204
+ context: [...(ticket.context ?? [])],
1205
+ screenshots: absoluteAttachments(this.repoRoot, ticket.attachments),
1206
+ diff,
1207
+ round,
1208
+ earlier,
1209
+ worktreePath: active.worktreePath,
1210
+ focus: "tests",
1211
+ });
1212
+ }
1213
+ catch {
1214
+ verdict = null;
1215
+ }
1216
+ if (!this.isLive(ticketId, active))
1217
+ return { kind: "skip" };
1218
+ if (!verdict) {
1219
+ note("The test review gave no usable answer, so the board approves the tests unreviewed.");
1220
+ return null;
1221
+ }
1222
+ if (verdict.verdict === "pass") {
1223
+ this.db.addComment({
1224
+ ticket_id: ticketId,
1225
+ type: "review",
1226
+ author: "reviewer",
1227
+ text: `Test review passed: ${verdict.summary}`,
1228
+ });
1229
+ return null;
1230
+ }
1231
+ this.db.addComment({
1232
+ ticket_id: ticketId,
1233
+ type: "review",
1234
+ author: "reviewer",
1235
+ text: `${TEST_REVIEW_HEADING}\n\n${verdict.findings}`,
1236
+ });
1237
+ return {
1238
+ kind: "continue",
1239
+ prompt: `${TEST_REVIEW_CHANGES_PROMPT}\n\n## Test review findings\n\n${verdict.findings}`,
1240
+ summary: "the test review asked for changes",
1241
+ label: `Revising the tests (round ${round}/${MAX_TEST_REVIEWS})`,
1242
+ };
1243
+ }
1244
+ /**
1245
+ * The automatic review between passing checks and publishing. Null means go
1246
+ * on and publish: the review passed, gave no usable answer, is not
1247
+ * configured, or has already sent this ticket back as often as it may. A
1248
+ * "changes" verdict returns the findings as the developer's next prompt.
1249
+ */
1250
+ async autoReview(ticketId, active, ticket) {
1251
+ const reviewer = this.reviewer;
1252
+ if (!reviewer)
1253
+ return null;
1254
+ const note = (text) => this.db.addComment({ ticket_id: ticketId, type: "system", author: "zelio", text });
1255
+ const earlier = this.db
1256
+ .listComments(ticketId)
1257
+ .filter((comment) => comment.author === "reviewer" &&
1258
+ comment.type === "review" &&
1259
+ comment.text.startsWith(REVIEW_CHANGES_HEADING))
1260
+ .map((comment) => comment.text.slice(REVIEW_CHANGES_HEADING.length).trim());
1261
+ if (earlier.length >= MAX_AUTO_REVIEWS) {
1262
+ note(`The automatic review sent this ticket back ${MAX_AUTO_REVIEWS} times; it goes to Review for you to decide, with the last findings above.`);
1263
+ return null;
1264
+ }
1265
+ const round = earlier.length + 1;
1266
+ this.update(ticketId, active, { label: "Reviewing against the request", tool: null });
1267
+ let verdict = null;
1268
+ try {
1269
+ verdict = await reviewer({
1270
+ ticketId,
1271
+ title: ticket.title,
1272
+ goal: ticket.goal,
1273
+ outOfScope: ticket.out_of_scope,
1274
+ acceptance: ticket.acceptance,
1275
+ context: [...(ticket.context ?? [])],
1276
+ screenshots: absoluteAttachments(this.repoRoot, ticket.attachments),
1277
+ diff: await ticketDiff(active.worktreePath),
1278
+ round,
1279
+ earlier,
1280
+ worktreePath: active.worktreePath,
1281
+ testsReviewed: active.testsFirstEnabled && approvedTests(this.db.listComments(ticketId)) !== null,
1282
+ });
1283
+ }
1284
+ catch {
1285
+ verdict = null;
1286
+ }
1287
+ if (!this.isLive(ticketId, active))
1288
+ return { kind: "skip" };
1289
+ if (!verdict) {
1290
+ note("The automatic review gave no usable answer, so this ticket goes to Review unreviewed.");
1291
+ return null;
1292
+ }
1293
+ if (verdict.verdict === "pass") {
1294
+ this.db.addComment({
1295
+ ticket_id: ticketId,
1296
+ type: "review",
1297
+ author: "reviewer",
1298
+ text: `Automatic review passed: ${verdict.summary}`,
1299
+ });
1300
+ return null;
1301
+ }
1302
+ this.db.addComment({
1303
+ ticket_id: ticketId,
1304
+ type: "review",
1305
+ author: "reviewer",
1306
+ text: `${REVIEW_CHANGES_HEADING}\n\n${verdict.findings}`,
1307
+ });
1308
+ return {
1309
+ kind: "continue",
1310
+ prompt: `${REVIEW_CHANGES_PROMPT}\n\n## Review findings\n\n${verdict.findings}`,
1311
+ summary: "the automatic review asked for changes",
1312
+ label: `Addressing review (round ${round}/${MAX_AUTO_REVIEWS})`,
1313
+ };
1314
+ }
731
1315
  /** One failed round: send the run back while rounds remain, otherwise block the ticket. */
732
1316
  failRound(ticketId, runId, active, final, round) {
733
- active.verifyRounds += 1;
1317
+ const rounds = round.handoffOnly ? ++active.handoffRounds : ++active.verifyRounds;
734
1318
  // The same check failing again on work that did not change is the developer
735
1319
  // repeating itself: the lead is asked now, not after the rounds run out.
736
1320
  const previous = active.lastFailure;
@@ -742,7 +1326,7 @@ export class RunManager {
742
1326
  round.check === undefined
743
1327
  ? undefined
744
1328
  : { check: round.check, fingerprint: round.fingerprint ?? null };
745
- const exhausted = active.verifyRounds > MAX_VERIFY_ROUNDS;
1329
+ const exhausted = rounds > MAX_VERIFY_ROUNDS;
746
1330
  if (exhausted || repeated) {
747
1331
  const { blocked } = round;
748
1332
  const current = this.db.getTicket(ticketId);
@@ -778,8 +1362,15 @@ export class RunManager {
778
1362
  }
779
1363
  // After the process has gone there is no session to send the prompt to.
780
1364
  if (final)
781
- this.update(ticketId, active, { label: "Checks failed", tool: null });
782
- return { kind: "continue", prompt: round.prompt, summary: round.summary };
1365
+ this.update(ticketId, active, { label: round.outcome ?? "Checks failed", tool: null });
1366
+ return {
1367
+ kind: "continue",
1368
+ prompt: round.prompt,
1369
+ summary: round.summary,
1370
+ ...(round.outcome && !round.handoffOnly
1371
+ ? { label: `${round.outcome}, fixing (round ${rounds}/${MAX_VERIFY_ROUNDS})` }
1372
+ : {}),
1373
+ };
783
1374
  }
784
1375
  /** Counts identical tool calls in a row; the fourth one sends the nudge, once per run. */
785
1376
  noteRepeat(active, tool, args) {
@@ -792,6 +1383,184 @@ export class RunManager {
792
1383
  active.nudged = true;
793
1384
  void active.run.sendMessage(REPEAT_NUDGE).catch(() => false);
794
1385
  }
1386
+ /** The watchdog's comments on a ticket that are steers, oldest first. */
1387
+ watchdogSteers(ticketId) {
1388
+ return this.db
1389
+ .listComments(ticketId)
1390
+ .filter((comment) => comment.author === "watchdog" && comment.text.startsWith(STEER_HEADING))
1391
+ .map((comment) => comment.text);
1392
+ }
1393
+ /**
1394
+ * One watchdog tick. The signals cost nothing; a model looks only when one
1395
+ * fires or the backstop comes due, never twice at once, and not during a
1396
+ * steer's cooldown or while the board's own checks run.
1397
+ */
1398
+ async watchdogTick(ticketId, worktree, runId, active) {
1399
+ const dog = active.watchdog;
1400
+ const watchdog = this.watchdog;
1401
+ if (!dog || !watchdog || dog.busy)
1402
+ return;
1403
+ if (!this.isLive(ticketId, active) || active.gating)
1404
+ return;
1405
+ dog.busy = true;
1406
+ try {
1407
+ await this.watchdogLook(ticketId, worktree, runId, active, dog, watchdog);
1408
+ }
1409
+ finally {
1410
+ dog.busy = false;
1411
+ }
1412
+ }
1413
+ async watchdogLook(ticketId, worktree, runId, active, dog, watchdog) {
1414
+ dog.tick += 1;
1415
+ const print = await worktreeFingerprint(worktree.path);
1416
+ dog.unchangedTicks = print !== null && print === dog.fingerprint ? dog.unchangedTicks + 1 : 0;
1417
+ dog.fingerprint = print;
1418
+ if (dog.tick < dog.quietUntil || dog.checks >= MAX_WATCHDOG_CHECKS)
1419
+ return;
1420
+ const ticket = this.db.getTicket(ticketId);
1421
+ if (!ticket || !this.isLive(ticketId, active) || active.gating)
1422
+ return;
1423
+ const calls = this.db.listToolCalls(runId);
1424
+ const { signals, offPlan } = watchdogSignals(calls, dog, {
1425
+ likelyFiles: ticket.likely_files,
1426
+ worktreePath: worktree.path,
1427
+ });
1428
+ const now = Date.now();
1429
+ const due = now - dog.lastCheckAt >= (watchdog.backstopMs ?? WATCHDOG_BACKSTOP_MS);
1430
+ if (signals.length === 0 && !due)
1431
+ return;
1432
+ // The window moves on now, so what this look answers is not raised again.
1433
+ const window = calls.filter((call) => call.seq > dog.lastSeq);
1434
+ dog.lastSeq = calls.at(-1)?.seq ?? dog.lastSeq;
1435
+ dog.edited ||= window.some((call) => (call.tool === "edit" || call.tool === "write") && call.state === "done");
1436
+ for (const path of offPlan)
1437
+ dog.offPlan.add(path);
1438
+ if (signals.some((signal) => signal.kind === "stalled"))
1439
+ dog.unchangedTicks = 0;
1440
+ dog.checks += 1;
1441
+ dog.lastCheckAt = now;
1442
+ const reasons = signals.length > 0
1443
+ ? signals.map((signal) => signal.text)
1444
+ : ["routine look: nothing has looked at this run for a while"];
1445
+ const look = { at: now - active.status.startedAt, reasons, answer: "pending" };
1446
+ dog.looks.push(look);
1447
+ const row = `watchdog-${runId}-${dog.looks.length}`;
1448
+ this.showLook(ticketId, active, look, row);
1449
+ const answered = (answer) => {
1450
+ look.answer = answer;
1451
+ this.showLook(ticketId, active, look, row);
1452
+ };
1453
+ const decision = await watchdog
1454
+ .consult({
1455
+ ticketId,
1456
+ title: ticket.title,
1457
+ goal: ticket.goal,
1458
+ outOfScope: ticket.out_of_scope,
1459
+ acceptance: ticket.acceptance,
1460
+ likelyFiles: [...ticket.likely_files],
1461
+ verify: ticket.verify,
1462
+ reasons,
1463
+ minutes: Math.round((now - active.status.startedAt) / 60_000),
1464
+ leadGuidance: this.db
1465
+ .listComments(ticketId)
1466
+ .filter((comment) => comment.author === "lead")
1467
+ .map((comment) => comment.text),
1468
+ earlierSteers: this.watchdogSteers(ticketId),
1469
+ steersLeft: MAX_WATCHDOG_STEERS - dog.steers,
1470
+ calls: callLines(calls),
1471
+ diff: await ticketDiff(worktree.path, 8_000),
1472
+ worktreePath: worktree.path,
1473
+ })
1474
+ .catch(() => null);
1475
+ // No answer is "continue": a watchdog that fails is a look that did not happen.
1476
+ if (!decision || decision.decision === "continue") {
1477
+ answered(decision ? "continue" : "none");
1478
+ return;
1479
+ }
1480
+ // An answer that lands after the run ended or reached its checks is not applied.
1481
+ if (!this.isLive(ticketId, active) || active.gating)
1482
+ return;
1483
+ if (decision.decision === "steer" &&
1484
+ dog.steers < MAX_WATCHDOG_STEERS &&
1485
+ active.run.sendMessage) {
1486
+ const accepted = await active.run
1487
+ .sendMessage(`A message from the board's watchdog, which is watching this run: ${decision.message}`)
1488
+ .catch(() => false);
1489
+ if (!accepted || !this.isLive(ticketId, active)) {
1490
+ answered("none");
1491
+ return;
1492
+ }
1493
+ answered("steer");
1494
+ dog.steers += 1;
1495
+ dog.quietUntil = dog.tick + 1 + WATCHDOG_COOLDOWN_TICKS;
1496
+ this.db.addComment({
1497
+ ticket_id: ticketId,
1498
+ type: "system",
1499
+ author: "watchdog",
1500
+ text: [
1501
+ `${STEER_HEADING} ${dog.steers} of ${MAX_WATCHDOG_STEERS}:`,
1502
+ "",
1503
+ decision.message,
1504
+ "",
1505
+ `Why it looked: ${reasons.join("; ")}`,
1506
+ ].join("\n"),
1507
+ run_id: runId,
1508
+ });
1509
+ return;
1510
+ }
1511
+ const reason = decision.decision === "escalate"
1512
+ ? decision.reason
1513
+ : `the run still needed steering after ${MAX_WATCHDOG_STEERS} messages: ${decision.message}`;
1514
+ if (!this.canConsultLead(ticket)) {
1515
+ // Nothing more a look can do for this run; stop paying for them.
1516
+ dog.checks = MAX_WATCHDOG_CHECKS;
1517
+ answered("lead_unavailable");
1518
+ this.db.addComment({
1519
+ ticket_id: ticketId,
1520
+ type: "system",
1521
+ author: "watchdog",
1522
+ text: `The watchdog would hand this run to the lead, but the lead is not available for this ticket, so the run goes on. Reason: ${reason}`,
1523
+ run_id: runId,
1524
+ });
1525
+ return;
1526
+ }
1527
+ this.db.addComment({
1528
+ ticket_id: ticketId,
1529
+ type: "system",
1530
+ author: "watchdog",
1531
+ text: `The watchdog stopped this run for the lead: ${reason}`,
1532
+ run_id: runId,
1533
+ });
1534
+ answered("escalate");
1535
+ // Settled first, so the abort reads as the board's own stop and the
1536
+ // completion gate skips a run that did not finish.
1537
+ active.leadRequest = { trigger: "drifting", reason, failure: "" };
1538
+ active.settled = true;
1539
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
1540
+ active.run.abort();
1541
+ }
1542
+ /**
1543
+ * A look's row in the run trace: "looking" while it is out, its answer once it
1544
+ * has one. Only the run that is still the ticket's current one is republished,
1545
+ * so a late answer never overwrites a finished run's status.
1546
+ */
1547
+ showLook(ticketId, active, look, id) {
1548
+ const label = lookLabel(look);
1549
+ const done = look.answer !== "pending";
1550
+ active.actions = active.actions.some((action) => action.id === id)
1551
+ ? active.actions.map((action) => action.id === id
1552
+ ? { ...action, label, state: done ? "done" : "running", endedAt: Date.now() }
1553
+ : action)
1554
+ : startAction(active.actions, {
1555
+ tool: "watchdog",
1556
+ label,
1557
+ detail: look.reasons.join("; ").slice(0, 160),
1558
+ callId: id,
1559
+ });
1560
+ if (this.active.get(ticketId) === active) {
1561
+ this.update(ticketId, active, { actions: active.actions });
1562
+ }
1563
+ }
795
1564
  isLive(ticketId, active) {
796
1565
  return (this.active.get(ticketId) === active &&
797
1566
  !active.cancelled &&
@@ -1096,7 +1865,8 @@ export class RunManager {
1096
1865
  /**
1097
1866
  * Ask the separate manager pass whether this run's evidence argues for a
1098
1867
  * better standing instruction. Gated by deterministic waste signals so a
1099
- * clean run costs nothing; the result is a proposal, never a workflow edit.
1868
+ * clean run costs nothing; the result is a note on the ticket, never a
1869
+ * workflow edit.
1100
1870
  */
1101
1871
  reviewRun(ticketId, runId, state, attempt, actions, durationMs, harness) {
1102
1872
  if (!this.retro)
@@ -1125,35 +1895,29 @@ export class RunManager {
1125
1895
  if (!result)
1126
1896
  return;
1127
1897
  const evidence = result.evidence.length > 0 ? result.evidence : signals;
1128
- const suggestion = this.db.addWorkflowSuggestion({
1129
- stage: record?.workflow_stage ?? "in_progress",
1898
+ const offered = commentActionsFor(result, details);
1899
+ // The notes stay on the ticket whose run they came from. A queue on the
1900
+ // Workflows page stacked one near-identical rewrite per run; on the
1901
+ // ticket the person reads it beside the run and copies what helps.
1902
+ this.db.addComment({
1130
1903
  ticket_id: ticketId,
1131
- evidence,
1132
- notes: result.notes,
1904
+ type: "system",
1905
+ author: "manager",
1906
+ text: [
1907
+ "Manager notes on this run",
1908
+ "",
1909
+ "In Progress notes that would have avoided the waste:",
1910
+ "",
1911
+ result.notes,
1912
+ "",
1913
+ "Why:",
1914
+ ...evidence.map((line) => `- ${line}`),
1915
+ ].join("\n"),
1916
+ run_id: runId,
1917
+ ...(offered.fixPrompt || offered.issue ? { actions: offered } : {}),
1133
1918
  });
1134
- // The suggestion lives beside the workflow, but the person meets it
1135
- // where they review the run. The comment is the pointer; applying still
1136
- // happens in Workflows, so a system message cannot rewrite config.
1137
- if (suggestion) {
1138
- this.db.addComment({
1139
- ticket_id: ticketId,
1140
- type: "system",
1141
- author: "manager",
1142
- text: [
1143
- "Workflow suggestion for In Progress",
1144
- "",
1145
- result.notes,
1146
- "",
1147
- "Why:",
1148
- ...evidence.map((line) => `- ${line}`),
1149
- "",
1150
- "Apply or dismiss it in Workflows.",
1151
- ].join("\n"),
1152
- actions: commentActionsFor(result, details),
1153
- });
1154
- }
1155
1919
  })
1156
- // A manager that fails is a missing suggestion, not a failed run.
1920
+ // A manager that fails is a missing note, not a failed run.
1157
1921
  .catch(() => { });
1158
1922
  }
1159
1923
  async execute(ticketId, worktree, runId, active) {
@@ -1165,6 +1929,11 @@ export class RunManager {
1165
1929
  const factsTimer = setInterval(() => {
1166
1930
  void this.pollFacts(ticketId, worktree, active);
1167
1931
  }, this.factsPollMs);
1932
+ const watchdogTimer = active.watchdog
1933
+ ? setInterval(() => {
1934
+ void this.watchdogTick(ticketId, worktree, runId, active).catch(() => { });
1935
+ }, this.watchdog?.tickMs ?? WATCHDOG_TICK_MS)
1936
+ : undefined;
1168
1937
  try {
1169
1938
  for await (const event of active.run.events) {
1170
1939
  if (event.type === "tool_start") {
@@ -1220,8 +1989,14 @@ export class RunManager {
1220
1989
  const id = event.callId ??
1221
1990
  active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
1222
1991
  const call = id ? active.toolCalls.get(id) : undefined;
1992
+ // A test run piped through tail exits 0 whatever the tests did; its
1993
+ // own summary is the outcome, so a failing piped run is a failed row.
1994
+ const piped = call?.command
1995
+ ? pipedEvidence(call.command, call.output, event.isError)
1996
+ : null;
1997
+ const callFailed = event.isError || piped?.outcome === "failed";
1223
1998
  active.actions = finishAction(active.actions, {
1224
- isError: event.isError,
1999
+ isError: callFailed,
1225
2000
  output: call?.output,
1226
2001
  callId: id,
1227
2002
  });
@@ -1233,19 +2008,56 @@ export class RunManager {
1233
2008
  tool: call?.tool ?? event.tool,
1234
2009
  detail: call?.detail ?? "",
1235
2010
  path: call?.path ?? null,
1236
- state: event.isError ? "failed" : "done",
2011
+ state: callFailed ? "failed" : "done",
1237
2012
  blocked: event.isError && bashGuardBlockedReader(call?.output) !== null,
1238
2013
  startedAt: call?.startedAt ?? endedAt,
1239
2014
  endedAt,
1240
2015
  output: call?.output,
1241
2016
  });
1242
2017
  if (call?.command && id) {
1243
- active.commandEvidence.push({
2018
+ const currentTicket = this.db.getTicket(ticketId);
2019
+ // Only agent-reported verification consumes a worktree hash. The
2020
+ // current ticket's Verify list can change while the run is active.
2021
+ const canUseAgentEvidence = !active.cancelled &&
2022
+ !active.job.outsideStage &&
2023
+ active.job.profile === "developer" &&
2024
+ active.job.stage !== "review";
2025
+ const evidence = {
1244
2026
  id,
1245
2027
  command: call.command,
1246
- outcome: event.isError ? "failed" : "passed",
1247
- revision: event.isError ? null : await evidenceRevision(worktree.path),
1248
- });
2028
+ outcome: callFailed ? "failed" : "passed",
2029
+ revision: null,
2030
+ };
2031
+ if (!callFailed && canUseAgentEvidence) {
2032
+ const pending = evidenceRevision(worktree.path);
2033
+ active.evidencePending = pending;
2034
+ try {
2035
+ evidence.revision = await pending;
2036
+ }
2037
+ finally {
2038
+ if (active.evidencePending === pending)
2039
+ active.evidencePending = undefined;
2040
+ }
2041
+ }
2042
+ // The filtered run also stands for the command under the filter, so
2043
+ // `pnpm test x | tail -15` that the summary shows passing satisfies
2044
+ // the Verify command `pnpm test x`.
2045
+ const recorded = piped
2046
+ ? [
2047
+ evidence,
2048
+ {
2049
+ id: `${id}:unpiped`,
2050
+ command: piped.command,
2051
+ outcome: piped.outcome,
2052
+ revision: evidence.revision,
2053
+ },
2054
+ ]
2055
+ : [evidence];
2056
+ active.commandEvidence.push(...recorded);
2057
+ if (canUseAgentEvidence && currentTicket?.verify.length) {
2058
+ active.developerCommandEvidence.push(...recorded);
2059
+ active.developerCommandEvidence = active.developerCommandEvidence.slice(-64);
2060
+ }
1249
2061
  active.commandEvidence = active.commandEvidence.slice(-64);
1250
2062
  this.db.recordCommandEvidence(runId, active.commandEvidence);
1251
2063
  }
@@ -1305,6 +2117,20 @@ export class RunManager {
1305
2117
  error = cause instanceof Error ? cause.message : "the agent run failed";
1306
2118
  }
1307
2119
  clearInterval(factsTimer);
2120
+ if (watchdogTimer)
2121
+ clearInterval(watchdogTimer);
2122
+ // A look that answered "continue" leaves nothing else behind, so the run
2123
+ // says how often it was looked at; without this a watchdog that never ran
2124
+ // and one that approved every look read the same.
2125
+ if (active.watchdog && active.watchdog.looks.length > 0) {
2126
+ this.db.addComment({
2127
+ ticket_id: ticketId,
2128
+ type: "system",
2129
+ author: "watchdog",
2130
+ text: watchdogSummary(active.watchdog.looks),
2131
+ run_id: runId,
2132
+ });
2133
+ }
1308
2134
  if (active.tokenTimer) {
1309
2135
  clearTimeout(active.tokenTimer);
1310
2136
  active.tokenTimer = undefined;
@@ -1486,8 +2312,10 @@ export class RunManager {
1486
2312
  if (job?.source === "comment") {
1487
2313
  // Keep the original task and add a factual lifecycle handoff: a fresh
1488
2314
  // comment turn must not have to rediscover why its predecessor ended.
1489
- this.start(ticket, worktree, attempt + 1, {
2315
+ await this.begin(ticket, worktree, attempt + 1, {
1490
2316
  ...job,
2317
+ // The earlier attempt may have made the change before it stalled.
2318
+ expectsChange: false,
1491
2319
  prompt: `${job.prompt}\n\n## Recovery handoff\n${notice.comment}\nContinue the original goal, acceptance, constraints, and authorizations above; inspect the previous run's output/trace, identify what remains, and do not repeat completed work without a reason.${notice.comment.includes("interrupted by a server restart") ? " The process was interrupted by a server restart; resume is unavailable or exhausted, so continue in this same worktree without claiming the work was lost." : " This was a normal turn completion without an accepted status report, not a process interruption."}`,
1492
2320
  });
1493
2321
  }
@@ -1495,7 +2323,7 @@ export class RunManager {
1495
2323
  // Rebuild the same authoritative brief and add the observed lifecycle
1496
2324
  // failure. A fresh session cannot see the prior conversation or trace.
1497
2325
  const retryPrompt = buildTicketPrompt(ticket, { number: attempt + 1, of: this.retry.maxAttempts }, this.db.listComments(ticketId), absoluteAttachments(this.repoRoot, ticket.attachments));
1498
- this.start(ticket, worktree, attempt + 1, {
2326
+ await this.begin(ticket, worktree, attempt + 1, {
1499
2327
  prompt: `${retryPrompt}\n\n## Recovery handoff\n${notice.comment}\nInspect the preserved work and run only checks that remain necessary.`,
1500
2328
  profile: job?.profile ?? ticket.profile ?? "developer",
1501
2329
  retry: true,
@@ -1552,6 +2380,8 @@ export class RunManager {
1552
2380
  goal: current.goal,
1553
2381
  outOfScope: current.out_of_scope,
1554
2382
  acceptance: current.acceptance,
2383
+ likelyFiles: [...current.likely_files],
2384
+ context: [...(current.context ?? [])],
1555
2385
  verify: current.verify,
1556
2386
  trigger: request.trigger,
1557
2387
  reason: request.reason,
@@ -1561,6 +2391,11 @@ export class RunManager {
1561
2391
  .slice(-25)
1562
2392
  .map((action) => `[${action.state === "failed" ? "FAILED" : action.state}] ${action.detail}`),
1563
2393
  consult,
2394
+ earlier: this.db
2395
+ .listComments(ticketId)
2396
+ .filter((comment) => comment.author === "lead")
2397
+ .map((comment) => comment.text),
2398
+ watchdog: this.watchdogSteers(ticketId),
1564
2399
  worktreePath: worktree.path,
1565
2400
  };
1566
2401
  decision = await lead(input).catch(() => null);
@@ -1583,7 +2418,7 @@ export class RunManager {
1583
2418
  return;
1584
2419
  }
1585
2420
  try {
1586
- this.applyLead(ticketId, worktree, decision);
2421
+ await this.applyLead(ticketId, worktree, decision);
1587
2422
  }
1588
2423
  catch (cause) {
1589
2424
  const message = cause instanceof Error ? cause.message : String(cause);
@@ -1600,7 +2435,7 @@ export class RunManager {
1600
2435
  });
1601
2436
  }
1602
2437
  }
1603
- applyLead(ticketId, worktree, decision) {
2438
+ async applyLead(ticketId, worktree, decision) {
1604
2439
  if (decision.decision === "guide") {
1605
2440
  this.db.addComment({
1606
2441
  ticket_id: ticketId,
@@ -1610,7 +2445,7 @@ export class RunManager {
1610
2445
  });
1611
2446
  const ticket = this.db.getTicket(ticketId);
1612
2447
  if (ticket)
1613
- this.restartWithLead(ticket, worktree, decision.guidance);
2448
+ await this.restartWithLead(ticket, worktree, decision.guidance, true);
1614
2449
  return;
1615
2450
  }
1616
2451
  if (decision.decision === "revise") {
@@ -1633,7 +2468,8 @@ export class RunManager {
1633
2468
  author: "lead",
1634
2469
  text: `Lead revised the ticket (${changed}):\n\n${decision.guidance}${verify}${acceptance}`,
1635
2470
  });
1636
- this.restartWithLead(updated, worktree, decision.guidance);
2471
+ // The ticket was wrong, not the work: the restart may have nothing to change.
2472
+ await this.restartWithLead(updated, worktree, decision.guidance, false);
1637
2473
  return;
1638
2474
  }
1639
2475
  const options = decision.options.map((option, index) => `${index + 1}) ${option}`);
@@ -1666,14 +2502,15 @@ export class RunManager {
1666
2502
  this.db.addComment({ ticket_id: ticketId, type: "blocker", author: "zelio", text });
1667
2503
  }
1668
2504
  /** The developer again, from the start, with the lead's guidance added to the brief. */
1669
- restartWithLead(ticket, worktree, guidance) {
2505
+ async restartWithLead(ticket, worktree, guidance, expectsChange) {
1670
2506
  try {
1671
- this.start(ticket, worktree, 1, {
2507
+ await this.begin(ticket, worktree, 1, {
1672
2508
  prompt: `${buildTicketPrompt(ticket, { number: 1, of: this.retry.maxAttempts }, this.db.listComments(ticket.id), absoluteAttachments(this.repoRoot, ticket.attachments))}\n\n## Guidance from the lead\n\n${guidance}`,
1673
2509
  profile: ticket.profile ?? "developer",
1674
2510
  label: "Following the lead",
1675
2511
  retry: true,
1676
2512
  source: "ticket",
2513
+ expectsChange,
1677
2514
  });
1678
2515
  }
1679
2516
  catch (cause) {