zelio-cli 0.0.0-stage → 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 (223) hide show
  1. package/README.md +71 -2
  2. package/dist/attachments.js +121 -0
  3. package/dist/attachments.js.map +1 -0
  4. package/dist/cli-main.js +521 -0
  5. package/dist/cli-main.js.map +1 -0
  6. package/dist/cli.js +22 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/cloud/account.js +109 -0
  9. package/dist/cloud/account.js.map +1 -0
  10. package/dist/cloud/board.js +311 -0
  11. package/dist/cloud/board.js.map +1 -0
  12. package/dist/cloud/command.js +265 -0
  13. package/dist/cloud/command.js.map +1 -0
  14. package/dist/cloud/config.js +132 -0
  15. package/dist/cloud/config.js.map +1 -0
  16. package/dist/cloud/credentials.js +134 -0
  17. package/dist/cloud/credentials.js.map +1 -0
  18. package/dist/cloud/login.js +166 -0
  19. package/dist/cloud/login.js.map +1 -0
  20. package/dist/cloud/pair.js +110 -0
  21. package/dist/cloud/pair.js.map +1 -0
  22. package/dist/cloud/pkce.js +16 -0
  23. package/dist/cloud/pkce.js.map +1 -0
  24. package/dist/cloud/push-nudge.js +65 -0
  25. package/dist/cloud/push-nudge.js.map +1 -0
  26. package/dist/cloud/relay.js +134 -0
  27. package/dist/cloud/relay.js.map +1 -0
  28. package/dist/cloud/token.js +66 -0
  29. package/dist/cloud/token.js.map +1 -0
  30. package/dist/cloud/tunnel.js +474 -0
  31. package/dist/cloud/tunnel.js.map +1 -0
  32. package/dist/db/db.js +1838 -0
  33. package/dist/db/db.js.map +1 -0
  34. package/dist/db/lifecycle.js +146 -0
  35. package/dist/db/lifecycle.js.map +1 -0
  36. package/dist/limits.js +35 -0
  37. package/dist/limits.js.map +1 -0
  38. package/dist/metrics.js +30 -0
  39. package/dist/metrics.js.map +1 -0
  40. package/dist/orchestrator/area-notes.js +87 -0
  41. package/dist/orchestrator/area-notes.js.map +1 -0
  42. package/dist/orchestrator/claude-session.js +208 -0
  43. package/dist/orchestrator/claude-session.js.map +1 -0
  44. package/dist/orchestrator/codex-session.js +327 -0
  45. package/dist/orchestrator/codex-session.js.map +1 -0
  46. package/dist/orchestrator/contract.js +189 -0
  47. package/dist/orchestrator/contract.js.map +1 -0
  48. package/dist/orchestrator/explore.js +176 -0
  49. package/dist/orchestrator/explore.js.map +1 -0
  50. package/dist/orchestrator/new-task-prompt.js +51 -0
  51. package/dist/orchestrator/new-task-prompt.js.map +1 -0
  52. package/dist/orchestrator/pi-session.js +234 -0
  53. package/dist/orchestrator/pi-session.js.map +1 -0
  54. package/dist/orchestrator/prompt.js +110 -0
  55. package/dist/orchestrator/prompt.js.map +1 -0
  56. package/dist/orchestrator/research.js +193 -0
  57. package/dist/orchestrator/research.js.map +1 -0
  58. package/dist/orchestrator/retrieval.js +333 -0
  59. package/dist/orchestrator/retrieval.js.map +1 -0
  60. package/dist/orchestrator/runtime.js +1217 -0
  61. package/dist/orchestrator/runtime.js.map +1 -0
  62. package/dist/orchestrator/session.js +2 -0
  63. package/dist/orchestrator/session.js.map +1 -0
  64. package/dist/orchestrator/types.js +2 -0
  65. package/dist/orchestrator/types.js.map +1 -0
  66. package/dist/orchestrator/web.js +276 -0
  67. package/dist/orchestrator/web.js.map +1 -0
  68. package/dist/repo/code-map.js +152 -0
  69. package/dist/repo/code-map.js.map +1 -0
  70. package/dist/repo/index.js +188 -0
  71. package/dist/repo/index.js.map +1 -0
  72. package/dist/repo/instructions.js +58 -0
  73. package/dist/repo/instructions.js.map +1 -0
  74. package/dist/repo/linked-boards.js +149 -0
  75. package/dist/repo/linked-boards.js.map +1 -0
  76. package/dist/repo/project-repos.js +78 -0
  77. package/dist/repo/project-repos.js.map +1 -0
  78. package/dist/run/actions.js +257 -0
  79. package/dist/run/actions.js.map +1 -0
  80. package/dist/run/auto-review.js +116 -0
  81. package/dist/run/auto-review.js.map +1 -0
  82. package/dist/run/bash-guard.js +183 -0
  83. package/dist/run/bash-guard.js.map +1 -0
  84. package/dist/run/claude-runtime.js +284 -0
  85. package/dist/run/claude-runtime.js.map +1 -0
  86. package/dist/run/claude-stream.js +306 -0
  87. package/dist/run/claude-stream.js.map +1 -0
  88. package/dist/run/codex-client.js +213 -0
  89. package/dist/run/codex-client.js.map +1 -0
  90. package/dist/run/codex-planner-config.js +26 -0
  91. package/dist/run/codex-planner-config.js.map +1 -0
  92. package/dist/run/codex-runtime.js +469 -0
  93. package/dist/run/codex-runtime.js.map +1 -0
  94. package/dist/run/consult.js +109 -0
  95. package/dist/run/consult.js.map +1 -0
  96. package/dist/run/context.js +87 -0
  97. package/dist/run/context.js.map +1 -0
  98. package/dist/run/developer-sandbox.js +67 -0
  99. package/dist/run/developer-sandbox.js.map +1 -0
  100. package/dist/run/diff.js +238 -0
  101. package/dist/run/diff.js.map +1 -0
  102. package/dist/run/evidence.js +48 -0
  103. package/dist/run/evidence.js.map +1 -0
  104. package/dist/run/finish.js +430 -0
  105. package/dist/run/finish.js.map +1 -0
  106. package/dist/run/handoff.js +51 -0
  107. package/dist/run/handoff.js.map +1 -0
  108. package/dist/run/harness-runtime.js +31 -0
  109. package/dist/run/harness-runtime.js.map +1 -0
  110. package/dist/run/harnesses.js +293 -0
  111. package/dist/run/harnesses.js.map +1 -0
  112. package/dist/run/issue.js +79 -0
  113. package/dist/run/issue.js.map +1 -0
  114. package/dist/run/keep-awake.js +58 -0
  115. package/dist/run/keep-awake.js.map +1 -0
  116. package/dist/run/lead.js +183 -0
  117. package/dist/run/lead.js.map +1 -0
  118. package/dist/run/manager.js +2737 -0
  119. package/dist/run/manager.js.map +1 -0
  120. package/dist/run/mentions.js +35 -0
  121. package/dist/run/mentions.js.map +1 -0
  122. package/dist/run/merge-watch.js +425 -0
  123. package/dist/run/merge-watch.js.map +1 -0
  124. package/dist/run/models.js +88 -0
  125. package/dist/run/models.js.map +1 -0
  126. package/dist/run/phases.js +23 -0
  127. package/dist/run/phases.js.map +1 -0
  128. package/dist/run/pi-packages.js +72 -0
  129. package/dist/run/pi-packages.js.map +1 -0
  130. package/dist/run/pi-rpc.js +464 -0
  131. package/dist/run/pi-rpc.js.map +1 -0
  132. package/dist/run/piped-check.js +56 -0
  133. package/dist/run/piped-check.js.map +1 -0
  134. package/dist/run/pr-checks.js +67 -0
  135. package/dist/run/pr-checks.js.map +1 -0
  136. package/dist/run/pr-merge.js +121 -0
  137. package/dist/run/pr-merge.js.map +1 -0
  138. package/dist/run/profiles.js +43 -0
  139. package/dist/run/profiles.js.map +1 -0
  140. package/dist/run/prompt.js +405 -0
  141. package/dist/run/prompt.js.map +1 -0
  142. package/dist/run/pull-request.js +23 -0
  143. package/dist/run/pull-request.js.map +1 -0
  144. package/dist/run/red-check.js +130 -0
  145. package/dist/run/red-check.js.map +1 -0
  146. package/dist/run/result-tool.js +93 -0
  147. package/dist/run/result-tool.js.map +1 -0
  148. package/dist/run/result.js +113 -0
  149. package/dist/run/result.js.map +1 -0
  150. package/dist/run/retro.js +346 -0
  151. package/dist/run/retro.js.map +1 -0
  152. package/dist/run/settings.js +28 -0
  153. package/dist/run/settings.js.map +1 -0
  154. package/dist/run/skills.js +146 -0
  155. package/dist/run/skills.js.map +1 -0
  156. package/dist/run/tests-first.js +146 -0
  157. package/dist/run/tests-first.js.map +1 -0
  158. package/dist/run/thinking.js +41 -0
  159. package/dist/run/thinking.js.map +1 -0
  160. package/dist/run/types.js +2 -0
  161. package/dist/run/types.js.map +1 -0
  162. package/dist/run/watchdog.js +266 -0
  163. package/dist/run/watchdog.js.map +1 -0
  164. package/dist/run/workflow.js +277 -0
  165. package/dist/run/workflow.js.map +1 -0
  166. package/dist/run/worktree.js +354 -0
  167. package/dist/run/worktree.js.map +1 -0
  168. package/dist/server/app.js +3286 -0
  169. package/dist/server/app.js.map +1 -0
  170. package/dist/server/auth.js +93 -0
  171. package/dist/server/auth.js.map +1 -0
  172. package/dist/server/demo.js +96 -0
  173. package/dist/server/demo.js.map +1 -0
  174. package/dist/server/idempotency.js +104 -0
  175. package/dist/server/idempotency.js.map +1 -0
  176. package/dist/server/port.js +36 -0
  177. package/dist/server/port.js.map +1 -0
  178. package/dist/server/principal.js +93 -0
  179. package/dist/server/principal.js.map +1 -0
  180. package/dist/server/provider-auth.js +206 -0
  181. package/dist/server/provider-auth.js.map +1 -0
  182. package/dist/server/repo-picker.js +18 -0
  183. package/dist/server/repo-picker.js.map +1 -0
  184. package/dist/server/terminal.js +285 -0
  185. package/dist/server/terminal.js.map +1 -0
  186. package/dist/setup/components.js +98 -0
  187. package/dist/setup/components.js.map +1 -0
  188. package/dist/setup/config.js +71 -0
  189. package/dist/setup/config.js.map +1 -0
  190. package/dist/setup/ink-ui.js +189 -0
  191. package/dist/setup/ink-ui.js.map +1 -0
  192. package/dist/setup/onboarding.js +157 -0
  193. package/dist/setup/onboarding.js.map +1 -0
  194. package/dist/setup/run.js +69 -0
  195. package/dist/setup/run.js.map +1 -0
  196. package/dist/skills.js +151 -0
  197. package/dist/skills.js.map +1 -0
  198. package/dist/ticket-cli.js +157 -0
  199. package/dist/ticket-cli.js.map +1 -0
  200. package/dist/version.js +13 -0
  201. package/dist/version.js.map +1 -0
  202. package/dist/voice/index.js +69 -0
  203. package/dist/voice/index.js.map +1 -0
  204. package/dist/voice/moonshine.js +247 -0
  205. package/dist/voice/moonshine.js.map +1 -0
  206. package/dist/voice/wav.js +54 -0
  207. package/dist/voice/wav.js.map +1 -0
  208. package/dist/voice/whisper.js +491 -0
  209. package/dist/voice/whisper.js.map +1 -0
  210. package/dist/web/assets/index-TN5sUF2z.css +1 -0
  211. package/dist/web/assets/index-vB3Cucuc.js +258 -0
  212. package/dist/web/icons/apple-touch-icon.png +0 -0
  213. package/dist/web/icons/icon-192.png +0 -0
  214. package/dist/web/icons/icon-512.png +0 -0
  215. package/dist/web/icons/maskable-512.png +0 -0
  216. package/dist/web/index.html +21 -0
  217. package/dist/web/manifest.webmanifest +30 -0
  218. package/dist/web/sw.js +185 -0
  219. package/media/board.png +0 -0
  220. package/media/mobile.png +0 -0
  221. package/media/new-task.png +0 -0
  222. package/media/review.png +0 -0
  223. package/package.json +105 -4
