zelio-cli 0.0.0-stage → 0.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/README.md +185 -2
  2. package/dist/attachments.js +121 -0
  3. package/dist/attachments.js.map +1 -0
  4. package/dist/cli.js +496 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/cloud/board.js +311 -0
  7. package/dist/cloud/board.js.map +1 -0
  8. package/dist/cloud/command.js +281 -0
  9. package/dist/cloud/command.js.map +1 -0
  10. package/dist/cloud/config.js +132 -0
  11. package/dist/cloud/config.js.map +1 -0
  12. package/dist/cloud/credentials.js +134 -0
  13. package/dist/cloud/credentials.js.map +1 -0
  14. package/dist/cloud/login.js +165 -0
  15. package/dist/cloud/login.js.map +1 -0
  16. package/dist/cloud/pair.js +110 -0
  17. package/dist/cloud/pair.js.map +1 -0
  18. package/dist/cloud/pkce.js +16 -0
  19. package/dist/cloud/pkce.js.map +1 -0
  20. package/dist/cloud/push-nudge.js +65 -0
  21. package/dist/cloud/push-nudge.js.map +1 -0
  22. package/dist/cloud/relay.js +134 -0
  23. package/dist/cloud/relay.js.map +1 -0
  24. package/dist/cloud/token.js +66 -0
  25. package/dist/cloud/token.js.map +1 -0
  26. package/dist/cloud/tunnel.js +474 -0
  27. package/dist/cloud/tunnel.js.map +1 -0
  28. package/dist/db/db.js +1741 -0
  29. package/dist/db/db.js.map +1 -0
  30. package/dist/db/lifecycle.js +146 -0
  31. package/dist/db/lifecycle.js.map +1 -0
  32. package/dist/limits.js +35 -0
  33. package/dist/limits.js.map +1 -0
  34. package/dist/metrics.js +30 -0
  35. package/dist/metrics.js.map +1 -0
  36. package/dist/orchestrator/claude-session.js +208 -0
  37. package/dist/orchestrator/claude-session.js.map +1 -0
  38. package/dist/orchestrator/codex-session.js +326 -0
  39. package/dist/orchestrator/codex-session.js.map +1 -0
  40. package/dist/orchestrator/contract.js +184 -0
  41. package/dist/orchestrator/contract.js.map +1 -0
  42. package/dist/orchestrator/explore.js +176 -0
  43. package/dist/orchestrator/explore.js.map +1 -0
  44. package/dist/orchestrator/new-task-prompt.js +51 -0
  45. package/dist/orchestrator/new-task-prompt.js.map +1 -0
  46. package/dist/orchestrator/pi-session.js +228 -0
  47. package/dist/orchestrator/pi-session.js.map +1 -0
  48. package/dist/orchestrator/prompt.js +110 -0
  49. package/dist/orchestrator/prompt.js.map +1 -0
  50. package/dist/orchestrator/research.js +178 -0
  51. package/dist/orchestrator/research.js.map +1 -0
  52. package/dist/orchestrator/runtime.js +1207 -0
  53. package/dist/orchestrator/runtime.js.map +1 -0
  54. package/dist/orchestrator/session.js +2 -0
  55. package/dist/orchestrator/session.js.map +1 -0
  56. package/dist/orchestrator/types.js +2 -0
  57. package/dist/orchestrator/types.js.map +1 -0
  58. package/dist/orchestrator/web.js +276 -0
  59. package/dist/orchestrator/web.js.map +1 -0
  60. package/dist/repo/index.js +188 -0
  61. package/dist/repo/index.js.map +1 -0
  62. package/dist/repo/instructions.js +58 -0
  63. package/dist/repo/instructions.js.map +1 -0
  64. package/dist/repo/linked-boards.js +137 -0
  65. package/dist/repo/linked-boards.js.map +1 -0
  66. package/dist/repo/project-repos.js +78 -0
  67. package/dist/repo/project-repos.js.map +1 -0
  68. package/dist/run/actions.js +257 -0
  69. package/dist/run/actions.js.map +1 -0
  70. package/dist/run/auto-review.js +102 -0
  71. package/dist/run/auto-review.js.map +1 -0
  72. package/dist/run/bash-guard.js +183 -0
  73. package/dist/run/bash-guard.js.map +1 -0
  74. package/dist/run/claude-runtime.js +270 -0
  75. package/dist/run/claude-runtime.js.map +1 -0
  76. package/dist/run/claude-stream.js +306 -0
  77. package/dist/run/claude-stream.js.map +1 -0
  78. package/dist/run/codex-client.js +202 -0
  79. package/dist/run/codex-client.js.map +1 -0
  80. package/dist/run/codex-runtime.js +460 -0
  81. package/dist/run/codex-runtime.js.map +1 -0
  82. package/dist/run/consult.js +105 -0
  83. package/dist/run/consult.js.map +1 -0
  84. package/dist/run/context.js +87 -0
  85. package/dist/run/context.js.map +1 -0
  86. package/dist/run/diff.js +238 -0
  87. package/dist/run/diff.js.map +1 -0
  88. package/dist/run/evidence.js +48 -0
  89. package/dist/run/evidence.js.map +1 -0
  90. package/dist/run/finish.js +408 -0
  91. package/dist/run/finish.js.map +1 -0
  92. package/dist/run/handoff.js +51 -0
  93. package/dist/run/handoff.js.map +1 -0
  94. package/dist/run/harness-runtime.js +31 -0
  95. package/dist/run/harness-runtime.js.map +1 -0
  96. package/dist/run/harnesses.js +273 -0
  97. package/dist/run/harnesses.js.map +1 -0
  98. package/dist/run/issue.js +79 -0
  99. package/dist/run/issue.js.map +1 -0
  100. package/dist/run/keep-awake.js +58 -0
  101. package/dist/run/keep-awake.js.map +1 -0
  102. package/dist/run/lead.js +159 -0
  103. package/dist/run/lead.js.map +1 -0
  104. package/dist/run/manager.js +2546 -0
  105. package/dist/run/manager.js.map +1 -0
  106. package/dist/run/mentions.js +35 -0
  107. package/dist/run/mentions.js.map +1 -0
  108. package/dist/run/merge-watch.js +425 -0
  109. package/dist/run/merge-watch.js.map +1 -0
  110. package/dist/run/models.js +88 -0
  111. package/dist/run/models.js.map +1 -0
  112. package/dist/run/phases.js +23 -0
  113. package/dist/run/phases.js.map +1 -0
  114. package/dist/run/pi-rpc.js +439 -0
  115. package/dist/run/pi-rpc.js.map +1 -0
  116. package/dist/run/piped-check.js +56 -0
  117. package/dist/run/piped-check.js.map +1 -0
  118. package/dist/run/pr-checks.js +67 -0
  119. package/dist/run/pr-checks.js.map +1 -0
  120. package/dist/run/pr-merge.js +121 -0
  121. package/dist/run/pr-merge.js.map +1 -0
  122. package/dist/run/profiles.js +43 -0
  123. package/dist/run/profiles.js.map +1 -0
  124. package/dist/run/prompt.js +388 -0
  125. package/dist/run/prompt.js.map +1 -0
  126. package/dist/run/pull-request.js +23 -0
  127. package/dist/run/pull-request.js.map +1 -0
  128. package/dist/run/red-check.js +130 -0
  129. package/dist/run/red-check.js.map +1 -0
  130. package/dist/run/result-tool.js +93 -0
  131. package/dist/run/result-tool.js.map +1 -0
  132. package/dist/run/result.js +113 -0
  133. package/dist/run/result.js.map +1 -0
  134. package/dist/run/retro.js +346 -0
  135. package/dist/run/retro.js.map +1 -0
  136. package/dist/run/settings.js +27 -0
  137. package/dist/run/settings.js.map +1 -0
  138. package/dist/run/skills.js +146 -0
  139. package/dist/run/skills.js.map +1 -0
  140. package/dist/run/tests-first.js +146 -0
  141. package/dist/run/tests-first.js.map +1 -0
  142. package/dist/run/thinking.js +41 -0
  143. package/dist/run/thinking.js.map +1 -0
  144. package/dist/run/types.js +2 -0
  145. package/dist/run/types.js.map +1 -0
  146. package/dist/run/watchdog.js +259 -0
  147. package/dist/run/watchdog.js.map +1 -0
  148. package/dist/run/workflow.js +277 -0
  149. package/dist/run/workflow.js.map +1 -0
  150. package/dist/run/worktree.js +354 -0
  151. package/dist/run/worktree.js.map +1 -0
  152. package/dist/server/app.js +2946 -0
  153. package/dist/server/app.js.map +1 -0
  154. package/dist/server/auth.js +93 -0
  155. package/dist/server/auth.js.map +1 -0
  156. package/dist/server/demo.js +96 -0
  157. package/dist/server/demo.js.map +1 -0
  158. package/dist/server/idempotency.js +104 -0
  159. package/dist/server/idempotency.js.map +1 -0
  160. package/dist/server/port.js +36 -0
  161. package/dist/server/port.js.map +1 -0
  162. package/dist/server/principal.js +93 -0
  163. package/dist/server/principal.js.map +1 -0
  164. package/dist/server/repo-picker.js +18 -0
  165. package/dist/server/repo-picker.js.map +1 -0
  166. package/dist/server/terminal.js +285 -0
  167. package/dist/server/terminal.js.map +1 -0
  168. package/dist/setup/components.js +98 -0
  169. package/dist/setup/components.js.map +1 -0
  170. package/dist/setup/config.js +102 -0
  171. package/dist/setup/config.js.map +1 -0
  172. package/dist/setup/ink-ui.js +189 -0
  173. package/dist/setup/ink-ui.js.map +1 -0
  174. package/dist/setup/onboarding.js +167 -0
  175. package/dist/setup/onboarding.js.map +1 -0
  176. package/dist/setup/run.js +70 -0
  177. package/dist/setup/run.js.map +1 -0
  178. package/dist/skills.js +151 -0
  179. package/dist/skills.js.map +1 -0
  180. package/dist/ticket-cli.js +157 -0
  181. package/dist/ticket-cli.js.map +1 -0
  182. package/dist/version.js +13 -0
  183. package/dist/version.js.map +1 -0
  184. package/dist/voice/index.js +69 -0
  185. package/dist/voice/index.js.map +1 -0
  186. package/dist/voice/moonshine.js +247 -0
  187. package/dist/voice/moonshine.js.map +1 -0
  188. package/dist/voice/wav.js +54 -0
  189. package/dist/voice/wav.js.map +1 -0
  190. package/dist/voice/whisper.js +491 -0
  191. package/dist/voice/whisper.js.map +1 -0
  192. package/dist/web/assets/index-CCQMrUIF.js +255 -0
  193. package/dist/web/assets/index-lzGSgTRQ.css +1 -0
  194. package/dist/web/icons/apple-touch-icon.png +0 -0
  195. package/dist/web/icons/icon-192.png +0 -0
  196. package/dist/web/icons/icon-512.png +0 -0
  197. package/dist/web/icons/maskable-512.png +0 -0
  198. package/dist/web/index.html +21 -0
  199. package/dist/web/manifest.webmanifest +30 -0
  200. package/dist/web/sw.js +185 -0
  201. package/package.json +96 -4
