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

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 (137) hide show
  1. package/README.md +41 -148
  2. package/dist/cli-main.js +521 -0
  3. package/dist/cli-main.js.map +1 -0
  4. package/dist/cli.js +17 -464
  5. package/dist/cli.js.map +1 -1
  6. package/dist/cloud/account.js +109 -0
  7. package/dist/cloud/account.js.map +1 -0
  8. package/dist/cloud/command.js +7 -2
  9. package/dist/cloud/command.js.map +1 -1
  10. package/dist/cloud/login.js +2 -1
  11. package/dist/cloud/login.js.map +1 -1
  12. package/dist/cloud/push-nudge.js +5 -3
  13. package/dist/cloud/push-nudge.js.map +1 -1
  14. package/dist/cloud/relay.js +5 -0
  15. package/dist/cloud/relay.js.map +1 -1
  16. package/dist/cloud/tunnel.js +65 -1
  17. package/dist/cloud/tunnel.js.map +1 -1
  18. package/dist/db/db.js +381 -157
  19. package/dist/db/db.js.map +1 -1
  20. package/dist/db/lifecycle.js +18 -5
  21. package/dist/db/lifecycle.js.map +1 -1
  22. package/dist/limits.js +1 -1
  23. package/dist/orchestrator/area-notes.js +87 -0
  24. package/dist/orchestrator/area-notes.js.map +1 -0
  25. package/dist/orchestrator/codex-session.js +10 -9
  26. package/dist/orchestrator/codex-session.js.map +1 -1
  27. package/dist/orchestrator/contract.js +30 -22
  28. package/dist/orchestrator/contract.js.map +1 -1
  29. package/dist/orchestrator/new-task-prompt.js +4 -4
  30. package/dist/orchestrator/pi-session.js +6 -0
  31. package/dist/orchestrator/pi-session.js.map +1 -1
  32. package/dist/orchestrator/prompt.js +4 -4
  33. package/dist/orchestrator/research.js +28 -13
  34. package/dist/orchestrator/research.js.map +1 -1
  35. package/dist/orchestrator/retrieval.js +333 -0
  36. package/dist/orchestrator/retrieval.js.map +1 -0
  37. package/dist/orchestrator/runtime.js +199 -36
  38. package/dist/orchestrator/runtime.js.map +1 -1
  39. package/dist/repo/code-map.js +152 -0
  40. package/dist/repo/code-map.js.map +1 -0
  41. package/dist/repo/instructions.js +9 -3
  42. package/dist/repo/instructions.js.map +1 -1
  43. package/dist/repo/linked-boards.js +20 -123
  44. package/dist/repo/linked-boards.js.map +1 -1
  45. package/dist/repo/project-repos.js +78 -0
  46. package/dist/repo/project-repos.js.map +1 -0
  47. package/dist/run/actions.js +24 -0
  48. package/dist/run/actions.js.map +1 -1
  49. package/dist/run/auto-review.js +116 -0
  50. package/dist/run/auto-review.js.map +1 -0
  51. package/dist/run/claude-runtime.js +54 -12
  52. package/dist/run/claude-runtime.js.map +1 -1
  53. package/dist/run/codex-client.js +17 -4
  54. package/dist/run/codex-client.js.map +1 -1
  55. package/dist/run/codex-planner-config.js +26 -0
  56. package/dist/run/codex-planner-config.js.map +1 -0
  57. package/dist/run/codex-runtime.js +200 -97
  58. package/dist/run/codex-runtime.js.map +1 -1
  59. package/dist/run/consult.js +109 -0
  60. package/dist/run/consult.js.map +1 -0
  61. package/dist/run/developer-sandbox.js +67 -0
  62. package/dist/run/developer-sandbox.js.map +1 -0
  63. package/dist/run/diff.js +42 -0
  64. package/dist/run/diff.js.map +1 -1
  65. package/dist/run/finish.js +53 -16
  66. package/dist/run/finish.js.map +1 -1
  67. package/dist/run/handoff.js +51 -0
  68. package/dist/run/handoff.js.map +1 -0
  69. package/dist/run/harness-runtime.js +4 -1
  70. package/dist/run/harness-runtime.js.map +1 -1
  71. package/dist/run/harnesses.js +20 -0
  72. package/dist/run/harnesses.js.map +1 -1
  73. package/dist/run/lead.js +65 -82
  74. package/dist/run/lead.js.map +1 -1
  75. package/dist/run/manager.js +1096 -68
  76. package/dist/run/manager.js.map +1 -1
  77. package/dist/run/merge-watch.js +48 -17
  78. package/dist/run/merge-watch.js.map +1 -1
  79. package/dist/run/pi-packages.js +72 -0
  80. package/dist/run/pi-packages.js.map +1 -0
  81. package/dist/run/pi-rpc.js +61 -9
  82. package/dist/run/pi-rpc.js.map +1 -1
  83. package/dist/run/piped-check.js +56 -0
  84. package/dist/run/piped-check.js.map +1 -0
  85. package/dist/run/pr-checks.js +67 -0
  86. package/dist/run/pr-checks.js.map +1 -0
  87. package/dist/run/prompt.js +64 -4
  88. package/dist/run/prompt.js.map +1 -1
  89. package/dist/run/red-check.js +130 -0
  90. package/dist/run/red-check.js.map +1 -0
  91. package/dist/run/retro.js +2 -2
  92. package/dist/run/retro.js.map +1 -1
  93. package/dist/run/settings.js +5 -2
  94. package/dist/run/settings.js.map +1 -1
  95. package/dist/run/skills.js +146 -0
  96. package/dist/run/skills.js.map +1 -0
  97. package/dist/run/tests-first.js +146 -0
  98. package/dist/run/tests-first.js.map +1 -0
  99. package/dist/run/watchdog.js +266 -0
  100. package/dist/run/watchdog.js.map +1 -0
  101. package/dist/run/workflow.js +17 -6
  102. package/dist/run/workflow.js.map +1 -1
  103. package/dist/server/app.js +1083 -300
  104. package/dist/server/app.js.map +1 -1
  105. package/dist/server/principal.js +5 -2
  106. package/dist/server/principal.js.map +1 -1
  107. package/dist/server/provider-auth.js +206 -0
  108. package/dist/server/provider-auth.js.map +1 -0
  109. package/dist/server/repo-picker.js +18 -0
  110. package/dist/server/repo-picker.js.map +1 -0
  111. package/dist/server/terminal.js +2 -2
  112. package/dist/server/terminal.js.map +1 -1
  113. package/dist/setup/config.js +0 -31
  114. package/dist/setup/config.js.map +1 -1
  115. package/dist/setup/ink-ui.js +1 -0
  116. package/dist/setup/ink-ui.js.map +1 -1
  117. package/dist/setup/onboarding.js +12 -38
  118. package/dist/setup/onboarding.js.map +1 -1
  119. package/dist/setup/run.js +4 -5
  120. package/dist/setup/run.js.map +1 -1
  121. package/dist/skills.js +151 -0
  122. package/dist/skills.js.map +1 -0
  123. package/dist/ticket-cli.js +41 -0
  124. package/dist/ticket-cli.js.map +1 -1
  125. package/dist/version.js +13 -0
  126. package/dist/version.js.map +1 -0
  127. package/dist/web/assets/index-TN5sUF2z.css +1 -0
  128. package/dist/web/assets/index-vB3Cucuc.js +258 -0
  129. package/dist/web/index.html +2 -2
  130. package/dist/web/sw.js +3 -1
  131. package/media/board.png +0 -0
  132. package/media/mobile.png +0 -0
  133. package/media/new-task.png +0 -0
  134. package/media/review.png +0 -0
  135. package/package.json +16 -7
  136. package/dist/web/assets/index-ChuS3qKc.js +0 -254
  137. package/dist/web/assets/index-DR6WkmzI.css +0 -1
@@ -4,21 +4,78 @@ 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
+ import { modelFitsHarness } from "./harnesses.js";
13
14
  import { profileFor } from "./profiles.js";
15
+ import { chosenSkills, readSkills, skillStoreOf } from "./skills.js";
14
16
  import { commentActionsFor, wasteSignalDetails } from "./retro.js";
15
17
  import { phaseForTool } from "./phases.js";
16
18
  import { buildRunSystemPrompt, emptyWorkflow, hasWorkflow, workflowSummary, } from "./workflow.js";
17
19
  import { evidenceRevision } from "./evidence.js";
18
20
  import { resultComment } from "./result.js";
19
21
  import { stripWorktreeCd } from "./actions.js";
20
- import { commitTicketWork, failureReport, hasTicketChanges, publishBranch, runChecks, ticketDiff, worktreeFingerprint, } from "./finish.js";
22
+ import { pipedEvidence, unpipedCommand } from "./piped-check.js";
23
+ import { commitTicketWork, failureReport, hasTicketChanges, publishBranch, runChecks, ticketDiff, ticketDiffWithBase, worktreeFingerprint, } from "./finish.js";
24
+ 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";
25
+ import { MAX_AUTO_REVIEWS } from "./auto-review.js";
26
+ import { isTestPath, redCheck, ticketChanges } from "./red-check.js";
27
+ 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
28
  const execFileAsync = promisify(execFile);