@@ -0,0 +1,2737 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
+ import { mkdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { absoluteAttachments } from "../attachments.js";
7
+ import { actionDetail, actionPath, checkActions, closeActions, finishAction, MAX_ACTION_OUTPUT, startAction, } from "./actions.js";
8
+ import { bashGuardBlockedReader } from "./bash-guard.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
+ import { readRepoInstructions } from "../repo/instructions.js";
12
+ import { buildDeveloperContextPack } from "./context.js";
13
+ import { modelFitsHarness } from "./harnesses.js";
14
+ import { profileFor } from "./profiles.js";
15
+ import { chosenSkills, readSkills, skillStoreOf } from "./skills.js";
16
+ import { commentActionsFor, wasteSignalDetails } from "./retro.js";
17
+ import { phaseForTool } from "./phases.js";
18
+ import { buildRunSystemPrompt, emptyWorkflow, hasWorkflow, workflowSummary, } from "./workflow.js";
19
+ import { evidenceRevision } from "./evidence.js";
20
+ import { resultComment } from "./result.js";
21
+ import { stripWorktreeCd } from "./actions.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";
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
+ }
79
+ export class RunAlreadyActiveError extends Error {
80
+ constructor(ticketId) {
81
+ super(`${ticketId} is already running`);
82
+ this.name = "RunAlreadyActiveError";
83
+ }
84
+ }
85
+ const FACTS_POLL_MS = 3_000;
86
+ /**
87
+ * How often a live token total reaches the board and the stored row. The
88
+ * harness reports after every assistant message, which can be far more often
89
+ * than a person reads; seven seconds keeps the number moving without turning
90
+ * the event stream into a token counter.
91
+ */
92
+ const TOKEN_PUBLISH_MS = 7_000;
93
+ const OUTPUT_LINES = 12;
94
+ const TAIL_LINES = 3;
95
+ const OUTPUT_DELAY_MS = 250;
96
+ const outputLine = (value) => {
97
+ const text = value.trim();
98
+ // A minified or single-line dump is only interesting where it ended.
99
+ return text.length > 400 ? `…${text.slice(-399)}` : text;
100
+ };
101
+ const tail = (value) => value.trim().split("\n").filter(Boolean).slice(-3).join(" ").slice(0, 500);
102
+ /**
103
+ * How many times one attempt may be resumed before the board stops trying.
104
+ * A resume is cheap and loses nothing, but a machine that sleeps every few
105
+ * minutes would otherwise keep the same run alive forever: after this many, the
106
+ * ticket falls back to the ordinary attempt budget and then to the person.
107
+ */
108
+ export const MAX_RESUMES = 3;
109
+ /** Idle developer turns may continue, but never beyond the attempt's deadline or this cap. */
110
+ export const MAX_TURN_CONTINUATIONS = 2;
111
+ /** Failed verification rounds before the board stops sending the run back and blocks the ticket. */
112
+ export const MAX_VERIFY_ROUNDS = 3;
113
+ /** Identical tool calls in a row, on a verified run, before the developer is told to change course. */
114
+ export const REPEAT_NUDGE_AT = 4;
115
+ /** Sent in-session once per run when the developer repeats the same tool call. */
116
+ export const REPEAT_NUDGE = "You have made the same tool call four times in a row. Change your approach, or end your turn if the work is done or blocked.";
117
+ /** JSON with sorted keys, so the same arguments always compare equal. */
118
+ function stableJson(value) {
119
+ if (Array.isArray(value))
120
+ return `[${value.map(stableJson).join(",")}]`;
121
+ if (value && typeof value === "object") {
122
+ const record = value;
123
+ const fields = Object.keys(record)
124
+ .sort()
125
+ .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`);
126
+ return `{${fields.join(",")}}`;
127
+ }
128
+ return JSON.stringify(value) ?? "null";
129
+ }
130
+ /** Lead consultations per verified ticket before the person is asked directly. */
131
+ export const MAX_LEAD_CONSULTS = 2;
132
+ const CONTINUATION_PROMPT = `Your last turn ended without an accepted ticket status. This is the same run, session, worktree, and branch. Continue the original ticket and its acceptance criteria from the work already done; do not restart inspection or repeat passing checks on unchanged code.
133
+
134
+ A summary, partial commit, or pull request is not completion. Finish the remaining implementation and required verification, then use report_result with the required evidence, limitations, and any previously agreed later assurance gates. Do not stop because work remains or ask to split the ticket; the planner owns decomposition. Report Blocked only for a concrete obstacle preventing further safe progress that requires an external resource, human decision, or resolution of a safety/explicit-constraint conflict. Name that obstacle and the specific unblock condition. Never claim Review for incomplete or unverified acceptance.`;
135
+ const VERIFY_FAILED_PROMPT = `The board ran this ticket's checks after your turn and at least one failed. This is the same session and worktree. Read the output below, fix the cause, and end your turn again; the board will re-run the checks. Do not commit, push, or report a status yourself.`;
136
+ const NO_CHANGES_PROMPT = `Your turn ended, but this worktree has no changes for the ticket yet. Implement the ticket so its Verify commands pass, then end your turn. Do not commit, push, or report a status yourself.`;
137
+ const COMMIT_TYPES = new Set([
138
+ "feat",
139
+ "fix",
140
+ "chore",
141
+ "docs",
142
+ "refactor",
143
+ "test",
144
+ "perf",
145
+ "style",
146
+ "build",
147
+ "ci",
148
+ ]);
149
+ /** A conventional subject from the ticket title, typed by the branch prefix when it names one. */
150
+ function commitMessage(title, branch) {
151
+ const prefix = branch.includes("/") ? branch.slice(0, branch.indexOf("/")) : "";
152
+ const type = COMMIT_TYPES.has(prefix) ? prefix : "feat";
153
+ return `${type}: ${title.trim().replace(/^./, (letter) => letter.toLowerCase())}`;
154
+ }
155
+ async function currentBranch(cwd) {
156
+ const { stdout } = await execFileAsync("git", ["-C", cwd, "branch", "--show-current"], {
157
+ timeout: 15_000,
158
+ }).catch(() => ({ stdout: "" }));
159
+ return String(stdout).trim();
160
+ }
161
+ const seconds = (ms) => (ms / 1000).toFixed(1);
162
+ const DEFAULT_RETRY = {
163
+ maxAttempts: 2,
164
+ breakerStalls: 3,
165
+ breakerWindowMs: 10 * 60_000,
166
+ };
167
+ /**
168
+ * Why a run that ended without moving its ticket is worth saying out loud. The
169
+ * exit code is evidence about the process; the silence is the point.
170
+ */
171
+ const stallReason = (exitCode) => exitCode === null || exitCode === 0
172
+ ? "the agent finished without reporting a status"
173
+ : `the agent exited with code ${exitCode} without reporting a status`;
174
+ /**
175
+ * Owns the in-flight ticket processes and their live status. It does not move
176
+ * tickets: a finished run leaves the card where it is until the agent says what
177
+ * happened through the status contract.
178
+ */
179
+ export class RunManager {
180
+ db;
181
+ runtime;
182
+ onStatus;
183
+ statusBaseUrl;
184
+ agentPath;
185
+ ghCommand;
186
+ factsPollMs;
187
+ tokenPublishMs;
188
+ repoRoot;
189
+ retro;
190
+ defaults;
191
+ lead;
192
+ rootFor;
193
+ reviewer;
194
+ redCheckEnabled;
195
+ testsFirstEnabled;
196
+ skills;
197
+ listModels;
198
+ watchdog;
199
+ plannerChoiceEnabled;
200
+ active = new Map();
201
+ statuses = new Map();
202
+ /**
203
+ * Callers waiting for the ticket's current run to end. A conflict resolution
204
+ * is started from a background pass that has to reconcile its own outcome, so
205
+ * it needs the run's ending and the trace the run left behind.
206
+ */
207
+ settleWaiters = new Map();
208
+ /** Stall timestamps, oldest first, for the breaker. */
209
+ stalls = [];
210
+ retry;
211
+ constructor(db, runtime, onStatus, statusBaseUrl, agentPath, ghCommand = "gh", factsPollMs = FACTS_POLL_MS, retry = {}, tokenPublishMs = TOKEN_PUBLISH_MS,
212
+ /** The checkout the board runs in, so a screenshot path resolves from a worktree. */
213
+ repoRoot = process.cwd(),
214
+ /**
215
+ * A separate manager pass that reads a finished run's evidence. Optional:
216
+ * tests and a board without a harness must not spawn one.
217
+ */
218
+ retro, defaults = () => ({ harness: "pi", model: "" }),
219
+ /** The stronger model a stuck verified ticket is sent to before the person. */
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) {
264
+ this.db = db;
265
+ this.runtime = runtime;
266
+ this.onStatus = onStatus;
267
+ this.statusBaseUrl = statusBaseUrl;
268
+ this.agentPath = agentPath;
269
+ this.ghCommand = ghCommand;
270
+ this.factsPollMs = factsPollMs;
271
+ this.tokenPublishMs = tokenPublishMs;
272
+ this.repoRoot = repoRoot;
273
+ this.retro = retro;
274
+ this.defaults = defaults;
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;
284
+ this.retry = { ...DEFAULT_RETRY, ...retry };
285
+ }
286
+ /** Where the harness keeps session files: with the board's own state. */
287
+ get sessionDir() {
288
+ return join(this.repoRoot, ".zelio", "sessions");
289
+ }
290
+ isRunning(ticketId) {
291
+ return this.active.has(ticketId);
292
+ }
293
+ /**
294
+ * Resolves when the ticket's current run has ended, with the status it ended
295
+ * on. Registered immediately after `start`, so the waiter can never miss the
296
+ * run it is about. A retry carries the waiter onto the next attempt, because
297
+ * that is still the same ticket settling.
298
+ */
299
+ whenSettled(ticketId) {
300
+ return new Promise((resolve) => {
301
+ const waiters = this.settleWaiters.get(ticketId) ?? new Set();
302
+ waiters.add(resolve);
303
+ this.settleWaiters.set(ticketId, waiters);
304
+ });
305
+ }
306
+ wakeSettleWaiters(ticketId, status) {
307
+ const waiters = this.settleWaiters.get(ticketId);
308
+ if (!waiters)
309
+ return;
310
+ this.settleWaiters.delete(ticketId);
311
+ for (const waiter of waiters)
312
+ waiter(status);
313
+ }
314
+ runningCount() {
315
+ return this.active.size;
316
+ }
317
+ /** Every run this server knows about, active or just finished. */
318
+ listStatuses() {
319
+ return [...this.statuses.values()];
320
+ }
321
+ /**
322
+ * A restart empties the in-memory run map, so a ticket that was mid-run comes
323
+ * back claiming `in_progress` with no process behind it. A run the restart
324
+ * killed is put back to work as the next attempt in the same worktree: a
325
+ * restart is not a decision to stop, and the work already on the branch is
326
+ * the input to the next attempt. Every other quiet ending is adopted: the
327
+ * process is gone, so the only honest thing left to say is that it never
328
+ * reported, and the ticket itself is not moved — a stall is the person's call.
329
+ */
330
+ async reconcileOrphans(worktreeFor) {
331
+ const adopted = [];
332
+ const restarted = "the server restarted while this ticket was running; the run never reported a status";
333
+ const orphaned = "nothing is running on this ticket; no run reported a status";
334
+ for (const ticket of this.db.listTickets()) {
335
+ if (ticket.state !== "in_progress" || this.active.has(ticket.id))
336
+ continue;
337
+ const latest = this.db.latestAgentRun(ticket.id);
338
+ if (latest?.state === "running" && worktreeFor) {
339
+ // Ticket order is the board's order, and one resume per ticket is the
340
+ // point: starting them in parallel would race the worktree creation.
341
+ // oxlint-disable-next-line no-await-in-loop
342
+ const resumed = await this.resumeInterrupted(ticket, latest, worktreeFor);
343
+ if (resumed) {
344
+ adopted.push(resumed);
345
+ continue;
346
+ }
347
+ }
348
+ // A failure already has a record that explains itself, so only the two
349
+ // quiet endings are rewritten: a run the restart killed, and a run that
350
+ // ended without reporting.
351
+ const error = latest ? restarted : orphaned;
352
+ const quiet = !latest || latest.state === "running" || latest.state === "completed";
353
+ const record = latest && quiet ? (this.db.markRunStalled(latest.id, error) ?? latest) : null;
354
+ const failed = latest?.state === "failed";
355
+ const startedAt = latest ? Date.parse(latest.started_at) : Number.NaN;
356
+ const endedAt = latest?.ended_at ? Date.parse(latest.ended_at) : startedAt;
357
+ const status = {
358
+ ticketId: ticket.id,
359
+ runId: latest?.id ?? "",
360
+ label: failed ? "Run failed" : "No status reported",
361
+ tool: null,
362
+ startedAt: Number.isNaN(startedAt) ? Date.now() : startedAt,
363
+ endedAt: Number.isNaN(endedAt) ? undefined : endedAt,
364
+ phase: failed ? "failed" : "stalled",
365
+ attempt: latest?.attempt ?? 1,
366
+ attempts: this.retry.maxAttempts,
367
+ tail: [],
368
+ error: failed ? (latest?.error ?? error) : (record?.error ?? error),
369
+ ...(latest?.workflow && latest.workflow_stage
370
+ ? { workflow: workflowSummary(latest.workflow_stage, latest.workflow) }
371
+ : {}),
372
+ };
373
+ this.statuses.set(ticket.id, status);
374
+ adopted.push(status);
375
+ }
376
+ return adopted;
377
+ }
378
+ /**
379
+ * The run the restart killed still says `running`, so it is closed as a stall
380
+ * before anything else: history never shows two live runs for one ticket.
381
+ *
382
+ * What happens next depends on whether the run left a session. With one, the
383
+ * same attempt is resumed: the agent keeps its conversation, so a restart
384
+ * costs the interruption and not the work, and the card does not spend an
385
+ * attempt on a lid closing. Without one - a row from before sessions, or an
386
+ * attempt that has used its resumes - the ticket falls back to the next cold
387
+ * attempt in the same worktree, which is what every restart used to do.
388
+ * Attempts are never extended by a restart, and a worktree that cannot be
389
+ * prepared leaves the ticket where it is with a comment saying why.
390
+ */
391
+ async resumeInterrupted(ticket, latest, worktreeFor) {
392
+ const restarted = "the server restarted while this ticket was running; the run never reported a status";
393
+ this.db.markRunStalled(latest.id, restarted);
394
+ const resumes = latest.resume_count;
395
+ const resumable = Boolean(latest.session_id) && resumes < MAX_RESUMES;
396
+ if (!resumable && latest.attempt >= this.retry.maxAttempts) {
397
+ // The budget is spent and this run has nothing left to resume. A restart
398
+ // cannot authorize an attempt the policy does not allow, so the card asks
399
+ // the person instead. Checked before the worktree: a card that is only
400
+ // going to be escalated must not pay for a checkout first.
401
+ this.escalate(ticket.id, latest.attempt);
402
+ return null;
403
+ }
404
+ let worktree;
405
+ try {
406
+ worktree = await worktreeFor(ticket.id);
407
+ }
408
+ catch (cause) {
409
+ this.db.addComment({
410
+ ticket_id: ticket.id,
411
+ type: "system",
412
+ author: "zelio",
413
+ text: `The server restarted while attempt ${latest.attempt} of ${this.retry.maxAttempts} was running, but the ticket could not be resumed: ${cause instanceof Error ? cause.message : "the worktree could not be prepared"}. Nothing is running on it, so start it again once the worktree can be prepared.`,
414
+ });
415
+ return null;
416
+ }
417
+ const current = this.db.getTicket(ticket.id);
418
+ if (!current || current.state !== "in_progress" || this.active.has(ticket.id))
419
+ return null;
420
+ if (resumable) {
421
+ this.db.addComment({
422
+ ticket_id: ticket.id,
423
+ type: "system",
424
+ author: "zelio",
425
+ text: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Resuming it from its last turn.`,
426
+ });
427
+ try {
428
+ await this.begin(ticket, worktree, latest.attempt, {
429
+ prompt: (ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT,
430
+ profile: latest.profile ?? ticket.profile ?? "developer",
431
+ label: "Resumed",
432
+ retry: true,
433
+ sessionId: latest.session_id ?? undefined,
434
+ resumes: resumes + 1,
435
+ resumeEvidence: latest.command_evidence,
436
+ source: latest.job_source,
437
+ command: latest.harness ?? undefined,
438
+ systemPrompt: latest.job_system_prompt ?? undefined,
439
+ originalPrompt: latest.job_prompt ?? undefined,
440
+ });
441
+ return this.statuses.get(ticket.id) ?? null;
442
+ }
443
+ catch {
444
+ // The slot went somewhere else in the meantime; the stall badge stands.
445
+ return null;
446
+ }
447
+ }
448
+ const started = await this.retryNow(ticket.id, worktree, latest.attempt, latest.job_source === "ticket"
449
+ ? undefined
450
+ : {
451
+ prompt: latest.job_prompt ??
452
+ ((ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT),
453
+ profile: latest.profile ?? ticket.profile ?? "developer",
454
+ systemPrompt: latest.job_system_prompt ?? undefined,
455
+ source: latest.job_source,
456
+ command: latest.harness ?? undefined,
457
+ originalPrompt: latest.job_prompt ?? undefined,
458
+ retry: true,
459
+ }, {
460
+ comment: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Retrying in the same worktree.`,
461
+ wip: `wip: attempt ${latest.attempt} was interrupted by a restart`,
462
+ });
463
+ return started ? (this.statuses.get(ticket.id) ?? null) : null;
464
+ }
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) {
579
+ if (this.active.has(ticket.id))
580
+ throw new RunAlreadyActiveError(ticket.id);
581
+ const testsFirstEnabled = this.testsFirstEnabled();
582
+ const resolvedJob = job ?? {
583
+ prompt: buildTicketPrompt(ticket, {
584
+ number: attempt,
585
+ of: this.retry.maxAttempts,
586
+ }, this.db.listComments(ticket.id), absoluteAttachments(this.repoRoot, ticket.attachments)),
587
+ profile: ticket.profile ?? "developer",
588
+ label: attempt > 1 ? `Attempt ${attempt} of ${this.retry.maxAttempts}` : "Starting",
589
+ retry: true,
590
+ source: "ticket",
591
+ };
592
+ // A stored row wins, so an edit on the Agents page is what the next run
593
+ // actually uses. The static profile is only the fallback for a name that
594
+ // predates the table.
595
+ const profile = this.db.getProfile(resolvedJob.profile) ?? profileFor(resolvedJob.profile);
596
+ const defaults = this.defaults();
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 : "");
627
+ // A pi run can seed its own session id before the process starts. Codex
628
+ // returns a thread id instead, so its row stays open until that arrives.
629
+ const seedId = !this.runtime.sessionIdFromHarness?.(command);
630
+ // The workflow belongs to the stage, not to the ticket. Every writer run in
631
+ // In Progress gets it: a first start, a retry, an unblock, a send-back, and
632
+ // a mention. A reviewer reads the Review column's instructions, which is a
633
+ // different list: no checks, and board rules that forbid editing. A conflict
634
+ // repair started from Review is neither, and takes no workflow.
635
+ const stage = resolvedJob.stage ?? "in_progress";
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");
639
+ const workflow = takesWorkflow
640
+ ? this.db.getStageWorkflow(stage)
641
+ : emptyWorkflow();
642
+ const snapshot = hasWorkflow(workflow) ? { stage, workflow } : null;
643
+ // The row carries the conversation, not just the attempt: a resume is given
644
+ // the id it already had, and a fresh run seeds one so the next restart has
645
+ // something to reopen.
646
+ const record = this.db.startAgentRun(ticket.id, attempt, snapshot, {
647
+ id: resolvedJob.sessionId ?? null,
648
+ resumeCount: resolvedJob.resumes ?? 0,
649
+ profile: resolvedJob.profile,
650
+ harness: command,
651
+ model: model || null,
652
+ source: resolvedJob.source,
653
+ prompt: resolvedJob.originalPrompt ?? resolvedJob.prompt,
654
+ systemPrompt: resolvedJob.systemPrompt ?? null,
655
+ seedId,
656
+ });
657
+ const statusToken = randomBytes(24).toString("hex");
658
+ // A verified ticket's developer is told the board checks and publishes: it
659
+ // never commits, pushes or reports Review, so it gets its own doctrine.
660
+ const verified = resolvedJob.profile === "developer" &&
661
+ stage === "in_progress" &&
662
+ !resolvedJob.outsideStage &&
663
+ (ticket.verify ?? []).length > 0;
664
+ const defaultPrompt = verified ? VERIFIED_CODING_AGENT_PROMPT : CODING_AGENT_PROMPT;
665
+ const basePrompt = resolvedJob.systemPrompt ?? defaultPrompt;
666
+ // Empty extra prompt must leave the prompt untouched, including "undefined"
667
+ // so the runtime applies its own default exactly as before. A verified run
668
+ // always names its prompt, because the runtime default is the unverified one.
669
+ const extraPrompt = profile.extraPrompt.trim()
670
+ ? withExtraInstructions(basePrompt, profile.extraPrompt)
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;
682
+ // The repository's own AGENTS.md/CLAUDE.md comes before the workflow: it is
683
+ // the person's standing word on this repo, and it is read at run time, so a
684
+ // change to it takes effect on the next run without touching the board.
685
+ const instructions = profile.touchesRepo
686
+ ? readRepoInstructions(this.rootFor ? this.rootFor(ticket) : this.repoRoot, undefined, this.runtime.instructionFilesFromHarness?.(command) ?? [])
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
+ : [];
693
+ // The workflow section goes last: it closes by restating the board rules no
694
+ // standing instruction may override, so it has to be the final thing the run
695
+ // reads. With nothing configured it is a no-op and the prompt is untouched.
696
+ const systemPrompt = hasWorkflow(workflow) ||
697
+ instructions.text ||
698
+ instructions.loadedByHarness?.length ||
699
+ skills.length > 0
700
+ ? buildRunSystemPrompt(profilePrompt ?? defaultPrompt, stage, workflow, instructions, {
701
+ verified,
702
+ skills,
703
+ })
704
+ : profilePrompt;
705
+ const status = {
706
+ ticketId: ticket.id,
707
+ runId: record.id,
708
+ label: resolvedJob.label ?? "Starting",
709
+ tool: null,
710
+ startedAt: Date.now(),
711
+ phase: "running",
712
+ ...(resolvedJob.profile === "developer" ? { executionPhase: "inspect" } : {}),
713
+ profile: resolvedJob.profile,
714
+ ...(resolvedJob.sourceCommentId ? { requestCommentId: resolvedJob.sourceCommentId } : {}),
715
+ attempt,
716
+ attempts: this.retry.maxAttempts,
717
+ tail: [],
718
+ actions: [],
719
+ ...(snapshot ? { workflow: workflowSummary(stage, workflow) } : {}),
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;
741
+ let run;
742
+ try {
743
+ const boardUrl = this.statusBaseUrl.replace(/\/$/, "");
744
+ const env = {
745
+ ZELIO_TICKET_ID: ticket.id,
746
+ ZELIO_BOARD_URL: boardUrl,
747
+ ZELIO_STATUS_URL: `${boardUrl}/api/tickets/${encodeURIComponent(ticket.id)}/status`,
748
+ ZELIO_TICKET_TOKEN: statusToken,
749
+ };
750
+ if (this.agentPath)
751
+ env.PATH = `${this.agentPath}:${process.env.PATH ?? ""}`;
752
+ // A harness may create its own session directory; making it first costs
753
+ // one syscall and removes the chance that every run fails on a missing
754
+ // parent under `.zelio`.
755
+ const sessionDir = this.sessionDir;
756
+ mkdirSync(sessionDir, { recursive: true });
757
+ const prompt = resolvedJob.profile === "developer" &&
758
+ resolvedJob.source === "ticket" &&
759
+ !resolvedJob.sessionId
760
+ ? `${resolvedJob.prompt}\n\n${buildDeveloperContextPack(worktree.path, ticket)}${phaseBrief ? `\n\n${phaseBrief}` : ""}`
761
+ : resolvedJob.prompt;
762
+ run = this.runtime.spawn(worktree.path, prompt, {
763
+ env,
764
+ thinking: resolvedJob.thinking ?? ticket.thinking ?? profile.thinking,
765
+ model: model || undefined,
766
+ command,
767
+ readOnly: !profile.touchesRepo,
768
+ systemPrompt,
769
+ shellGuard: resolvedJob.profile === "developer",
770
+ reporting: resolvedJob.profile === "developer" && !resolvedJob.outsideStage,
771
+ ...(resolvedJob.profile === "developer" &&
772
+ stage === "in_progress" &&
773
+ !resolvedJob.outsideStage
774
+ ? { continuationPrompt: () => this.continuationPrompt(ticket.id, record.id) }
775
+ : {}),
776
+ // The session lives beside the board's database, never in the person's
777
+ // home directory: a board is one repo, and its conversations go with it.
778
+ sessionId: record.session_id ?? (seedId ? record.id : undefined),
779
+ sessionDir,
780
+ });
781
+ }
782
+ catch (cause) {
783
+ const error = cause instanceof Error ? cause.message : "the agent could not start";
784
+ this.finishRecord(record.id, "failed", null, null, null, error);
785
+ const failed = {
786
+ ...status,
787
+ label: "Run failed",
788
+ phase: "failed",
789
+ endedAt: Date.now(),
790
+ error,
791
+ };
792
+ this.statuses.set(ticket.id, failed);
793
+ this.onStatus(failed);
794
+ return failed;
795
+ }
796
+ const active = {
797
+ run,
798
+ job: resolvedJob,
799
+ command,
800
+ status,
801
+ statusToken,
802
+ testsFirstEnabled,
803
+ startHead: worktreeHead(worktree.path),
804
+ cancelled: false,
805
+ settled: false,
806
+ continuations: 0,
807
+ emittedCommits: new Set(),
808
+ emittedPrUrl: null,
809
+ output: [],
810
+ partial: "",
811
+ actions: [],
812
+ toolCalls: new Map(),
813
+ commandEvidence: [...(resolvedJob.resumeEvidence ?? [])],
814
+ developerCommandEvidence: [],
815
+ checks: stage === "in_progress" && !resolvedJob.outsideStage
816
+ ? workflow.checks.map((check) => ({ label: check.label, command: check.command }))
817
+ : [],
818
+ verifyRounds: 0,
819
+ handoffRounds: 0,
820
+ verified: ticket.verify.length > 0,
821
+ repeat: { key: "", count: 0 },
822
+ nudged: false,
823
+ redSentBack: false,
824
+ startTree,
825
+ idleSentBack: false,
826
+ testsPhase,
827
+ approved: testsPhase === "implement" ? (approved?.tests ?? null) : null,
828
+ gating: false,
829
+ gateAbort: new AbortController(),
830
+ worktreePath: worktree.path,
831
+ tokens: null,
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
+ : {}),
855
+ };
856
+ if (active.commandEvidence.length)
857
+ this.db.recordCommandEvidence(record.id, active.commandEvidence);
858
+ this.active.set(ticket.id, active);
859
+ this.statuses.set(ticket.id, status);
860
+ this.onStatus(status);
861
+ void this.execute(ticket.id, worktree, record.id, active);
862
+ return status;
863
+ }
864
+ async continuationPrompt(ticketId, runId) {
865
+ await this.evidenceCaughtUp(ticketId, runId);
866
+ const gate = await this.completionGate(ticketId, runId, false);
867
+ if (gate.kind === "completed" || gate.kind === "escalated")
868
+ return undefined;
869
+ if (gate.kind === "continue") {
870
+ const current = this.active.get(ticketId);
871
+ if (current?.status.runId === runId) {
872
+ this.update(ticketId, current, {
873
+ label: gate.label ?? `Fixing checks (round ${current.verifyRounds}/${MAX_VERIFY_ROUNDS})`,
874
+ tool: null,
875
+ });
876
+ }
877
+ return gate.prompt;
878
+ }
879
+ const active = this.active.get(ticketId);
880
+ if (!active ||
881
+ active.status.runId !== runId ||
882
+ active.cancelled ||
883
+ active.settled ||
884
+ active.continuations >= MAX_TURN_CONTINUATIONS ||
885
+ this.db.getTicket(ticketId)?.state !== "in_progress")
886
+ return undefined;
887
+ active.continuations += 1;
888
+ this.update(ticketId, active, {
889
+ label: `Continuing (${active.continuations}/${MAX_TURN_CONTINUATIONS})`,
890
+ tool: null,
891
+ });
892
+ return CONTINUATION_PROMPT;
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
+ }
911
+ /**
912
+ * The board's own completion check for a verified In Progress ticket. The
913
+ * ticket's verify commands and the stage checks run in the worktree; when they
914
+ * pass, the board commits, pushes, opens the pull request and records the
915
+ * result. Anything else is a skip, which leaves the run to the ordinary flow.
916
+ */
917
+ async completionGate(ticketId, runId, final) {
918
+ const active = this.active.get(ticketId);
919
+ const ticket = this.db.getTicket(ticketId);
920
+ const job = active?.job;
921
+ if (!active ||
922
+ !ticket ||
923
+ !job ||
924
+ active.status.runId !== runId ||
925
+ active.cancelled ||
926
+ active.settled ||
927
+ active.gating ||
928
+ job.profile !== "developer" ||
929
+ job.outsideStage ||
930
+ (job.stage ?? "in_progress") !== "in_progress" ||
931
+ ticket.state !== "in_progress" ||
932
+ ticket.verify.length === 0)
933
+ return { kind: "skip" };
934
+ active.gating = true;
935
+ this.update(ticketId, active, { label: "Verifying", tool: null });
936
+ try {
937
+ return await this.verifyTicket(ticketId, runId, active, ticket, final);
938
+ }
939
+ catch (cause) {
940
+ const message = cause instanceof Error ? cause.message : String(cause);
941
+ this.db.addComment({
942
+ ticket_id: ticketId,
943
+ type: "system",
944
+ author: "zelio",
945
+ text: `The board could not verify this run: ${message}`,
946
+ });
947
+ return { kind: "skip" };
948
+ }
949
+ finally {
950
+ active.gating = false;
951
+ }
952
+ }
953
+ async verifyTicket(ticketId, runId, active, ticket, final) {
954
+ const cwd = active.worktreePath;
955
+ const max = MAX_VERIFY_ROUNDS;
956
+ if (active.testsPhase === "tests")
957
+ return this.testsGate(ticketId, runId, active, ticket, final);
958
+ const changed = await hasTicketChanges(cwd);
959
+ if (!this.isLive(ticketId, active))
960
+ return { kind: "skip" };
961
+ if (!changed) {
962
+ return this.failRound(ticketId, runId, active, final, {
963
+ prompt: NO_CHANGES_PROMPT,
964
+ summary: "no changes for the ticket",
965
+ blocked: {
966
+ summary: `The ticket still has no changes after ${max} verification rounds.`,
967
+ reason: `the worktree still has no changes for the ticket after ${max} verification rounds`,
968
+ unblock: "Implement the ticket so its Verify commands pass, then mention @developer to continue.",
969
+ detail: "",
970
+ },
971
+ });
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
+ }
1053
+ const checks = [...ticket.verify, ...active.checks];
1054
+ const env = this.agentPath
1055
+ ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
1056
+ : process.env;
1057
+ const results = await runChecks(cwd, checks, {
1058
+ env,
1059
+ signal: active.gateAbort.signal,
1060
+ rerunFailed: true,
1061
+ });
1062
+ if (!this.isLive(ticketId, active))
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
+ }
1071
+ for (const result of results.filter((item) => item.flaky)) {
1072
+ this.db.addComment({
1073
+ ticket_id: ticketId,
1074
+ type: "system",
1075
+ author: "zelio",
1076
+ text: `Check "${result.label}" failed once and passed on rerun, so the board counted it as passed. It looks flaky: \`${result.command}\`.`,
1077
+ });
1078
+ }
1079
+ for (const result of results) {
1080
+ active.commandEvidence.push({
1081
+ id: randomUUID(),
1082
+ command: result.command,
1083
+ outcome: result.passed ? "passed" : "failed",
1084
+ revision: null,
1085
+ });
1086
+ }
1087
+ active.commandEvidence = active.commandEvidence.slice(-64);
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 });
1093
+ const failed = results.find((result) => !result.passed);
1094
+ if (failed) {
1095
+ const detail = failureReport(results);
1096
+ const fingerprint = await worktreeFingerprint(cwd);
1097
+ if (!this.isLive(ticketId, active))
1098
+ return { kind: "skip" };
1099
+ return this.failRound(ticketId, runId, active, final, {
1100
+ prompt: `${VERIFY_FAILED_PROMPT}\n\n${detail}`,
1101
+ summary: failed.timedOut ? `${failed.label} timed out` : failed.label,
1102
+ outcome: failed.timedOut ? "Check timed out" : "Check failed",
1103
+ check: failed.label,
1104
+ fingerprint,
1105
+ blocked: {
1106
+ summary: `The board's checks still fail after ${max} rounds.`,
1107
+ reason: `Check "${failed.label}" still fails after ${max} verification rounds: ${failed.command}`,
1108
+ unblock: "Fix the failing check or correct the ticket's verify commands, then mention @developer to continue.",
1109
+ detail,
1110
+ },
1111
+ });
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" };
1165
+ const branch = ticket.branch?.trim() || (await currentBranch(cwd));
1166
+ if (!this.isLive(ticketId, active))
1167
+ return { kind: "skip" };
1168
+ const commit = await commitTicketWork(cwd, commitMessage(ticket.title, branch));
1169
+ if (!this.isLive(ticketId, active))
1170
+ return { kind: "skip" };
1171
+ if (commit.error) {
1172
+ const hook = `The commit hook failed:\n\n\`\`\`text\n${commit.error}\n\`\`\``;
1173
+ return this.failRound(ticketId, runId, active, final, {
1174
+ prompt: `${VERIFY_FAILED_PROMPT}\n\n${hook}`,
1175
+ summary: "the commit hook failed",
1176
+ blocked: {
1177
+ summary: `The commit hook still fails after ${max} rounds.`,
1178
+ reason: `The commit hook still fails after ${max} verification rounds`,
1179
+ unblock: "Fix the commit hook failure, then mention @developer to continue.",
1180
+ detail: hook,
1181
+ },
1182
+ });
1183
+ }
1184
+ const prBody = [
1185
+ `## Goal\n\n${ticket.goal.trim() || ticket.title}`,
1186
+ `## Acceptance\n\n${ticket.acceptance.trim() || "See the ticket."}`,
1187
+ [
1188
+ "## Verified by Zelio",
1189
+ ...results.map((result) => `- ${result.label}: \`${result.command}\` — passed in ${seconds(result.durationMs)}s`),
1190
+ ].join("\n"),
1191
+ ].join("\n\n");
1192
+ const publish = branch
1193
+ ? await publishBranch(cwd, branch, { title: ticket.title, body: prBody }, { gh: this.ghCommand })
1194
+ : { pushed: false, prUrl: null, error: "the worktree is not on a branch" };
1195
+ if (!this.isLive(ticketId, active))
1196
+ return { kind: "skip" };
1197
+ const summary = [
1198
+ `Verified by the board: ${results.length} ${results.length === 1 ? "check" : "checks"} passed.`,
1199
+ publish.prUrl ? `Pull request: ${publish.prUrl}.` : "",
1200
+ publish.error
1201
+ ? `Publishing failed: ${publish.error}. The work is committed on ${branch} at ${commit.head?.slice(0, 7) ?? "an unknown commit"}.`
1202
+ : "",
1203
+ commit.refused.length ? `Not committed (secret-looking): ${commit.refused.join(", ")}.` : "",
1204
+ ]
1205
+ .filter(Boolean)
1206
+ .join(" ");
1207
+ const report = {
1208
+ outcome: "ready_for_review",
1209
+ summary,
1210
+ required_evidence: results.map((result) => ({
1211
+ requirement: result.label,
1212
+ result: "met",
1213
+ evidence: `exit 0 in ${seconds(result.durationMs)}s`,
1214
+ command: result.command,
1215
+ })),
1216
+ remaining_assurance: [],
1217
+ };
1218
+ this.db.recordAgentResult(runId, report, resultComment(report));
1219
+ if (publish.prUrl)
1220
+ this.db.setPullRequest(ticketId, publish.prUrl);
1221
+ active.settled = true;
1222
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1223
+ return { kind: "completed" };
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
+ }
1466
+ /** One failed round: send the run back while rounds remain, otherwise block the ticket. */
1467
+ failRound(ticketId, runId, active, final, round) {
1468
+ const rounds = round.handoffOnly ? ++active.handoffRounds : ++active.verifyRounds;
1469
+ // The same check failing again on work that did not change is the developer
1470
+ // repeating itself: the lead is asked now, not after the rounds run out.
1471
+ const previous = active.lastFailure;
1472
+ const repeated = round.check !== undefined &&
1473
+ round.fingerprint != null &&
1474
+ previous?.check === round.check &&
1475
+ previous.fingerprint === round.fingerprint;
1476
+ active.lastFailure =
1477
+ round.check === undefined
1478
+ ? undefined
1479
+ : { check: round.check, fingerprint: round.fingerprint ?? null };
1480
+ const exhausted = rounds > MAX_VERIFY_ROUNDS;
1481
+ if (exhausted || repeated) {
1482
+ const { blocked } = round;
1483
+ const current = this.db.getTicket(ticketId);
1484
+ if (current && this.canConsultLead(current)) {
1485
+ active.leadRequest = {
1486
+ trigger: "checks_failing",
1487
+ reason: exhausted
1488
+ ? blocked.reason
1489
+ : `Check "${round.check}" failed again and the work did not change between the rounds.`,
1490
+ failure: blocked.detail,
1491
+ };
1492
+ active.settled = true;
1493
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
1494
+ return { kind: "escalated" };
1495
+ }
1496
+ }
1497
+ if (exhausted) {
1498
+ const { blocked } = round;
1499
+ const current = this.db.getTicket(ticketId);
1500
+ const report = {
1501
+ outcome: "blocked",
1502
+ summary: blocked.summary,
1503
+ required_evidence: [],
1504
+ remaining_assurance: [],
1505
+ reason: `${current ? this.leadLimitNote(current) : ""}${blocked.reason}`,
1506
+ unblock: blocked.unblock,
1507
+ };
1508
+ const text = [resultComment(report), blocked.detail].filter(Boolean).join("\n\n");
1509
+ this.db.recordAgentResult(runId, report, text);
1510
+ active.settled = true;
1511
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1512
+ return { kind: "escalated" };
1513
+ }
1514
+ // After the process has gone there is no session to send the prompt to.
1515
+ if (final)
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
+ };
1525
+ }
1526
+ /** Counts identical tool calls in a row; the fourth one sends the nudge, once per run. */
1527
+ noteRepeat(active, tool, args) {
1528
+ if (!active.verified || active.nudged || !active.run.sendMessage)
1529
+ return;
1530
+ const key = `${tool} ${stableJson(args)}`;
1531
+ active.repeat = { key, count: active.repeat.key === key ? active.repeat.count + 1 : 1 };
1532
+ if (active.repeat.count < REPEAT_NUDGE_AT)
1533
+ return;
1534
+ active.nudged = true;
1535
+ void active.run.sendMessage(REPEAT_NUDGE).catch(() => false);
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
+ }
1723
+ isLive(ticketId, active) {
1724
+ return (this.active.get(ticketId) === active &&
1725
+ !active.cancelled &&
1726
+ !active.settled &&
1727
+ this.db.getTicket(ticketId)?.state === "in_progress");
1728
+ }
1729
+ cancel(ticketId) {
1730
+ const active = this.active.get(ticketId);
1731
+ if (!active)
1732
+ return false;
1733
+ active.cancelled = true;
1734
+ this.update(ticketId, active, { label: "Cancelling", tool: null });
1735
+ active.gateAbort.abort();
1736
+ active.run.abort();
1737
+ return true;
1738
+ }
1739
+ /**
1740
+ * The agent said what happened, so the process has done its job. Stop it
1741
+ * without recording a user cancellation; the ticket move is the record.
1742
+ */
1743
+ settle(ticketId) {
1744
+ const active = this.active.get(ticketId);
1745
+ if (!active || active.settled || active.cancelled)
1746
+ return false;
1747
+ active.settled = true;
1748
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1749
+ active.run.abort();
1750
+ return true;
1751
+ }
1752
+ async reportResult(ticketId, report) {
1753
+ const active = this.active.get(ticketId);
1754
+ if (!active || active.cancelled || active.job.outsideStage || active.job.stage === "review") {
1755
+ return { ok: false, error: "no writable ticket run is accepting results" };
1756
+ }
1757
+ if (report.outcome === "ready_for_review" &&
1758
+ (this.db.getTicket(ticketId)?.verify.length ?? 0) > 0) {
1759
+ return {
1760
+ ok: false,
1761
+ error: "This ticket is verified by the board. End your turn instead: the board runs its checks and, if they pass, commits, pushes, opens the pull request and moves the ticket to Review. Do not report Review yourself.",
1762
+ };
1763
+ }
1764
+ const recorded = this.db.getAgentRun(active.status.runId)?.result_report;
1765
+ if (recorded) {
1766
+ const ticket = this.db.getTicket(ticketId);
1767
+ return JSON.stringify(recorded) === JSON.stringify(report) && ticket
1768
+ ? { ok: true, ticket }
1769
+ : { ok: false, error: "this run already accepted a different result" };
1770
+ }
1771
+ if (active.settled || this.db.getTicket(ticketId)?.state !== "in_progress") {
1772
+ return { ok: false, error: "this run is no longer In Progress" };
1773
+ }
1774
+ if (report.outcome === "ready_for_review") {
1775
+ const revision = await evidenceRevision(active.worktreePath);
1776
+ if (!revision)
1777
+ return {
1778
+ ok: false,
1779
+ error: "could not identify current worktree inputs; verification evidence cannot be confirmed",
1780
+ };
1781
+ for (const item of report.required_evidence) {
1782
+ if (!item.command)
1783
+ continue;
1784
+ const command = stripWorktreeCd(item.command);
1785
+ const observed = active.commandEvidence.findLast((entry) => entry.command === command);
1786
+ if (!observed || observed.outcome !== "passed" || observed.revision !== revision) {
1787
+ return {
1788
+ ok: false,
1789
+ error: `No current passed evidence for: ${command}. A running, failed, stale, or unobserved command cannot establish this requirement. Continue the required implementation/verification.`,
1790
+ };
1791
+ }
1792
+ }
1793
+ }
1794
+ // Hashing yields; cancellation or another accepted report must still win.
1795
+ if (this.active.get(ticketId) !== active ||
1796
+ active.cancelled ||
1797
+ active.settled ||
1798
+ this.db.getTicket(ticketId)?.state !== "in_progress") {
1799
+ return { ok: false, error: "the run changed while this result was being validated" };
1800
+ }
1801
+ if (report.outcome === "blocked") {
1802
+ // A verified ticket's blocker goes to the lead first; the run ends here
1803
+ // either way, so the developer's report becomes the lead's question.
1804
+ const current = this.db.getTicket(ticketId);
1805
+ if (current && this.canConsultLead(current)) {
1806
+ this.db.addComment({
1807
+ ticket_id: ticketId,
1808
+ type: "comment",
1809
+ author: active.job.profile || "developer",
1810
+ text: resultComment(report),
1811
+ run_id: active.status.runId,
1812
+ });
1813
+ active.leadRequest = {
1814
+ trigger: "developer_blocked",
1815
+ reason: report.reason ?? report.summary,
1816
+ failure: report.unblock ?? "",
1817
+ };
1818
+ active.settled = true;
1819
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
1820
+ return { ok: true, ticket: current, escalated: true };
1821
+ }
1822
+ }
1823
+ const ticket = this.db.recordAgentResult(active.status.runId, report, resultComment(report));
1824
+ active.settled = true;
1825
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1826
+ // Let the reporting tool receive its receipt; tool_end/settled then stops the process.
1827
+ return { ok: true, ticket };
1828
+ }
1829
+ /** Current-run verification only; a successful command is not acceptance by itself. */
1830
+ recordVerification(ticketId, evidence) {
1831
+ const active = this.active.get(ticketId);
1832
+ if (!active)
1833
+ return false;
1834
+ if (evidence.outcome === "passed" &&
1835
+ !active.actions.some((action) => action.tool === "bash" &&
1836
+ action.state === "done" &&
1837
+ action.detail.includes(evidence.command.trim()))) {
1838
+ return false;
1839
+ }
1840
+ active.verification = evidence;
1841
+ return true;
1842
+ }
1843
+ reviewVerification(ticketId) {
1844
+ return this.active.get(ticketId)?.verification;
1845
+ }
1846
+ runStartedAt(ticketId) {
1847
+ return this.active.get(ticketId)?.status.startedAt;
1848
+ }
1849
+ /** A status token only belongs to the one run it was minted for. */
1850
+ verifyStatusToken(ticketId, token) {
1851
+ const expected = this.active.get(ticketId)?.statusToken;
1852
+ if (!expected || !token || expected.length !== token.length)
1853
+ return false;
1854
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(token));
1855
+ }
1856
+ /** Deliver only when the current run belongs to the mentioned profile and its adapter accepts steering. */
1857
+ async sendMessage(ticketId, profile, text, commentId) {
1858
+ const active = this.active.get(ticketId);
1859
+ if (!active ||
1860
+ active.status.profile !== profile ||
1861
+ active.status.phase !== "running" ||
1862
+ active.cancelled ||
1863
+ active.settled ||
1864
+ !active.run.sendMessage)
1865
+ return false;
1866
+ try {
1867
+ const accepted = await active.run.sendMessage(text);
1868
+ if (accepted) {
1869
+ if (this.active.get(ticketId) === active &&
1870
+ active.status.phase === "running" &&
1871
+ !active.cancelled &&
1872
+ !active.settled) {
1873
+ this.update(ticketId, active, { requestCommentId: commentId });
1874
+ }
1875
+ }
1876
+ return accepted;
1877
+ }
1878
+ catch {
1879
+ return false;
1880
+ }
1881
+ }
1882
+ activeIdentity(ticketId) {
1883
+ const active = this.active.get(ticketId);
1884
+ return active
1885
+ ? { profile: active.status.profile ?? "agent", runId: active.status.runId }
1886
+ : null;
1887
+ }
1888
+ tailOf(active) {
1889
+ const partial = outputLine(active.partial);
1890
+ return [...active.output, ...(partial ? [partial] : [])].slice(-TAIL_LINES);
1891
+ }
1892
+ publishOutput(ticketId, active) {
1893
+ if (active.outputTimer) {
1894
+ clearTimeout(active.outputTimer);
1895
+ active.outputTimer = undefined;
1896
+ }
1897
+ this.update(ticketId, active, { tail: this.tailOf(active) });
1898
+ }
1899
+ appendLine(ticketId, active, line) {
1900
+ const text = outputLine(line);
1901
+ if (!text)
1902
+ return;
1903
+ active.output.push(text);
1904
+ active.output = active.output.slice(-OUTPUT_LINES);
1905
+ this.publishOutput(ticketId, active);
1906
+ }
1907
+ appendText(ticketId, active, text) {
1908
+ active.partial += text;
1909
+ const lines = active.partial.split("\n");
1910
+ // A file being printed without a newline must not grow without bound; the
1911
+ // part that matters is the end, which is what a terminal would show.
1912
+ active.partial = (lines.pop() ?? "").slice(-2000);
1913
+ for (const line of lines) {
1914
+ const clipped = outputLine(line);
1915
+ if (clipped)
1916
+ active.output.push(clipped);
1917
+ }
1918
+ active.output = active.output.slice(-OUTPUT_LINES);
1919
+ if (lines.length > 0) {
1920
+ this.publishOutput(ticketId, active);
1921
+ return;
1922
+ }
1923
+ if (active.outputTimer)
1924
+ return;
1925
+ active.outputTimer = setTimeout(() => {
1926
+ active.outputTimer = undefined;
1927
+ this.publishOutput(ticketId, active);
1928
+ }, OUTPUT_DELAY_MS);
1929
+ }
1930
+ update(ticketId, active, patch) {
1931
+ active.status = { ...active.status, ...patch };
1932
+ this.statuses.set(ticketId, active.status);
1933
+ this.onStatus(active.status);
1934
+ }
1935
+ /**
1936
+ * Send the total so far to the board and write it to the run row. The row
1937
+ * matters as much as the stream: reopening the ticket, or reloading the tab,
1938
+ * reads the stored row rather than replaying events it never saw.
1939
+ */
1940
+ publishTokens(ticketId, runId, active) {
1941
+ active.tokenTimer = undefined;
1942
+ if (!active.tokens)
1943
+ return;
1944
+ this.db.updateAgentRunTokens(runId, active.tokens, active.tokens.cost);
1945
+ this.update(ticketId, active, { tokens: active.tokens });
1946
+ }
1947
+ /**
1948
+ * Commits and pull requests are facts the runtime can observe, so they land
1949
+ * in the timeline even if the agent forgot to say them in a comment.
1950
+ */
1951
+ recordFacts(ticketId, facts, active) {
1952
+ for (const commit of facts.commits) {
1953
+ if (active.emittedCommits.has(commit.sha))
1954
+ continue;
1955
+ active.emittedCommits.add(commit.sha);
1956
+ this.db.addComment({
1957
+ ticket_id: ticketId,
1958
+ type: "system",
1959
+ author: "git",
1960
+ text: `Committed ${commit.sha.slice(0, 7)} ${commit.subject} on ${facts.branch ?? "the ticket branch"}`,
1961
+ });
1962
+ }
1963
+ if (facts.prUrl && facts.prUrl !== active.emittedPrUrl) {
1964
+ active.emittedPrUrl = facts.prUrl;
1965
+ this.db.setPullRequest(ticketId, facts.prUrl);
1966
+ const text = `Pull request opened: ${facts.prUrl}`;
1967
+ // Run-local state resets on retries, resumes, and server restarts. The
1968
+ // timeline is the durable record of which PRs were already announced.
1969
+ const announced = this.db
1970
+ .listComments(ticketId)
1971
+ .some((comment) => comment.type === "system" && comment.text === text);
1972
+ if (!announced) {
1973
+ this.db.addComment({
1974
+ ticket_id: ticketId,
1975
+ type: "system",
1976
+ author: "github",
1977
+ text,
1978
+ });
1979
+ }
1980
+ }
1981
+ }
1982
+ async captureFacts(ticketId, worktree, active) {
1983
+ // A conflict repair commits a merge, not the ticket's work: "Committed …"
1984
+ // and "Pull request opened …" would describe a PR that already existed.
1985
+ if (active.job.outsideStage)
1986
+ return;
1987
+ try {
1988
+ const facts = await captureRunFacts(worktree.path, active.startHead, this.ghCommand);
1989
+ this.recordFacts(ticketId, facts, active);
1990
+ }
1991
+ catch {
1992
+ // Facts are an observation, not a reason to fail the run.
1993
+ }
1994
+ }
1995
+ /** One poll at a time: an in-flight capture already describes the worktree. */
1996
+ pollFacts(ticketId, worktree, active) {
1997
+ if (active.factsPoll)
1998
+ return active.factsPoll;
1999
+ active.factsPoll = this.captureFacts(ticketId, worktree, active).finally(() => {
2000
+ active.factsPoll = undefined;
2001
+ });
2002
+ return active.factsPoll;
2003
+ }
2004
+ /**
2005
+ * The run is over, so let any in-flight poll land and then read the worktree
2006
+ * once more: a commit made just before exit could predate that poll.
2007
+ */
2008
+ async finalFacts(ticketId, worktree, active) {
2009
+ await active.factsPoll;
2010
+ await this.captureFacts(ticketId, worktree, active);
2011
+ }
2012
+ finishRecord(runId, state, exitCode, gitStatus, gitDiff, error, tokens = null) {
2013
+ this.db.finishAgentRun(runId, {
2014
+ state,
2015
+ exit_code: exitCode,
2016
+ git_status: gitStatus,
2017
+ git_diff: gitDiff,
2018
+ error,
2019
+ input_tokens: tokens?.input ?? null,
2020
+ output_tokens: tokens?.output ?? null,
2021
+ cost: tokens?.cost ?? null,
2022
+ });
2023
+ }
2024
+ /**
2025
+ * Ask the separate manager pass whether this run's evidence argues for a
2026
+ * better standing instruction. Gated by deterministic waste signals so a
2027
+ * clean run costs nothing; the result is a note on the ticket, never a
2028
+ * workflow edit.
2029
+ */
2030
+ reviewRun(ticketId, runId, state, attempt, actions, durationMs, harness) {
2031
+ if (!this.retro)
2032
+ return;
2033
+ // The trace keeps 12 rows; the full history is what shows repeated reads
2034
+ // and guard blocks, so the manager reads every call the run recorded.
2035
+ const details = wasteSignalDetails(actions, durationMs, this.db.listToolCalls(runId));
2036
+ if (details.length === 0)
2037
+ return;
2038
+ const signals = details.map((signal) => signal.text);
2039
+ const signalCauses = Object.fromEntries(details.map((signal) => [signal.text, signal.cause]));
2040
+ const record = this.db.latestAgentRun(ticketId);
2041
+ const workflow = record?.workflow ?? emptyWorkflow();
2042
+ void this.retro({
2043
+ ticketId,
2044
+ state,
2045
+ attempt,
2046
+ durationMs,
2047
+ actions,
2048
+ workflow,
2049
+ signals,
2050
+ signalCauses,
2051
+ harness,
2052
+ })
2053
+ .then((result) => {
2054
+ if (!result)
2055
+ return;
2056
+ const evidence = result.evidence.length > 0 ? result.evidence : signals;
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({
2062
+ ticket_id: ticketId,
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 } : {}),
2077
+ });
2078
+ })
2079
+ // A manager that fails is a missing note, not a failed run.
2080
+ .catch(() => { });
2081
+ }
2082
+ async execute(ticketId, worktree, runId, active) {
2083
+ let exitCode = null;
2084
+ let stderr = "";
2085
+ let timedOut = false;
2086
+ let spawnError = false;
2087
+ let error = null;
2088
+ const factsTimer = setInterval(() => {
2089
+ void this.pollFacts(ticketId, worktree, active);
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;
2096
+ try {
2097
+ for await (const event of active.run.events) {
2098
+ if (event.type === "tool_start") {
2099
+ if (active.executionPhase) {
2100
+ active.executionPhase = phaseForTool(active.executionPhase, event.tool, event.args);
2101
+ }
2102
+ // The label already says what is starting, so the tail stays output:
2103
+ // the assistant's prose and whatever the command prints.
2104
+ active.actions = startAction(active.actions, {
2105
+ tool: event.tool,
2106
+ label: event.label,
2107
+ detail: actionDetail(event.tool, event.args),
2108
+ callId: event.callId,
2109
+ });
2110
+ this.noteRepeat(active, event.tool, event.args);
2111
+ const id = active.actions.at(-1)?.id;
2112
+ if (id) {
2113
+ const args = event.args;
2114
+ active.toolCalls.set(id, {
2115
+ output: "",
2116
+ tool: event.tool,
2117
+ detail: actionDetail(event.tool, event.args),
2118
+ path: actionPath(event.tool, event.args),
2119
+ startedAt: Date.now(),
2120
+ ...(event.tool === "bash" &&
2121
+ typeof args?.command === "string" &&
2122
+ args.command.length <= 3_000
2123
+ ? { command: stripWorktreeCd(args.command) }
2124
+ : {}),
2125
+ });
2126
+ }
2127
+ this.update(ticketId, active, {
2128
+ label: event.label,
2129
+ tool: event.tool,
2130
+ actions: active.actions,
2131
+ ...(active.executionPhase ? { executionPhase: active.executionPhase } : {}),
2132
+ });
2133
+ }
2134
+ else if (event.type === "tool_output") {
2135
+ // Only the failed row keeps this; the cap is the memory the run pays
2136
+ // for evidence it may never need.
2137
+ const id = event.callId ??
2138
+ active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
2139
+ const call = id ? active.toolCalls.get(id) : undefined;
2140
+ if (call)
2141
+ call.output = (call.output + event.text).slice(-MAX_ACTION_OUTPUT);
2142
+ this.appendText(ticketId, active, event.text);
2143
+ }
2144
+ else if (event.type === "tool_end") {
2145
+ if (active.executionPhase) {
2146
+ active.executionPhase = phaseForTool(active.executionPhase, "", {}, event.isError);
2147
+ }
2148
+ const id = event.callId ??
2149
+ active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
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";
2157
+ active.actions = finishAction(active.actions, {
2158
+ isError: callFailed,
2159
+ output: call?.output,
2160
+ callId: id,
2161
+ });
2162
+ // The full history keeps every completed call, not just the trace's
2163
+ // tail. A refused bash command is still a call, marked as blocked.
2164
+ const endedAt = Date.now();
2165
+ this.db.recordToolCall({
2166
+ runId,
2167
+ tool: call?.tool ?? event.tool,
2168
+ detail: call?.detail ?? "",
2169
+ path: call?.path ?? null,
2170
+ state: callFailed ? "failed" : "done",
2171
+ blocked: event.isError && bashGuardBlockedReader(call?.output) !== null,
2172
+ startedAt: call?.startedAt ?? endedAt,
2173
+ endedAt,
2174
+ output: call?.output,
2175
+ });
2176
+ if (call?.command && id) {
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 = {
2185
+ id,
2186
+ command: call.command,
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;
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
+ }
2224
+ active.commandEvidence = active.commandEvidence.slice(-64);
2225
+ this.db.recordCommandEvidence(runId, active.commandEvidence);
2226
+ }
2227
+ if (id)
2228
+ active.toolCalls.delete(id);
2229
+ this.update(ticketId, active, {
2230
+ label: "Thinking",
2231
+ tool: null,
2232
+ actions: active.actions,
2233
+ ...(active.executionPhase ? { executionPhase: active.executionPhase } : {}),
2234
+ });
2235
+ const reported = event.tool === "report_result" ||
2236
+ (event.tool === "bash" && /\bzelio\s+ticket\s+report\b/.test(call?.command ?? ""));
2237
+ if (active.settled && !active.cancelled && reported)
2238
+ active.run.abort();
2239
+ }
2240
+ else if (event.type === "settled") {
2241
+ if (active.settled && !active.cancelled)
2242
+ active.run.abort();
2243
+ }
2244
+ else if (event.type === "text") {
2245
+ this.appendText(ticketId, active, event.text);
2246
+ }
2247
+ else if (event.type === "session") {
2248
+ this.db.setAgentRunSessionId(runId, event.id);
2249
+ }
2250
+ else if (event.type === "usage") {
2251
+ // The harness may report usage more than once per run; the run is the
2252
+ // sum of what it said, never a guess from the transcript.
2253
+ active.tokens = {
2254
+ input: (active.tokens?.input ?? 0) + event.input,
2255
+ output: (active.tokens?.output ?? 0) + event.output,
2256
+ // A harness that reports no price on one message must not erase the
2257
+ // prices it did report: silence is null, and null plus a number is
2258
+ // that number.
2259
+ cost: event.cost === null
2260
+ ? (active.tokens?.cost ?? null)
2261
+ : (active.tokens?.cost ?? 0) + event.cost,
2262
+ };
2263
+ // Publish on a timer instead of per message: one report is a turn,
2264
+ // not a number a person needs to see change mid-sentence.
2265
+ if (!active.tokenTimer) {
2266
+ active.tokenTimer = setTimeout(() => {
2267
+ this.publishTokens(ticketId, runId, active);
2268
+ }, this.tokenPublishMs);
2269
+ }
2270
+ }
2271
+ else if (event.type === "exit") {
2272
+ exitCode = event.code;
2273
+ stderr = event.stderr;
2274
+ timedOut = event.timedOut;
2275
+ spawnError = event.spawnError === true;
2276
+ }
2277
+ }
2278
+ }
2279
+ catch (cause) {
2280
+ error = cause instanceof Error ? cause.message : "the agent run failed";
2281
+ }
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
+ }
2297
+ if (active.tokenTimer) {
2298
+ clearTimeout(active.tokenTimer);
2299
+ active.tokenTimer = undefined;
2300
+ }
2301
+ let gitStatus = null;
2302
+ let gitDiff = null;
2303
+ try {
2304
+ const captured = await captureWorktree(worktree.path, active.startHead);
2305
+ gitStatus = captured.status;
2306
+ gitDiff = captured.diff;
2307
+ }
2308
+ catch (cause) {
2309
+ error ??= `could not capture the worktree diff: ${cause instanceof Error ? cause.message : "git failed"}`;
2310
+ }
2311
+ await this.finalFacts(ticketId, worktree, active);
2312
+ if (active.outputTimer) {
2313
+ clearTimeout(active.outputTimer);
2314
+ active.outputTimer = undefined;
2315
+ }
2316
+ const cancelled = active.cancelled;
2317
+ // A settled run is the agent saying it is done, so the SIGTERM that follows
2318
+ // is our own abort. Its exit code describes how we stopped pi, not how the
2319
+ // work went: a clean run would otherwise be recorded as `failed` with
2320
+ // "the agent exited with code 143".
2321
+ const stoppedByUs = active.settled || cancelled;
2322
+ const cleanExit = stoppedByUs || exitCode === null || exitCode === 0;
2323
+ const failed = !cancelled && (error !== null || timedOut || spawnError || !cleanExit);
2324
+ if (!cancelled && failed) {
2325
+ error ??= spawnError
2326
+ ? "the harness could not start"
2327
+ : timedOut
2328
+ ? "the agent timed out"
2329
+ : `the agent exited with code ${exitCode ?? "unknown"}`;
2330
+ const detail = tail(stderr);
2331
+ if (detail)
2332
+ error = `${error}: ${detail}`;
2333
+ }
2334
+ // The agent reports *before* it stops: the status route moves the ticket and
2335
+ // then settles the process. So a run that ends while its ticket still says
2336
+ // `in_progress` did not report, and the card keeps claiming a job nobody is
2337
+ // doing. The run says so instead of letting that pass, and the ticket is
2338
+ // left untouched: only the agent or a person moves it.
2339
+ // A run that ended without its ticket moving may still have finished its
2340
+ // work: the board runs the gate here for harnesses with no in-session hook.
2341
+ let gate = { kind: "skip" };
2342
+ if (!cancelled && !failed && this.db.getTicket(ticketId)?.state === "in_progress") {
2343
+ gate = await this.completionGate(ticketId, runId, true);
2344
+ }
2345
+ // A request to the lead leaves the ticket In Progress while the lead reads
2346
+ // it; that is the board's own question, not a stall.
2347
+ const open = !cancelled && !failed && this.db.getTicket(ticketId)?.state === "in_progress";
2348
+ const stalled = open && !active.leadRequest;
2349
+ const attempt = active.status.attempt ?? 1;
2350
+ const job = active.job;
2351
+ // Recorded before the decision, so the breaker counts the failure that just
2352
+ // happened and not only the earlier ones. A comment run that opted out of
2353
+ // retries never inherits the ticket's original brief.
2354
+ const decision = stalled && job.retry !== false ? this.retryDecision(attempt) : "none";
2355
+ if (stalled) {
2356
+ const cause = gate.kind === "continue" ? `checks failed: ${gate.summary}` : stallReason(exitCode);
2357
+ error =
2358
+ decision === "hold"
2359
+ ? `${cause}; not retrying, because ${this.stalls.length} runs stalled recently and the harness looks unhealthy`
2360
+ : cause;
2361
+ }
2362
+ // Attempts are spent: a verified ticket goes to the lead before the person.
2363
+ if (decision === "escalate") {
2364
+ const current = this.db.getTicket(ticketId);
2365
+ if (current && this.canConsultLead(current)) {
2366
+ const failedAction = active.actions.findLast((action) => action.state === "failed");
2367
+ active.leadRequest = {
2368
+ trigger: "no_status",
2369
+ reason: error ?? stallReason(exitCode),
2370
+ failure: failedAction?.output ?? "",
2371
+ };
2372
+ }
2373
+ }
2374
+ const state = cancelled ? "cancelled" : failed ? "failed" : stalled ? "stalled" : "completed";
2375
+ this.finishRecord(runId, state, exitCode, gitStatus, gitDiff, error, active.tokens);
2376
+ this.active.delete(ticketId);
2377
+ // A retry starts before the finishing status is published, so the card never
2378
+ // blinks through "finished" and the allocator never sees a free slot and
2379
+ // hands it to another ticket. The next attempt owns the status line from
2380
+ // here; if it cannot start, the stall is published below.
2381
+ if (decision === "retry") {
2382
+ const failedAction = active.actions.findLast((action) => action.state === "failed");
2383
+ const summary = [
2384
+ error ?? stallReason(exitCode),
2385
+ failedAction
2386
+ ? `Last failed tool: ${failedAction.detail}. ${failedAction.output ?? ""}`
2387
+ : "",
2388
+ gate.kind === "continue" ? gate.prompt : "",
2389
+ "Worktree and commits are preserved.",
2390
+ ]
2391
+ .filter(Boolean)
2392
+ .join(" ");
2393
+ if (await this.retryNow(ticketId, worktree, attempt, job, {
2394
+ comment: `Attempt ${attempt} of ${this.retry.maxAttempts} ended without an accepted status. Observed outcome: ${summary}`,
2395
+ wip: `wip: attempt ${attempt} ended without reporting`,
2396
+ }))
2397
+ return;
2398
+ }
2399
+ const label = cancelled
2400
+ ? "Run cancelled"
2401
+ : failed
2402
+ ? "Run failed"
2403
+ : active.leadRequest
2404
+ ? "Asking the lead"
2405
+ : stalled
2406
+ ? "No status reported"
2407
+ : "Run finished";
2408
+ const final = {
2409
+ ...active.status,
2410
+ label,
2411
+ tool: null,
2412
+ endedAt: Date.now(),
2413
+ phase: cancelled ? "cancelled" : failed ? "failed" : stalled ? "stalled" : "done",
2414
+ // A call that was still live when the process ended did not finish; the
2415
+ // row says how the run ended instead of staying a spinner forever.
2416
+ actions: closeActions(active.actions, cancelled ? "cancelled" : failed || stalled ? "failed" : "done", Date.now(), error ?? undefined),
2417
+ error,
2418
+ tokens: active.tokens ?? undefined,
2419
+ };
2420
+ this.statuses.set(ticketId, final);
2421
+ this.onStatus(final);
2422
+ // The run is over and its trace is final. Anything waiting on this ticket's
2423
+ // run — a conflict repair reconciling its own outcome — is told now.
2424
+ this.wakeSettleWaiters(ticketId, final);
2425
+ // The run is over, so the manager pass can read its trail without holding
2426
+ // the slot or the card. It never blocks the finish and never moves a card.
2427
+ // A conflict repair is not In Progress work, so it proposes nothing there.
2428
+ if (!active.job.outsideStage) {
2429
+ this.reviewRun(ticketId, runId, final.phase, attempt, final.actions ?? [], Math.max(0, (final.endedAt ?? Date.now()) - active.status.startedAt), active.command);
2430
+ }
2431
+ if (decision === "escalate" && !active.leadRequest)
2432
+ this.escalate(ticketId, attempt);
2433
+ if (active.leadRequest)
2434
+ void this.runLead(ticketId, worktree, active, active.leadRequest);
2435
+ }
2436
+ /**
2437
+ * Retry, escalate, or leave the card with its stall badge. The numbers live in
2438
+ * §21 of the design notes: two attempts per ticket, and the breaker shuts
2439
+ * retrying down after three stalls in ten minutes.
2440
+ */
2441
+ retryDecision(attempt) {
2442
+ const now = Date.now();
2443
+ const cutoff = now - this.retry.breakerWindowMs;
2444
+ while (this.stalls.length > 0 && (this.stalls[0] ?? now) < cutoff)
2445
+ this.stalls.shift();
2446
+ this.stalls.push(now);
2447
+ if (attempt >= this.retry.maxAttempts)
2448
+ return "escalate";
2449
+ // A downed provider or a dead key fails every ticket the same way. Retrying
2450
+ // past that pays twice for the same outage, so the board stops and says so.
2451
+ return this.stalls.length >= this.retry.breakerStalls ? "hold" : "retry";
2452
+ }
2453
+ /**
2454
+ * The retry itself: commit what the failed attempt left behind, say so on the
2455
+ * timeline, then start again in the same worktree. Work is never lost to a
2456
+ * retry, and the attempt is never invisible.
2457
+ */
2458
+ async retryNow(ticketId, worktree, attempt, job, notice = {
2459
+ comment: `Attempt ${attempt} of ${this.retry.maxAttempts} ended without reporting a status. Retrying in the same worktree.`,
2460
+ wip: `wip: attempt ${attempt} ended without reporting`,
2461
+ }) {
2462
+ this.db.addComment({
2463
+ ticket_id: ticketId,
2464
+ type: "system",
2465
+ author: "zelio",
2466
+ text: notice.comment,
2467
+ });
2468
+ await commitAttempt(worktree.path, notice.wip);
2469
+ // The person may have moved or cancelled the card while the attempt was
2470
+ // settling. A retry never overrules them.
2471
+ const ticket = this.db.getTicket(ticketId);
2472
+ if (!ticket || ticket.state !== "in_progress" || this.active.has(ticketId))
2473
+ return false;
2474
+ try {
2475
+ if (job?.source === "comment") {
2476
+ // Keep the original task and add a factual lifecycle handoff: a fresh
2477
+ // comment turn must not have to rediscover why its predecessor ended.
2478
+ await this.begin(ticket, worktree, attempt + 1, {
2479
+ ...job,
2480
+ // The earlier attempt may have made the change before it stalled.
2481
+ expectsChange: false,
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."}`,
2483
+ });
2484
+ }
2485
+ else {
2486
+ // Rebuild the same authoritative brief and add the observed lifecycle
2487
+ // failure. A fresh session cannot see the prior conversation or trace.
2488
+ const retryPrompt = buildTicketPrompt(ticket, { number: attempt + 1, of: this.retry.maxAttempts }, this.db.listComments(ticketId), absoluteAttachments(this.repoRoot, ticket.attachments));
2489
+ await this.begin(ticket, worktree, attempt + 1, {
2490
+ prompt: `${retryPrompt}\n\n## Recovery handoff\n${notice.comment}\nInspect the preserved work and run only checks that remain necessary.`,
2491
+ profile: job?.profile ?? ticket.profile ?? "developer",
2492
+ retry: true,
2493
+ source: "ticket",
2494
+ command: job?.command,
2495
+ systemPrompt: job?.systemPrompt,
2496
+ });
2497
+ }
2498
+ return true;
2499
+ }
2500
+ catch {
2501
+ // The slot went somewhere else in the meantime; the stall badge stands.
2502
+ return false;
2503
+ }
2504
+ }
2505
+ leadConsults(ticketId) {
2506
+ return this.db.listComments(ticketId).filter((comment) => comment.author === "lead").length;
2507
+ }
2508
+ canConsultLead(ticket) {
2509
+ return (!!this.lead && ticket.verify.length > 0 && this.leadConsults(ticket.id) < MAX_LEAD_CONSULTS);
2510
+ }
2511
+ /** Said ahead of a block or an escalation once a verified ticket has used up its lead consults. */
2512
+ leadLimitNote(ticket) {
2513
+ return this.lead &&
2514
+ ticket.verify.length > 0 &&
2515
+ this.leadConsults(ticket.id) >= MAX_LEAD_CONSULTS
2516
+ ? `The lead already intervened ${MAX_LEAD_CONSULTS} times. `
2517
+ : "";
2518
+ }
2519
+ /**
2520
+ * One read-only consult of the lead, after the run has ended. The ticket stays
2521
+ * In Progress with no process behind it until the answer is applied here. This
2522
+ * never throws: an unanswered or broken consult blocks the ticket as before.
2523
+ */
2524
+ async runLead(ticketId, worktree, active, request) {
2525
+ const lead = this.lead;
2526
+ const current = this.db.getTicket(ticketId);
2527
+ if (!lead || !current || current.state !== "in_progress" || this.active.has(ticketId))
2528
+ return;
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 };
2538
+ const consult = this.leadConsults(ticketId) + 1;
2539
+ this.db.addComment({
2540
+ ticket_id: ticketId,
2541
+ type: "system",
2542
+ author: "zelio",
2543
+ text: `Asking the lead to look (consult ${consult} of ${MAX_LEAD_CONSULTS}): ${request.reason}`,
2544
+ });
2545
+ let decision = null;
2546
+ let problem = null;
2547
+ let attempt = "";
2548
+ try {
2549
+ const input = {
2550
+ ticketId,
2551
+ title: current.title,
2552
+ goal: current.goal,
2553
+ outOfScope: current.out_of_scope,
2554
+ acceptance: current.acceptance,
2555
+ likelyFiles: [...current.likely_files],
2556
+ context: [...(current.context ?? [])],
2557
+ verify: current.verify,
2558
+ trigger: request.trigger,
2559
+ reason: request.reason,
2560
+ failure,
2561
+ onAttempt: (text) => {
2562
+ attempt = text.slice(-3000);
2563
+ },
2564
+ diff: await ticketDiff(worktree.path),
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
+ ],
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),
2585
+ worktreePath: worktree.path,
2586
+ };
2587
+ decision = await lead(input);
2588
+ }
2589
+ catch (cause) {
2590
+ problem = cause instanceof Error ? cause.message : String(cause);
2591
+ }
2592
+ const live = this.db.getTicket(ticketId);
2593
+ if (!live || live.state !== "in_progress" || this.active.has(ticketId)) {
2594
+ this.db.addComment({
2595
+ ticket_id: ticketId,
2596
+ type: "system",
2597
+ author: "zelio",
2598
+ text: "The lead answered after the ticket moved; its answer was not applied.",
2599
+ });
2600
+ return;
2601
+ }
2602
+ if (!decision) {
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);
2609
+ return;
2610
+ }
2611
+ try {
2612
+ await this.applyLead(ticketId, worktree, decision);
2613
+ }
2614
+ catch (cause) {
2615
+ const message = cause instanceof Error ? cause.message : String(cause);
2616
+ this.blockForLead(ticketId, enrichedRequest, `The lead's answer could not be applied: ${message}`);
2617
+ }
2618
+ }
2619
+ catch (cause) {
2620
+ const message = cause instanceof Error ? cause.message : String(cause);
2621
+ this.db.addComment({
2622
+ ticket_id: ticketId,
2623
+ type: "system",
2624
+ author: "zelio",
2625
+ text: `The board could not consult the lead: ${message}`,
2626
+ });
2627
+ }
2628
+ }
2629
+ async applyLead(ticketId, worktree, decision) {
2630
+ if (decision.decision === "guide") {
2631
+ this.db.addComment({
2632
+ ticket_id: ticketId,
2633
+ type: "decision",
2634
+ author: "lead",
2635
+ text: `Lead guidance:\n\n${decision.guidance}`,
2636
+ });
2637
+ const ticket = this.db.getTicket(ticketId);
2638
+ if (ticket)
2639
+ await this.restartWithLead(ticket, worktree, decision.guidance, true);
2640
+ return;
2641
+ }
2642
+ if (decision.decision === "revise") {
2643
+ const updated = this.db.updateSpec(ticketId, {
2644
+ ...(decision.verify ? { verify: decision.verify } : {}),
2645
+ ...(decision.acceptance ? { acceptance: decision.acceptance } : {}),
2646
+ });
2647
+ if (!updated)
2648
+ return;
2649
+ const changed = [decision.verify ? "verify" : "", decision.acceptance ? "acceptance" : ""]
2650
+ .filter(Boolean)
2651
+ .join(" and ");
2652
+ const verify = decision.verify
2653
+ ? `\n\nVerify:\n${decision.verify.map((check) => `- ${check.label}: ${check.command}`).join("\n")}`
2654
+ : "";
2655
+ const acceptance = decision.acceptance ? `\n\nAcceptance:\n${decision.acceptance}` : "";
2656
+ this.db.addComment({
2657
+ ticket_id: ticketId,
2658
+ type: "decision",
2659
+ author: "lead",
2660
+ text: `Lead revised the ticket (${changed}):\n\n${decision.guidance}${verify}${acceptance}`,
2661
+ });
2662
+ // The ticket was wrong, not the work: the restart may have nothing to change.
2663
+ await this.restartWithLead(updated, worktree, decision.guidance, false);
2664
+ return;
2665
+ }
2666
+ const options = decision.options.map((option, index) => `${index + 1}) ${option}`);
2667
+ this.db.transition(ticketId, "blocked", {
2668
+ blocker_kind: "needs_human",
2669
+ blocker_reason: decision.question,
2670
+ blocker_unblock: `Reply with one of: ${options.join("; ")} — then mention @developer.`,
2671
+ });
2672
+ this.db.addComment({
2673
+ ticket_id: ticketId,
2674
+ type: "blocker",
2675
+ author: "lead",
2676
+ blocker_kind: "needs_human",
2677
+ text: [decision.question, options.join("\n")].join("\n\n"),
2678
+ });
2679
+ }
2680
+ /** The lead could not decide: the ticket blocks with the reason it was asked about. */
2681
+ blockForLead(ticketId, request, note) {
2682
+ this.db.transition(ticketId, "blocked", {
2683
+ blocker_kind: "decision",
2684
+ blocker_reason: request.reason,
2685
+ blocker_unblock: "The lead could not decide. Fix the failing check or answer the developer's question, then mention @developer to continue.",
2686
+ });
2687
+ const text = [
2688
+ `The lead could not decide. ${request.reason}${request.failure ? `\n\n${request.failure}` : ""}`,
2689
+ note,
2690
+ ]
2691
+ .filter(Boolean)
2692
+ .join("\n\n");
2693
+ this.db.addComment({ ticket_id: ticketId, type: "blocker", author: "zelio", text });
2694
+ }
2695
+ /** The developer again, from the start, with the lead's guidance added to the brief. */
2696
+ async restartWithLead(ticket, worktree, guidance, expectsChange) {
2697
+ try {
2698
+ await this.begin(ticket, worktree, 1, {
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}`,
2700
+ profile: ticket.profile ?? "developer",
2701
+ label: "Following the lead",
2702
+ retry: true,
2703
+ source: "ticket",
2704
+ expectsChange,
2705
+ });
2706
+ }
2707
+ catch (cause) {
2708
+ const message = cause instanceof Error ? cause.message : String(cause);
2709
+ this.db.addComment({
2710
+ ticket_id: ticket.id,
2711
+ type: "system",
2712
+ author: "zelio",
2713
+ text: `Could not restart the developer: ${message}`,
2714
+ });
2715
+ this.db.transition(ticket.id, "blocked", {
2716
+ blocker_kind: "decision",
2717
+ blocker_reason: "the developer could not be restarted with the lead's guidance",
2718
+ blocker_unblock: "Check the server log, then mention @developer to continue.",
2719
+ });
2720
+ }
2721
+ }
2722
+ /** Exhaustion is an execution stall, not an agent-declared human blocker. */
2723
+ escalate(ticketId, attempt) {
2724
+ const ticket = this.db.getTicket(ticketId);
2725
+ if (!ticket || ticket.state !== "in_progress")
2726
+ return;
2727
+ const reason = `the agent ended ${attempt} ${attempt === 1 ? "time" : "times"} without reporting a status`;
2728
+ const unblock = "The ticket worktree is preserved with any work and commits already there. Inspect the latest run's finish reporting and trace to diagnose the execution failure, then resume the ticket and continue its original acceptance criteria. Missing status does not establish a scope problem.";
2729
+ this.db.addComment({
2730
+ ticket_id: ticketId,
2731
+ type: "system",
2732
+ author: "zelio",
2733
+ text: `${this.leadLimitNote(ticket)}Execution needs attention: ${reason}. ${unblock} Mention @developer to continue the preserved work.`,
2734
+ });
2735
+ }
2736
+ }
2737
+ //# sourceMappingURL=manager.js.map