@@ -0,0 +1,2546 @@
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 { profileFor } from "./profiles.js";
14
+ import { chosenSkills, readSkills, skillStoreOf } from "./skills.js";
15
+ import { commentActionsFor, wasteSignalDetails } from "./retro.js";
16
+ import { phaseForTool } from "./phases.js";
17
+ import { buildRunSystemPrompt, emptyWorkflow, hasWorkflow, workflowSummary, } from "./workflow.js";
18
+ import { evidenceRevision } from "./evidence.js";
19
+ import { resultComment } from "./result.js";
20
+ import { stripWorktreeCd } from "./actions.js";
21
+ import { pipedEvidence, unpipedCommand } from "./piped-check.js";
22
+ import { commitTicketWork, failureReport, hasTicketChanges, publishBranch, runChecks, ticketDiff, worktreeFingerprint, } from "./finish.js";
23
+ import { MAX_WATCHDOG_CHECKS, MAX_WATCHDOG_STEERS, STEER_HEADING, WATCHDOG_BACKSTOP_MS, WATCHDOG_COOLDOWN_TICKS, WATCHDOG_TICK_MS, callLines, lookLabel, watchdogSignals, watchdogSummary, } from "./watchdog.js";
24
+ import { MAX_AUTO_REVIEWS } from "./auto-review.js";
25
+ import { isTestPath, redCheck, ticketChanges } from "./red-check.js";
26
+ import { MAX_TEST_REVIEWS, TEST_REVIEW_CHANGES_PROMPT, TEST_REVIEW_HEADING, TESTS_FIRST_PROMPT, TESTS_MISSING_PROMPT, TESTS_PASS_ALREADY_PROMPT, approvalComment, approvedTests, implementPrompt, testsChangedPrompt, testsDiff, testsOnlyPrompt, weakenedTests, } from "./tests-first.js";
27
+ const execFileAsync = promisify(execFile);
28
+ /** How a review that sent the work back starts its board comment; the count reads it. */
29
+ export const REVIEW_CHANGES_HEADING = "Automatic review: changes needed before Review.";
30
+ /** Sent to the developer with the reviewer's findings, the way a failed check's output is. */
31
+ export const REVIEW_CHANGES_PROMPT = `The board's checks pass, but the automatic review found that the work does not yet give the person what they asked for. The checks are the minimum; done means the person gets what they asked for. Read the findings below, open the ticket's screenshots if it has any, make the change, and end your turn when it is done. Do not argue with a finding by restating the acceptance: if a finding is wrong, say why in your reply and change nothing for it.`;
32
+ /** Sent when the ticket's checks also pass on the code before the change; the test files it copied are named after it. */
33
+ export const RED_CHECK_PROMPT = "The board's checks pass, but they also pass on the code before your change, with your test changes copied in. So they do not test what the ticket asks for. Add or extend tests that fail without your change and pass with it, one for each acceptance criterion including its failure case, then end your turn. Do not weaken or delete existing assertions. If the ticket is a refactor that must not change behaviour, say so in your reply and end your turn without new tests.";
34
+ /** Sent when a run that was asked for a change ends without changing the worktree. */
35
+ export const IDLE_RUN_PROMPT = "Your turn ended without changing anything in the worktree since this run started. The ticket's earlier work is still there, but you were asked for a change: make it now, run the checks it needs, and end your turn when it is done. If what you were asked was only a question that needs no change, say so in your reply and end your turn again.";
36
+ /** Said on the ticket when the tests still pass without the change after the one send-back. */
37
+ export const RED_CHECK_STILL_PASSES = "The ticket's checks still pass on the code before the change, so they do not prove it. That is expected for a refactor; otherwise, check the tests in review.";
38
+ /** Whether this run's latest completed command proves a check on the current tree. */
39
+ export function developerCheckPassed(command, evidence, inFlightCommands, currentRevision) {
40
+ const normalized = stripWorktreeCd(command);
41
+ if (inFlightCommands.includes(normalized) || !currentRevision)
42
+ return false;
43
+ const latest = evidence.findLast((item) => item.command === normalized);
44
+ return latest?.outcome === "passed" && latest.revision === currentRevision;
45
+ }
46
+ export class RunAlreadyActiveError extends Error {
47
+ constructor(ticketId) {
48
+ super(`${ticketId} is already running`);
49
+ this.name = "RunAlreadyActiveError";
50
+ }
51
+ }
52
+ const FACTS_POLL_MS = 3_000;
53
+ /**
54
+ * How often a live token total reaches the board and the stored row. The
55
+ * harness reports after every assistant message, which can be far more often
56
+ * than a person reads; seven seconds keeps the number moving without turning
57
+ * the event stream into a token counter.
58
+ */
59
+ const TOKEN_PUBLISH_MS = 7_000;
60
+ const OUTPUT_LINES = 12;
61
+ const TAIL_LINES = 3;
62
+ const OUTPUT_DELAY_MS = 250;
63
+ const outputLine = (value) => {
64
+ const text = value.trim();
65
+ // A minified or single-line dump is only interesting where it ended.
66
+ return text.length > 400 ? `…${text.slice(-399)}` : text;
67
+ };
68
+ const tail = (value) => value.trim().split("\n").filter(Boolean).slice(-3).join(" ").slice(0, 500);
69
+ /**
70
+ * How many times one attempt may be resumed before the board stops trying.
71
+ * A resume is cheap and loses nothing, but a machine that sleeps every few
72
+ * minutes would otherwise keep the same run alive forever: after this many, the
73
+ * ticket falls back to the ordinary attempt budget and then to the person.
74
+ */
75
+ export const MAX_RESUMES = 3;
76
+ /** Idle developer turns may continue, but never beyond the attempt's deadline or this cap. */
77
+ export const MAX_TURN_CONTINUATIONS = 2;
78
+ /** Failed verification rounds before the board stops sending the run back and blocks the ticket. */
79
+ export const MAX_VERIFY_ROUNDS = 3;
80
+ /** Identical tool calls in a row, on a verified run, before the developer is told to change course. */
81
+ export const REPEAT_NUDGE_AT = 4;
82
+ /** Sent in-session once per run when the developer repeats the same tool call. */
83
+ 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.";
84
+ /** JSON with sorted keys, so the same arguments always compare equal. */
85
+ function stableJson(value) {
86
+ if (Array.isArray(value))
87
+ return `[${value.map(stableJson).join(",")}]`;
88
+ if (value && typeof value === "object") {
89
+ const record = value;
90
+ const fields = Object.keys(record)
91
+ .sort()
92
+ .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`);
93
+ return `{${fields.join(",")}}`;
94
+ }
95
+ return JSON.stringify(value) ?? "null";
96
+ }
97
+ /** Lead consultations per verified ticket before the person is asked directly. */
98
+ export const MAX_LEAD_CONSULTS = 2;
99
+ 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.
100
+
101
+ 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.`;
102
+ 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.`;
103
+ 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.`;
104
+ const COMMIT_TYPES = new Set([
105
+ "feat",
106
+ "fix",
107
+ "chore",
108
+ "docs",
109
+ "refactor",
110
+ "test",
111
+ "perf",
112
+ "style",
113
+ "build",
114
+ "ci",
115
+ ]);
116
+ /** A conventional subject from the ticket title, typed by the branch prefix when it names one. */
117
+ function commitMessage(title, branch) {
118
+ const prefix = branch.includes("/") ? branch.slice(0, branch.indexOf("/")) : "";
119
+ const type = COMMIT_TYPES.has(prefix) ? prefix : "feat";
120
+ return `${type}: ${title.trim().replace(/^./, (letter) => letter.toLowerCase())}`;
121
+ }
122
+ async function currentBranch(cwd) {
123
+ const { stdout } = await execFileAsync("git", ["-C", cwd, "branch", "--show-current"], {
124
+ timeout: 15_000,
125
+ }).catch(() => ({ stdout: "" }));
126
+ return String(stdout).trim();
127
+ }
128
+ const seconds = (ms) => (ms / 1000).toFixed(1);
129
+ const DEFAULT_RETRY = {
130
+ maxAttempts: 2,
131
+ breakerStalls: 3,
132
+ breakerWindowMs: 10 * 60_000,
133
+ };
134
+ /**
135
+ * Why a run that ended without moving its ticket is worth saying out loud. The
136
+ * exit code is evidence about the process; the silence is the point.
137
+ */
138
+ const stallReason = (exitCode) => exitCode === null || exitCode === 0
139
+ ? "the agent finished without reporting a status"
140
+ : `the agent exited with code ${exitCode} without reporting a status`;
141
+ /**
142
+ * Owns the in-flight ticket processes and their live status. It does not move
143
+ * tickets: a finished run leaves the card where it is until the agent says what
144
+ * happened through the status contract.
145
+ */
146
+ export class RunManager {
147
+ db;
148
+ runtime;
149
+ onStatus;
150
+ statusBaseUrl;
151
+ agentPath;
152
+ ghCommand;
153
+ factsPollMs;
154
+ tokenPublishMs;
155
+ repoRoot;
156
+ retro;
157
+ defaults;
158
+ lead;
159
+ rootFor;
160
+ reviewer;
161
+ redCheckEnabled;
162
+ testsFirstEnabled;
163
+ skills;
164
+ listModels;
165
+ watchdog;
166
+ active = new Map();
167
+ statuses = new Map();
168
+ /**
169
+ * Callers waiting for the ticket's current run to end. A conflict resolution
170
+ * is started from a background pass that has to reconcile its own outcome, so
171
+ * it needs the run's ending and the trace the run left behind.
172
+ */
173
+ settleWaiters = new Map();
174
+ /** Stall timestamps, oldest first, for the breaker. */
175
+ stalls = [];
176
+ retry;
177
+ constructor(db, runtime, onStatus, statusBaseUrl, agentPath, ghCommand = "gh", factsPollMs = FACTS_POLL_MS, retry = {}, tokenPublishMs = TOKEN_PUBLISH_MS,
178
+ /** The checkout the board runs in, so a screenshot path resolves from a worktree. */
179
+ repoRoot = process.cwd(),
180
+ /**
181
+ * A separate manager pass that reads a finished run's evidence. Optional:
182
+ * tests and a board without a harness must not spawn one.
183
+ */
184
+ retro, defaults = () => ({ harness: "pi", model: "" }),
185
+ /** The stronger model a stuck verified ticket is sent to before the person. */
186
+ lead,
187
+ /**
188
+ * The checkout root a ticket works in. Absent means every ticket works in
189
+ * `repoRoot`; a card for an added repository has its own root.
190
+ */
191
+ rootFor,
192
+ /**
193
+ * The read-only reviewer asked, once a verified ticket's checks pass,
194
+ * whether the work gives the person what they asked for. Absent, the board
195
+ * publishes on passing checks alone.
196
+ */
197
+ reviewer,
198
+ /**
199
+ * Once a verified ticket's checks pass, they must also fail on the code
200
+ * before the change, with only the developer's test files copied in.
201
+ * Off, the board trusts the checks as written.
202
+ */
203
+ redCheckEnabled = false,
204
+ /**
205
+ * A verified ticket's first runs write only the tests, which must fail and
206
+ * pass a test review before the developer implements against them.
207
+ */
208
+ testsFirstEnabled = () => false,
209
+ /**
210
+ * Where the skills a ticket chose are read from. Absent, the board's own
211
+ * database once it keeps skills, and no skills until then.
212
+ */
213
+ skills = skillStoreOf(db),
214
+ /**
215
+ * The models a harness lists. A card's model is kept only if the harness
216
+ * that runs it lists it; a list that cannot be read is empty, so the card
217
+ * runs on the default model instead of an unknown one.
218
+ */
219
+ listModels = async () => [],
220
+ /**
221
+ * Looks over a live developer run and may steer it or stop it for the lead.
222
+ * Absent, a run is only looked at once it has stopped.
223
+ */
224
+ watchdog) {
225
+ this.db = db;
226
+ this.runtime = runtime;
227
+ this.onStatus = onStatus;
228
+ this.statusBaseUrl = statusBaseUrl;
229
+ this.agentPath = agentPath;
230
+ this.ghCommand = ghCommand;
231
+ this.factsPollMs = factsPollMs;
232
+ this.tokenPublishMs = tokenPublishMs;
233
+ this.repoRoot = repoRoot;
234
+ this.retro = retro;
235
+ this.defaults = defaults;
236
+ this.lead = lead;
237
+ this.rootFor = rootFor;
238
+ this.reviewer = reviewer;
239
+ this.redCheckEnabled = redCheckEnabled;
240
+ this.testsFirstEnabled = testsFirstEnabled;
241
+ this.skills = skills;
242
+ this.listModels = listModels;
243
+ this.watchdog = watchdog;
244
+ this.retry = { ...DEFAULT_RETRY, ...retry };
245
+ }
246
+ /** Where the harness keeps session files: with the board's own state. */
247
+ get sessionDir() {
248
+ return join(this.repoRoot, ".zelio", "sessions");
249
+ }
250
+ isRunning(ticketId) {
251
+ return this.active.has(ticketId);
252
+ }
253
+ /**
254
+ * Resolves when the ticket's current run has ended, with the status it ended
255
+ * on. Registered immediately after `start`, so the waiter can never miss the
256
+ * run it is about. A retry carries the waiter onto the next attempt, because
257
+ * that is still the same ticket settling.
258
+ */
259
+ whenSettled(ticketId) {
260
+ return new Promise((resolve) => {
261
+ const waiters = this.settleWaiters.get(ticketId) ?? new Set();
262
+ waiters.add(resolve);
263
+ this.settleWaiters.set(ticketId, waiters);
264
+ });
265
+ }
266
+ wakeSettleWaiters(ticketId, status) {
267
+ const waiters = this.settleWaiters.get(ticketId);
268
+ if (!waiters)
269
+ return;
270
+ this.settleWaiters.delete(ticketId);
271
+ for (const waiter of waiters)
272
+ waiter(status);
273
+ }
274
+ runningCount() {
275
+ return this.active.size;
276
+ }
277
+ /** Every run this server knows about, active or just finished. */
278
+ listStatuses() {
279
+ return [...this.statuses.values()];
280
+ }
281
+ /**
282
+ * A restart empties the in-memory run map, so a ticket that was mid-run comes
283
+ * back claiming `in_progress` with no process behind it. A run the restart
284
+ * killed is put back to work as the next attempt in the same worktree: a
285
+ * restart is not a decision to stop, and the work already on the branch is
286
+ * the input to the next attempt. Every other quiet ending is adopted: the
287
+ * process is gone, so the only honest thing left to say is that it never
288
+ * reported, and the ticket itself is not moved — a stall is the person's call.
289
+ */
290
+ async reconcileOrphans(worktreeFor) {
291
+ const adopted = [];
292
+ const restarted = "the server restarted while this ticket was running; the run never reported a status";
293
+ const orphaned = "nothing is running on this ticket; no run reported a status";
294
+ for (const ticket of this.db.listTickets()) {
295
+ if (ticket.state !== "in_progress" || this.active.has(ticket.id))
296
+ continue;
297
+ const latest = this.db.latestAgentRun(ticket.id);
298
+ if (latest?.state === "running" && worktreeFor) {
299
+ // Ticket order is the board's order, and one resume per ticket is the
300
+ // point: starting them in parallel would race the worktree creation.
301
+ // oxlint-disable-next-line no-await-in-loop
302
+ const resumed = await this.resumeInterrupted(ticket, latest, worktreeFor);
303
+ if (resumed) {
304
+ adopted.push(resumed);
305
+ continue;
306
+ }
307
+ }
308
+ // A failure already has a record that explains itself, so only the two
309
+ // quiet endings are rewritten: a run the restart killed, and a run that
310
+ // ended without reporting.
311
+ const error = latest ? restarted : orphaned;
312
+ const quiet = !latest || latest.state === "running" || latest.state === "completed";
313
+ const record = latest && quiet ? (this.db.markRunStalled(latest.id, error) ?? latest) : null;
314
+ const failed = latest?.state === "failed";
315
+ const startedAt = latest ? Date.parse(latest.started_at) : Number.NaN;
316
+ const endedAt = latest?.ended_at ? Date.parse(latest.ended_at) : startedAt;
317
+ const status = {
318
+ ticketId: ticket.id,
319
+ runId: latest?.id ?? "",
320
+ label: failed ? "Run failed" : "No status reported",
321
+ tool: null,
322
+ startedAt: Number.isNaN(startedAt) ? Date.now() : startedAt,
323
+ endedAt: Number.isNaN(endedAt) ? undefined : endedAt,
324
+ phase: failed ? "failed" : "stalled",
325
+ attempt: latest?.attempt ?? 1,
326
+ attempts: this.retry.maxAttempts,
327
+ tail: [],
328
+ error: failed ? (latest?.error ?? error) : (record?.error ?? error),
329
+ ...(latest?.workflow && latest.workflow_stage
330
+ ? { workflow: workflowSummary(latest.workflow_stage, latest.workflow) }
331
+ : {}),
332
+ };
333
+ this.statuses.set(ticket.id, status);
334
+ adopted.push(status);
335
+ }
336
+ return adopted;
337
+ }
338
+ /**
339
+ * The run the restart killed still says `running`, so it is closed as a stall
340
+ * before anything else: history never shows two live runs for one ticket.
341
+ *
342
+ * What happens next depends on whether the run left a session. With one, the
343
+ * same attempt is resumed: the agent keeps its conversation, so a restart
344
+ * costs the interruption and not the work, and the card does not spend an
345
+ * attempt on a lid closing. Without one - a row from before sessions, or an
346
+ * attempt that has used its resumes - the ticket falls back to the next cold
347
+ * attempt in the same worktree, which is what every restart used to do.
348
+ * Attempts are never extended by a restart, and a worktree that cannot be
349
+ * prepared leaves the ticket where it is with a comment saying why.
350
+ */
351
+ async resumeInterrupted(ticket, latest, worktreeFor) {
352
+ const restarted = "the server restarted while this ticket was running; the run never reported a status";
353
+ this.db.markRunStalled(latest.id, restarted);
354
+ const resumes = latest.resume_count;
355
+ const resumable = Boolean(latest.session_id) && resumes < MAX_RESUMES;
356
+ if (!resumable && latest.attempt >= this.retry.maxAttempts) {
357
+ // The budget is spent and this run has nothing left to resume. A restart
358
+ // cannot authorize an attempt the policy does not allow, so the card asks
359
+ // the person instead. Checked before the worktree: a card that is only
360
+ // going to be escalated must not pay for a checkout first.
361
+ this.escalate(ticket.id, latest.attempt);
362
+ return null;
363
+ }
364
+ let worktree;
365
+ try {
366
+ worktree = await worktreeFor(ticket.id);
367
+ }
368
+ catch (cause) {
369
+ this.db.addComment({
370
+ ticket_id: ticket.id,
371
+ type: "system",
372
+ author: "zelio",
373
+ 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.`,
374
+ });
375
+ return null;
376
+ }
377
+ const current = this.db.getTicket(ticket.id);
378
+ if (!current || current.state !== "in_progress" || this.active.has(ticket.id))
379
+ return null;
380
+ if (resumable) {
381
+ this.db.addComment({
382
+ ticket_id: ticket.id,
383
+ type: "system",
384
+ author: "zelio",
385
+ text: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Resuming it from its last turn.`,
386
+ });
387
+ try {
388
+ await this.begin(ticket, worktree, latest.attempt, {
389
+ prompt: (ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT,
390
+ profile: latest.profile ?? ticket.profile ?? "developer",
391
+ label: "Resumed",
392
+ retry: true,
393
+ sessionId: latest.session_id ?? undefined,
394
+ resumes: resumes + 1,
395
+ resumeEvidence: latest.command_evidence,
396
+ source: latest.job_source,
397
+ command: latest.harness ?? undefined,
398
+ systemPrompt: latest.job_system_prompt ?? undefined,
399
+ originalPrompt: latest.job_prompt ?? undefined,
400
+ });
401
+ return this.statuses.get(ticket.id) ?? null;
402
+ }
403
+ catch {
404
+ // The slot went somewhere else in the meantime; the stall badge stands.
405
+ return null;
406
+ }
407
+ }
408
+ const started = await this.retryNow(ticket.id, worktree, latest.attempt, latest.job_source === "ticket"
409
+ ? undefined
410
+ : {
411
+ prompt: latest.job_prompt ??
412
+ ((ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT),
413
+ profile: latest.profile ?? ticket.profile ?? "developer",
414
+ systemPrompt: latest.job_system_prompt ?? undefined,
415
+ source: latest.job_source,
416
+ command: latest.harness ?? undefined,
417
+ originalPrompt: latest.job_prompt ?? undefined,
418
+ retry: true,
419
+ }, {
420
+ comment: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Retrying in the same worktree.`,
421
+ wip: `wip: attempt ${latest.attempt} was interrupted by a restart`,
422
+ });
423
+ return started ? (this.statuses.get(ticket.id) ?? null) : null;
424
+ }
425
+ /**
426
+ * Starts a run once the model list it needs is read. Only a developer run on
427
+ * the harness that names the card's model needs the list; every other run
428
+ * starts at once with `start`.
429
+ */
430
+ async begin(ticket, worktree, attempt = 1, job) {
431
+ const profileName = job?.profile ?? ticket.profile ?? "developer";
432
+ const profile = this.db.getProfile(profileName) ?? profileFor(profileName);
433
+ const defaults = this.defaults();
434
+ const command = job?.command?.trim() || profile.harness.trim() || defaults.harness;
435
+ const profileHarness = profile.harness.trim() || defaults.harness;
436
+ const cardOnHarness = profileName === "developer" && command === profileHarness && Boolean(ticket.model?.trim());
437
+ const models = cardOnHarness ? await this.modelsOf(command) : undefined;
438
+ return this.start(ticket, worktree, attempt, job, models);
439
+ }
440
+ async modelsOf(command) {
441
+ return Promise.resolve()
442
+ .then(() => this.listModels(command))
443
+ .catch(() => []);
444
+ }
445
+ /**
446
+ * `models` is the list of the run's harness when the card's model needs one;
447
+ * absent means it is unknown, so the card's model is not used.
448
+ */
449
+ start(ticket, worktree, attempt = 1, job, models) {
450
+ if (this.active.has(ticket.id))
451
+ throw new RunAlreadyActiveError(ticket.id);
452
+ const testsFirstEnabled = this.testsFirstEnabled();
453
+ const resolvedJob = job ?? {
454
+ prompt: buildTicketPrompt(ticket, {
455
+ number: attempt,
456
+ of: this.retry.maxAttempts,
457
+ }, this.db.listComments(ticket.id), absoluteAttachments(this.repoRoot, ticket.attachments)),
458
+ profile: ticket.profile ?? "developer",
459
+ label: attempt > 1 ? `Attempt ${attempt} of ${this.retry.maxAttempts}` : "Starting",
460
+ retry: true,
461
+ source: "ticket",
462
+ };
463
+ // A stored row wins, so an edit on the Agents page is what the next run
464
+ // actually uses. The static profile is only the fallback for a name that
465
+ // predates the table.
466
+ const profile = this.db.getProfile(resolvedJob.profile) ?? profileFor(resolvedJob.profile);
467
+ const defaults = this.defaults();
468
+ const command = resolvedJob.command?.trim() || profile.harness.trim() || defaults.harness;
469
+ // A profile's model is named by its own harness, so it applies only on that
470
+ // harness: a send-back pinned to an earlier one never gets the new model.
471
+ const profileHarness = profile.harness.trim() || defaults.harness;
472
+ // A card's model is named by the developer harness, so it applies only to a
473
+ // developer run on that harness, and only if that harness lists it. Anything
474
+ // else runs on the default model, which is the one the board records.
475
+ const cardModel = resolvedJob.profile === "developer" &&
476
+ command === profileHarness &&
477
+ models?.includes(ticket.model?.trim() ?? "")
478
+ ? (ticket.model?.trim() ?? "")
479
+ : "";
480
+ const model = cardModel ||
481
+ (command === profileHarness ? profile.model.trim() : "") ||
482
+ (command === defaults.harness ? defaults.model : "");
483
+ // A pi run can seed its own session id before the process starts. Codex
484
+ // returns a thread id instead, so its row stays open until that arrives.
485
+ const seedId = !this.runtime.sessionIdFromHarness?.(command);
486
+ // The workflow belongs to the stage, not to the ticket. Every writer run in
487
+ // In Progress gets it: a first start, a retry, an unblock, a send-back, and
488
+ // a mention. A reviewer reads the Review column's instructions, which is a
489
+ // different list: no checks, and board rules that forbid editing. A conflict
490
+ // repair started from Review is neither, and takes no workflow.
491
+ const stage = resolvedJob.stage ?? "in_progress";
492
+ // A card for an added repo runs only its own verify commands: the board's
493
+ // stage checks were written for the home repo and would fail there.
494
+ const takesWorkflow = !resolvedJob.outsideStage && !ticket.repo && (profile.touchesRepo || stage === "review");
495
+ const workflow = takesWorkflow
496
+ ? this.db.getStageWorkflow(stage)
497
+ : emptyWorkflow();
498
+ const snapshot = hasWorkflow(workflow) ? { stage, workflow } : null;
499
+ // The row carries the conversation, not just the attempt: a resume is given
500
+ // the id it already had, and a fresh run seeds one so the next restart has
501
+ // something to reopen.
502
+ const record = this.db.startAgentRun(ticket.id, attempt, snapshot, {
503
+ id: resolvedJob.sessionId ?? null,
504
+ resumeCount: resolvedJob.resumes ?? 0,
505
+ profile: resolvedJob.profile,
506
+ harness: command,
507
+ model: model || null,
508
+ source: resolvedJob.source,
509
+ prompt: resolvedJob.originalPrompt ?? resolvedJob.prompt,
510
+ systemPrompt: resolvedJob.systemPrompt ?? null,
511
+ seedId,
512
+ });
513
+ const statusToken = randomBytes(24).toString("hex");
514
+ // A verified ticket's developer is told the board checks and publishes: it
515
+ // never commits, pushes or reports Review, so it gets its own doctrine.
516
+ const verified = resolvedJob.profile === "developer" &&
517
+ stage === "in_progress" &&
518
+ !resolvedJob.outsideStage &&
519
+ (ticket.verify ?? []).length > 0;
520
+ const defaultPrompt = verified ? VERIFIED_CODING_AGENT_PROMPT : CODING_AGENT_PROMPT;
521
+ const basePrompt = resolvedJob.systemPrompt ?? defaultPrompt;
522
+ // Empty extra prompt must leave the prompt untouched, including "undefined"
523
+ // so the runtime applies its own default exactly as before. A verified run
524
+ // always names its prompt, because the runtime default is the unverified one.
525
+ const extraPrompt = profile.extraPrompt.trim()
526
+ ? withExtraInstructions(basePrompt, profile.extraPrompt)
527
+ : (resolvedJob.systemPrompt ?? (verified ? VERIFIED_CODING_AGENT_PROMPT : undefined));
528
+ // A developer in In Progress is told how long each of its checks took the
529
+ // last time the board ran them, so a slow one is run once and waited out.
530
+ // A command the board has never timed adds nothing.
531
+ const timedCommands = resolvedJob.profile === "developer" && stage === "in_progress" && !resolvedJob.outsideStage
532
+ ? [...(ticket.verify ?? []), ...workflow.checks].map((check) => check.command)
533
+ : [];
534
+ const timings = timedCommands.length
535
+ ? commandTimingsSection(timedCommands, this.db.commandDurations(ticket.repo ?? null, timedCommands))
536
+ : "";
537
+ const profilePrompt = timings ? `${extraPrompt ?? defaultPrompt}\n\n${timings}` : extraPrompt;
538
+ // The repository's own AGENTS.md/CLAUDE.md comes before the workflow: it is
539
+ // the person's standing word on this repo, and it is read at run time, so a
540
+ // change to it takes effect on the next run without touching the board.
541
+ const instructions = profile.touchesRepo
542
+ ? readRepoInstructions(this.rootFor ? this.rootFor(ticket) : this.repoRoot, undefined, this.runtime.instructionFilesFromHarness?.(command) ?? [])
543
+ : { files: [], text: "" };
544
+ // The skills the planner chose for the card, read now so a skill disabled or
545
+ // deleted since is simply absent. The harness loads none of its own.
546
+ const skills = resolvedJob.profile === "developer" && (ticket.skills ?? []).length > 0
547
+ ? chosenSkills(ticket.skills, readSkills(this.skills))
548
+ : [];
549
+ // The workflow section goes last: it closes by restating the board rules no
550
+ // standing instruction may override, so it has to be the final thing the run
551
+ // reads. With nothing configured it is a no-op and the prompt is untouched.
552
+ const systemPrompt = hasWorkflow(workflow) ||
553
+ instructions.text ||
554
+ instructions.loadedByHarness?.length ||
555
+ skills.length > 0
556
+ ? buildRunSystemPrompt(profilePrompt ?? defaultPrompt, stage, workflow, instructions, {
557
+ verified,
558
+ skills,
559
+ })
560
+ : profilePrompt;
561
+ const status = {
562
+ ticketId: ticket.id,
563
+ runId: record.id,
564
+ label: resolvedJob.label ?? "Starting",
565
+ tool: null,
566
+ startedAt: Date.now(),
567
+ phase: "running",
568
+ ...(resolvedJob.profile === "developer" ? { executionPhase: "inspect" } : {}),
569
+ profile: resolvedJob.profile,
570
+ ...(resolvedJob.sourceCommentId ? { requestCommentId: resolvedJob.sourceCommentId } : {}),
571
+ attempt,
572
+ attempts: this.retry.maxAttempts,
573
+ tail: [],
574
+ actions: [],
575
+ ...(snapshot ? { workflow: workflowSummary(stage, workflow) } : {}),
576
+ };
577
+ // Tests first applies to the ticket's own brief, not to a person's send-back:
578
+ // a follow-up may change what the tests should say. The phase is read back
579
+ // from the board's approval comment, so a restart or a retry picks it up.
580
+ const approved = testsFirstEnabled &&
581
+ resolvedJob.profile === "developer" &&
582
+ resolvedJob.source === "ticket" &&
583
+ !resolvedJob.outsideStage &&
584
+ ticket.verify.length > 0
585
+ ? { tests: approvedTests(this.db.listComments(ticket.id)) }
586
+ : null;
587
+ const testsPhase = !approved ? null : approved.tests ? "implement" : "tests";
588
+ const phaseBrief = resolvedJob.sessionId || !testsPhase
589
+ ? ""
590
+ : testsPhase === "tests"
591
+ ? TESTS_FIRST_PROMPT
592
+ : implementPrompt(approved.tests.sha, approved.tests.files);
593
+ // Read before the harness starts, so no edit of the run can land in it.
594
+ const startTree = resolvedJob.profile === "developer" && resolvedJob.expectsChange
595
+ ? worktreeTree(worktree.path)
596
+ : null;
597
+ let run;
598
+ try {
599
+ const boardUrl = this.statusBaseUrl.replace(/\/$/, "");
600
+ const env = {
601
+ ZELIO_TICKET_ID: ticket.id,
602
+ ZELIO_BOARD_URL: boardUrl,
603
+ ZELIO_STATUS_URL: `${boardUrl}/api/tickets/${encodeURIComponent(ticket.id)}/status`,
604
+ ZELIO_TICKET_TOKEN: statusToken,
605
+ };
606
+ if (this.agentPath)
607
+ env.PATH = `${this.agentPath}:${process.env.PATH ?? ""}`;
608
+ // A harness may create its own session directory; making it first costs
609
+ // one syscall and removes the chance that every run fails on a missing
610
+ // parent under `.zelio`.
611
+ const sessionDir = this.sessionDir;
612
+ mkdirSync(sessionDir, { recursive: true });
613
+ const prompt = resolvedJob.profile === "developer" &&
614
+ resolvedJob.source === "ticket" &&
615
+ !resolvedJob.sessionId
616
+ ? `${resolvedJob.prompt}\n\n${buildDeveloperContextPack(worktree.path, ticket)}${phaseBrief ? `\n\n${phaseBrief}` : ""}`
617
+ : resolvedJob.prompt;
618
+ run = this.runtime.spawn(worktree.path, prompt, {
619
+ env,
620
+ thinking: ticket.thinking ?? profile.thinking,
621
+ model: model || undefined,
622
+ command,
623
+ readOnly: !profile.touchesRepo,
624
+ systemPrompt,
625
+ shellGuard: resolvedJob.profile === "developer",
626
+ reporting: resolvedJob.profile === "developer" && !resolvedJob.outsideStage,
627
+ ...(resolvedJob.profile === "developer" &&
628
+ stage === "in_progress" &&
629
+ !resolvedJob.outsideStage
630
+ ? { continuationPrompt: () => this.continuationPrompt(ticket.id, record.id) }
631
+ : {}),
632
+ // The session lives beside the board's database, never in the person's
633
+ // home directory: a board is one repo, and its conversations go with it.
634
+ sessionId: record.session_id ?? (seedId ? record.id : undefined),
635
+ sessionDir,
636
+ });
637
+ }
638
+ catch (cause) {
639
+ const error = cause instanceof Error ? cause.message : "the agent could not start";
640
+ this.finishRecord(record.id, "failed", null, null, null, error);
641
+ const failed = {
642
+ ...status,
643
+ label: "Run failed",
644
+ phase: "failed",
645
+ endedAt: Date.now(),
646
+ error,
647
+ };
648
+ this.statuses.set(ticket.id, failed);
649
+ this.onStatus(failed);
650
+ return failed;
651
+ }
652
+ const active = {
653
+ run,
654
+ job: resolvedJob,
655
+ command,
656
+ status,
657
+ statusToken,
658
+ testsFirstEnabled,
659
+ startHead: worktreeHead(worktree.path),
660
+ cancelled: false,
661
+ settled: false,
662
+ continuations: 0,
663
+ emittedCommits: new Set(),
664
+ emittedPrUrl: null,
665
+ output: [],
666
+ partial: "",
667
+ actions: [],
668
+ toolCalls: new Map(),
669
+ commandEvidence: [...(resolvedJob.resumeEvidence ?? [])],
670
+ developerCommandEvidence: [],
671
+ checks: stage === "in_progress" && !resolvedJob.outsideStage
672
+ ? workflow.checks.map((check) => ({ label: check.label, command: check.command }))
673
+ : [],
674
+ verifyRounds: 0,
675
+ handoffRounds: 0,
676
+ verified: ticket.verify.length > 0,
677
+ repeat: { key: "", count: 0 },
678
+ nudged: false,
679
+ redSentBack: false,
680
+ startTree,
681
+ idleSentBack: false,
682
+ testsPhase,
683
+ approved: testsPhase === "implement" ? (approved?.tests ?? null) : null,
684
+ gating: false,
685
+ gateAbort: new AbortController(),
686
+ worktreePath: worktree.path,
687
+ tokens: null,
688
+ ...(resolvedJob.profile === "developer" ? { executionPhase: "inspect" } : {}),
689
+ ...(this.watchdog &&
690
+ run.sendMessage &&
691
+ resolvedJob.profile === "developer" &&
692
+ stage === "in_progress" &&
693
+ !resolvedJob.outsideStage
694
+ ? {
695
+ watchdog: {
696
+ tick: 0,
697
+ busy: false,
698
+ checks: 0,
699
+ steers: 0,
700
+ quietUntil: 0,
701
+ lastCheckAt: Date.now(),
702
+ lastSeq: 0,
703
+ edited: false,
704
+ fingerprint: null,
705
+ unchangedTicks: 0,
706
+ offPlan: new Set(),
707
+ looks: [],
708
+ },
709
+ }
710
+ : {}),
711
+ };
712
+ if (active.commandEvidence.length)
713
+ this.db.recordCommandEvidence(record.id, active.commandEvidence);
714
+ this.active.set(ticket.id, active);
715
+ this.statuses.set(ticket.id, status);
716
+ this.onStatus(status);
717
+ void this.execute(ticket.id, worktree, record.id, active);
718
+ return status;
719
+ }
720
+ async continuationPrompt(ticketId, runId) {
721
+ await this.evidenceCaughtUp(ticketId, runId);
722
+ const gate = await this.completionGate(ticketId, runId, false);
723
+ if (gate.kind === "completed" || gate.kind === "escalated")
724
+ return undefined;
725
+ if (gate.kind === "continue") {
726
+ const current = this.active.get(ticketId);
727
+ if (current?.status.runId === runId) {
728
+ this.update(ticketId, current, {
729
+ label: gate.label ?? `Fixing checks (round ${current.verifyRounds}/${MAX_VERIFY_ROUNDS})`,
730
+ tool: null,
731
+ });
732
+ }
733
+ return gate.prompt;
734
+ }
735
+ const active = this.active.get(ticketId);
736
+ if (!active ||
737
+ active.status.runId !== runId ||
738
+ active.cancelled ||
739
+ active.settled ||
740
+ active.continuations >= MAX_TURN_CONTINUATIONS ||
741
+ this.db.getTicket(ticketId)?.state !== "in_progress")
742
+ return undefined;
743
+ active.continuations += 1;
744
+ this.update(ticketId, active, {
745
+ label: `Continuing (${active.continuations}/${MAX_TURN_CONTINUATIONS})`,
746
+ tool: null,
747
+ });
748
+ return CONTINUATION_PROMPT;
749
+ }
750
+ /**
751
+ * A harness asks "keep going?" the moment it reads its own settle, which can
752
+ * be before the event loop has recorded the command that just finished: the
753
+ * loop hashes the worktree for that evidence asynchronously. Wait until every
754
+ * queued event has been handled, so the gate never misses a passing check
755
+ * the developer just ran.
756
+ */
757
+ async evidenceCaughtUp(ticketId, runId) {
758
+ for (;;) {
759
+ // Queued events reach the loop as microtasks; this runs after them.
760
+ await new Promise((resolve) => setImmediate(resolve));
761
+ const active = this.active.get(ticketId);
762
+ if (!active || active.status.runId !== runId || !active.evidencePending)
763
+ return;
764
+ await active.evidencePending.catch(() => null);
765
+ }
766
+ }
767
+ /**
768
+ * The board's own completion check for a verified In Progress ticket. The
769
+ * ticket's verify commands and the stage checks run in the worktree; when they
770
+ * pass, the board commits, pushes, opens the pull request and records the
771
+ * result. Anything else is a skip, which leaves the run to the ordinary flow.
772
+ */
773
+ async completionGate(ticketId, runId, final) {
774
+ const active = this.active.get(ticketId);
775
+ const ticket = this.db.getTicket(ticketId);
776
+ const job = active?.job;
777
+ if (!active ||
778
+ !ticket ||
779
+ !job ||
780
+ active.status.runId !== runId ||
781
+ active.cancelled ||
782
+ active.settled ||
783
+ active.gating ||
784
+ job.profile !== "developer" ||
785
+ job.outsideStage ||
786
+ (job.stage ?? "in_progress") !== "in_progress" ||
787
+ ticket.state !== "in_progress" ||
788
+ ticket.verify.length === 0)
789
+ return { kind: "skip" };
790
+ active.gating = true;
791
+ this.update(ticketId, active, { label: "Verifying", tool: null });
792
+ try {
793
+ return await this.verifyTicket(ticketId, runId, active, ticket, final);
794
+ }
795
+ catch (cause) {
796
+ const message = cause instanceof Error ? cause.message : String(cause);
797
+ this.db.addComment({
798
+ ticket_id: ticketId,
799
+ type: "system",
800
+ author: "zelio",
801
+ text: `The board could not verify this run: ${message}`,
802
+ });
803
+ return { kind: "skip" };
804
+ }
805
+ finally {
806
+ active.gating = false;
807
+ }
808
+ }
809
+ async verifyTicket(ticketId, runId, active, ticket, final) {
810
+ const cwd = active.worktreePath;
811
+ const max = MAX_VERIFY_ROUNDS;
812
+ if (active.testsPhase === "tests")
813
+ return this.testsGate(ticketId, runId, active, ticket, final);
814
+ const changed = await hasTicketChanges(cwd);
815
+ if (!this.isLive(ticketId, active))
816
+ return { kind: "skip" };
817
+ if (!changed) {
818
+ return this.failRound(ticketId, runId, active, final, {
819
+ prompt: NO_CHANGES_PROMPT,
820
+ summary: "no changes for the ticket",
821
+ blocked: {
822
+ summary: `The ticket still has no changes after ${max} verification rounds.`,
823
+ reason: `the worktree still has no changes for the ticket after ${max} verification rounds`,
824
+ unblock: "Implement the ticket so its Verify commands pass, then mention @developer to continue.",
825
+ detail: "",
826
+ },
827
+ });
828
+ }
829
+ // The ticket has work, but this run may have added none: a run told to make
830
+ // a change that ends after reading files is not done because an earlier
831
+ // run's work still passes. It is sent back once; a second time it goes on,
832
+ // because a question needs no edit. Only a run asked for a change has a
833
+ // start tree to compare with.
834
+ const nowTree = active.startTree === null ? null : worktreeTree(cwd);
835
+ const idle = nowTree !== null && nowTree === active.startTree;
836
+ if (idle && !active.idleSentBack) {
837
+ active.idleSentBack = true;
838
+ const nowPrint = await worktreeFingerprint(cwd);
839
+ if (!this.isLive(ticketId, active))
840
+ return { kind: "skip" };
841
+ return this.failRound(ticketId, runId, active, final, {
842
+ prompt: IDLE_RUN_PROMPT,
843
+ summary: "the run changed nothing",
844
+ check: "the run changed nothing",
845
+ fingerprint: nowPrint,
846
+ blocked: {
847
+ summary: `The run still changed nothing after ${max} rounds.`,
848
+ reason: `the run ended without changing the worktree after ${max} verification rounds`,
849
+ unblock: "Make the requested change, then mention @developer to continue.",
850
+ detail: "",
851
+ },
852
+ });
853
+ }
854
+ // Requiring a local pass before this stage makes the handoff meaningful:
855
+ // otherwise the board would be the first actor to discover a known failure.
856
+ // Evidence is tied to both a completed bash call and the exact worktree
857
+ // content at its end; edits after the pass make it stale.
858
+ const currentRevision = await evidenceRevision(cwd);
859
+ if (!this.isLive(ticketId, active))
860
+ return { kind: "skip" };
861
+ const inFlightCommands = [...active.toolCalls.values()]
862
+ .filter((call) => call.tool === "bash" && call.command)
863
+ .flatMap((call) => {
864
+ const base = unpipedCommand(call.command);
865
+ return base ? [call.command, base] : [call.command];
866
+ });
867
+ const missingDeveloperChecks = ticket.verify.filter((check) => !developerCheckPassed(check.command, active.developerCommandEvidence, inFlightCommands, currentRevision));
868
+ if (missingDeveloperChecks.length) {
869
+ const commands = missingDeveloperChecks.map((check) => `\`${check.command}\``).join(", ");
870
+ return this.failRound(ticketId, runId, active, final, {
871
+ handoffOnly: true,
872
+ prompt: `Before handing this ticket to the board, run and finish these Verify commands yourself, each in its own shell call and exactly as written, without piping the output through tail, head or grep: ${commands}. The board will wait for your checks before its next verification. A command that is still running, failed, or passed before your latest edits does not count. If the shell returns a session id, keep reading that same session until it exits, then fix any failure and run the command again.`,
873
+ summary: `the developer did not finish Verify: ${missingDeveloperChecks.map((check) => check.label).join(", ")}`,
874
+ blocked: {
875
+ summary: `The developer did not finish the ticket's Verify command after ${MAX_VERIFY_ROUNDS} handoff attempts.`,
876
+ reason: `the developer did not record completed passing runs of ${commands} against the current worktree after ${MAX_VERIFY_ROUNDS} handoff attempts`,
877
+ unblock: `Run ${commands} in the ticket worktree, fix any failure, and continue the ticket.`,
878
+ detail: "",
879
+ },
880
+ });
881
+ }
882
+ // Implementing against approved tests: they may be fixed and may grow, but
883
+ // no approved check may go.
884
+ if (active.testsPhase === "implement" && active.approved) {
885
+ const weakened = await weakenedTests(cwd, active.approved.sha, active.approved.files);
886
+ if (!this.isLive(ticketId, active))
887
+ return { kind: "skip" };
888
+ if (weakened.length > 0) {
889
+ const fingerprint = await worktreeFingerprint(cwd);
890
+ if (!this.isLive(ticketId, active))
891
+ return { kind: "skip" };
892
+ return this.failRound(ticketId, runId, active, final, {
893
+ prompt: testsChangedPrompt(weakened),
894
+ summary: "an approved check was removed",
895
+ check: "approved tests kept",
896
+ fingerprint,
897
+ blocked: {
898
+ summary: `The approved tests were still changed after ${max} rounds.`,
899
+ reason: `approved checks in ${weakened.map((item) => item.file).join(", ")} were removed or changed after ${max} verification rounds`,
900
+ unblock: "Restore the approved tests, or mention @developer with the change you want to the tests.",
901
+ detail: "",
902
+ },
903
+ });
904
+ }
905
+ }
906
+ const checks = [...ticket.verify, ...active.checks];
907
+ const env = this.agentPath
908
+ ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
909
+ : process.env;
910
+ const results = await runChecks(cwd, checks, {
911
+ env,
912
+ signal: active.gateAbort.signal,
913
+ rerunFailed: true,
914
+ });
915
+ if (!this.isLive(ticketId, active))
916
+ return { kind: "skip" };
917
+ // A check that exited or hit its timeout ran for a real duration; one that
918
+ // never started or was aborted did not, and leaves the last one in place.
919
+ for (const result of results) {
920
+ if (result.exitCode === null && !result.timedOut)
921
+ continue;
922
+ this.db.recordCommandDuration(ticket.repo ?? null, result.command, result.durationMs);
923
+ }
924
+ for (const result of results.filter((item) => item.flaky)) {
925
+ this.db.addComment({
926
+ ticket_id: ticketId,
927
+ type: "system",
928
+ author: "zelio",
929
+ text: `Check "${result.label}" failed once and passed on rerun, so the board counted it as passed. It looks flaky: \`${result.command}\`.`,
930
+ });
931
+ }
932
+ for (const result of results) {
933
+ active.commandEvidence.push({
934
+ id: randomUUID(),
935
+ command: result.command,
936
+ outcome: result.passed ? "passed" : "failed",
937
+ revision: null,
938
+ });
939
+ }
940
+ active.commandEvidence = active.commandEvidence.slice(-64);
941
+ this.db.recordCommandEvidence(runId, active.commandEvidence);
942
+ // The board's checks land in the trace, so a timeout reads as a timeout
943
+ // there rather than hiding behind the agent's own passing run.
944
+ active.actions = checkActions(active.actions, results);
945
+ this.update(ticketId, active, { actions: active.actions });
946
+ const failed = results.find((result) => !result.passed);
947
+ if (failed) {
948
+ const detail = failureReport(results);
949
+ const fingerprint = await worktreeFingerprint(cwd);
950
+ if (!this.isLive(ticketId, active))
951
+ return { kind: "skip" };
952
+ return this.failRound(ticketId, runId, active, final, {
953
+ prompt: `${VERIFY_FAILED_PROMPT}\n\n${detail}`,
954
+ summary: failed.timedOut ? `${failed.label} timed out` : failed.label,
955
+ outcome: failed.timedOut ? "Check timed out" : "Check failed",
956
+ check: failed.label,
957
+ fingerprint,
958
+ blocked: {
959
+ summary: `The board's checks still fail after ${max} rounds.`,
960
+ reason: `Check "${failed.label}" still fails after ${max} verification rounds: ${failed.command}`,
961
+ unblock: "Fix the failing check or correct the ticket's verify commands, then mention @developer to continue.",
962
+ detail,
963
+ },
964
+ });
965
+ }
966
+ // Passing checks must also fail on the code before the change; otherwise
967
+ // they prove nothing, and the developer is asked for tests that do.
968
+ if (this.redCheckEnabled) {
969
+ this.update(ticketId, active, {
970
+ label: "Checking the tests fail without the change",
971
+ tool: null,
972
+ });
973
+ const red = await redCheck(cwd, ticket.verify, { env, signal: active.gateAbort.signal });
974
+ if (!this.isLive(ticketId, active))
975
+ return { kind: "skip" };
976
+ if (red.kind === "proves-nothing" && active.redSentBack) {
977
+ this.db.addComment({
978
+ ticket_id: ticketId,
979
+ type: "system",
980
+ author: "zelio",
981
+ text: RED_CHECK_STILL_PASSES,
982
+ });
983
+ }
984
+ else if (red.kind === "proves-nothing") {
985
+ active.redSentBack = true;
986
+ const fingerprint = await worktreeFingerprint(cwd);
987
+ if (!this.isLive(ticketId, active))
988
+ return { kind: "skip" };
989
+ return this.failRound(ticketId, runId, active, final, {
990
+ prompt: `${RED_CHECK_PROMPT}\n\nTest files the board copied onto the old code: ${red.testFiles.join(", ") || "none"}`,
991
+ summary: "the tests pass without the change",
992
+ check: "tests fail without the change",
993
+ fingerprint,
994
+ blocked: {
995
+ summary: `The ticket's tests still pass without the change after ${max} rounds.`,
996
+ reason: `The Verify commands pass on the code before the change after ${max} verification rounds, so they do not test the ticket`,
997
+ unblock: "Add tests that fail without the change, or correct the ticket's verify commands, then mention @developer to continue.",
998
+ detail: "",
999
+ },
1000
+ });
1001
+ }
1002
+ if (red.kind === "unavailable") {
1003
+ this.db.addComment({
1004
+ ticket_id: ticketId,
1005
+ type: "system",
1006
+ author: "zelio",
1007
+ text: `The board could not check that the tests fail without the change: ${red.reason}`,
1008
+ });
1009
+ }
1010
+ }
1011
+ // Checks prove what they test; the review asks whether the person got what
1012
+ // they asked for, before anything is committed or published.
1013
+ const review = await this.autoReview(ticketId, active, ticket);
1014
+ if (review)
1015
+ return review;
1016
+ if (!this.isLive(ticketId, active))
1017
+ return { kind: "skip" };
1018
+ const branch = ticket.branch?.trim() || (await currentBranch(cwd));
1019
+ if (!this.isLive(ticketId, active))
1020
+ return { kind: "skip" };
1021
+ const commit = await commitTicketWork(cwd, commitMessage(ticket.title, branch));
1022
+ if (!this.isLive(ticketId, active))
1023
+ return { kind: "skip" };
1024
+ if (commit.error) {
1025
+ const hook = `The commit hook failed:\n\n\`\`\`text\n${commit.error}\n\`\`\``;
1026
+ return this.failRound(ticketId, runId, active, final, {
1027
+ prompt: `${VERIFY_FAILED_PROMPT}\n\n${hook}`,
1028
+ summary: "the commit hook failed",
1029
+ blocked: {
1030
+ summary: `The commit hook still fails after ${max} rounds.`,
1031
+ reason: `The commit hook still fails after ${max} verification rounds`,
1032
+ unblock: "Fix the commit hook failure, then mention @developer to continue.",
1033
+ detail: hook,
1034
+ },
1035
+ });
1036
+ }
1037
+ const prBody = [
1038
+ `## Goal\n\n${ticket.goal.trim() || ticket.title}`,
1039
+ `## Acceptance\n\n${ticket.acceptance.trim() || "See the ticket."}`,
1040
+ [
1041
+ "## Verified by Zelio",
1042
+ ...results.map((result) => `- ${result.label}: \`${result.command}\` — passed in ${seconds(result.durationMs)}s`),
1043
+ ].join("\n"),
1044
+ ].join("\n\n");
1045
+ const publish = branch
1046
+ ? await publishBranch(cwd, branch, { title: ticket.title, body: prBody }, { gh: this.ghCommand })
1047
+ : { pushed: false, prUrl: null, error: "the worktree is not on a branch" };
1048
+ if (!this.isLive(ticketId, active))
1049
+ return { kind: "skip" };
1050
+ const summary = [
1051
+ `Verified by the board: ${results.length} ${results.length === 1 ? "check" : "checks"} passed.`,
1052
+ publish.prUrl ? `Pull request: ${publish.prUrl}.` : "",
1053
+ publish.error
1054
+ ? `Publishing failed: ${publish.error}. The work is committed on ${branch} at ${commit.head?.slice(0, 7) ?? "an unknown commit"}.`
1055
+ : "",
1056
+ commit.refused.length ? `Not committed (secret-looking): ${commit.refused.join(", ")}.` : "",
1057
+ ]
1058
+ .filter(Boolean)
1059
+ .join(" ");
1060
+ const report = {
1061
+ outcome: "ready_for_review",
1062
+ summary,
1063
+ required_evidence: results.map((result) => ({
1064
+ requirement: result.label,
1065
+ result: "met",
1066
+ evidence: `exit 0 in ${seconds(result.durationMs)}s`,
1067
+ command: result.command,
1068
+ })),
1069
+ remaining_assurance: [],
1070
+ };
1071
+ this.db.recordAgentResult(runId, report, resultComment(report));
1072
+ if (publish.prUrl)
1073
+ this.db.setPullRequest(ticketId, publish.prUrl);
1074
+ active.settled = true;
1075
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1076
+ return { kind: "completed" };
1077
+ }
1078
+ /**
1079
+ * The end of a tests-only turn. The tests must be the only change, must fail
1080
+ * on the code as it is, and must pass the test review; then the board commits
1081
+ * them and the same session goes on to implement against them. Anything else
1082
+ * sends the turn back the way a failed check does.
1083
+ */
1084
+ async testsGate(ticketId, runId, active, ticket, final) {
1085
+ const cwd = active.worktreePath;
1086
+ const max = MAX_VERIFY_ROUNDS;
1087
+ const sendBack = async (prompt, summary, reason) => {
1088
+ const fingerprint = await worktreeFingerprint(cwd);
1089
+ if (!this.isLive(ticketId, active))
1090
+ return { kind: "skip" };
1091
+ return this.failRound(ticketId, runId, active, final, {
1092
+ prompt,
1093
+ summary,
1094
+ check: summary,
1095
+ fingerprint,
1096
+ blocked: {
1097
+ summary: `The tests were still not ready after ${max} rounds: ${summary}.`,
1098
+ reason: `${reason} after ${max} verification rounds`,
1099
+ unblock: "Write tests that fail on the current code and check what was asked, then mention @developer to continue.",
1100
+ detail: "",
1101
+ },
1102
+ });
1103
+ };
1104
+ const changes = await ticketChanges(cwd);
1105
+ if (!this.isLive(ticketId, active))
1106
+ return { kind: "skip" };
1107
+ if (!changes) {
1108
+ // Without a base the board cannot tell tests from code; it does not hold
1109
+ // the ticket for that, and the run implements without the test phase.
1110
+ this.db.addComment({
1111
+ ticket_id: ticketId,
1112
+ type: "system",
1113
+ author: "zelio",
1114
+ text: "The board could not find the base to check the tests against, so this ticket skips the test phase.",
1115
+ });
1116
+ active.testsPhase = null;
1117
+ return this.verifyTicket(ticketId, runId, active, ticket, final);
1118
+ }
1119
+ const tests = changes.files.filter(isTestPath);
1120
+ const others = changes.files.filter((file) => !isTestPath(file));
1121
+ if (tests.length === 0) {
1122
+ return sendBack(TESTS_MISSING_PROMPT, "no tests were written", "no test file changed");
1123
+ }
1124
+ if (others.length > 0) {
1125
+ return sendBack(testsOnlyPrompt(others), "files outside tests changed", `files outside tests changed in the test phase (${others.join(", ")})`);
1126
+ }
1127
+ // The code is untouched, so the ticket's checks run here exactly as they
1128
+ // would on the old code: one of them has to fail.
1129
+ this.update(ticketId, active, { label: "Checking the tests fail", tool: null });
1130
+ const env = this.agentPath
1131
+ ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
1132
+ : process.env;
1133
+ const results = await runChecks(cwd, ticket.verify, { env, signal: active.gateAbort.signal });
1134
+ if (!this.isLive(ticketId, active))
1135
+ return { kind: "skip" };
1136
+ if (results.length === ticket.verify.length && results.every((result) => result.passed)) {
1137
+ return sendBack(TESTS_PASS_ALREADY_PROMPT, "the tests pass without the change", "the tests pass on the code before the change");
1138
+ }
1139
+ const diff = await testsDiff(cwd, changes.mergeBase, tests);
1140
+ if (!this.isLive(ticketId, active))
1141
+ return { kind: "skip" };
1142
+ const review = await this.testReview(ticketId, active, ticket, diff);
1143
+ if (review)
1144
+ return review;
1145
+ if (!this.isLive(ticketId, active))
1146
+ return { kind: "skip" };
1147
+ const commit = await commitTicketWork(cwd, `test: ${ticket.title}`);
1148
+ if (!this.isLive(ticketId, active))
1149
+ return { kind: "skip" };
1150
+ if (commit.error || !commit.head) {
1151
+ const hook = commit.error
1152
+ ? `The commit hook failed:\n\n\`\`\`text\n${commit.error}\n\`\`\``
1153
+ : "The board could not commit the tests.";
1154
+ return sendBack(`${VERIFY_FAILED_PROMPT}\n\n${hook}`, "the tests could not be committed", "the tests could not be committed");
1155
+ }
1156
+ this.db.addComment({
1157
+ ticket_id: ticketId,
1158
+ type: "system",
1159
+ author: "zelio",
1160
+ text: approvalComment(commit.head, tests),
1161
+ });
1162
+ active.testsPhase = "implement";
1163
+ active.approved = { sha: commit.head, files: tests };
1164
+ // The test phase's rounds were spent on the tests; implementing starts fresh.
1165
+ active.verifyRounds = 0;
1166
+ active.lastFailure = undefined;
1167
+ return {
1168
+ kind: "continue",
1169
+ prompt: implementPrompt(commit.head, tests),
1170
+ summary: "the tests were approved",
1171
+ label: "Implementing against the approved tests",
1172
+ };
1173
+ }
1174
+ /**
1175
+ * The reviewer reads the tests alone against the person's request. Null means
1176
+ * approve them: they passed, the review gave no usable answer or is not
1177
+ * configured, or it has sent them back as often as it may.
1178
+ */
1179
+ async testReview(ticketId, active, ticket, diff) {
1180
+ const reviewer = this.reviewer;
1181
+ if (!reviewer)
1182
+ return null;
1183
+ const note = (text) => this.db.addComment({ ticket_id: ticketId, type: "system", author: "zelio", text });
1184
+ const earlier = this.db
1185
+ .listComments(ticketId)
1186
+ .filter((comment) => comment.author === "reviewer" &&
1187
+ comment.type === "review" &&
1188
+ comment.text.startsWith(TEST_REVIEW_HEADING))
1189
+ .map((comment) => comment.text.slice(TEST_REVIEW_HEADING.length).trim());
1190
+ if (earlier.length >= MAX_TEST_REVIEWS) {
1191
+ note(`The test review sent the tests back ${MAX_TEST_REVIEWS} times; the board approves them as they are, with the last findings above for Review.`);
1192
+ return null;
1193
+ }
1194
+ const round = earlier.length + 1;
1195
+ this.update(ticketId, active, { label: "Reviewing the tests", tool: null });
1196
+ let verdict = null;
1197
+ try {
1198
+ verdict = await reviewer({
1199
+ ticketId,
1200
+ title: ticket.title,
1201
+ goal: ticket.goal,
1202
+ outOfScope: ticket.out_of_scope,
1203
+ acceptance: ticket.acceptance,
1204
+ context: [...(ticket.context ?? [])],
1205
+ screenshots: absoluteAttachments(this.repoRoot, ticket.attachments),
1206
+ diff,
1207
+ round,
1208
+ earlier,
1209
+ worktreePath: active.worktreePath,
1210
+ focus: "tests",
1211
+ });
1212
+ }
1213
+ catch {
1214
+ verdict = null;
1215
+ }
1216
+ if (!this.isLive(ticketId, active))
1217
+ return { kind: "skip" };
1218
+ if (!verdict) {
1219
+ note("The test review gave no usable answer, so the board approves the tests unreviewed.");
1220
+ return null;
1221
+ }
1222
+ if (verdict.verdict === "pass") {
1223
+ this.db.addComment({
1224
+ ticket_id: ticketId,
1225
+ type: "review",
1226
+ author: "reviewer",
1227
+ text: `Test review passed: ${verdict.summary}`,
1228
+ });
1229
+ return null;
1230
+ }
1231
+ this.db.addComment({
1232
+ ticket_id: ticketId,
1233
+ type: "review",
1234
+ author: "reviewer",
1235
+ text: `${TEST_REVIEW_HEADING}\n\n${verdict.findings}`,
1236
+ });
1237
+ return {
1238
+ kind: "continue",
1239
+ prompt: `${TEST_REVIEW_CHANGES_PROMPT}\n\n## Test review findings\n\n${verdict.findings}`,
1240
+ summary: "the test review asked for changes",
1241
+ label: `Revising the tests (round ${round}/${MAX_TEST_REVIEWS})`,
1242
+ };
1243
+ }
1244
+ /**
1245
+ * The automatic review between passing checks and publishing. Null means go
1246
+ * on and publish: the review passed, gave no usable answer, is not
1247
+ * configured, or has already sent this ticket back as often as it may. A
1248
+ * "changes" verdict returns the findings as the developer's next prompt.
1249
+ */
1250
+ async autoReview(ticketId, active, ticket) {
1251
+ const reviewer = this.reviewer;
1252
+ if (!reviewer)
1253
+ return null;
1254
+ const note = (text) => this.db.addComment({ ticket_id: ticketId, type: "system", author: "zelio", text });
1255
+ const earlier = this.db
1256
+ .listComments(ticketId)
1257
+ .filter((comment) => comment.author === "reviewer" &&
1258
+ comment.type === "review" &&
1259
+ comment.text.startsWith(REVIEW_CHANGES_HEADING))
1260
+ .map((comment) => comment.text.slice(REVIEW_CHANGES_HEADING.length).trim());
1261
+ if (earlier.length >= MAX_AUTO_REVIEWS) {
1262
+ note(`The automatic review sent this ticket back ${MAX_AUTO_REVIEWS} times; it goes to Review for you to decide, with the last findings above.`);
1263
+ return null;
1264
+ }
1265
+ const round = earlier.length + 1;
1266
+ this.update(ticketId, active, { label: "Reviewing against the request", tool: null });
1267
+ let verdict = null;
1268
+ try {
1269
+ verdict = await reviewer({
1270
+ ticketId,
1271
+ title: ticket.title,
1272
+ goal: ticket.goal,
1273
+ outOfScope: ticket.out_of_scope,
1274
+ acceptance: ticket.acceptance,
1275
+ context: [...(ticket.context ?? [])],
1276
+ screenshots: absoluteAttachments(this.repoRoot, ticket.attachments),
1277
+ diff: await ticketDiff(active.worktreePath),
1278
+ round,
1279
+ earlier,
1280
+ worktreePath: active.worktreePath,
1281
+ testsReviewed: active.testsFirstEnabled && approvedTests(this.db.listComments(ticketId)) !== null,
1282
+ });
1283
+ }
1284
+ catch {
1285
+ verdict = null;
1286
+ }
1287
+ if (!this.isLive(ticketId, active))
1288
+ return { kind: "skip" };
1289
+ if (!verdict) {
1290
+ note("The automatic review gave no usable answer, so this ticket goes to Review unreviewed.");
1291
+ return null;
1292
+ }
1293
+ if (verdict.verdict === "pass") {
1294
+ this.db.addComment({
1295
+ ticket_id: ticketId,
1296
+ type: "review",
1297
+ author: "reviewer",
1298
+ text: `Automatic review passed: ${verdict.summary}`,
1299
+ });
1300
+ return null;
1301
+ }
1302
+ this.db.addComment({
1303
+ ticket_id: ticketId,
1304
+ type: "review",
1305
+ author: "reviewer",
1306
+ text: `${REVIEW_CHANGES_HEADING}\n\n${verdict.findings}`,
1307
+ });
1308
+ return {
1309
+ kind: "continue",
1310
+ prompt: `${REVIEW_CHANGES_PROMPT}\n\n## Review findings\n\n${verdict.findings}`,
1311
+ summary: "the automatic review asked for changes",
1312
+ label: `Addressing review (round ${round}/${MAX_AUTO_REVIEWS})`,
1313
+ };
1314
+ }
1315
+ /** One failed round: send the run back while rounds remain, otherwise block the ticket. */
1316
+ failRound(ticketId, runId, active, final, round) {
1317
+ const rounds = round.handoffOnly ? ++active.handoffRounds : ++active.verifyRounds;
1318
+ // The same check failing again on work that did not change is the developer
1319
+ // repeating itself: the lead is asked now, not after the rounds run out.
1320
+ const previous = active.lastFailure;
1321
+ const repeated = round.check !== undefined &&
1322
+ round.fingerprint != null &&
1323
+ previous?.check === round.check &&
1324
+ previous.fingerprint === round.fingerprint;
1325
+ active.lastFailure =
1326
+ round.check === undefined
1327
+ ? undefined
1328
+ : { check: round.check, fingerprint: round.fingerprint ?? null };
1329
+ const exhausted = rounds > MAX_VERIFY_ROUNDS;
1330
+ if (exhausted || repeated) {
1331
+ const { blocked } = round;
1332
+ const current = this.db.getTicket(ticketId);
1333
+ if (current && this.canConsultLead(current)) {
1334
+ active.leadRequest = {
1335
+ trigger: "checks_failing",
1336
+ reason: exhausted
1337
+ ? blocked.reason
1338
+ : `Check "${round.check}" failed again and the work did not change between the rounds.`,
1339
+ failure: blocked.detail,
1340
+ };
1341
+ active.settled = true;
1342
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
1343
+ return { kind: "escalated" };
1344
+ }
1345
+ }
1346
+ if (exhausted) {
1347
+ const { blocked } = round;
1348
+ const current = this.db.getTicket(ticketId);
1349
+ const report = {
1350
+ outcome: "blocked",
1351
+ summary: blocked.summary,
1352
+ required_evidence: [],
1353
+ remaining_assurance: [],
1354
+ reason: `${current ? this.leadLimitNote(current) : ""}${blocked.reason}`,
1355
+ unblock: blocked.unblock,
1356
+ };
1357
+ const text = [resultComment(report), blocked.detail].filter(Boolean).join("\n\n");
1358
+ this.db.recordAgentResult(runId, report, text);
1359
+ active.settled = true;
1360
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1361
+ return { kind: "escalated" };
1362
+ }
1363
+ // After the process has gone there is no session to send the prompt to.
1364
+ if (final)
1365
+ this.update(ticketId, active, { label: round.outcome ?? "Checks failed", tool: null });
1366
+ return {
1367
+ kind: "continue",
1368
+ prompt: round.prompt,
1369
+ summary: round.summary,
1370
+ ...(round.outcome && !round.handoffOnly
1371
+ ? { label: `${round.outcome}, fixing (round ${rounds}/${MAX_VERIFY_ROUNDS})` }
1372
+ : {}),
1373
+ };
1374
+ }
1375
+ /** Counts identical tool calls in a row; the fourth one sends the nudge, once per run. */
1376
+ noteRepeat(active, tool, args) {
1377
+ if (!active.verified || active.nudged || !active.run.sendMessage)
1378
+ return;
1379
+ const key = `${tool} ${stableJson(args)}`;
1380
+ active.repeat = { key, count: active.repeat.key === key ? active.repeat.count + 1 : 1 };
1381
+ if (active.repeat.count < REPEAT_NUDGE_AT)
1382
+ return;
1383
+ active.nudged = true;
1384
+ void active.run.sendMessage(REPEAT_NUDGE).catch(() => false);
1385
+ }
1386
+ /** The watchdog's comments on a ticket that are steers, oldest first. */
1387
+ watchdogSteers(ticketId) {
1388
+ return this.db
1389
+ .listComments(ticketId)
1390
+ .filter((comment) => comment.author === "watchdog" && comment.text.startsWith(STEER_HEADING))
1391
+ .map((comment) => comment.text);
1392
+ }
1393
+ /**
1394
+ * One watchdog tick. The signals cost nothing; a model looks only when one
1395
+ * fires or the backstop comes due, never twice at once, and not during a
1396
+ * steer's cooldown or while the board's own checks run.
1397
+ */
1398
+ async watchdogTick(ticketId, worktree, runId, active) {
1399
+ const dog = active.watchdog;
1400
+ const watchdog = this.watchdog;
1401
+ if (!dog || !watchdog || dog.busy)
1402
+ return;
1403
+ if (!this.isLive(ticketId, active) || active.gating)
1404
+ return;
1405
+ dog.busy = true;
1406
+ try {
1407
+ await this.watchdogLook(ticketId, worktree, runId, active, dog, watchdog);
1408
+ }
1409
+ finally {
1410
+ dog.busy = false;
1411
+ }
1412
+ }
1413
+ async watchdogLook(ticketId, worktree, runId, active, dog, watchdog) {
1414
+ dog.tick += 1;
1415
+ const print = await worktreeFingerprint(worktree.path);
1416
+ dog.unchangedTicks = print !== null && print === dog.fingerprint ? dog.unchangedTicks + 1 : 0;
1417
+ dog.fingerprint = print;
1418
+ if (dog.tick < dog.quietUntil || dog.checks >= MAX_WATCHDOG_CHECKS)
1419
+ return;
1420
+ const ticket = this.db.getTicket(ticketId);
1421
+ if (!ticket || !this.isLive(ticketId, active) || active.gating)
1422
+ return;
1423
+ const calls = this.db.listToolCalls(runId);
1424
+ const { signals, offPlan } = watchdogSignals(calls, dog, {
1425
+ likelyFiles: ticket.likely_files,
1426
+ worktreePath: worktree.path,
1427
+ });
1428
+ const now = Date.now();
1429
+ const due = now - dog.lastCheckAt >= (watchdog.backstopMs ?? WATCHDOG_BACKSTOP_MS);
1430
+ if (signals.length === 0 && !due)
1431
+ return;
1432
+ // The window moves on now, so what this look answers is not raised again.
1433
+ const window = calls.filter((call) => call.seq > dog.lastSeq);
1434
+ dog.lastSeq = calls.at(-1)?.seq ?? dog.lastSeq;
1435
+ dog.edited ||= window.some((call) => (call.tool === "edit" || call.tool === "write") && call.state === "done");
1436
+ for (const path of offPlan)
1437
+ dog.offPlan.add(path);
1438
+ if (signals.some((signal) => signal.kind === "stalled"))
1439
+ dog.unchangedTicks = 0;
1440
+ dog.checks += 1;
1441
+ dog.lastCheckAt = now;
1442
+ const reasons = signals.length > 0
1443
+ ? signals.map((signal) => signal.text)
1444
+ : ["routine look: nothing has looked at this run for a while"];
1445
+ const look = { at: now - active.status.startedAt, reasons, answer: "pending" };
1446
+ dog.looks.push(look);
1447
+ const row = `watchdog-${runId}-${dog.looks.length}`;
1448
+ this.showLook(ticketId, active, look, row);
1449
+ const answered = (answer) => {
1450
+ look.answer = answer;
1451
+ this.showLook(ticketId, active, look, row);
1452
+ };
1453
+ const decision = await watchdog
1454
+ .consult({
1455
+ ticketId,
1456
+ title: ticket.title,
1457
+ goal: ticket.goal,
1458
+ outOfScope: ticket.out_of_scope,
1459
+ acceptance: ticket.acceptance,
1460
+ likelyFiles: [...ticket.likely_files],
1461
+ verify: ticket.verify,
1462
+ reasons,
1463
+ minutes: Math.round((now - active.status.startedAt) / 60_000),
1464
+ leadGuidance: this.db
1465
+ .listComments(ticketId)
1466
+ .filter((comment) => comment.author === "lead")
1467
+ .map((comment) => comment.text),
1468
+ earlierSteers: this.watchdogSteers(ticketId),
1469
+ steersLeft: MAX_WATCHDOG_STEERS - dog.steers,
1470
+ calls: callLines(calls),
1471
+ diff: await ticketDiff(worktree.path, 8_000),
1472
+ worktreePath: worktree.path,
1473
+ })
1474
+ .catch(() => null);
1475
+ // No answer is "continue": a watchdog that fails is a look that did not happen.
1476
+ if (!decision || decision.decision === "continue") {
1477
+ answered(decision ? "continue" : "none");
1478
+ return;
1479
+ }
1480
+ // An answer that lands after the run ended or reached its checks is not applied.
1481
+ if (!this.isLive(ticketId, active) || active.gating)
1482
+ return;
1483
+ if (decision.decision === "steer" &&
1484
+ dog.steers < MAX_WATCHDOG_STEERS &&
1485
+ active.run.sendMessage) {
1486
+ const accepted = await active.run
1487
+ .sendMessage(`A message from the board's watchdog, which is watching this run: ${decision.message}`)
1488
+ .catch(() => false);
1489
+ if (!accepted || !this.isLive(ticketId, active)) {
1490
+ answered("none");
1491
+ return;
1492
+ }
1493
+ answered("steer");
1494
+ dog.steers += 1;
1495
+ dog.quietUntil = dog.tick + 1 + WATCHDOG_COOLDOWN_TICKS;
1496
+ this.db.addComment({
1497
+ ticket_id: ticketId,
1498
+ type: "system",
1499
+ author: "watchdog",
1500
+ text: [
1501
+ `${STEER_HEADING} ${dog.steers} of ${MAX_WATCHDOG_STEERS}:`,
1502
+ "",
1503
+ decision.message,
1504
+ "",
1505
+ `Why it looked: ${reasons.join("; ")}`,
1506
+ ].join("\n"),
1507
+ run_id: runId,
1508
+ });
1509
+ return;
1510
+ }
1511
+ const reason = decision.decision === "escalate"
1512
+ ? decision.reason
1513
+ : `the run still needed steering after ${MAX_WATCHDOG_STEERS} messages: ${decision.message}`;
1514
+ if (!this.canConsultLead(ticket)) {
1515
+ // Nothing more a look can do for this run; stop paying for them.
1516
+ dog.checks = MAX_WATCHDOG_CHECKS;
1517
+ answered("lead_unavailable");
1518
+ this.db.addComment({
1519
+ ticket_id: ticketId,
1520
+ type: "system",
1521
+ author: "watchdog",
1522
+ text: `The watchdog would hand this run to the lead, but the lead is not available for this ticket, so the run goes on. Reason: ${reason}`,
1523
+ run_id: runId,
1524
+ });
1525
+ return;
1526
+ }
1527
+ this.db.addComment({
1528
+ ticket_id: ticketId,
1529
+ type: "system",
1530
+ author: "watchdog",
1531
+ text: `The watchdog stopped this run for the lead: ${reason}`,
1532
+ run_id: runId,
1533
+ });
1534
+ answered("escalate");
1535
+ // Settled first, so the abort reads as the board's own stop and the
1536
+ // completion gate skips a run that did not finish.
1537
+ active.leadRequest = { trigger: "drifting", reason, failure: "" };
1538
+ active.settled = true;
1539
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
1540
+ active.run.abort();
1541
+ }
1542
+ /**
1543
+ * A look's row in the run trace: "looking" while it is out, its answer once it
1544
+ * has one. Only the run that is still the ticket's current one is republished,
1545
+ * so a late answer never overwrites a finished run's status.
1546
+ */
1547
+ showLook(ticketId, active, look, id) {
1548
+ const label = lookLabel(look);
1549
+ const done = look.answer !== "pending";
1550
+ active.actions = active.actions.some((action) => action.id === id)
1551
+ ? active.actions.map((action) => action.id === id
1552
+ ? { ...action, label, state: done ? "done" : "running", endedAt: Date.now() }
1553
+ : action)
1554
+ : startAction(active.actions, {
1555
+ tool: "watchdog",
1556
+ label,
1557
+ detail: look.reasons.join("; ").slice(0, 160),
1558
+ callId: id,
1559
+ });
1560
+ if (this.active.get(ticketId) === active) {
1561
+ this.update(ticketId, active, { actions: active.actions });
1562
+ }
1563
+ }
1564
+ isLive(ticketId, active) {
1565
+ return (this.active.get(ticketId) === active &&
1566
+ !active.cancelled &&
1567
+ !active.settled &&
1568
+ this.db.getTicket(ticketId)?.state === "in_progress");
1569
+ }
1570
+ cancel(ticketId) {
1571
+ const active = this.active.get(ticketId);
1572
+ if (!active)
1573
+ return false;
1574
+ active.cancelled = true;
1575
+ this.update(ticketId, active, { label: "Cancelling", tool: null });
1576
+ active.gateAbort.abort();
1577
+ active.run.abort();
1578
+ return true;
1579
+ }
1580
+ /**
1581
+ * The agent said what happened, so the process has done its job. Stop it
1582
+ * without recording a user cancellation; the ticket move is the record.
1583
+ */
1584
+ settle(ticketId) {
1585
+ const active = this.active.get(ticketId);
1586
+ if (!active || active.settled || active.cancelled)
1587
+ return false;
1588
+ active.settled = true;
1589
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1590
+ active.run.abort();
1591
+ return true;
1592
+ }
1593
+ async reportResult(ticketId, report) {
1594
+ const active = this.active.get(ticketId);
1595
+ if (!active || active.cancelled || active.job.outsideStage || active.job.stage === "review") {
1596
+ return { ok: false, error: "no writable ticket run is accepting results" };
1597
+ }
1598
+ if (report.outcome === "ready_for_review" &&
1599
+ (this.db.getTicket(ticketId)?.verify.length ?? 0) > 0) {
1600
+ return {
1601
+ ok: false,
1602
+ 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.",
1603
+ };
1604
+ }
1605
+ const recorded = this.db.getAgentRun(active.status.runId)?.result_report;
1606
+ if (recorded) {
1607
+ const ticket = this.db.getTicket(ticketId);
1608
+ return JSON.stringify(recorded) === JSON.stringify(report) && ticket
1609
+ ? { ok: true, ticket }
1610
+ : { ok: false, error: "this run already accepted a different result" };
1611
+ }
1612
+ if (active.settled || this.db.getTicket(ticketId)?.state !== "in_progress") {
1613
+ return { ok: false, error: "this run is no longer In Progress" };
1614
+ }
1615
+ if (report.outcome === "ready_for_review") {
1616
+ const revision = await evidenceRevision(active.worktreePath);
1617
+ if (!revision)
1618
+ return {
1619
+ ok: false,
1620
+ error: "could not identify current worktree inputs; verification evidence cannot be confirmed",
1621
+ };
1622
+ for (const item of report.required_evidence) {
1623
+ if (!item.command)
1624
+ continue;
1625
+ const command = stripWorktreeCd(item.command);
1626
+ const observed = active.commandEvidence.findLast((entry) => entry.command === command);
1627
+ if (!observed || observed.outcome !== "passed" || observed.revision !== revision) {
1628
+ return {
1629
+ ok: false,
1630
+ error: `No current passed evidence for: ${command}. A running, failed, stale, or unobserved command cannot establish this requirement. Continue the required implementation/verification.`,
1631
+ };
1632
+ }
1633
+ }
1634
+ }
1635
+ // Hashing yields; cancellation or another accepted report must still win.
1636
+ if (this.active.get(ticketId) !== active ||
1637
+ active.cancelled ||
1638
+ active.settled ||
1639
+ this.db.getTicket(ticketId)?.state !== "in_progress") {
1640
+ return { ok: false, error: "the run changed while this result was being validated" };
1641
+ }
1642
+ if (report.outcome === "blocked") {
1643
+ // A verified ticket's blocker goes to the lead first; the run ends here
1644
+ // either way, so the developer's report becomes the lead's question.
1645
+ const current = this.db.getTicket(ticketId);
1646
+ if (current && this.canConsultLead(current)) {
1647
+ this.db.addComment({
1648
+ ticket_id: ticketId,
1649
+ type: "comment",
1650
+ author: active.job.profile || "developer",
1651
+ text: resultComment(report),
1652
+ run_id: active.status.runId,
1653
+ });
1654
+ active.leadRequest = {
1655
+ trigger: "developer_blocked",
1656
+ reason: report.reason ?? report.summary,
1657
+ failure: report.unblock ?? "",
1658
+ };
1659
+ active.settled = true;
1660
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
1661
+ return { ok: true, ticket: current, escalated: true };
1662
+ }
1663
+ }
1664
+ const ticket = this.db.recordAgentResult(active.status.runId, report, resultComment(report));
1665
+ active.settled = true;
1666
+ this.update(ticketId, active, { label: "Finishing", tool: null });
1667
+ // Let the reporting tool receive its receipt; tool_end/settled then stops the process.
1668
+ return { ok: true, ticket };
1669
+ }
1670
+ /** Current-run verification only; a successful command is not acceptance by itself. */
1671
+ recordVerification(ticketId, evidence) {
1672
+ const active = this.active.get(ticketId);
1673
+ if (!active)
1674
+ return false;
1675
+ if (evidence.outcome === "passed" &&
1676
+ !active.actions.some((action) => action.tool === "bash" &&
1677
+ action.state === "done" &&
1678
+ action.detail.includes(evidence.command.trim()))) {
1679
+ return false;
1680
+ }
1681
+ active.verification = evidence;
1682
+ return true;
1683
+ }
1684
+ reviewVerification(ticketId) {
1685
+ return this.active.get(ticketId)?.verification;
1686
+ }
1687
+ runStartedAt(ticketId) {
1688
+ return this.active.get(ticketId)?.status.startedAt;
1689
+ }
1690
+ /** A status token only belongs to the one run it was minted for. */
1691
+ verifyStatusToken(ticketId, token) {
1692
+ const expected = this.active.get(ticketId)?.statusToken;
1693
+ if (!expected || !token || expected.length !== token.length)
1694
+ return false;
1695
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(token));
1696
+ }
1697
+ /** Deliver only when the current run belongs to the mentioned profile and its adapter accepts steering. */
1698
+ async sendMessage(ticketId, profile, text, commentId) {
1699
+ const active = this.active.get(ticketId);
1700
+ if (!active ||
1701
+ active.status.profile !== profile ||
1702
+ active.status.phase !== "running" ||
1703
+ active.cancelled ||
1704
+ active.settled ||
1705
+ !active.run.sendMessage)
1706
+ return false;
1707
+ try {
1708
+ const accepted = await active.run.sendMessage(text);
1709
+ if (accepted) {
1710
+ if (this.active.get(ticketId) === active &&
1711
+ active.status.phase === "running" &&
1712
+ !active.cancelled &&
1713
+ !active.settled) {
1714
+ this.update(ticketId, active, { requestCommentId: commentId });
1715
+ }
1716
+ }
1717
+ return accepted;
1718
+ }
1719
+ catch {
1720
+ return false;
1721
+ }
1722
+ }
1723
+ activeIdentity(ticketId) {
1724
+ const active = this.active.get(ticketId);
1725
+ return active
1726
+ ? { profile: active.status.profile ?? "agent", runId: active.status.runId }
1727
+ : null;
1728
+ }
1729
+ tailOf(active) {
1730
+ const partial = outputLine(active.partial);
1731
+ return [...active.output, ...(partial ? [partial] : [])].slice(-TAIL_LINES);
1732
+ }
1733
+ publishOutput(ticketId, active) {
1734
+ if (active.outputTimer) {
1735
+ clearTimeout(active.outputTimer);
1736
+ active.outputTimer = undefined;
1737
+ }
1738
+ this.update(ticketId, active, { tail: this.tailOf(active) });
1739
+ }
1740
+ appendLine(ticketId, active, line) {
1741
+ const text = outputLine(line);
1742
+ if (!text)
1743
+ return;
1744
+ active.output.push(text);
1745
+ active.output = active.output.slice(-OUTPUT_LINES);
1746
+ this.publishOutput(ticketId, active);
1747
+ }
1748
+ appendText(ticketId, active, text) {
1749
+ active.partial += text;
1750
+ const lines = active.partial.split("\n");
1751
+ // A file being printed without a newline must not grow without bound; the
1752
+ // part that matters is the end, which is what a terminal would show.
1753
+ active.partial = (lines.pop() ?? "").slice(-2000);
1754
+ for (const line of lines) {
1755
+ const clipped = outputLine(line);
1756
+ if (clipped)
1757
+ active.output.push(clipped);
1758
+ }
1759
+ active.output = active.output.slice(-OUTPUT_LINES);
1760
+ if (lines.length > 0) {
1761
+ this.publishOutput(ticketId, active);
1762
+ return;
1763
+ }
1764
+ if (active.outputTimer)
1765
+ return;
1766
+ active.outputTimer = setTimeout(() => {
1767
+ active.outputTimer = undefined;
1768
+ this.publishOutput(ticketId, active);
1769
+ }, OUTPUT_DELAY_MS);
1770
+ }
1771
+ update(ticketId, active, patch) {
1772
+ active.status = { ...active.status, ...patch };
1773
+ this.statuses.set(ticketId, active.status);
1774
+ this.onStatus(active.status);
1775
+ }
1776
+ /**
1777
+ * Send the total so far to the board and write it to the run row. The row
1778
+ * matters as much as the stream: reopening the ticket, or reloading the tab,
1779
+ * reads the stored row rather than replaying events it never saw.
1780
+ */
1781
+ publishTokens(ticketId, runId, active) {
1782
+ active.tokenTimer = undefined;
1783
+ if (!active.tokens)
1784
+ return;
1785
+ this.db.updateAgentRunTokens(runId, active.tokens, active.tokens.cost);
1786
+ this.update(ticketId, active, { tokens: active.tokens });
1787
+ }
1788
+ /**
1789
+ * Commits and pull requests are facts the runtime can observe, so they land
1790
+ * in the timeline even if the agent forgot to say them in a comment.
1791
+ */
1792
+ recordFacts(ticketId, facts, active) {
1793
+ for (const commit of facts.commits) {
1794
+ if (active.emittedCommits.has(commit.sha))
1795
+ continue;
1796
+ active.emittedCommits.add(commit.sha);
1797
+ this.db.addComment({
1798
+ ticket_id: ticketId,
1799
+ type: "system",
1800
+ author: "git",
1801
+ text: `Committed ${commit.sha.slice(0, 7)} ${commit.subject} on ${facts.branch ?? "the ticket branch"}`,
1802
+ });
1803
+ }
1804
+ if (facts.prUrl && facts.prUrl !== active.emittedPrUrl) {
1805
+ active.emittedPrUrl = facts.prUrl;
1806
+ this.db.setPullRequest(ticketId, facts.prUrl);
1807
+ const text = `Pull request opened: ${facts.prUrl}`;
1808
+ // Run-local state resets on retries, resumes, and server restarts. The
1809
+ // timeline is the durable record of which PRs were already announced.
1810
+ const announced = this.db
1811
+ .listComments(ticketId)
1812
+ .some((comment) => comment.type === "system" && comment.text === text);
1813
+ if (!announced) {
1814
+ this.db.addComment({
1815
+ ticket_id: ticketId,
1816
+ type: "system",
1817
+ author: "github",
1818
+ text,
1819
+ });
1820
+ }
1821
+ }
1822
+ }
1823
+ async captureFacts(ticketId, worktree, active) {
1824
+ // A conflict repair commits a merge, not the ticket's work: "Committed …"
1825
+ // and "Pull request opened …" would describe a PR that already existed.
1826
+ if (active.job.outsideStage)
1827
+ return;
1828
+ try {
1829
+ const facts = await captureRunFacts(worktree.path, active.startHead, this.ghCommand);
1830
+ this.recordFacts(ticketId, facts, active);
1831
+ }
1832
+ catch {
1833
+ // Facts are an observation, not a reason to fail the run.
1834
+ }
1835
+ }
1836
+ /** One poll at a time: an in-flight capture already describes the worktree. */
1837
+ pollFacts(ticketId, worktree, active) {
1838
+ if (active.factsPoll)
1839
+ return active.factsPoll;
1840
+ active.factsPoll = this.captureFacts(ticketId, worktree, active).finally(() => {
1841
+ active.factsPoll = undefined;
1842
+ });
1843
+ return active.factsPoll;
1844
+ }
1845
+ /**
1846
+ * The run is over, so let any in-flight poll land and then read the worktree
1847
+ * once more: a commit made just before exit could predate that poll.
1848
+ */
1849
+ async finalFacts(ticketId, worktree, active) {
1850
+ await active.factsPoll;
1851
+ await this.captureFacts(ticketId, worktree, active);
1852
+ }
1853
+ finishRecord(runId, state, exitCode, gitStatus, gitDiff, error, tokens = null) {
1854
+ this.db.finishAgentRun(runId, {
1855
+ state,
1856
+ exit_code: exitCode,
1857
+ git_status: gitStatus,
1858
+ git_diff: gitDiff,
1859
+ error,
1860
+ input_tokens: tokens?.input ?? null,
1861
+ output_tokens: tokens?.output ?? null,
1862
+ cost: tokens?.cost ?? null,
1863
+ });
1864
+ }
1865
+ /**
1866
+ * Ask the separate manager pass whether this run's evidence argues for a
1867
+ * better standing instruction. Gated by deterministic waste signals so a
1868
+ * clean run costs nothing; the result is a note on the ticket, never a
1869
+ * workflow edit.
1870
+ */
1871
+ reviewRun(ticketId, runId, state, attempt, actions, durationMs, harness) {
1872
+ if (!this.retro)
1873
+ return;
1874
+ // The trace keeps 12 rows; the full history is what shows repeated reads
1875
+ // and guard blocks, so the manager reads every call the run recorded.
1876
+ const details = wasteSignalDetails(actions, durationMs, this.db.listToolCalls(runId));
1877
+ if (details.length === 0)
1878
+ return;
1879
+ const signals = details.map((signal) => signal.text);
1880
+ const signalCauses = Object.fromEntries(details.map((signal) => [signal.text, signal.cause]));
1881
+ const record = this.db.latestAgentRun(ticketId);
1882
+ const workflow = record?.workflow ?? emptyWorkflow();
1883
+ void this.retro({
1884
+ ticketId,
1885
+ state,
1886
+ attempt,
1887
+ durationMs,
1888
+ actions,
1889
+ workflow,
1890
+ signals,
1891
+ signalCauses,
1892
+ harness,
1893
+ })
1894
+ .then((result) => {
1895
+ if (!result)
1896
+ return;
1897
+ const evidence = result.evidence.length > 0 ? result.evidence : signals;
1898
+ const offered = commentActionsFor(result, details);
1899
+ // The notes stay on the ticket whose run they came from. A queue on the
1900
+ // Workflows page stacked one near-identical rewrite per run; on the
1901
+ // ticket the person reads it beside the run and copies what helps.
1902
+ this.db.addComment({
1903
+ ticket_id: ticketId,
1904
+ type: "system",
1905
+ author: "manager",
1906
+ text: [
1907
+ "Manager notes on this run",
1908
+ "",
1909
+ "In Progress notes that would have avoided the waste:",
1910
+ "",
1911
+ result.notes,
1912
+ "",
1913
+ "Why:",
1914
+ ...evidence.map((line) => `- ${line}`),
1915
+ ].join("\n"),
1916
+ run_id: runId,
1917
+ ...(offered.fixPrompt || offered.issue ? { actions: offered } : {}),
1918
+ });
1919
+ })
1920
+ // A manager that fails is a missing note, not a failed run.
1921
+ .catch(() => { });
1922
+ }
1923
+ async execute(ticketId, worktree, runId, active) {
1924
+ let exitCode = null;
1925
+ let stderr = "";
1926
+ let timedOut = false;
1927
+ let spawnError = false;
1928
+ let error = null;
1929
+ const factsTimer = setInterval(() => {
1930
+ void this.pollFacts(ticketId, worktree, active);
1931
+ }, this.factsPollMs);
1932
+ const watchdogTimer = active.watchdog
1933
+ ? setInterval(() => {
1934
+ void this.watchdogTick(ticketId, worktree, runId, active).catch(() => { });
1935
+ }, this.watchdog?.tickMs ?? WATCHDOG_TICK_MS)
1936
+ : undefined;
1937
+ try {
1938
+ for await (const event of active.run.events) {
1939
+ if (event.type === "tool_start") {
1940
+ if (active.executionPhase) {
1941
+ active.executionPhase = phaseForTool(active.executionPhase, event.tool, event.args);
1942
+ }
1943
+ // The label already says what is starting, so the tail stays output:
1944
+ // the assistant's prose and whatever the command prints.
1945
+ active.actions = startAction(active.actions, {
1946
+ tool: event.tool,
1947
+ label: event.label,
1948
+ detail: actionDetail(event.tool, event.args),
1949
+ callId: event.callId,
1950
+ });
1951
+ this.noteRepeat(active, event.tool, event.args);
1952
+ const id = active.actions.at(-1)?.id;
1953
+ if (id) {
1954
+ const args = event.args;
1955
+ active.toolCalls.set(id, {
1956
+ output: "",
1957
+ tool: event.tool,
1958
+ detail: actionDetail(event.tool, event.args),
1959
+ path: actionPath(event.tool, event.args),
1960
+ startedAt: Date.now(),
1961
+ ...(event.tool === "bash" &&
1962
+ typeof args?.command === "string" &&
1963
+ args.command.length <= 3_000
1964
+ ? { command: stripWorktreeCd(args.command) }
1965
+ : {}),
1966
+ });
1967
+ }
1968
+ this.update(ticketId, active, {
1969
+ label: event.label,
1970
+ tool: event.tool,
1971
+ actions: active.actions,
1972
+ ...(active.executionPhase ? { executionPhase: active.executionPhase } : {}),
1973
+ });
1974
+ }
1975
+ else if (event.type === "tool_output") {
1976
+ // Only the failed row keeps this; the cap is the memory the run pays
1977
+ // for evidence it may never need.
1978
+ const id = event.callId ??
1979
+ active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
1980
+ const call = id ? active.toolCalls.get(id) : undefined;
1981
+ if (call)
1982
+ call.output = (call.output + event.text).slice(-MAX_ACTION_OUTPUT);
1983
+ this.appendText(ticketId, active, event.text);
1984
+ }
1985
+ else if (event.type === "tool_end") {
1986
+ if (active.executionPhase) {
1987
+ active.executionPhase = phaseForTool(active.executionPhase, "", {}, event.isError);
1988
+ }
1989
+ const id = event.callId ??
1990
+ active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
1991
+ const call = id ? active.toolCalls.get(id) : undefined;
1992
+ // A test run piped through tail exits 0 whatever the tests did; its
1993
+ // own summary is the outcome, so a failing piped run is a failed row.
1994
+ const piped = call?.command
1995
+ ? pipedEvidence(call.command, call.output, event.isError)
1996
+ : null;
1997
+ const callFailed = event.isError || piped?.outcome === "failed";
1998
+ active.actions = finishAction(active.actions, {
1999
+ isError: callFailed,
2000
+ output: call?.output,
2001
+ callId: id,
2002
+ });
2003
+ // The full history keeps every completed call, not just the trace's
2004
+ // tail. A refused bash command is still a call, marked as blocked.
2005
+ const endedAt = Date.now();
2006
+ this.db.recordToolCall({
2007
+ runId,
2008
+ tool: call?.tool ?? event.tool,
2009
+ detail: call?.detail ?? "",
2010
+ path: call?.path ?? null,
2011
+ state: callFailed ? "failed" : "done",
2012
+ blocked: event.isError && bashGuardBlockedReader(call?.output) !== null,
2013
+ startedAt: call?.startedAt ?? endedAt,
2014
+ endedAt,
2015
+ output: call?.output,
2016
+ });
2017
+ if (call?.command && id) {
2018
+ const currentTicket = this.db.getTicket(ticketId);
2019
+ // Only agent-reported verification consumes a worktree hash. The
2020
+ // current ticket's Verify list can change while the run is active.
2021
+ const canUseAgentEvidence = !active.cancelled &&
2022
+ !active.job.outsideStage &&
2023
+ active.job.profile === "developer" &&
2024
+ active.job.stage !== "review";
2025
+ const evidence = {
2026
+ id,
2027
+ command: call.command,
2028
+ outcome: callFailed ? "failed" : "passed",
2029
+ revision: null,
2030
+ };
2031
+ if (!callFailed && canUseAgentEvidence) {
2032
+ const pending = evidenceRevision(worktree.path);
2033
+ active.evidencePending = pending;
2034
+ try {
2035
+ evidence.revision = await pending;
2036
+ }
2037
+ finally {
2038
+ if (active.evidencePending === pending)
2039
+ active.evidencePending = undefined;
2040
+ }
2041
+ }
2042
+ // The filtered run also stands for the command under the filter, so
2043
+ // `pnpm test x | tail -15` that the summary shows passing satisfies
2044
+ // the Verify command `pnpm test x`.
2045
+ const recorded = piped
2046
+ ? [
2047
+ evidence,
2048
+ {
2049
+ id: `${id}:unpiped`,
2050
+ command: piped.command,
2051
+ outcome: piped.outcome,
2052
+ revision: evidence.revision,
2053
+ },
2054
+ ]
2055
+ : [evidence];
2056
+ active.commandEvidence.push(...recorded);
2057
+ if (canUseAgentEvidence && currentTicket?.verify.length) {
2058
+ active.developerCommandEvidence.push(...recorded);
2059
+ active.developerCommandEvidence = active.developerCommandEvidence.slice(-64);
2060
+ }
2061
+ active.commandEvidence = active.commandEvidence.slice(-64);
2062
+ this.db.recordCommandEvidence(runId, active.commandEvidence);
2063
+ }
2064
+ if (id)
2065
+ active.toolCalls.delete(id);
2066
+ this.update(ticketId, active, {
2067
+ label: "Thinking",
2068
+ tool: null,
2069
+ actions: active.actions,
2070
+ ...(active.executionPhase ? { executionPhase: active.executionPhase } : {}),
2071
+ });
2072
+ const reported = event.tool === "report_result" ||
2073
+ (event.tool === "bash" && /\bzelio\s+ticket\s+report\b/.test(call?.command ?? ""));
2074
+ if (active.settled && !active.cancelled && reported)
2075
+ active.run.abort();
2076
+ }
2077
+ else if (event.type === "settled") {
2078
+ if (active.settled && !active.cancelled)
2079
+ active.run.abort();
2080
+ }
2081
+ else if (event.type === "text") {
2082
+ this.appendText(ticketId, active, event.text);
2083
+ }
2084
+ else if (event.type === "session") {
2085
+ this.db.setAgentRunSessionId(runId, event.id);
2086
+ }
2087
+ else if (event.type === "usage") {
2088
+ // The harness may report usage more than once per run; the run is the
2089
+ // sum of what it said, never a guess from the transcript.
2090
+ active.tokens = {
2091
+ input: (active.tokens?.input ?? 0) + event.input,
2092
+ output: (active.tokens?.output ?? 0) + event.output,
2093
+ // A harness that reports no price on one message must not erase the
2094
+ // prices it did report: silence is null, and null plus a number is
2095
+ // that number.
2096
+ cost: event.cost === null
2097
+ ? (active.tokens?.cost ?? null)
2098
+ : (active.tokens?.cost ?? 0) + event.cost,
2099
+ };
2100
+ // Publish on a timer instead of per message: one report is a turn,
2101
+ // not a number a person needs to see change mid-sentence.
2102
+ if (!active.tokenTimer) {
2103
+ active.tokenTimer = setTimeout(() => {
2104
+ this.publishTokens(ticketId, runId, active);
2105
+ }, this.tokenPublishMs);
2106
+ }
2107
+ }
2108
+ else if (event.type === "exit") {
2109
+ exitCode = event.code;
2110
+ stderr = event.stderr;
2111
+ timedOut = event.timedOut;
2112
+ spawnError = event.spawnError === true;
2113
+ }
2114
+ }
2115
+ }
2116
+ catch (cause) {
2117
+ error = cause instanceof Error ? cause.message : "the agent run failed";
2118
+ }
2119
+ clearInterval(factsTimer);
2120
+ if (watchdogTimer)
2121
+ clearInterval(watchdogTimer);
2122
+ // A look that answered "continue" leaves nothing else behind, so the run
2123
+ // says how often it was looked at; without this a watchdog that never ran
2124
+ // and one that approved every look read the same.
2125
+ if (active.watchdog && active.watchdog.looks.length > 0) {
2126
+ this.db.addComment({
2127
+ ticket_id: ticketId,
2128
+ type: "system",
2129
+ author: "watchdog",
2130
+ text: watchdogSummary(active.watchdog.looks),
2131
+ run_id: runId,
2132
+ });
2133
+ }
2134
+ if (active.tokenTimer) {
2135
+ clearTimeout(active.tokenTimer);
2136
+ active.tokenTimer = undefined;
2137
+ }
2138
+ let gitStatus = null;
2139
+ let gitDiff = null;
2140
+ try {
2141
+ const captured = await captureWorktree(worktree.path, active.startHead);
2142
+ gitStatus = captured.status;
2143
+ gitDiff = captured.diff;
2144
+ }
2145
+ catch (cause) {
2146
+ error ??= `could not capture the worktree diff: ${cause instanceof Error ? cause.message : "git failed"}`;
2147
+ }
2148
+ await this.finalFacts(ticketId, worktree, active);
2149
+ if (active.outputTimer) {
2150
+ clearTimeout(active.outputTimer);
2151
+ active.outputTimer = undefined;
2152
+ }
2153
+ const cancelled = active.cancelled;
2154
+ // A settled run is the agent saying it is done, so the SIGTERM that follows
2155
+ // is our own abort. Its exit code describes how we stopped pi, not how the
2156
+ // work went: a clean run would otherwise be recorded as `failed` with
2157
+ // "the agent exited with code 143".
2158
+ const stoppedByUs = active.settled || cancelled;
2159
+ const cleanExit = stoppedByUs || exitCode === null || exitCode === 0;
2160
+ const failed = !cancelled && (error !== null || timedOut || spawnError || !cleanExit);
2161
+ if (!cancelled && failed) {
2162
+ error ??= spawnError
2163
+ ? "the harness could not start"
2164
+ : timedOut
2165
+ ? "the agent timed out"
2166
+ : `the agent exited with code ${exitCode ?? "unknown"}`;
2167
+ const detail = tail(stderr);
2168
+ if (detail)
2169
+ error = `${error}: ${detail}`;
2170
+ }
2171
+ // The agent reports *before* it stops: the status route moves the ticket and
2172
+ // then settles the process. So a run that ends while its ticket still says
2173
+ // `in_progress` did not report, and the card keeps claiming a job nobody is
2174
+ // doing. The run says so instead of letting that pass, and the ticket is
2175
+ // left untouched: only the agent or a person moves it.
2176
+ // A run that ended without its ticket moving may still have finished its
2177
+ // work: the board runs the gate here for harnesses with no in-session hook.
2178
+ let gate = { kind: "skip" };
2179
+ if (!cancelled && !failed && this.db.getTicket(ticketId)?.state === "in_progress") {
2180
+ gate = await this.completionGate(ticketId, runId, true);
2181
+ }
2182
+ // A request to the lead leaves the ticket In Progress while the lead reads
2183
+ // it; that is the board's own question, not a stall.
2184
+ const open = !cancelled && !failed && this.db.getTicket(ticketId)?.state === "in_progress";
2185
+ const stalled = open && !active.leadRequest;
2186
+ const attempt = active.status.attempt ?? 1;
2187
+ const job = active.job;
2188
+ // Recorded before the decision, so the breaker counts the failure that just
2189
+ // happened and not only the earlier ones. A comment run that opted out of
2190
+ // retries never inherits the ticket's original brief.
2191
+ const decision = stalled && job.retry !== false ? this.retryDecision(attempt) : "none";
2192
+ if (stalled) {
2193
+ const cause = gate.kind === "continue" ? `checks failed: ${gate.summary}` : stallReason(exitCode);
2194
+ error =
2195
+ decision === "hold"
2196
+ ? `${cause}; not retrying, because ${this.stalls.length} runs stalled recently and the harness looks unhealthy`
2197
+ : cause;
2198
+ }
2199
+ // Attempts are spent: a verified ticket goes to the lead before the person.
2200
+ if (decision === "escalate") {
2201
+ const current = this.db.getTicket(ticketId);
2202
+ if (current && this.canConsultLead(current)) {
2203
+ const failedAction = active.actions.findLast((action) => action.state === "failed");
2204
+ active.leadRequest = {
2205
+ trigger: "no_status",
2206
+ reason: error ?? stallReason(exitCode),
2207
+ failure: failedAction?.output ?? "",
2208
+ };
2209
+ }
2210
+ }
2211
+ const state = cancelled ? "cancelled" : failed ? "failed" : stalled ? "stalled" : "completed";
2212
+ this.finishRecord(runId, state, exitCode, gitStatus, gitDiff, error, active.tokens);
2213
+ this.active.delete(ticketId);
2214
+ // A retry starts before the finishing status is published, so the card never
2215
+ // blinks through "finished" and the allocator never sees a free slot and
2216
+ // hands it to another ticket. The next attempt owns the status line from
2217
+ // here; if it cannot start, the stall is published below.
2218
+ if (decision === "retry") {
2219
+ const failedAction = active.actions.findLast((action) => action.state === "failed");
2220
+ const summary = [
2221
+ error ?? stallReason(exitCode),
2222
+ failedAction
2223
+ ? `Last failed tool: ${failedAction.detail}. ${failedAction.output ?? ""}`
2224
+ : "",
2225
+ gate.kind === "continue" ? gate.prompt : "",
2226
+ "Worktree and commits are preserved.",
2227
+ ]
2228
+ .filter(Boolean)
2229
+ .join(" ");
2230
+ if (await this.retryNow(ticketId, worktree, attempt, job, {
2231
+ comment: `Attempt ${attempt} of ${this.retry.maxAttempts} ended without an accepted status. Observed outcome: ${summary}`,
2232
+ wip: `wip: attempt ${attempt} ended without reporting`,
2233
+ }))
2234
+ return;
2235
+ }
2236
+ const label = cancelled
2237
+ ? "Run cancelled"
2238
+ : failed
2239
+ ? "Run failed"
2240
+ : active.leadRequest
2241
+ ? "Asking the lead"
2242
+ : stalled
2243
+ ? "No status reported"
2244
+ : "Run finished";
2245
+ const final = {
2246
+ ...active.status,
2247
+ label,
2248
+ tool: null,
2249
+ endedAt: Date.now(),
2250
+ phase: cancelled ? "cancelled" : failed ? "failed" : stalled ? "stalled" : "done",
2251
+ // A call that was still live when the process ended did not finish; the
2252
+ // row says how the run ended instead of staying a spinner forever.
2253
+ actions: closeActions(active.actions, cancelled ? "cancelled" : failed || stalled ? "failed" : "done", Date.now(), error ?? undefined),
2254
+ error,
2255
+ tokens: active.tokens ?? undefined,
2256
+ };
2257
+ this.statuses.set(ticketId, final);
2258
+ this.onStatus(final);
2259
+ // The run is over and its trace is final. Anything waiting on this ticket's
2260
+ // run — a conflict repair reconciling its own outcome — is told now.
2261
+ this.wakeSettleWaiters(ticketId, final);
2262
+ // The run is over, so the manager pass can read its trail without holding
2263
+ // the slot or the card. It never blocks the finish and never moves a card.
2264
+ // A conflict repair is not In Progress work, so it proposes nothing there.
2265
+ if (!active.job.outsideStage) {
2266
+ this.reviewRun(ticketId, runId, final.phase, attempt, final.actions ?? [], Math.max(0, (final.endedAt ?? Date.now()) - active.status.startedAt), active.command);
2267
+ }
2268
+ if (decision === "escalate" && !active.leadRequest)
2269
+ this.escalate(ticketId, attempt);
2270
+ if (active.leadRequest)
2271
+ void this.runLead(ticketId, worktree, active, active.leadRequest);
2272
+ }
2273
+ /**
2274
+ * Retry, escalate, or leave the card with its stall badge. The numbers live in
2275
+ * §21 of the design notes: two attempts per ticket, and the breaker shuts
2276
+ * retrying down after three stalls in ten minutes.
2277
+ */
2278
+ retryDecision(attempt) {
2279
+ const now = Date.now();
2280
+ const cutoff = now - this.retry.breakerWindowMs;
2281
+ while (this.stalls.length > 0 && (this.stalls[0] ?? now) < cutoff)
2282
+ this.stalls.shift();
2283
+ this.stalls.push(now);
2284
+ if (attempt >= this.retry.maxAttempts)
2285
+ return "escalate";
2286
+ // A downed provider or a dead key fails every ticket the same way. Retrying
2287
+ // past that pays twice for the same outage, so the board stops and says so.
2288
+ return this.stalls.length >= this.retry.breakerStalls ? "hold" : "retry";
2289
+ }
2290
+ /**
2291
+ * The retry itself: commit what the failed attempt left behind, say so on the
2292
+ * timeline, then start again in the same worktree. Work is never lost to a
2293
+ * retry, and the attempt is never invisible.
2294
+ */
2295
+ async retryNow(ticketId, worktree, attempt, job, notice = {
2296
+ comment: `Attempt ${attempt} of ${this.retry.maxAttempts} ended without reporting a status. Retrying in the same worktree.`,
2297
+ wip: `wip: attempt ${attempt} ended without reporting`,
2298
+ }) {
2299
+ this.db.addComment({
2300
+ ticket_id: ticketId,
2301
+ type: "system",
2302
+ author: "zelio",
2303
+ text: notice.comment,
2304
+ });
2305
+ await commitAttempt(worktree.path, notice.wip);
2306
+ // The person may have moved or cancelled the card while the attempt was
2307
+ // settling. A retry never overrules them.
2308
+ const ticket = this.db.getTicket(ticketId);
2309
+ if (!ticket || ticket.state !== "in_progress" || this.active.has(ticketId))
2310
+ return false;
2311
+ try {
2312
+ if (job?.source === "comment") {
2313
+ // Keep the original task and add a factual lifecycle handoff: a fresh
2314
+ // comment turn must not have to rediscover why its predecessor ended.
2315
+ await this.begin(ticket, worktree, attempt + 1, {
2316
+ ...job,
2317
+ // The earlier attempt may have made the change before it stalled.
2318
+ expectsChange: false,
2319
+ prompt: `${job.prompt}\n\n## Recovery handoff\n${notice.comment}\nContinue the original goal, acceptance, constraints, and authorizations above; inspect the previous run's output/trace, identify what remains, and do not repeat completed work without a reason.${notice.comment.includes("interrupted by a server restart") ? " The process was interrupted by a server restart; resume is unavailable or exhausted, so continue in this same worktree without claiming the work was lost." : " This was a normal turn completion without an accepted status report, not a process interruption."}`,
2320
+ });
2321
+ }
2322
+ else {
2323
+ // Rebuild the same authoritative brief and add the observed lifecycle
2324
+ // failure. A fresh session cannot see the prior conversation or trace.
2325
+ const retryPrompt = buildTicketPrompt(ticket, { number: attempt + 1, of: this.retry.maxAttempts }, this.db.listComments(ticketId), absoluteAttachments(this.repoRoot, ticket.attachments));
2326
+ await this.begin(ticket, worktree, attempt + 1, {
2327
+ prompt: `${retryPrompt}\n\n## Recovery handoff\n${notice.comment}\nInspect the preserved work and run only checks that remain necessary.`,
2328
+ profile: job?.profile ?? ticket.profile ?? "developer",
2329
+ retry: true,
2330
+ source: "ticket",
2331
+ command: job?.command,
2332
+ systemPrompt: job?.systemPrompt,
2333
+ });
2334
+ }
2335
+ return true;
2336
+ }
2337
+ catch {
2338
+ // The slot went somewhere else in the meantime; the stall badge stands.
2339
+ return false;
2340
+ }
2341
+ }
2342
+ leadConsults(ticketId) {
2343
+ return this.db.listComments(ticketId).filter((comment) => comment.author === "lead").length;
2344
+ }
2345
+ canConsultLead(ticket) {
2346
+ return (!!this.lead && ticket.verify.length > 0 && this.leadConsults(ticket.id) < MAX_LEAD_CONSULTS);
2347
+ }
2348
+ /** Said ahead of a block or an escalation once a verified ticket has used up its lead consults. */
2349
+ leadLimitNote(ticket) {
2350
+ return this.lead &&
2351
+ ticket.verify.length > 0 &&
2352
+ this.leadConsults(ticket.id) >= MAX_LEAD_CONSULTS
2353
+ ? `The lead already intervened ${MAX_LEAD_CONSULTS} times. `
2354
+ : "";
2355
+ }
2356
+ /**
2357
+ * One read-only consult of the lead, after the run has ended. The ticket stays
2358
+ * In Progress with no process behind it until the answer is applied here. This
2359
+ * never throws: an unanswered or broken consult blocks the ticket as before.
2360
+ */
2361
+ async runLead(ticketId, worktree, active, request) {
2362
+ const lead = this.lead;
2363
+ const current = this.db.getTicket(ticketId);
2364
+ if (!lead || !current || current.state !== "in_progress" || this.active.has(ticketId))
2365
+ return;
2366
+ try {
2367
+ const consult = this.leadConsults(ticketId) + 1;
2368
+ this.db.addComment({
2369
+ ticket_id: ticketId,
2370
+ type: "system",
2371
+ author: "zelio",
2372
+ text: `Asking the lead to look (consult ${consult} of ${MAX_LEAD_CONSULTS}): ${request.reason}`,
2373
+ });
2374
+ let decision = null;
2375
+ let problem = null;
2376
+ try {
2377
+ const input = {
2378
+ ticketId,
2379
+ title: current.title,
2380
+ goal: current.goal,
2381
+ outOfScope: current.out_of_scope,
2382
+ acceptance: current.acceptance,
2383
+ likelyFiles: [...current.likely_files],
2384
+ context: [...(current.context ?? [])],
2385
+ verify: current.verify,
2386
+ trigger: request.trigger,
2387
+ reason: request.reason,
2388
+ failure: request.failure,
2389
+ diff: await ticketDiff(worktree.path),
2390
+ actions: active.actions
2391
+ .slice(-25)
2392
+ .map((action) => `[${action.state === "failed" ? "FAILED" : action.state}] ${action.detail}`),
2393
+ consult,
2394
+ earlier: this.db
2395
+ .listComments(ticketId)
2396
+ .filter((comment) => comment.author === "lead")
2397
+ .map((comment) => comment.text),
2398
+ watchdog: this.watchdogSteers(ticketId),
2399
+ worktreePath: worktree.path,
2400
+ };
2401
+ decision = await lead(input).catch(() => null);
2402
+ }
2403
+ catch (cause) {
2404
+ problem = cause instanceof Error ? cause.message : String(cause);
2405
+ }
2406
+ const live = this.db.getTicket(ticketId);
2407
+ if (!live || live.state !== "in_progress" || this.active.has(ticketId)) {
2408
+ this.db.addComment({
2409
+ ticket_id: ticketId,
2410
+ type: "system",
2411
+ author: "zelio",
2412
+ text: "The lead answered after the ticket moved; its answer was not applied.",
2413
+ });
2414
+ return;
2415
+ }
2416
+ if (!decision) {
2417
+ this.blockForLead(ticketId, request, problem === null ? null : `The lead failed: ${problem}`);
2418
+ return;
2419
+ }
2420
+ try {
2421
+ await this.applyLead(ticketId, worktree, decision);
2422
+ }
2423
+ catch (cause) {
2424
+ const message = cause instanceof Error ? cause.message : String(cause);
2425
+ this.blockForLead(ticketId, request, `The lead's answer could not be applied: ${message}`);
2426
+ }
2427
+ }
2428
+ catch (cause) {
2429
+ const message = cause instanceof Error ? cause.message : String(cause);
2430
+ this.db.addComment({
2431
+ ticket_id: ticketId,
2432
+ type: "system",
2433
+ author: "zelio",
2434
+ text: `The board could not consult the lead: ${message}`,
2435
+ });
2436
+ }
2437
+ }
2438
+ async applyLead(ticketId, worktree, decision) {
2439
+ if (decision.decision === "guide") {
2440
+ this.db.addComment({
2441
+ ticket_id: ticketId,
2442
+ type: "decision",
2443
+ author: "lead",
2444
+ text: `Lead guidance:\n\n${decision.guidance}`,
2445
+ });
2446
+ const ticket = this.db.getTicket(ticketId);
2447
+ if (ticket)
2448
+ await this.restartWithLead(ticket, worktree, decision.guidance, true);
2449
+ return;
2450
+ }
2451
+ if (decision.decision === "revise") {
2452
+ const updated = this.db.updateSpec(ticketId, {
2453
+ ...(decision.verify ? { verify: decision.verify } : {}),
2454
+ ...(decision.acceptance ? { acceptance: decision.acceptance } : {}),
2455
+ });
2456
+ if (!updated)
2457
+ return;
2458
+ const changed = [decision.verify ? "verify" : "", decision.acceptance ? "acceptance" : ""]
2459
+ .filter(Boolean)
2460
+ .join(" and ");
2461
+ const verify = decision.verify
2462
+ ? `\n\nVerify:\n${decision.verify.map((check) => `- ${check.label}: ${check.command}`).join("\n")}`
2463
+ : "";
2464
+ const acceptance = decision.acceptance ? `\n\nAcceptance:\n${decision.acceptance}` : "";
2465
+ this.db.addComment({
2466
+ ticket_id: ticketId,
2467
+ type: "decision",
2468
+ author: "lead",
2469
+ text: `Lead revised the ticket (${changed}):\n\n${decision.guidance}${verify}${acceptance}`,
2470
+ });
2471
+ // The ticket was wrong, not the work: the restart may have nothing to change.
2472
+ await this.restartWithLead(updated, worktree, decision.guidance, false);
2473
+ return;
2474
+ }
2475
+ const options = decision.options.map((option, index) => `${index + 1}) ${option}`);
2476
+ this.db.transition(ticketId, "blocked", {
2477
+ blocker_kind: "needs_human",
2478
+ blocker_reason: decision.question,
2479
+ blocker_unblock: `Reply with one of: ${options.join("; ")} — then mention @developer.`,
2480
+ });
2481
+ this.db.addComment({
2482
+ ticket_id: ticketId,
2483
+ type: "blocker",
2484
+ author: "lead",
2485
+ blocker_kind: "needs_human",
2486
+ text: [decision.question, options.join("\n")].join("\n\n"),
2487
+ });
2488
+ }
2489
+ /** The lead could not decide: the ticket blocks with the reason it was asked about. */
2490
+ blockForLead(ticketId, request, note) {
2491
+ this.db.transition(ticketId, "blocked", {
2492
+ blocker_kind: "decision",
2493
+ blocker_reason: request.reason,
2494
+ blocker_unblock: "The lead could not decide. Fix the failing check or answer the developer's question, then mention @developer to continue.",
2495
+ });
2496
+ const text = [
2497
+ `The lead could not decide. ${request.reason}${request.failure ? `\n\n${request.failure}` : ""}`,
2498
+ note,
2499
+ ]
2500
+ .filter(Boolean)
2501
+ .join("\n\n");
2502
+ this.db.addComment({ ticket_id: ticketId, type: "blocker", author: "zelio", text });
2503
+ }
2504
+ /** The developer again, from the start, with the lead's guidance added to the brief. */
2505
+ async restartWithLead(ticket, worktree, guidance, expectsChange) {
2506
+ try {
2507
+ await this.begin(ticket, worktree, 1, {
2508
+ prompt: `${buildTicketPrompt(ticket, { number: 1, of: this.retry.maxAttempts }, this.db.listComments(ticket.id), absoluteAttachments(this.repoRoot, ticket.attachments))}\n\n## Guidance from the lead\n\n${guidance}`,
2509
+ profile: ticket.profile ?? "developer",
2510
+ label: "Following the lead",
2511
+ retry: true,
2512
+ source: "ticket",
2513
+ expectsChange,
2514
+ });
2515
+ }
2516
+ catch (cause) {
2517
+ const message = cause instanceof Error ? cause.message : String(cause);
2518
+ this.db.addComment({
2519
+ ticket_id: ticket.id,
2520
+ type: "system",
2521
+ author: "zelio",
2522
+ text: `Could not restart the developer: ${message}`,
2523
+ });
2524
+ this.db.transition(ticket.id, "blocked", {
2525
+ blocker_kind: "decision",
2526
+ blocker_reason: "the developer could not be restarted with the lead's guidance",
2527
+ blocker_unblock: "Check the server log, then mention @developer to continue.",
2528
+ });
2529
+ }
2530
+ }
2531
+ /** Exhaustion is an execution stall, not an agent-declared human blocker. */
2532
+ escalate(ticketId, attempt) {
2533
+ const ticket = this.db.getTicket(ticketId);
2534
+ if (!ticket || ticket.state !== "in_progress")
2535
+ return;
2536
+ const reason = `the agent ended ${attempt} ${attempt === 1 ? "time" : "times"} without reporting a status`;
2537
+ 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.";
2538
+ this.db.addComment({
2539
+ ticket_id: ticketId,
2540
+ type: "system",
2541
+ author: "zelio",
2542
+ text: `${this.leadLimitNote(ticket)}Execution needs attention: ${reason}. ${unblock} Mention @developer to continue the preserved work.`,
2543
+ });
2544
+ }
2545
+ }
2546
+ //# sourceMappingURL=manager.js.map