29
+ /** How a review that sent the work back starts its board comment; the count reads it. */
30
+ export const REVIEW_CHANGES_HEADING = "Automatic review: changes needed before Review.";
31
+ /** Sent to the developer with the reviewer's findings, the way a failed check's output is. */
32
+ 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.
33
+
34
+ Before changing code, reproduce each finding against the ticket's own diff. The board names the commit it reviewed when it knows it; the branch can also carry commits that were already on main before this ticket started, and those are not this ticket's work to revert. If a finding describes files this run did not change, say so with the diff you checked and leave them alone.
35
+
36
+ Read the findings below, open the ticket's screenshots if it has any, make the rest of 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.`;
37
+ /** The line that names the commit a review's findings were read from. */
38
+ function reviewBaseNote(base) {
39
+ return base
40
+ ? `\n\nReviewed against ${base}: \`git diff ${base}...HEAD\` shows only this ticket's change.`
41
+ : "";
42
+ }
43
+ /** A review comment's findings, without the diff-base note the board appends. */
44
+ function reviewFindings(text) {
45
+ return text
46
+ .slice(REVIEW_CHANGES_HEADING.length)
47
+ .replace(/\n\nReviewed against [0-9a-f]+: `git diff [0-9a-f]+\.\.\.HEAD` shows only this ticket's change\.$/, "")
48
+ .trim();
49
+ }
50
+ /** Sent when the ticket's checks also pass on the code before the change; the test files it copied are named after it. */
51
+ 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.";
52
+ /** Sent when a run that was asked for a change ends without changing the worktree. */
53
+ 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.";
54
+ /** Said on the ticket when the tests still pass without the change after the one send-back. */
55
+ 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.";
56
+ /** Whether this run's latest completed command proves a check on the current tree. */
57
+ export function developerCheckPassed(command, evidence, inFlightCommands, currentRevision) {
58
+ const normalized = stripWorktreeCd(command);
59
+ if (inFlightCommands.includes(normalized) || !currentRevision)
60
+ return false;
61
+ const latest = evidence.findLast((item) => item.command === normalized);
62
+ return latest?.outcome === "passed" && latest.revision === currentRevision;
63
+ }
64
+ /** Two consecutive failures of the same Verify command on known identical work. */
65
+ export function repeatedVerifyFailure(verify, evidence) {
66
+ const commands = new Set(verify.map((check) => stripWorktreeCd(check.command)));
67
+ for (const command of commands) {
68
+ const matching = evidence.filter((item) => item.command === command);
69
+ const last = matching.at(-1);
70
+ const previous = matching.at(-2);
71
+ if (last?.outcome === "failed" &&
72
+ previous?.outcome === "failed" &&
73
+ last.revision !== null &&
74
+ last.revision === previous.revision)
75
+ return last;
76
+ }
77
+ return undefined;
78
+ }
22
79
  export class RunAlreadyActiveError extends Error {
23
80
  constructor(ticketId) {
24
81
  super(`${ticketId} is already running`);
@@ -132,6 +189,14 @@ export class RunManager {
132
189
  retro;
133
190
  defaults;
134
191
  lead;
192
+ rootFor;
193
+ reviewer;
194
+ redCheckEnabled;
195
+ testsFirstEnabled;
196
+ skills;
197
+ listModels;
198
+ watchdog;
199
+ plannerChoiceEnabled;
135
200
  active = new Map();
136
201
  statuses = new Map();
137
202
  /**
@@ -152,7 +217,50 @@ export class RunManager {
152
217
  */
153
218
  retro, defaults = () => ({ harness: "pi", model: "" }),
154
219
  /** The stronger model a stuck verified ticket is sent to before the person. */
155
- lead) {
220
+ lead,
221
+ /**
222
+ * The checkout root a ticket works in. Absent means every ticket works in
223
+ * `repoRoot`; a card for an added repository has its own root.
224
+ */
225
+ rootFor,
226
+ /**
227
+ * The read-only reviewer asked, once a verified ticket's checks pass,
228
+ * whether the work gives the person what they asked for. Absent, the board
229
+ * publishes on passing checks alone.
230
+ */
231
+ reviewer,
232
+ /**
233
+ * Once a verified ticket's checks pass, they must also fail on the code
234
+ * before the change, with only the developer's test files copied in.
235
+ * Off, the board trusts the checks as written.
236
+ */
237
+ redCheckEnabled = false,
238
+ /**
239
+ * A verified ticket's first runs write only the tests, which must fail and
240
+ * pass a test review before the developer implements against them.
241
+ */
242
+ testsFirstEnabled = () => false,
243
+ /**
244
+ * Where the skills a ticket chose are read from. Absent, the board's own
245
+ * database once it keeps skills, and no skills until then.
246
+ */
247
+ skills = skillStoreOf(db),
248
+ /**
249
+ * The models a harness lists. A card's model is kept only if the harness
250
+ * that runs it lists it; a list that cannot be read is empty, so the card
251
+ * runs on the default model instead of an unknown one.
252
+ */
253
+ listModels = async () => [],
254
+ /**
255
+ * Looks over a live developer run and may steer it or stop it for the lead.
256
+ * Absent, a run is only looked at once it has stopped.
257
+ */
258
+ watchdog,
259
+ /**
260
+ * Read when a developer run starts. On, the run uses the model the planner
261
+ * chose for its ticket; off, it uses the developer agent's own model.
262
+ */
263
+ plannerChoiceEnabled = () => false) {
156
264
  this.db = db;
157
265
  this.runtime = runtime;
158
266
  this.onStatus = onStatus;
@@ -165,6 +273,14 @@ export class RunManager {
165
273
  this.retro = retro;
166
274
  this.defaults = defaults;
167
275
  this.lead = lead;
276
+ this.rootFor = rootFor;
277
+ this.reviewer = reviewer;
278
+ this.redCheckEnabled = redCheckEnabled;
279
+ this.testsFirstEnabled = testsFirstEnabled;
280
+ this.skills = skills;
281
+ this.listModels = listModels;
282
+ this.watchdog = watchdog;
283
+ this.plannerChoiceEnabled = plannerChoiceEnabled;
168
284
  this.retry = { ...DEFAULT_RETRY, ...retry };
169
285
  }
170
286
  /** Where the harness keeps session files: with the board's own state. */
@@ -309,7 +425,7 @@ export class RunManager {
309
425
  text: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Resuming it from its last turn.`,
310
426
  });
311
427
  try {
312
- this.start(ticket, worktree, latest.attempt, {
428
+ await this.begin(ticket, worktree, latest.attempt, {
313
429
  prompt: (ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT,
314
430
  profile: latest.profile ?? ticket.profile ?? "developer",
315
431
  label: "Resumed",
@@ -346,9 +462,123 @@ export class RunManager {
346
462
  });
347
463
  return started ? (this.statuses.get(ticket.id) ?? null) : null;
348
464
  }
349
- start(ticket, worktree, attempt = 1, job) {
465
+ /**
466
+ * Starts a run once the model it will use is checked against the harness's
467
+ * list. A model the harness does not list never reaches the harness: the
468
+ * ticket blocks with the reason instead. Only a run with a model needs the
469
+ * list; every other run starts at once with `start`.
470
+ */
471
+ async begin(ticket, worktree, attempt = 1, job) {
472
+ const profileName = job?.profile ?? ticket.profile ?? "developer";
473
+ const profile = this.db.getProfile(profileName) ?? profileFor(profileName);
474
+ const defaults = this.defaults();
475
+ const profileHarness = profile.harness.trim() || defaults.harness;
476
+ const command = job?.command?.trim() ||
477
+ (profileName === "developer" ? ticket.developer_harness?.trim() : "") ||
478
+ (this.plannerChoiceEnabled() && profileName === "developer" && ticket.planner_harness?.trim()
479
+ ? ticket.planner_harness.trim()
480
+ : profileHarness);
481
+ const cardOnHarness = (this.plannerChoiceEnabled() || Boolean(ticket.developer_harness?.trim())) &&
482
+ profileName === "developer" &&
483
+ command ===
484
+ (ticket.developer_harness?.trim() || ticket.planner_harness?.trim() || profileHarness) &&
485
+ Boolean(ticket.model?.trim());
486
+ // The same choice `start` makes for the model it passes on.
487
+ const profileModel = command === profileHarness ? profile.model.trim() : "";
488
+ const defaultModel = command === defaults.harness ? defaults.model.trim() : "";
489
+ const requested = job?.model !== undefined
490
+ ? { model: job.model.trim(), from: "planner" }
491
+ : cardOnHarness
492
+ ? { model: ticket.model?.trim() ?? "", from: "card" }
493
+ : profileModel
494
+ ? { model: profileModel, from: "agent" }
495
+ : { model: defaultModel, from: "default" };
496
+ if (requested.model === "")
497
+ return this.start(ticket, worktree, attempt, job);
498
+ const models = await this.modelsOf(command);
499
+ if (!modelFitsHarness(command, requested.model, models)) {
500
+ return this.refuseModel(ticket, { command, ...requested }, attempt, job);
501
+ }
502
+ return this.start(ticket, worktree, attempt, job, models);
503
+ }
504
+ /**
505
+ * A model the harness does not list fails there, or is dropped without a word.
506
+ * The ticket blocks with the reason, and no process starts. Only an in-progress
507
+ * ticket blocks; a conflict repair from Review just reports the failure.
508
+ */
509
+ refuseModel(ticket, request, attempt, job) {
510
+ const profile = job?.profile ?? ticket.profile ?? "developer";
511
+ // Each source has one place to fix it. The planner's pick on the card is
512
+ // cleared here, so the next run falls back to the agent instead of
513
+ // refusing again: there is nowhere to edit a card's model once it exists.
514
+ const missing = `Model "${request.model}" isn't available on ${request.command}`;
515
+ const advice = {
516
+ card: {
517
+ text: `${missing}. It was the planner's pick for this card, so it was removed from the card.`,
518
+ unblock: `Mention @developer to continue on the developer agent's model, or pick one in Edit agents first.`,
519
+ },
520
+ agent: {
521
+ text: `${missing}. It is the ${profile} agent's model.`,
522
+ unblock: `Pick another model for the ${profile} in Edit agents, then mention @${profile} to continue.`,
523
+ },
524
+ default: {
525
+ text: `${missing}. It is the default developer model.`,
526
+ unblock: `Pick a model for the developer in Edit agents, then mention @developer to continue.`,
527
+ },
528
+ planner: {
529
+ text: `${missing}. It is the planner's model, which the ${profile} runs on.`,
530
+ unblock: `Pick another planner model in New task, then mention @${profile} again.`,
531
+ },
532
+ }[request.from];
533
+ const text = advice.text;
534
+ const record = this.db.startAgentRun(ticket.id, attempt, null, {
535
+ profile,
536
+ harness: request.command,
537
+ model: request.model,
538
+ source: job?.source ?? "ticket",
539
+ });
540
+ this.finishRecord(record.id, "failed", null, null, null, text);
541
+ const failed = {
542
+ ticketId: ticket.id,
543
+ runId: record.id,
544
+ label: "Run failed",
545
+ tool: null,
546
+ startedAt: Date.now(),
547
+ endedAt: Date.now(),
548
+ phase: "failed",
549
+ profile,
550
+ attempt,
551
+ attempts: this.retry.maxAttempts,
552
+ tail: [],
553
+ error: text,
554
+ };
555
+ this.statuses.set(ticket.id, failed);
556
+ this.onStatus(failed);
557
+ if (this.db.getTicket(ticket.id)?.state === "in_progress") {
558
+ this.db.transition(ticket.id, "blocked", {
559
+ blocker_kind: "needs_human",
560
+ blocker_reason: text,
561
+ blocker_unblock: advice.unblock,
562
+ ...(request.from === "planner" ? {} : { blocker_action: "edit_agents" }),
563
+ ...(request.from === "card" ? { model: null } : {}),
564
+ });
565
+ this.db.addComment({ ticket_id: ticket.id, type: "system", author: "zelio", text });
566
+ }
567
+ return failed;
568
+ }
569
+ async modelsOf(command) {
570
+ return Promise.resolve()
571
+ .then(() => this.listModels(command))
572
+ .catch(() => []);
573
+ }
574
+ /**
575
+ * `models` is the list of the run's harness when the card's model needs one;
576
+ * absent means it is unknown, so the card's model is not used.
577
+ */
578
+ start(ticket, worktree, attempt = 1, job, models) {
350
579
  if (this.active.has(ticket.id))
351
580
  throw new RunAlreadyActiveError(ticket.id);
581
+ const testsFirstEnabled = this.testsFirstEnabled();
352
582
  const resolvedJob = job ?? {
353
583
  prompt: buildTicketPrompt(ticket, {
354
584
  number: attempt,
@@ -364,8 +594,36 @@ export class RunManager {
364
594
  // predates the table.
365
595
  const profile = this.db.getProfile(resolvedJob.profile) ?? profileFor(resolvedJob.profile);
366
596
  const defaults = this.defaults();
367
- const command = resolvedJob.command?.trim() || profile.harness.trim() || defaults.harness;
368
- const model = profile.model.trim() || (command === defaults.harness ? defaults.model : "");
597
+ const command = resolvedJob.command?.trim() ||
598
+ (resolvedJob.profile === "developer" ? ticket.developer_harness?.trim() : "") ||
599
+ (this.plannerChoiceEnabled() &&
600
+ resolvedJob.profile === "developer" &&
601
+ ticket.planner_harness?.trim()
602
+ ? ticket.planner_harness.trim()
603
+ : profile.harness.trim() || defaults.harness);
604
+ // A profile's model is named by its own harness, so it applies only on that
605
+ // harness: a send-back pinned to an earlier one never gets the new model.
606
+ const profileHarness = profile.harness.trim() || defaults.harness;
607
+ // A card's model is named by the developer harness, so it applies only to a
608
+ // developer run on that harness, and only if that harness lists it. Anything
609
+ // else runs on the default model, which is the one the board records. The
610
+ // person's switch decides whether the planner's choice applies at all.
611
+ const cardModel = (this.plannerChoiceEnabled() || Boolean(ticket.developer_harness?.trim())) &&
612
+ resolvedJob.profile === "developer" &&
613
+ command ===
614
+ (ticket.developer_harness?.trim() || ticket.planner_harness?.trim() || profileHarness) &&
615
+ models !== undefined &&
616
+ models.length > 0 &&
617
+ modelFitsHarness(command, ticket.model?.trim() ?? "", models)
618
+ ? (ticket.model?.trim() ?? "")
619
+ : "";
620
+ // A job that names its model (the reviewer's planner setup) uses exactly
621
+ // that; an empty one means the harness default, never the profile's.
622
+ const model = resolvedJob.model !== undefined
623
+ ? resolvedJob.model.trim()
624
+ : cardModel ||
625
+ (command === profileHarness ? profile.model.trim() : "") ||
626
+ (command === defaults.harness ? defaults.model : "");
369
627
  // A pi run can seed its own session id before the process starts. Codex
370
628
  // returns a thread id instead, so its row stays open until that arrives.
371
629
  const seedId = !this.runtime.sessionIdFromHarness?.(command);
@@ -375,7 +633,9 @@ export class RunManager {
375
633
  // different list: no checks, and board rules that forbid editing. A conflict
376
634
  // repair started from Review is neither, and takes no workflow.
377
635
  const stage = resolvedJob.stage ?? "in_progress";
378
- const takesWorkflow = !resolvedJob.outsideStage && (profile.touchesRepo || stage === "review");
636
+ // A card for an added repo runs only its own verify commands: the board's
637
+ // stage checks were written for the home repo and would fail there.
638
+ const takesWorkflow = !resolvedJob.outsideStage && !ticket.repo && (profile.touchesRepo || stage === "review");
379
639
  const workflow = takesWorkflow
380
640
  ? this.db.getStageWorkflow(stage)
381
641
  : emptyWorkflow();
@@ -388,6 +648,7 @@ export class RunManager {
388
648
  resumeCount: resolvedJob.resumes ?? 0,
389
649
  profile: resolvedJob.profile,
390
650
  harness: command,
651
+ model: model || null,
391
652
  source: resolvedJob.source,
392
653
  prompt: resolvedJob.originalPrompt ?? resolvedJob.prompt,
393
654
  systemPrompt: resolvedJob.systemPrompt ?? null,
@@ -405,21 +666,40 @@ export class RunManager {
405
666
  // Empty extra prompt must leave the prompt untouched, including "undefined"
406
667
  // so the runtime applies its own default exactly as before. A verified run
407
668
  // always names its prompt, because the runtime default is the unverified one.
408
- const profilePrompt = profile.extraPrompt.trim()
669
+ const extraPrompt = profile.extraPrompt.trim()
409
670
  ? withExtraInstructions(basePrompt, profile.extraPrompt)
410
671
  : (resolvedJob.systemPrompt ?? (verified ? VERIFIED_CODING_AGENT_PROMPT : undefined));
672
+ // A developer in In Progress is told how long each of its checks took the
673
+ // last time the board ran them, so a slow one is run once and waited out.
674
+ // A command the board has never timed adds nothing.
675
+ const timedCommands = resolvedJob.profile === "developer" && stage === "in_progress" && !resolvedJob.outsideStage
676
+ ? [...(ticket.verify ?? []), ...workflow.checks].map((check) => check.command)
677
+ : [];
678
+ const timings = timedCommands.length
679
+ ? commandTimingsSection(timedCommands, this.db.commandDurations(ticket.repo ?? null, timedCommands))
680
+ : "";
681
+ const profilePrompt = timings ? `${extraPrompt ?? defaultPrompt}\n\n${timings}` : extraPrompt;
411
682
  // The repository's own AGENTS.md/CLAUDE.md comes before the workflow: it is
412
683
  // the person's standing word on this repo, and it is read at run time, so a
413
684
  // change to it takes effect on the next run without touching the board.
414
685
  const instructions = profile.touchesRepo
415
- ? readRepoInstructions(this.repoRoot)
686
+ ? readRepoInstructions(this.rootFor ? this.rootFor(ticket) : this.repoRoot, undefined, this.runtime.instructionFilesFromHarness?.(command) ?? [])
416
687
  : { files: [], text: "" };
688
+ // The skills the planner chose for the card, read now so a skill disabled or
689
+ // deleted since is simply absent. The harness loads none of its own.
690
+ const skills = resolvedJob.profile === "developer" && (ticket.skills ?? []).length > 0
691
+ ? chosenSkills(ticket.skills, readSkills(this.skills))
692
+ : [];
417
693
  // The workflow section goes last: it closes by restating the board rules no
418
694
  // standing instruction may override, so it has to be the final thing the run
419
695
  // reads. With nothing configured it is a no-op and the prompt is untouched.
420
- const systemPrompt = hasWorkflow(workflow) || instructions.text
696
+ const systemPrompt = hasWorkflow(workflow) ||
697
+ instructions.text ||
698
+ instructions.loadedByHarness?.length ||
699
+ skills.length > 0
421
700
  ? buildRunSystemPrompt(profilePrompt ?? defaultPrompt, stage, workflow, instructions, {
422
701
  verified,
702
+ skills,
423
703
  })
424
704
  : profilePrompt;
425
705
  const status = {
@@ -438,6 +718,26 @@ export class RunManager {
438
718
  actions: [],
439
719
  ...(snapshot ? { workflow: workflowSummary(stage, workflow) } : {}),
440
720
  };
721
+ // Tests first applies to the ticket's own brief, not to a person's send-back:
722
+ // a follow-up may change what the tests should say. The phase is read back
723
+ // from the board's approval comment, so a restart or a retry picks it up.
724
+ const approved = testsFirstEnabled &&
725
+ resolvedJob.profile === "developer" &&
726
+ resolvedJob.source === "ticket" &&
727
+ !resolvedJob.outsideStage &&
728
+ ticket.verify.length > 0
729
+ ? { tests: approvedTests(this.db.listComments(ticket.id)) }
730
+ : null;
731
+ const testsPhase = !approved ? null : approved.tests ? "implement" : "tests";
732
+ const phaseBrief = resolvedJob.sessionId || !testsPhase
733
+ ? ""
734
+ : testsPhase === "tests"
735
+ ? TESTS_FIRST_PROMPT
736
+ : implementPrompt(approved.tests.sha, approved.tests.files);
737
+ // Read before the harness starts, so no edit of the run can land in it.
738
+ const startTree = resolvedJob.profile === "developer" && resolvedJob.expectsChange
739
+ ? worktreeTree(worktree.path)
740
+ : null;
441
741
  let run;
442
742
  try {
443
743
  const boardUrl = this.statusBaseUrl.replace(/\/$/, "");
@@ -457,11 +757,11 @@ export class RunManager {
457
757
  const prompt = resolvedJob.profile === "developer" &&
458
758
  resolvedJob.source === "ticket" &&
459
759
  !resolvedJob.sessionId
460
- ? `${resolvedJob.prompt}\n\n${buildDeveloperContextPack(worktree.path, ticket)}`
760
+ ? `${resolvedJob.prompt}\n\n${buildDeveloperContextPack(worktree.path, ticket)}${phaseBrief ? `\n\n${phaseBrief}` : ""}`
461
761
  : resolvedJob.prompt;
462
762
  run = this.runtime.spawn(worktree.path, prompt, {
463
763
  env,
464
- thinking: ticket.thinking ?? profile.thinking,
764
+ thinking: resolvedJob.thinking ?? ticket.thinking ?? profile.thinking,
465
765
  model: model || undefined,
466
766
  command,
467
767
  readOnly: !profile.touchesRepo,
@@ -499,6 +799,7 @@ export class RunManager {
499
799
  command,
500
800
  status,
501
801
  statusToken,
802
+ testsFirstEnabled,
502
803
  startHead: worktreeHead(worktree.path),
503
804
  cancelled: false,
504
805
  settled: false,
@@ -510,18 +811,47 @@ export class RunManager {
510
811
  actions: [],
511
812
  toolCalls: new Map(),
512
813
  commandEvidence: [...(resolvedJob.resumeEvidence ?? [])],
814
+ developerCommandEvidence: [],
513
815
  checks: stage === "in_progress" && !resolvedJob.outsideStage
514
816
  ? workflow.checks.map((check) => ({ label: check.label, command: check.command }))
515
817
  : [],
516
818
  verifyRounds: 0,
819
+ handoffRounds: 0,
517
820
  verified: ticket.verify.length > 0,
518
821
  repeat: { key: "", count: 0 },
519
822
  nudged: false,
823
+ redSentBack: false,
824
+ startTree,
825
+ idleSentBack: false,
826
+ testsPhase,
827
+ approved: testsPhase === "implement" ? (approved?.tests ?? null) : null,
520
828
  gating: false,
521
829
  gateAbort: new AbortController(),
522
830
  worktreePath: worktree.path,
523
831
  tokens: null,
524
832
  ...(resolvedJob.profile === "developer" ? { executionPhase: "inspect" } : {}),
833
+ ...(this.watchdog &&
834
+ run.sendMessage &&
835
+ resolvedJob.profile === "developer" &&
836
+ stage === "in_progress" &&
837
+ !resolvedJob.outsideStage
838
+ ? {
839
+ watchdog: {
840
+ tick: 0,
841
+ busy: false,
842
+ checks: 0,
843
+ steers: 0,
844
+ quietUntil: 0,
845
+ lastCheckAt: Date.now(),
846
+ lastSeq: 0,
847
+ edited: false,
848
+ fingerprint: null,
849
+ unchangedTicks: 0,
850
+ offPlan: new Set(),
851
+ looks: [],
852
+ },
853
+ }
854
+ : {}),
525
855
  };
526
856
  if (active.commandEvidence.length)
527
857
  this.db.recordCommandEvidence(record.id, active.commandEvidence);
@@ -532,6 +862,7 @@ export class RunManager {
532
862
  return status;
533
863
  }
534
864
  async continuationPrompt(ticketId, runId) {
865
+ await this.evidenceCaughtUp(ticketId, runId);
535
866
  const gate = await this.completionGate(ticketId, runId, false);
536
867
  if (gate.kind === "completed" || gate.kind === "escalated")
537
868
  return undefined;
@@ -539,7 +870,7 @@ export class RunManager {
539
870
  const current = this.active.get(ticketId);
540
871
  if (current?.status.runId === runId) {
541
872
  this.update(ticketId, current, {
542
- label: `Fixing checks (round ${current.verifyRounds}/${MAX_VERIFY_ROUNDS})`,
873
+ label: gate.label ?? `Fixing checks (round ${current.verifyRounds}/${MAX_VERIFY_ROUNDS})`,
543
874
  tool: null,
544
875
  });
545
876
  }
@@ -560,6 +891,23 @@ export class RunManager {
560
891
  });
561
892
  return CONTINUATION_PROMPT;
562
893
  }
894
+ /**
895
+ * A harness asks "keep going?" the moment it reads its own settle, which can
896
+ * be before the event loop has recorded the command that just finished: the
897
+ * loop hashes the worktree for that evidence asynchronously. Wait until every
898
+ * queued event has been handled, so the gate never misses a passing check
899
+ * the developer just ran.
900
+ */
901
+ async evidenceCaughtUp(ticketId, runId) {
902
+ for (;;) {
903
+ // Queued events reach the loop as microtasks; this runs after them.
904
+ await new Promise((resolve) => setImmediate(resolve));
905
+ const active = this.active.get(ticketId);
906
+ if (!active || active.status.runId !== runId || !active.evidencePending)
907
+ return;
908
+ await active.evidencePending.catch(() => null);
909
+ }
910
+ }
563
911
  /**
564
912
  * The board's own completion check for a verified In Progress ticket. The
565
913
  * ticket's verify commands and the stage checks run in the worktree; when they
@@ -605,6 +953,8 @@ export class RunManager {
605
953
  async verifyTicket(ticketId, runId, active, ticket, final) {
606
954
  const cwd = active.worktreePath;
607
955
  const max = MAX_VERIFY_ROUNDS;
956
+ if (active.testsPhase === "tests")
957
+ return this.testsGate(ticketId, runId, active, ticket, final);
608
958
  const changed = await hasTicketChanges(cwd);
609
959
  if (!this.isLive(ticketId, active))
610
960
  return { kind: "skip" };
@@ -620,6 +970,86 @@ export class RunManager {
620
970
  },
621
971
  });
622
972
  }
973
+ // The ticket has work, but this run may have added none: a run told to make
974
+ // a change that ends after reading files is not done because an earlier
975
+ // run's work still passes. It is sent back once; a second time it goes on,
976
+ // because a question needs no edit. Only a run asked for a change has a
977
+ // start tree to compare with.
978
+ const nowTree = active.startTree === null ? null : worktreeTree(cwd);
979
+ const idle = nowTree !== null && nowTree === active.startTree;
980
+ if (idle && !active.idleSentBack) {
981
+ active.idleSentBack = true;
982
+ const nowPrint = await worktreeFingerprint(cwd);
983
+ if (!this.isLive(ticketId, active))
984
+ return { kind: "skip" };
985
+ return this.failRound(ticketId, runId, active, final, {
986
+ prompt: IDLE_RUN_PROMPT,
987
+ summary: "the run changed nothing",
988
+ check: "the run changed nothing",
989
+ fingerprint: nowPrint,
990
+ blocked: {
991
+ summary: `The run still changed nothing after ${max} rounds.`,
992
+ reason: `the run ended without changing the worktree after ${max} verification rounds`,
993
+ unblock: "Make the requested change, then mention @developer to continue.",
994
+ detail: "",
995
+ },
996
+ });
997
+ }
998
+ // Requiring a local pass before this stage makes the handoff meaningful:
999
+ // otherwise the board would be the first actor to discover a known failure.
1000
+ // Evidence is tied to both a completed bash call and the exact worktree
1001
+ // content at its end; edits after the pass make it stale.
1002
+ const currentRevision = await evidenceRevision(cwd);
1003
+ if (!this.isLive(ticketId, active))
1004
+ return { kind: "skip" };
1005
+ const inFlightCommands = [...active.toolCalls.values()]
1006
+ .filter((call) => call.tool === "bash" && call.command)
1007
+ .flatMap((call) => {
1008
+ const base = unpipedCommand(call.command);
1009
+ return base ? [call.command, base] : [call.command];
1010
+ });
1011
+ const missingDeveloperChecks = ticket.verify.filter((check) => !developerCheckPassed(check.command, active.developerCommandEvidence, inFlightCommands, currentRevision));
1012
+ if (missingDeveloperChecks.length) {
1013
+ const commands = missingDeveloperChecks.map((check) => `\`${check.command}\``).join(", ");
1014
+ const repeated = repeatedVerifyFailure(missingDeveloperChecks, active.developerCommandEvidence);
1015
+ return this.failRound(ticketId, runId, active, final, {
1016
+ handoffOnly: true,
1017
+ prompt: repeated
1018
+ ? `The Verify command \`${repeated.command}\` failed twice on unchanged work. Do not simply rerun it. Inspect the failure output, failing test, setup and relevant code; identify the cause or missing evidence first. Stay within the ticket's authorization. Before handing this ticket to the board, finish these Verify commands yourself, each in its own shell call and exactly as written: ${commands}.`
1019
+ : `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.`,
1020
+ summary: `the developer did not finish Verify: ${missingDeveloperChecks.map((check) => check.label).join(", ")}`,
1021
+ blocked: {
1022
+ summary: `The developer did not finish the ticket's Verify command after ${MAX_VERIFY_ROUNDS} handoff attempts.`,
1023
+ reason: `the developer did not record completed passing runs of ${commands} against the current worktree after ${MAX_VERIFY_ROUNDS} handoff attempts`,
1024
+ unblock: `Run ${commands} in the ticket worktree, fix any failure, and continue the ticket.`,
1025
+ detail: "",
1026
+ },
1027
+ });
1028
+ }
1029
+ // Implementing against approved tests: they may be fixed and may grow, but
1030
+ // no approved check may go.
1031
+ if (active.testsPhase === "implement" && active.approved) {
1032
+ const weakened = await weakenedTests(cwd, active.approved.sha, active.approved.files);
1033
+ if (!this.isLive(ticketId, active))
1034
+ return { kind: "skip" };
1035
+ if (weakened.length > 0) {
1036
+ const fingerprint = await worktreeFingerprint(cwd);
1037
+ if (!this.isLive(ticketId, active))
1038
+ return { kind: "skip" };
1039
+ return this.failRound(ticketId, runId, active, final, {
1040
+ prompt: testsChangedPrompt(weakened),
1041
+ summary: "an approved check was removed",
1042
+ check: "approved tests kept",
1043
+ fingerprint,
1044
+ blocked: {
1045
+ summary: `The approved tests were still changed after ${max} rounds.`,
1046
+ reason: `approved checks in ${weakened.map((item) => item.file).join(", ")} were removed or changed after ${max} verification rounds`,
1047
+ unblock: "Restore the approved tests, or mention @developer with the change you want to the tests.",
1048
+ detail: "",
1049
+ },
1050
+ });
1051
+ }
1052
+ }
623
1053
  const checks = [...ticket.verify, ...active.checks];
624
1054
  const env = this.agentPath
625
1055
  ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
@@ -631,6 +1061,13 @@ export class RunManager {
631
1061
  });
632
1062
  if (!this.isLive(ticketId, active))
633
1063
  return { kind: "skip" };
1064
+ // A check that exited or hit its timeout ran for a real duration; one that
1065
+ // never started or was aborted did not, and leaves the last one in place.
1066
+ for (const result of results) {
1067
+ if (result.exitCode === null && !result.timedOut)
1068
+ continue;
1069
+ this.db.recordCommandDuration(ticket.repo ?? null, result.command, result.durationMs);
1070
+ }
634
1071
  for (const result of results.filter((item) => item.flaky)) {
635
1072
  this.db.addComment({
636
1073
  ticket_id: ticketId,
@@ -649,6 +1086,10 @@ export class RunManager {
649
1086
  }
650
1087
  active.commandEvidence = active.commandEvidence.slice(-64);
651
1088
  this.db.recordCommandEvidence(runId, active.commandEvidence);
1089
+ // The board's checks land in the trace, so a timeout reads as a timeout
1090
+ // there rather than hiding behind the agent's own passing run.
1091
+ active.actions = checkActions(active.actions, results);
1092
+ this.update(ticketId, active, { actions: active.actions });
652
1093
  const failed = results.find((result) => !result.passed);
653
1094
  if (failed) {
654
1095
  const detail = failureReport(results);
@@ -657,7 +1098,8 @@ export class RunManager {
657
1098
  return { kind: "skip" };
658
1099
  return this.failRound(ticketId, runId, active, final, {
659
1100
  prompt: `${VERIFY_FAILED_PROMPT}\n\n${detail}`,
660
- summary: failed.label,
1101
+ summary: failed.timedOut ? `${failed.label} timed out` : failed.label,
1102
+ outcome: failed.timedOut ? "Check timed out" : "Check failed",
661
1103
  check: failed.label,
662
1104
  fingerprint,
663
1105
  blocked: {
@@ -668,6 +1110,58 @@ export class RunManager {
668
1110
  },
669
1111
  });
670
1112
  }
1113
+ // Passing checks must also fail on the code before the change; otherwise
1114
+ // they prove nothing, and the developer is asked for tests that do.
1115
+ if (this.redCheckEnabled) {
1116
+ this.update(ticketId, active, {
1117
+ label: "Checking the tests fail without the change",
1118
+ tool: null,
1119
+ });
1120
+ const red = await redCheck(cwd, ticket.verify, { env, signal: active.gateAbort.signal });
1121
+ if (!this.isLive(ticketId, active))
1122
+ return { kind: "skip" };
1123
+ if (red.kind === "proves-nothing" && active.redSentBack) {
1124
+ this.db.addComment({
1125
+ ticket_id: ticketId,
1126
+ type: "system",
1127
+ author: "zelio",
1128
+ text: RED_CHECK_STILL_PASSES,
1129
+ });
1130
+ }
1131
+ else if (red.kind === "proves-nothing") {
1132
+ active.redSentBack = true;
1133
+ const fingerprint = await worktreeFingerprint(cwd);
1134
+ if (!this.isLive(ticketId, active))
1135
+ return { kind: "skip" };
1136
+ return this.failRound(ticketId, runId, active, final, {
1137
+ prompt: `${RED_CHECK_PROMPT}\n\nTest files the board copied onto the old code: ${red.testFiles.join(", ") || "none"}`,
1138
+ summary: "the tests pass without the change",
1139
+ check: "tests fail without the change",
1140
+ fingerprint,
1141
+ blocked: {
1142
+ summary: `The ticket's tests still pass without the change after ${max} rounds.`,
1143
+ reason: `The Verify commands pass on the code before the change after ${max} verification rounds, so they do not test the ticket`,
1144
+ unblock: "Add tests that fail without the change, or correct the ticket's verify commands, then mention @developer to continue.",
1145
+ detail: "",
1146
+ },
1147
+ });
1148
+ }
1149
+ if (red.kind === "unavailable") {
1150
+ this.db.addComment({
1151
+ ticket_id: ticketId,
1152
+ type: "system",
1153
+ author: "zelio",
1154
+ text: `The board could not check that the tests fail without the change: ${red.reason}`,
1155
+ });
1156
+ }
1157
+ }
1158
+ // Checks prove what they test; the review asks whether the person got what
1159
+ // they asked for, before anything is committed or published.
1160
+ const review = await this.autoReview(ticketId, active, ticket);
1161
+ if (review)
1162
+ return review;
1163
+ if (!this.isLive(ticketId, active))
1164
+ return { kind: "skip" };
671
1165
  const branch = ticket.branch?.trim() || (await currentBranch(cwd));
672
1166
  if (!this.isLive(ticketId, active))
673
1167
  return { kind: "skip" };
@@ -728,9 +1222,250 @@ export class RunManager {
728
1222
  this.update(ticketId, active, { label: "Finishing", tool: null });
729
1223
  return { kind: "completed" };
730
1224
  }
1225
+ /**
1226
+ * The end of a tests-only turn. The tests must be the only change, must fail
1227
+ * on the code as it is, and must pass the test review; then the board commits
1228
+ * them and the same session goes on to implement against them. Anything else
1229
+ * sends the turn back the way a failed check does.
1230
+ */
1231
+ async testsGate(ticketId, runId, active, ticket, final) {
1232
+ const cwd = active.worktreePath;
1233
+ const max = MAX_VERIFY_ROUNDS;
1234
+ const sendBack = async (prompt, summary, reason) => {
1235
+ const fingerprint = await worktreeFingerprint(cwd);
1236
+ if (!this.isLive(ticketId, active))
1237
+ return { kind: "skip" };
1238
+ return this.failRound(ticketId, runId, active, final, {
1239
+ prompt,
1240
+ summary,
1241
+ check: summary,
1242
+ fingerprint,
1243
+ blocked: {
1244
+ summary: `The tests were still not ready after ${max} rounds: ${summary}.`,
1245
+ reason: `${reason} after ${max} verification rounds`,
1246
+ unblock: "Write tests that fail on the current code and check what was asked, then mention @developer to continue.",
1247
+ detail: "",
1248
+ },
1249
+ });
1250
+ };
1251
+ const changes = await ticketChanges(cwd);
1252
+ if (!this.isLive(ticketId, active))
1253
+ return { kind: "skip" };
1254
+ if (!changes) {
1255
+ // Without a base the board cannot tell tests from code; it does not hold
1256
+ // the ticket for that, and the run implements without the test phase.
1257
+ this.db.addComment({
1258
+ ticket_id: ticketId,
1259
+ type: "system",
1260
+ author: "zelio",
1261
+ text: "The board could not find the base to check the tests against, so this ticket skips the test phase.",
1262
+ });
1263
+ active.testsPhase = null;
1264
+ return this.verifyTicket(ticketId, runId, active, ticket, final);
1265
+ }
1266
+ const tests = changes.files.filter(isTestPath);
1267
+ const others = changes.files.filter((file) => !isTestPath(file));
1268
+ if (tests.length === 0) {
1269
+ return sendBack(TESTS_MISSING_PROMPT, "no tests were written", "no test file changed");
1270
+ }
1271
+ if (others.length > 0) {
1272
+ return sendBack(testsOnlyPrompt(others), "files outside tests changed", `files outside tests changed in the test phase (${others.join(", ")})`);
1273
+ }
1274
+ // The code is untouched, so the ticket's checks run here exactly as they
1275
+ // would on the old code: one of them has to fail.
1276
+ this.update(ticketId, active, { label: "Checking the tests fail", tool: null });
1277
+ const env = this.agentPath
1278
+ ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
1279
+ : process.env;
1280
+ const results = await runChecks(cwd, ticket.verify, { env, signal: active.gateAbort.signal });
1281
+ if (!this.isLive(ticketId, active))
1282
+ return { kind: "skip" };
1283
+ if (results.length === ticket.verify.length && results.every((result) => result.passed)) {
1284
+ return sendBack(TESTS_PASS_ALREADY_PROMPT, "the tests pass without the change", "the tests pass on the code before the change");
1285
+ }
1286
+ const diff = await testsDiff(cwd, changes.mergeBase, tests);
1287
+ if (!this.isLive(ticketId, active))
1288
+ return { kind: "skip" };
1289
+ const review = await this.testReview(ticketId, active, ticket, diff);
1290
+ if (review)
1291
+ return review;
1292
+ if (!this.isLive(ticketId, active))
1293
+ return { kind: "skip" };
1294
+ const commit = await commitTicketWork(cwd, `test: ${ticket.title}`);
1295
+ if (!this.isLive(ticketId, active))
1296
+ return { kind: "skip" };
1297
+ if (commit.error || !commit.head) {
1298
+ const hook = commit.error
1299
+ ? `The commit hook failed:\n\n\`\`\`text\n${commit.error}\n\`\`\``
1300
+ : "The board could not commit the tests.";
1301
+ return sendBack(`${VERIFY_FAILED_PROMPT}\n\n${hook}`, "the tests could not be committed", "the tests could not be committed");
1302
+ }
1303
+ this.db.addComment({
1304
+ ticket_id: ticketId,
1305
+ type: "system",
1306
+ author: "zelio",
1307
+ text: approvalComment(commit.head, tests),
1308
+ });
1309
+ active.testsPhase = "implement";
1310
+ active.approved = { sha: commit.head, files: tests };
1311
+ // The test phase's rounds were spent on the tests; implementing starts fresh.
1312
+ active.verifyRounds = 0;
1313
+ active.lastFailure = undefined;
1314
+ return {
1315
+ kind: "continue",
1316
+ prompt: implementPrompt(commit.head, tests),
1317
+ summary: "the tests were approved",
1318
+ label: "Implementing against the approved tests",
1319
+ };
1320
+ }
1321
+ /**
1322
+ * The reviewer reads the tests alone against the person's request. Null means
1323
+ * approve them: they passed, the review gave no usable answer or is not
1324
+ * configured, or it has sent them back as often as it may.
1325
+ */
1326
+ async testReview(ticketId, active, ticket, diff) {
1327
+ const reviewer = this.reviewer;
1328
+ if (!reviewer)
1329
+ return null;
1330
+ const note = (text) => this.db.addComment({ ticket_id: ticketId, type: "system", author: "zelio", text });
1331
+ const earlier = this.db
1332
+ .listComments(ticketId)
1333
+ .filter((comment) => comment.author === "reviewer" &&
1334
+ comment.type === "review" &&
1335
+ comment.text.startsWith(TEST_REVIEW_HEADING))
1336
+ .map((comment) => comment.text.slice(TEST_REVIEW_HEADING.length).trim());
1337
+ if (earlier.length >= MAX_TEST_REVIEWS) {
1338
+ 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.`);
1339
+ return null;
1340
+ }
1341
+ const round = earlier.length + 1;
1342
+ this.update(ticketId, active, { label: "Reviewing the tests", tool: null });
1343
+ let verdict = null;
1344
+ try {
1345
+ verdict = await reviewer({
1346
+ ticketId,
1347
+ title: ticket.title,
1348
+ goal: ticket.goal,
1349
+ outOfScope: ticket.out_of_scope,
1350
+ acceptance: ticket.acceptance,
1351
+ context: [...(ticket.context ?? [])],
1352
+ plan: ticket.plan ?? null,
1353
+ screenshots: absoluteAttachments(this.repoRoot, ticket.attachments),
1354
+ diff,
1355
+ round,
1356
+ earlier,
1357
+ worktreePath: active.worktreePath,
1358
+ focus: "tests",
1359
+ });
1360
+ }
1361
+ catch {
1362
+ verdict = null;
1363
+ }
1364
+ if (!this.isLive(ticketId, active))
1365
+ return { kind: "skip" };
1366
+ if (!verdict) {
1367
+ note("The test review gave no usable answer, so the board approves the tests unreviewed.");
1368
+ return null;
1369
+ }
1370
+ if (verdict.verdict === "pass") {
1371
+ this.db.addComment({
1372
+ ticket_id: ticketId,
1373
+ type: "review",
1374
+ author: "reviewer",
1375
+ text: `Test review passed: ${verdict.summary}`,
1376
+ });
1377
+ return null;
1378
+ }
1379
+ this.db.addComment({
1380
+ ticket_id: ticketId,
1381
+ type: "review",
1382
+ author: "reviewer",
1383
+ text: `${TEST_REVIEW_HEADING}\n\n${verdict.findings}`,
1384
+ });
1385
+ return {
1386
+ kind: "continue",
1387
+ prompt: `${TEST_REVIEW_CHANGES_PROMPT}\n\n## Test review findings\n\n${verdict.findings}`,
1388
+ summary: "the test review asked for changes",
1389
+ label: `Revising the tests (round ${round}/${MAX_TEST_REVIEWS})`,
1390
+ };
1391
+ }
1392
+ /**
1393
+ * The automatic review between passing checks and publishing. Null means go
1394
+ * on and publish: the review passed, gave no usable answer, is not
1395
+ * configured, or has already sent this ticket back as often as it may. A
1396
+ * "changes" verdict returns the findings as the developer's next prompt.
1397
+ */
1398
+ async autoReview(ticketId, active, ticket) {
1399
+ const reviewer = this.reviewer;
1400
+ if (!reviewer)
1401
+ return null;
1402
+ const note = (text) => this.db.addComment({ ticket_id: ticketId, type: "system", author: "zelio", text });
1403
+ const earlier = this.db
1404
+ .listComments(ticketId)
1405
+ .filter((comment) => comment.author === "reviewer" &&
1406
+ comment.type === "review" &&
1407
+ comment.text.startsWith(REVIEW_CHANGES_HEADING))
1408
+ .map((comment) => reviewFindings(comment.text));
1409
+ if (earlier.length >= MAX_AUTO_REVIEWS) {
1410
+ 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.`);
1411
+ return null;
1412
+ }
1413
+ const round = earlier.length + 1;
1414
+ this.update(ticketId, active, { label: "Reviewing against the request", tool: null });
1415
+ const change = await ticketDiffWithBase(active.worktreePath);
1416
+ let verdict = null;
1417
+ try {
1418
+ verdict = await reviewer({
1419
+ ticketId,
1420
+ title: ticket.title,
1421
+ goal: ticket.goal,
1422
+ outOfScope: ticket.out_of_scope,
1423
+ acceptance: ticket.acceptance,
1424
+ context: [...(ticket.context ?? [])],
1425
+ plan: ticket.plan ?? null,
1426
+ screenshots: absoluteAttachments(this.repoRoot, ticket.attachments),
1427
+ diff: change.diff,
1428
+ diffBase: change.base,
1429
+ round,
1430
+ earlier,
1431
+ worktreePath: active.worktreePath,
1432
+ testsReviewed: active.testsFirstEnabled && approvedTests(this.db.listComments(ticketId)) !== null,
1433
+ });
1434
+ }
1435
+ catch {
1436
+ verdict = null;
1437
+ }
1438
+ if (!this.isLive(ticketId, active))
1439
+ return { kind: "skip" };
1440
+ if (!verdict) {
1441
+ note("The automatic review gave no usable answer, so this ticket goes to Review unreviewed.");
1442
+ return null;
1443
+ }
1444
+ if (verdict.verdict === "pass") {
1445
+ this.db.addComment({
1446
+ ticket_id: ticketId,
1447
+ type: "review",
1448
+ author: "reviewer",
1449
+ text: `Automatic review passed: ${verdict.summary}`,
1450
+ });
1451
+ return null;
1452
+ }
1453
+ this.db.addComment({
1454
+ ticket_id: ticketId,
1455
+ type: "review",
1456
+ author: "reviewer",
1457
+ text: `${REVIEW_CHANGES_HEADING}\n\n${verdict.findings}${reviewBaseNote(change.base)}`,
1458
+ });
1459
+ return {
1460
+ kind: "continue",
1461
+ prompt: `${REVIEW_CHANGES_PROMPT}\n\n## Review findings\n\n${verdict.findings}${reviewBaseNote(change.base)}`,
1462
+ summary: "the automatic review asked for changes",
1463
+ label: `Addressing review (round ${round}/${MAX_AUTO_REVIEWS})`,
1464
+ };
1465
+ }
731
1466
  /** One failed round: send the run back while rounds remain, otherwise block the ticket. */
732
1467
  failRound(ticketId, runId, active, final, round) {
733
- active.verifyRounds += 1;
1468
+ const rounds = round.handoffOnly ? ++active.handoffRounds : ++active.verifyRounds;
734
1469
  // The same check failing again on work that did not change is the developer
735
1470
  // repeating itself: the lead is asked now, not after the rounds run out.
736
1471
  const previous = active.lastFailure;
@@ -742,7 +1477,7 @@ export class RunManager {
742
1477
  round.check === undefined
743
1478
  ? undefined
744
1479
  : { check: round.check, fingerprint: round.fingerprint ?? null };
745
- const exhausted = active.verifyRounds > MAX_VERIFY_ROUNDS;
1480
+ const exhausted = rounds > MAX_VERIFY_ROUNDS;
746
1481
  if (exhausted || repeated) {
747
1482
  const { blocked } = round;
748
1483
  const current = this.db.getTicket(ticketId);
@@ -778,8 +1513,15 @@ export class RunManager {
778
1513
  }
779
1514
  // After the process has gone there is no session to send the prompt to.
780
1515
  if (final)
781
- this.update(ticketId, active, { label: "Checks failed", tool: null });
782
- return { kind: "continue", prompt: round.prompt, summary: round.summary };
1516
+ this.update(ticketId, active, { label: round.outcome ?? "Checks failed", tool: null });
1517
+ return {
1518
+ kind: "continue",
1519
+ prompt: round.prompt,
1520
+ summary: round.summary,
1521
+ ...(round.outcome && !round.handoffOnly
1522
+ ? { label: `${round.outcome}, fixing (round ${rounds}/${MAX_VERIFY_ROUNDS})` }
1523
+ : {}),
1524
+ };
783
1525
  }
784
1526
  /** Counts identical tool calls in a row; the fourth one sends the nudge, once per run. */
785
1527
  noteRepeat(active, tool, args) {
@@ -792,6 +1534,192 @@ export class RunManager {
792
1534
  active.nudged = true;
793
1535
  void active.run.sendMessage(REPEAT_NUDGE).catch(() => false);
794
1536
  }
1537
+ /** The watchdog's comments on a ticket that are steers, oldest first. */
1538
+ watchdogSteers(ticketId) {
1539
+ return this.db
1540
+ .listComments(ticketId)
1541
+ .filter((comment) => comment.author === "watchdog" && comment.text.startsWith(STEER_HEADING))
1542
+ .map((comment) => comment.text);
1543
+ }
1544
+ /**
1545
+ * One watchdog tick. The signals cost nothing; a model looks only when one
1546
+ * fires or the backstop comes due, never twice at once, and not during a
1547
+ * steer's cooldown or while the board's own checks run.
1548
+ */
1549
+ async watchdogTick(ticketId, worktree, runId, active) {
1550
+ const dog = active.watchdog;
1551
+ const watchdog = this.watchdog;
1552
+ if (!dog || !watchdog || dog.busy)
1553
+ return;
1554
+ if (!this.isLive(ticketId, active) || active.gating)
1555
+ return;
1556
+ dog.busy = true;
1557
+ try {
1558
+ await this.watchdogLook(ticketId, worktree, runId, active, dog, watchdog);
1559
+ }
1560
+ finally {
1561
+ dog.busy = false;
1562
+ }
1563
+ }
1564
+ async watchdogLook(ticketId, worktree, runId, active, dog, watchdog) {
1565
+ dog.tick += 1;
1566
+ const print = await worktreeFingerprint(worktree.path);
1567
+ dog.unchangedTicks = print !== null && print === dog.fingerprint ? dog.unchangedTicks + 1 : 0;
1568
+ dog.fingerprint = print;
1569
+ if (dog.tick < dog.quietUntil || dog.checks >= MAX_WATCHDOG_CHECKS)
1570
+ return;
1571
+ const ticket = this.db.getTicket(ticketId);
1572
+ if (!ticket || !this.isLive(ticketId, active) || active.gating)
1573
+ return;
1574
+ const calls = this.db.listToolCalls(runId);
1575
+ const { signals, offPlan } = watchdogSignals(calls, dog, {
1576
+ likelyFiles: ticket.likely_files,
1577
+ worktreePath: worktree.path,
1578
+ });
1579
+ const repeated = repeatedVerifyFailure(ticket.verify, active.developerCommandEvidence);
1580
+ if (repeated && repeated.id !== dog.repeatFailureId) {
1581
+ signals.push({
1582
+ kind: "repeating",
1583
+ text: `Verify command "${repeated.command}" failed twice on unchanged work; investigate before rerunning`,
1584
+ });
1585
+ dog.repeatFailureId = repeated.id;
1586
+ }
1587
+ const now = Date.now();
1588
+ const due = now - dog.lastCheckAt >= (watchdog.backstopMs ?? WATCHDOG_BACKSTOP_MS);
1589
+ if (signals.length === 0 && !due)
1590
+ return;
1591
+ // The window moves on now, so what this look answers is not raised again.
1592
+ const window = calls.filter((call) => call.seq > dog.lastSeq);
1593
+ dog.lastSeq = calls.at(-1)?.seq ?? dog.lastSeq;
1594
+ dog.edited ||= window.some((call) => (call.tool === "edit" || call.tool === "write") && call.state === "done");
1595
+ for (const path of offPlan)
1596
+ dog.offPlan.add(path);
1597
+ if (signals.some((signal) => signal.kind === "stalled"))
1598
+ dog.unchangedTicks = 0;
1599
+ dog.checks += 1;
1600
+ dog.lastCheckAt = now;
1601
+ const reasons = signals.length > 0
1602
+ ? signals.map((signal) => signal.text)
1603
+ : ["routine look: nothing has looked at this run for a while"];
1604
+ const look = { at: now - active.status.startedAt, reasons, answer: "pending" };
1605
+ dog.looks.push(look);
1606
+ const row = `watchdog-${runId}-${dog.looks.length}`;
1607
+ this.showLook(ticketId, active, look, row);
1608
+ const answered = (answer) => {
1609
+ look.answer = answer;
1610
+ this.showLook(ticketId, active, look, row);
1611
+ };
1612
+ const decision = await watchdog
1613
+ .consult({
1614
+ ticketId,
1615
+ title: ticket.title,
1616
+ goal: ticket.goal,
1617
+ outOfScope: ticket.out_of_scope,
1618
+ acceptance: ticket.acceptance,
1619
+ likelyFiles: [...ticket.likely_files],
1620
+ verify: ticket.verify,
1621
+ reasons,
1622
+ minutes: Math.round((now - active.status.startedAt) / 60_000),
1623
+ leadGuidance: this.db
1624
+ .listComments(ticketId)
1625
+ .filter((comment) => comment.author === "lead")
1626
+ .map((comment) => comment.text),
1627
+ earlierSteers: this.watchdogSteers(ticketId),
1628
+ steersLeft: MAX_WATCHDOG_STEERS - dog.steers,
1629
+ calls: callLines(calls),
1630
+ diff: await ticketDiff(worktree.path, 8_000),
1631
+ worktreePath: worktree.path,
1632
+ })
1633
+ .catch(() => null);
1634
+ // No answer is "continue": a watchdog that fails is a look that did not happen.
1635
+ if (!decision || decision.decision === "continue") {
1636
+ answered(decision ? "continue" : "none");
1637
+ return;
1638
+ }
1639
+ // An answer that lands after the run ended or reached its checks is not applied.
1640
+ if (!this.isLive(ticketId, active) || active.gating)
1641
+ return;
1642
+ if (decision.decision === "steer" &&
1643
+ dog.steers < MAX_WATCHDOG_STEERS &&
1644
+ active.run.sendMessage) {
1645
+ const accepted = await active.run
1646
+ .sendMessage(`A message from the board's watchdog, which is watching this run: ${decision.message}`)
1647
+ .catch(() => false);
1648
+ if (!accepted || !this.isLive(ticketId, active)) {
1649
+ answered("none");
1650
+ return;
1651
+ }
1652
+ answered("steer");
1653
+ dog.steers += 1;
1654
+ dog.quietUntil = dog.tick + 1 + WATCHDOG_COOLDOWN_TICKS;
1655
+ this.db.addComment({
1656
+ ticket_id: ticketId,
1657
+ type: "system",
1658
+ author: "watchdog",
1659
+ text: [
1660
+ `${STEER_HEADING} ${dog.steers} of ${MAX_WATCHDOG_STEERS}:`,
1661
+ "",
1662
+ decision.message,
1663
+ "",
1664
+ `Why it looked: ${reasons.join("; ")}`,
1665
+ ].join("\n"),
1666
+ run_id: runId,
1667
+ });
1668
+ return;
1669
+ }
1670
+ const reason = decision.decision === "escalate"
1671
+ ? decision.reason
1672
+ : `the run still needed steering after ${MAX_WATCHDOG_STEERS} messages: ${decision.message}`;
1673
+ if (!this.canConsultLead(ticket)) {
1674
+ // Nothing more a look can do for this run; stop paying for them.
1675
+ dog.checks = MAX_WATCHDOG_CHECKS;
1676
+ answered("lead_unavailable");
1677
+ this.db.addComment({
1678
+ ticket_id: ticketId,
1679
+ type: "system",
1680
+ author: "watchdog",
1681
+ 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}`,
1682
+ run_id: runId,
1683
+ });
1684
+ return;
1685
+ }
1686
+ this.db.addComment({
1687
+ ticket_id: ticketId,
1688
+ type: "system",
1689
+ author: "watchdog",
1690
+ text: `The watchdog stopped this run for the lead: ${reason}`,
1691
+ run_id: runId,
1692
+ });
1693
+ answered("escalate");
1694
+ // Settled first, so the abort reads as the board's own stop and the
1695
+ // completion gate skips a run that did not finish.
1696
+ active.leadRequest = { trigger: "drifting", reason, failure: "" };
1697
+ active.settled = true;
1698
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
1699
+ active.run.abort();
1700
+ }
1701
+ /**
1702
+ * A look's row in the run trace: "looking" while it is out, its answer once it
1703
+ * has one. Only the run that is still the ticket's current one is republished,
1704
+ * so a late answer never overwrites a finished run's status.
1705
+ */
1706
+ showLook(ticketId, active, look, id) {
1707
+ const label = lookLabel(look);
1708
+ const done = look.answer !== "pending";
1709
+ active.actions = active.actions.some((action) => action.id === id)
1710
+ ? active.actions.map((action) => action.id === id
1711
+ ? { ...action, label, state: done ? "done" : "running", endedAt: Date.now() }
1712
+ : action)
1713
+ : startAction(active.actions, {
1714
+ tool: "watchdog",
1715
+ label,
1716
+ detail: look.reasons.join("; ").slice(0, 160),
1717
+ callId: id,
1718
+ });
1719
+ if (this.active.get(ticketId) === active) {
1720
+ this.update(ticketId, active, { actions: active.actions });
1721
+ }
1722
+ }
795
1723
  isLive(ticketId, active) {
796
1724
  return (this.active.get(ticketId) === active &&
797
1725
  !active.cancelled &&
@@ -1096,7 +2024,8 @@ export class RunManager {
1096
2024
  /**
1097
2025
  * Ask the separate manager pass whether this run's evidence argues for a
1098
2026
  * better standing instruction. Gated by deterministic waste signals so a
1099
- * clean run costs nothing; the result is a proposal, never a workflow edit.
2027
+ * clean run costs nothing; the result is a note on the ticket, never a
2028
+ * workflow edit.
1100
2029
  */
1101
2030
  reviewRun(ticketId, runId, state, attempt, actions, durationMs, harness) {
1102
2031
  if (!this.retro)
@@ -1125,35 +2054,29 @@ export class RunManager {
1125
2054
  if (!result)
1126
2055
  return;
1127
2056
  const evidence = result.evidence.length > 0 ? result.evidence : signals;
1128
- const suggestion = this.db.addWorkflowSuggestion({
1129
- stage: record?.workflow_stage ?? "in_progress",
2057
+ const offered = commentActionsFor(result, details);
2058
+ // The notes stay on the ticket whose run they came from. A queue on the
2059
+ // Workflows page stacked one near-identical rewrite per run; on the
2060
+ // ticket the person reads it beside the run and copies what helps.
2061
+ this.db.addComment({
1130
2062
  ticket_id: ticketId,
1131
- evidence,
1132
- notes: result.notes,
2063
+ type: "system",
2064
+ author: "manager",
2065
+ text: [
2066
+ "Manager notes on this run",
2067
+ "",
2068
+ "In Progress notes that would have avoided the waste:",
2069
+ "",
2070
+ result.notes,
2071
+ "",
2072
+ "Why:",
2073
+ ...evidence.map((line) => `- ${line}`),
2074
+ ].join("\n"),
2075
+ run_id: runId,
2076
+ ...(offered.fixPrompt || offered.issue ? { actions: offered } : {}),
1133
2077
  });
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
2078
  })
1156
- // A manager that fails is a missing suggestion, not a failed run.
2079
+ // A manager that fails is a missing note, not a failed run.
1157
2080
  .catch(() => { });
1158
2081
  }
1159
2082
  async execute(ticketId, worktree, runId, active) {
@@ -1165,6 +2088,11 @@ export class RunManager {
1165
2088
  const factsTimer = setInterval(() => {
1166
2089
  void this.pollFacts(ticketId, worktree, active);
1167
2090
  }, this.factsPollMs);
2091
+ const watchdogTimer = active.watchdog
2092
+ ? setInterval(() => {
2093
+ void this.watchdogTick(ticketId, worktree, runId, active).catch(() => { });
2094
+ }, this.watchdog?.tickMs ?? WATCHDOG_TICK_MS)
2095
+ : undefined;
1168
2096
  try {
1169
2097
  for await (const event of active.run.events) {
1170
2098
  if (event.type === "tool_start") {
@@ -1220,8 +2148,14 @@ export class RunManager {
1220
2148
  const id = event.callId ??
1221
2149
  active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
1222
2150
  const call = id ? active.toolCalls.get(id) : undefined;
2151
+ // A test run piped through tail exits 0 whatever the tests did; its
2152
+ // own summary is the outcome, so a failing piped run is a failed row.
2153
+ const piped = call?.command
2154
+ ? pipedEvidence(call.command, call.output, event.isError)
2155
+ : null;
2156
+ const callFailed = event.isError || piped?.outcome === "failed";
1223
2157
  active.actions = finishAction(active.actions, {
1224
- isError: event.isError,
2158
+ isError: callFailed,
1225
2159
  output: call?.output,
1226
2160
  callId: id,
1227
2161
  });
@@ -1233,19 +2167,60 @@ export class RunManager {
1233
2167
  tool: call?.tool ?? event.tool,
1234
2168
  detail: call?.detail ?? "",
1235
2169
  path: call?.path ?? null,
1236
- state: event.isError ? "failed" : "done",
2170
+ state: callFailed ? "failed" : "done",
1237
2171
  blocked: event.isError && bashGuardBlockedReader(call?.output) !== null,
1238
2172
  startedAt: call?.startedAt ?? endedAt,
1239
2173
  endedAt,
1240
2174
  output: call?.output,
1241
2175
  });
1242
2176
  if (call?.command && id) {
1243
- active.commandEvidence.push({
2177
+ const currentTicket = this.db.getTicket(ticketId);
2178
+ // Only agent-reported verification consumes a worktree hash. The
2179
+ // current ticket's Verify list can change while the run is active.
2180
+ const canUseAgentEvidence = !active.cancelled &&
2181
+ !active.job.outsideStage &&
2182
+ active.job.profile === "developer" &&
2183
+ active.job.stage !== "review";
2184
+ const evidence = {
1244
2185
  id,
1245
2186
  command: call.command,
1246
- outcome: event.isError ? "failed" : "passed",
1247
- revision: event.isError ? null : await evidenceRevision(worktree.path),
2187
+ outcome: callFailed ? "failed" : "passed",
2188
+ revision: null,
2189
+ };
2190
+ const isVerify = currentTicket?.verify.some((check) => {
2191
+ const command = stripWorktreeCd(check.command);
2192
+ return command === stripWorktreeCd(call.command) || command === piped?.command;
1248
2193
  });
2194
+ if (canUseAgentEvidence && (!callFailed || isVerify)) {
2195
+ const pending = evidenceRevision(worktree.path);
2196
+ active.evidencePending = pending;
2197
+ try {
2198
+ evidence.revision = await pending;
2199
+ }
2200
+ finally {
2201
+ if (active.evidencePending === pending)
2202
+ active.evidencePending = undefined;
2203
+ }
2204
+ }
2205
+ // The filtered run also stands for the command under the filter, so
2206
+ // `pnpm test x | tail -15` that the summary shows passing satisfies
2207
+ // the Verify command `pnpm test x`.
2208
+ const recorded = piped
2209
+ ? [
2210
+ evidence,
2211
+ {
2212
+ id: `${id}:unpiped`,
2213
+ command: piped.command,
2214
+ outcome: piped.outcome,
2215
+ revision: evidence.revision,
2216
+ },
2217
+ ]
2218
+ : [evidence];
2219
+ active.commandEvidence.push(...recorded);
2220
+ if (canUseAgentEvidence && currentTicket?.verify.length) {
2221
+ active.developerCommandEvidence.push(...recorded);
2222
+ active.developerCommandEvidence = active.developerCommandEvidence.slice(-64);
2223
+ }
1249
2224
  active.commandEvidence = active.commandEvidence.slice(-64);
1250
2225
  this.db.recordCommandEvidence(runId, active.commandEvidence);
1251
2226
  }
@@ -1305,6 +2280,20 @@ export class RunManager {
1305
2280
  error = cause instanceof Error ? cause.message : "the agent run failed";
1306
2281
  }
1307
2282
  clearInterval(factsTimer);
2283
+ if (watchdogTimer)
2284
+ clearInterval(watchdogTimer);
2285
+ // A look that answered "continue" leaves nothing else behind, so the run
2286
+ // says how often it was looked at; without this a watchdog that never ran
2287
+ // and one that approved every look read the same.
2288
+ if (active.watchdog && active.watchdog.looks.length > 0) {
2289
+ this.db.addComment({
2290
+ ticket_id: ticketId,
2291
+ type: "system",
2292
+ author: "watchdog",
2293
+ text: watchdogSummary(active.watchdog.looks),
2294
+ run_id: runId,
2295
+ });
2296
+ }
1308
2297
  if (active.tokenTimer) {
1309
2298
  clearTimeout(active.tokenTimer);
1310
2299
  active.tokenTimer = undefined;
@@ -1486,8 +2475,10 @@ export class RunManager {
1486
2475
  if (job?.source === "comment") {
1487
2476
  // Keep the original task and add a factual lifecycle handoff: a fresh
1488
2477
  // comment turn must not have to rediscover why its predecessor ended.
1489
- this.start(ticket, worktree, attempt + 1, {
2478
+ await this.begin(ticket, worktree, attempt + 1, {
1490
2479
  ...job,
2480
+ // The earlier attempt may have made the change before it stalled.
2481
+ expectsChange: false,
1491
2482
  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
2483
  });
1493
2484
  }
@@ -1495,7 +2486,7 @@ export class RunManager {
1495
2486
  // Rebuild the same authoritative brief and add the observed lifecycle
1496
2487
  // failure. A fresh session cannot see the prior conversation or trace.
1497
2488
  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, {
2489
+ await this.begin(ticket, worktree, attempt + 1, {
1499
2490
  prompt: `${retryPrompt}\n\n## Recovery handoff\n${notice.comment}\nInspect the preserved work and run only checks that remain necessary.`,
1500
2491
  profile: job?.profile ?? ticket.profile ?? "developer",
1501
2492
  retry: true,
@@ -1536,6 +2527,14 @@ export class RunManager {
1536
2527
  if (!lead || !current || current.state !== "in_progress" || this.active.has(ticketId))
1537
2528
  return;
1538
2529
  try {
2530
+ const failedCall = this.db
2531
+ .listToolCalls(active.status.runId)
2532
+ .findLast((call) => call.tool === "bash" && call.state === "failed" && call.output?.trim());
2533
+ const captured = failedCall?.output
2534
+ ? `Latest failed developer command: ${failedCall.detail}\nCaptured output (tail):\n${failedCall.output.slice(-3000)}`
2535
+ : "";
2536
+ const failure = [request.failure.slice(-3000), captured].filter(Boolean).join("\n\n");
2537
+ const enrichedRequest = { ...request, failure };
1539
2538
  const consult = this.leadConsults(ticketId) + 1;
1540
2539
  this.db.addComment({
1541
2540
  ticket_id: ticketId,
@@ -1545,6 +2544,7 @@ export class RunManager {
1545
2544
  });
1546
2545
  let decision = null;
1547
2546
  let problem = null;
2547
+ let attempt = "";
1548
2548
  try {
1549
2549
  const input = {
1550
2550
  ticketId,
@@ -1552,18 +2552,39 @@ export class RunManager {
1552
2552
  goal: current.goal,
1553
2553
  outOfScope: current.out_of_scope,
1554
2554
  acceptance: current.acceptance,
2555
+ likelyFiles: [...current.likely_files],
2556
+ context: [...(current.context ?? [])],
1555
2557
  verify: current.verify,
1556
2558
  trigger: request.trigger,
1557
2559
  reason: request.reason,
1558
- failure: request.failure,
2560
+ failure,
2561
+ onAttempt: (text) => {
2562
+ attempt = text.slice(-3000);
2563
+ },
1559
2564
  diff: await ticketDiff(worktree.path),
1560
- actions: active.actions
1561
- .slice(-25)
1562
- .map((action) => `[${action.state === "failed" ? "FAILED" : action.state}] ${action.detail}`),
2565
+ actions: [
2566
+ ...active.actions
2567
+ .slice(-25)
2568
+ .map((action) => `[${action.state === "failed" ? "FAILED" : action.state}] ${action.detail}`),
2569
+ ...active.developerCommandEvidence.slice(-10).map((item, index, items) => {
2570
+ const previous = items[index - 1];
2571
+ const change = !item.revision || !previous?.revision
2572
+ ? "worktree comparison unavailable"
2573
+ : item.revision === previous.revision
2574
+ ? "worktree unchanged since previous command"
2575
+ : "worktree changed since previous command";
2576
+ return `[developer ${item.outcome}; ${change}] ${item.command}`;
2577
+ }),
2578
+ ],
1563
2579
  consult,
2580
+ earlier: this.db
2581
+ .listComments(ticketId)
2582
+ .filter((comment) => comment.author === "lead")
2583
+ .map((comment) => comment.text),
2584
+ watchdog: this.watchdogSteers(ticketId),
1564
2585
  worktreePath: worktree.path,
1565
2586
  };
1566
- decision = await lead(input).catch(() => null);
2587
+ decision = await lead(input);
1567
2588
  }
1568
2589
  catch (cause) {
1569
2590
  problem = cause instanceof Error ? cause.message : String(cause);
@@ -1579,15 +2600,20 @@ export class RunManager {
1579
2600
  return;
1580
2601
  }
1581
2602
  if (!decision) {
1582
- this.blockForLead(ticketId, request, problem === null ? null : `The lead failed: ${problem}`);
2603
+ this.blockForLead(ticketId, enrichedRequest, [
2604
+ problem === null ? null : `The lead failed: ${problem}`,
2605
+ attempt ? `Lead attempt (tail):\n${attempt}` : "",
2606
+ ]
2607
+ .filter(Boolean)
2608
+ .join("\n\n") || null);
1583
2609
  return;
1584
2610
  }
1585
2611
  try {
1586
- this.applyLead(ticketId, worktree, decision);
2612
+ await this.applyLead(ticketId, worktree, decision);
1587
2613
  }
1588
2614
  catch (cause) {
1589
2615
  const message = cause instanceof Error ? cause.message : String(cause);
1590
- this.blockForLead(ticketId, request, `The lead's answer could not be applied: ${message}`);
2616
+ this.blockForLead(ticketId, enrichedRequest, `The lead's answer could not be applied: ${message}`);
1591
2617
  }
1592
2618
  }
1593
2619
  catch (cause) {
@@ -1600,7 +2626,7 @@ export class RunManager {
1600
2626
  });
1601
2627
  }
1602
2628
  }
1603
- applyLead(ticketId, worktree, decision) {
2629
+ async applyLead(ticketId, worktree, decision) {
1604
2630
  if (decision.decision === "guide") {
1605
2631
  this.db.addComment({
1606
2632
  ticket_id: ticketId,
@@ -1610,7 +2636,7 @@ export class RunManager {
1610
2636
  });
1611
2637
  const ticket = this.db.getTicket(ticketId);
1612
2638
  if (ticket)
1613
- this.restartWithLead(ticket, worktree, decision.guidance);
2639
+ await this.restartWithLead(ticket, worktree, decision.guidance, true);
1614
2640
  return;
1615
2641
  }
1616
2642
  if (decision.decision === "revise") {
@@ -1633,7 +2659,8 @@ export class RunManager {
1633
2659
  author: "lead",
1634
2660
  text: `Lead revised the ticket (${changed}):\n\n${decision.guidance}${verify}${acceptance}`,
1635
2661
  });
1636
- this.restartWithLead(updated, worktree, decision.guidance);
2662
+ // The ticket was wrong, not the work: the restart may have nothing to change.
2663
+ await this.restartWithLead(updated, worktree, decision.guidance, false);
1637
2664
  return;
1638
2665
  }
1639
2666
  const options = decision.options.map((option, index) => `${index + 1}) ${option}`);
@@ -1666,14 +2693,15 @@ export class RunManager {
1666
2693
  this.db.addComment({ ticket_id: ticketId, type: "blocker", author: "zelio", text });
1667
2694
  }
1668
2695
  /** The developer again, from the start, with the lead's guidance added to the brief. */
1669
- restartWithLead(ticket, worktree, guidance) {
2696
+ async restartWithLead(ticket, worktree, guidance, expectsChange) {
1670
2697
  try {
1671
- this.start(ticket, worktree, 1, {
2698
+ await this.begin(ticket, worktree, 1, {
1672
2699
  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
2700
  profile: ticket.profile ?? "developer",
1674
2701
  label: "Following the lead",
1675
2702
  retry: true,
1676
2703
  source: "ticket",
2704
+ expectsChange,
1677
2705
  });
1678
2706
  }
1679
2707
  catch (cause) {