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

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 (175) hide show
  1. package/README.md +178 -2
  2. package/dist/attachments.js +121 -0
  3. package/dist/attachments.js.map +1 -0
  4. package/dist/cli.js +469 -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 +260 -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 +63 -0
  21. package/dist/cloud/push-nudge.js.map +1 -0
  22. package/dist/cloud/relay.js +129 -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 +410 -0
  27. package/dist/cloud/tunnel.js.map +1 -0
  28. package/dist/db/db.js +1614 -0
  29. package/dist/db/db.js.map +1 -0
  30. package/dist/db/lifecycle.js +133 -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 +181 -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 +1054 -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 +52 -0
  63. package/dist/repo/instructions.js.map +1 -0
  64. package/dist/repo/linked-boards.js +252 -0
  65. package/dist/repo/linked-boards.js.map +1 -0
  66. package/dist/run/actions.js +233 -0
  67. package/dist/run/actions.js.map +1 -0
  68. package/dist/run/bash-guard.js +183 -0
  69. package/dist/run/bash-guard.js.map +1 -0
  70. package/dist/run/claude-runtime.js +242 -0
  71. package/dist/run/claude-runtime.js.map +1 -0
  72. package/dist/run/claude-stream.js +306 -0
  73. package/dist/run/claude-stream.js.map +1 -0
  74. package/dist/run/codex-client.js +200 -0
  75. package/dist/run/codex-client.js.map +1 -0
  76. package/dist/run/codex-runtime.js +366 -0
  77. package/dist/run/codex-runtime.js.map +1 -0
  78. package/dist/run/context.js +87 -0
  79. package/dist/run/context.js.map +1 -0
  80. package/dist/run/diff.js +196 -0
  81. package/dist/run/diff.js.map +1 -0
  82. package/dist/run/evidence.js +48 -0
  83. package/dist/run/evidence.js.map +1 -0
  84. package/dist/run/finish.js +393 -0
  85. package/dist/run/finish.js.map +1 -0
  86. package/dist/run/harness-runtime.js +28 -0
  87. package/dist/run/harness-runtime.js.map +1 -0
  88. package/dist/run/harnesses.js +273 -0
  89. package/dist/run/harnesses.js.map +1 -0
  90. package/dist/run/issue.js +79 -0
  91. package/dist/run/issue.js.map +1 -0
  92. package/dist/run/keep-awake.js +58 -0
  93. package/dist/run/keep-awake.js.map +1 -0
  94. package/dist/run/lead.js +200 -0
  95. package/dist/run/lead.js.map +1 -0
  96. package/dist/run/manager.js +1709 -0
  97. package/dist/run/manager.js.map +1 -0
  98. package/dist/run/mentions.js +35 -0
  99. package/dist/run/mentions.js.map +1 -0
  100. package/dist/run/merge-watch.js +394 -0
  101. package/dist/run/merge-watch.js.map +1 -0
  102. package/dist/run/models.js +88 -0
  103. package/dist/run/models.js.map +1 -0
  104. package/dist/run/phases.js +23 -0
  105. package/dist/run/phases.js.map +1 -0
  106. package/dist/run/pi-rpc.js +412 -0
  107. package/dist/run/pi-rpc.js.map +1 -0
  108. package/dist/run/pr-merge.js +121 -0
  109. package/dist/run/pr-merge.js.map +1 -0
  110. package/dist/run/profiles.js +43 -0
  111. package/dist/run/profiles.js.map +1 -0
  112. package/dist/run/prompt.js +345 -0
  113. package/dist/run/prompt.js.map +1 -0
  114. package/dist/run/pull-request.js +23 -0
  115. package/dist/run/pull-request.js.map +1 -0
  116. package/dist/run/result-tool.js +93 -0
  117. package/dist/run/result-tool.js.map +1 -0
  118. package/dist/run/result.js +113 -0
  119. package/dist/run/result.js.map +1 -0
  120. package/dist/run/retro.js +346 -0
  121. package/dist/run/retro.js.map +1 -0
  122. package/dist/run/settings.js +25 -0
  123. package/dist/run/settings.js.map +1 -0
  124. package/dist/run/thinking.js +41 -0
  125. package/dist/run/thinking.js.map +1 -0
  126. package/dist/run/types.js +2 -0
  127. package/dist/run/types.js.map +1 -0
  128. package/dist/run/workflow.js +266 -0
  129. package/dist/run/workflow.js.map +1 -0
  130. package/dist/run/worktree.js +354 -0
  131. package/dist/run/worktree.js.map +1 -0
  132. package/dist/server/app.js +2503 -0
  133. package/dist/server/app.js.map +1 -0
  134. package/dist/server/auth.js +93 -0
  135. package/dist/server/auth.js.map +1 -0
  136. package/dist/server/demo.js +96 -0
  137. package/dist/server/demo.js.map +1 -0
  138. package/dist/server/idempotency.js +104 -0
  139. package/dist/server/idempotency.js.map +1 -0
  140. package/dist/server/port.js +36 -0
  141. package/dist/server/port.js.map +1 -0
  142. package/dist/server/principal.js +90 -0
  143. package/dist/server/principal.js.map +1 -0
  144. package/dist/server/terminal.js +285 -0
  145. package/dist/server/terminal.js.map +1 -0
  146. package/dist/setup/components.js +98 -0
  147. package/dist/setup/components.js.map +1 -0
  148. package/dist/setup/config.js +102 -0
  149. package/dist/setup/config.js.map +1 -0
  150. package/dist/setup/ink-ui.js +188 -0
  151. package/dist/setup/ink-ui.js.map +1 -0
  152. package/dist/setup/onboarding.js +183 -0
  153. package/dist/setup/onboarding.js.map +1 -0
  154. package/dist/setup/run.js +70 -0
  155. package/dist/setup/run.js.map +1 -0
  156. package/dist/ticket-cli.js +116 -0
  157. package/dist/ticket-cli.js.map +1 -0
  158. package/dist/voice/index.js +69 -0
  159. package/dist/voice/index.js.map +1 -0
  160. package/dist/voice/moonshine.js +247 -0
  161. package/dist/voice/moonshine.js.map +1 -0
  162. package/dist/voice/wav.js +54 -0
  163. package/dist/voice/wav.js.map +1 -0
  164. package/dist/voice/whisper.js +491 -0
  165. package/dist/voice/whisper.js.map +1 -0
  166. package/dist/web/assets/index-ChuS3qKc.js +254 -0
  167. package/dist/web/assets/index-DR6WkmzI.css +1 -0
  168. package/dist/web/icons/apple-touch-icon.png +0 -0
  169. package/dist/web/icons/icon-192.png +0 -0
  170. package/dist/web/icons/icon-512.png +0 -0
  171. package/dist/web/icons/maskable-512.png +0 -0
  172. package/dist/web/index.html +21 -0
  173. package/dist/web/manifest.webmanifest +30 -0
  174. package/dist/web/sw.js +183 -0
  175. package/package.json +96 -4
@@ -0,0 +1,1709 @@
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, closeActions, finishAction, MAX_ACTION_OUTPUT, startAction, } from "./actions.js";
8
+ import { bashGuardBlockedReader } from "./bash-guard.js";
9
+ import { captureRunFacts, captureWorktree, commitAttempt, worktreeHead, } from "./diff.js";
10
+ import { buildTicketPrompt, CODING_AGENT_PROMPT, RESUME_PROMPT, VERIFIED_CODING_AGENT_PROMPT, VERIFIED_RESUME_PROMPT, withExtraInstructions, } from "./prompt.js";
11
+ import { readRepoInstructions } from "../repo/instructions.js";
12
+ import { buildDeveloperContextPack } from "./context.js";
13
+ import { profileFor } from "./profiles.js";
14
+ import { commentActionsFor, wasteSignalDetails } from "./retro.js";
15
+ import { phaseForTool } from "./phases.js";
16
+ import { buildRunSystemPrompt, emptyWorkflow, hasWorkflow, workflowSummary, } from "./workflow.js";
17
+ import { evidenceRevision } from "./evidence.js";
18
+ import { resultComment } from "./result.js";
19
+ import { stripWorktreeCd } from "./actions.js";
20
+ import { commitTicketWork, failureReport, hasTicketChanges, publishBranch, runChecks, ticketDiff, worktreeFingerprint, } from "./finish.js";
21
+ const execFileAsync = promisify(execFile);
22
+ export class RunAlreadyActiveError extends Error {
23
+ constructor(ticketId) {
24
+ super(`${ticketId} is already running`);
25
+ this.name = "RunAlreadyActiveError";
26
+ }
27
+ }
28
+ const FACTS_POLL_MS = 3_000;
29
+ /**
30
+ * How often a live token total reaches the board and the stored row. The
31
+ * harness reports after every assistant message, which can be far more often
32
+ * than a person reads; seven seconds keeps the number moving without turning
33
+ * the event stream into a token counter.
34
+ */
35
+ const TOKEN_PUBLISH_MS = 7_000;
36
+ const OUTPUT_LINES = 12;
37
+ const TAIL_LINES = 3;
38
+ const OUTPUT_DELAY_MS = 250;
39
+ const outputLine = (value) => {
40
+ const text = value.trim();
41
+ // A minified or single-line dump is only interesting where it ended.
42
+ return text.length > 400 ? `…${text.slice(-399)}` : text;
43
+ };
44
+ const tail = (value) => value.trim().split("\n").filter(Boolean).slice(-3).join(" ").slice(0, 500);
45
+ /**
46
+ * How many times one attempt may be resumed before the board stops trying.
47
+ * A resume is cheap and loses nothing, but a machine that sleeps every few
48
+ * minutes would otherwise keep the same run alive forever: after this many, the
49
+ * ticket falls back to the ordinary attempt budget and then to the person.
50
+ */
51
+ export const MAX_RESUMES = 3;
52
+ /** Idle developer turns may continue, but never beyond the attempt's deadline or this cap. */
53
+ export const MAX_TURN_CONTINUATIONS = 2;
54
+ /** Failed verification rounds before the board stops sending the run back and blocks the ticket. */
55
+ export const MAX_VERIFY_ROUNDS = 3;
56
+ /** Identical tool calls in a row, on a verified run, before the developer is told to change course. */
57
+ export const REPEAT_NUDGE_AT = 4;
58
+ /** Sent in-session once per run when the developer repeats the same tool call. */
59
+ 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.";
60
+ /** JSON with sorted keys, so the same arguments always compare equal. */
61
+ function stableJson(value) {
62
+ if (Array.isArray(value))
63
+ return `[${value.map(stableJson).join(",")}]`;
64
+ if (value && typeof value === "object") {
65
+ const record = value;
66
+ const fields = Object.keys(record)
67
+ .sort()
68
+ .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`);
69
+ return `{${fields.join(",")}}`;
70
+ }
71
+ return JSON.stringify(value) ?? "null";
72
+ }
73
+ /** Lead consultations per verified ticket before the person is asked directly. */
74
+ export const MAX_LEAD_CONSULTS = 2;
75
+ 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.
76
+
77
+ 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.`;
78
+ 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.`;
79
+ 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.`;
80
+ const COMMIT_TYPES = new Set([
81
+ "feat",
82
+ "fix",
83
+ "chore",
84
+ "docs",
85
+ "refactor",
86
+ "test",
87
+ "perf",
88
+ "style",
89
+ "build",
90
+ "ci",
91
+ ]);
92
+ /** A conventional subject from the ticket title, typed by the branch prefix when it names one. */
93
+ function commitMessage(title, branch) {
94
+ const prefix = branch.includes("/") ? branch.slice(0, branch.indexOf("/")) : "";
95
+ const type = COMMIT_TYPES.has(prefix) ? prefix : "feat";
96
+ return `${type}: ${title.trim().replace(/^./, (letter) => letter.toLowerCase())}`;
97
+ }
98
+ async function currentBranch(cwd) {
99
+ const { stdout } = await execFileAsync("git", ["-C", cwd, "branch", "--show-current"], {
100
+ timeout: 15_000,
101
+ }).catch(() => ({ stdout: "" }));
102
+ return String(stdout).trim();
103
+ }
104
+ const seconds = (ms) => (ms / 1000).toFixed(1);
105
+ const DEFAULT_RETRY = {
106
+ maxAttempts: 2,
107
+ breakerStalls: 3,
108
+ breakerWindowMs: 10 * 60_000,
109
+ };
110
+ /**
111
+ * Why a run that ended without moving its ticket is worth saying out loud. The
112
+ * exit code is evidence about the process; the silence is the point.
113
+ */
114
+ const stallReason = (exitCode) => exitCode === null || exitCode === 0
115
+ ? "the agent finished without reporting a status"
116
+ : `the agent exited with code ${exitCode} without reporting a status`;
117
+ /**
118
+ * Owns the in-flight ticket processes and their live status. It does not move
119
+ * tickets: a finished run leaves the card where it is until the agent says what
120
+ * happened through the status contract.
121
+ */
122
+ export class RunManager {
123
+ db;
124
+ runtime;
125
+ onStatus;
126
+ statusBaseUrl;
127
+ agentPath;
128
+ ghCommand;
129
+ factsPollMs;
130
+ tokenPublishMs;
131
+ repoRoot;
132
+ retro;
133
+ defaults;
134
+ lead;
135
+ active = new Map();
136
+ statuses = new Map();
137
+ /**
138
+ * Callers waiting for the ticket's current run to end. A conflict resolution
139
+ * is started from a background pass that has to reconcile its own outcome, so
140
+ * it needs the run's ending and the trace the run left behind.
141
+ */
142
+ settleWaiters = new Map();
143
+ /** Stall timestamps, oldest first, for the breaker. */
144
+ stalls = [];
145
+ retry;
146
+ constructor(db, runtime, onStatus, statusBaseUrl, agentPath, ghCommand = "gh", factsPollMs = FACTS_POLL_MS, retry = {}, tokenPublishMs = TOKEN_PUBLISH_MS,
147
+ /** The checkout the board runs in, so a screenshot path resolves from a worktree. */
148
+ repoRoot = process.cwd(),
149
+ /**
150
+ * A separate manager pass that reads a finished run's evidence. Optional:
151
+ * tests and a board without a harness must not spawn one.
152
+ */
153
+ retro, defaults = () => ({ harness: "pi", model: "" }),
154
+ /** The stronger model a stuck verified ticket is sent to before the person. */
155
+ lead) {
156
+ this.db = db;
157
+ this.runtime = runtime;
158
+ this.onStatus = onStatus;
159
+ this.statusBaseUrl = statusBaseUrl;
160
+ this.agentPath = agentPath;
161
+ this.ghCommand = ghCommand;
162
+ this.factsPollMs = factsPollMs;
163
+ this.tokenPublishMs = tokenPublishMs;
164
+ this.repoRoot = repoRoot;
165
+ this.retro = retro;
166
+ this.defaults = defaults;
167
+ this.lead = lead;
168
+ this.retry = { ...DEFAULT_RETRY, ...retry };
169
+ }
170
+ /** Where the harness keeps session files: with the board's own state. */
171
+ get sessionDir() {
172
+ return join(this.repoRoot, ".zelio", "sessions");
173
+ }
174
+ isRunning(ticketId) {
175
+ return this.active.has(ticketId);
176
+ }
177
+ /**
178
+ * Resolves when the ticket's current run has ended, with the status it ended
179
+ * on. Registered immediately after `start`, so the waiter can never miss the
180
+ * run it is about. A retry carries the waiter onto the next attempt, because
181
+ * that is still the same ticket settling.
182
+ */
183
+ whenSettled(ticketId) {
184
+ return new Promise((resolve) => {
185
+ const waiters = this.settleWaiters.get(ticketId) ?? new Set();
186
+ waiters.add(resolve);
187
+ this.settleWaiters.set(ticketId, waiters);
188
+ });
189
+ }
190
+ wakeSettleWaiters(ticketId, status) {
191
+ const waiters = this.settleWaiters.get(ticketId);
192
+ if (!waiters)
193
+ return;
194
+ this.settleWaiters.delete(ticketId);
195
+ for (const waiter of waiters)
196
+ waiter(status);
197
+ }
198
+ runningCount() {
199
+ return this.active.size;
200
+ }
201
+ /** Every run this server knows about, active or just finished. */
202
+ listStatuses() {
203
+ return [...this.statuses.values()];
204
+ }
205
+ /**
206
+ * A restart empties the in-memory run map, so a ticket that was mid-run comes
207
+ * back claiming `in_progress` with no process behind it. A run the restart
208
+ * killed is put back to work as the next attempt in the same worktree: a
209
+ * restart is not a decision to stop, and the work already on the branch is
210
+ * the input to the next attempt. Every other quiet ending is adopted: the
211
+ * process is gone, so the only honest thing left to say is that it never
212
+ * reported, and the ticket itself is not moved — a stall is the person's call.
213
+ */
214
+ async reconcileOrphans(worktreeFor) {
215
+ const adopted = [];
216
+ const restarted = "the server restarted while this ticket was running; the run never reported a status";
217
+ const orphaned = "nothing is running on this ticket; no run reported a status";
218
+ for (const ticket of this.db.listTickets()) {
219
+ if (ticket.state !== "in_progress" || this.active.has(ticket.id))
220
+ continue;
221
+ const latest = this.db.latestAgentRun(ticket.id);
222
+ if (latest?.state === "running" && worktreeFor) {
223
+ // Ticket order is the board's order, and one resume per ticket is the
224
+ // point: starting them in parallel would race the worktree creation.
225
+ // oxlint-disable-next-line no-await-in-loop
226
+ const resumed = await this.resumeInterrupted(ticket, latest, worktreeFor);
227
+ if (resumed) {
228
+ adopted.push(resumed);
229
+ continue;
230
+ }
231
+ }
232
+ // A failure already has a record that explains itself, so only the two
233
+ // quiet endings are rewritten: a run the restart killed, and a run that
234
+ // ended without reporting.
235
+ const error = latest ? restarted : orphaned;
236
+ const quiet = !latest || latest.state === "running" || latest.state === "completed";
237
+ const record = latest && quiet ? (this.db.markRunStalled(latest.id, error) ?? latest) : null;
238
+ const failed = latest?.state === "failed";
239
+ const startedAt = latest ? Date.parse(latest.started_at) : Number.NaN;
240
+ const endedAt = latest?.ended_at ? Date.parse(latest.ended_at) : startedAt;
241
+ const status = {
242
+ ticketId: ticket.id,
243
+ runId: latest?.id ?? "",
244
+ label: failed ? "Run failed" : "No status reported",
245
+ tool: null,
246
+ startedAt: Number.isNaN(startedAt) ? Date.now() : startedAt,
247
+ endedAt: Number.isNaN(endedAt) ? undefined : endedAt,
248
+ phase: failed ? "failed" : "stalled",
249
+ attempt: latest?.attempt ?? 1,
250
+ attempts: this.retry.maxAttempts,
251
+ tail: [],
252
+ error: failed ? (latest?.error ?? error) : (record?.error ?? error),
253
+ ...(latest?.workflow && latest.workflow_stage
254
+ ? { workflow: workflowSummary(latest.workflow_stage, latest.workflow) }
255
+ : {}),
256
+ };
257
+ this.statuses.set(ticket.id, status);
258
+ adopted.push(status);
259
+ }
260
+ return adopted;
261
+ }
262
+ /**
263
+ * The run the restart killed still says `running`, so it is closed as a stall
264
+ * before anything else: history never shows two live runs for one ticket.
265
+ *
266
+ * What happens next depends on whether the run left a session. With one, the
267
+ * same attempt is resumed: the agent keeps its conversation, so a restart
268
+ * costs the interruption and not the work, and the card does not spend an
269
+ * attempt on a lid closing. Without one - a row from before sessions, or an
270
+ * attempt that has used its resumes - the ticket falls back to the next cold
271
+ * attempt in the same worktree, which is what every restart used to do.
272
+ * Attempts are never extended by a restart, and a worktree that cannot be
273
+ * prepared leaves the ticket where it is with a comment saying why.
274
+ */
275
+ async resumeInterrupted(ticket, latest, worktreeFor) {
276
+ const restarted = "the server restarted while this ticket was running; the run never reported a status";
277
+ this.db.markRunStalled(latest.id, restarted);
278
+ const resumes = latest.resume_count;
279
+ const resumable = Boolean(latest.session_id) && resumes < MAX_RESUMES;
280
+ if (!resumable && latest.attempt >= this.retry.maxAttempts) {
281
+ // The budget is spent and this run has nothing left to resume. A restart
282
+ // cannot authorize an attempt the policy does not allow, so the card asks
283
+ // the person instead. Checked before the worktree: a card that is only
284
+ // going to be escalated must not pay for a checkout first.
285
+ this.escalate(ticket.id, latest.attempt);
286
+ return null;
287
+ }
288
+ let worktree;
289
+ try {
290
+ worktree = await worktreeFor(ticket.id);
291
+ }
292
+ catch (cause) {
293
+ this.db.addComment({
294
+ ticket_id: ticket.id,
295
+ type: "system",
296
+ author: "zelio",
297
+ 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.`,
298
+ });
299
+ return null;
300
+ }
301
+ const current = this.db.getTicket(ticket.id);
302
+ if (!current || current.state !== "in_progress" || this.active.has(ticket.id))
303
+ return null;
304
+ if (resumable) {
305
+ this.db.addComment({
306
+ ticket_id: ticket.id,
307
+ type: "system",
308
+ author: "zelio",
309
+ text: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Resuming it from its last turn.`,
310
+ });
311
+ try {
312
+ this.start(ticket, worktree, latest.attempt, {
313
+ prompt: (ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT,
314
+ profile: latest.profile ?? ticket.profile ?? "developer",
315
+ label: "Resumed",
316
+ retry: true,
317
+ sessionId: latest.session_id ?? undefined,
318
+ resumes: resumes + 1,
319
+ resumeEvidence: latest.command_evidence,
320
+ source: latest.job_source,
321
+ command: latest.harness ?? undefined,
322
+ systemPrompt: latest.job_system_prompt ?? undefined,
323
+ originalPrompt: latest.job_prompt ?? undefined,
324
+ });
325
+ return this.statuses.get(ticket.id) ?? null;
326
+ }
327
+ catch {
328
+ // The slot went somewhere else in the meantime; the stall badge stands.
329
+ return null;
330
+ }
331
+ }
332
+ const started = await this.retryNow(ticket.id, worktree, latest.attempt, latest.job_source === "ticket"
333
+ ? undefined
334
+ : {
335
+ prompt: latest.job_prompt ??
336
+ ((ticket.verify ?? []).length > 0 ? VERIFIED_RESUME_PROMPT : RESUME_PROMPT),
337
+ profile: latest.profile ?? ticket.profile ?? "developer",
338
+ systemPrompt: latest.job_system_prompt ?? undefined,
339
+ source: latest.job_source,
340
+ command: latest.harness ?? undefined,
341
+ originalPrompt: latest.job_prompt ?? undefined,
342
+ retry: true,
343
+ }, {
344
+ comment: `Attempt ${latest.attempt} of ${this.retry.maxAttempts} was interrupted by a server restart. Retrying in the same worktree.`,
345
+ wip: `wip: attempt ${latest.attempt} was interrupted by a restart`,
346
+ });
347
+ return started ? (this.statuses.get(ticket.id) ?? null) : null;
348
+ }
349
+ start(ticket, worktree, attempt = 1, job) {
350
+ if (this.active.has(ticket.id))
351
+ throw new RunAlreadyActiveError(ticket.id);
352
+ const resolvedJob = job ?? {
353
+ prompt: buildTicketPrompt(ticket, {
354
+ number: attempt,
355
+ of: this.retry.maxAttempts,
356
+ }, this.db.listComments(ticket.id), absoluteAttachments(this.repoRoot, ticket.attachments)),
357
+ profile: ticket.profile ?? "developer",
358
+ label: attempt > 1 ? `Attempt ${attempt} of ${this.retry.maxAttempts}` : "Starting",
359
+ retry: true,
360
+ source: "ticket",
361
+ };
362
+ // A stored row wins, so an edit on the Agents page is what the next run
363
+ // actually uses. The static profile is only the fallback for a name that
364
+ // predates the table.
365
+ const profile = this.db.getProfile(resolvedJob.profile) ?? profileFor(resolvedJob.profile);
366
+ const defaults = this.defaults();
367
+ const command = resolvedJob.command?.trim() || profile.harness.trim() || defaults.harness;
368
+ const model = profile.model.trim() || (command === defaults.harness ? defaults.model : "");
369
+ // A pi run can seed its own session id before the process starts. Codex
370
+ // returns a thread id instead, so its row stays open until that arrives.
371
+ const seedId = !this.runtime.sessionIdFromHarness?.(command);
372
+ // The workflow belongs to the stage, not to the ticket. Every writer run in
373
+ // In Progress gets it: a first start, a retry, an unblock, a send-back, and
374
+ // a mention. A reviewer reads the Review column's instructions, which is a
375
+ // different list: no checks, and board rules that forbid editing. A conflict
376
+ // repair started from Review is neither, and takes no workflow.
377
+ const stage = resolvedJob.stage ?? "in_progress";
378
+ const takesWorkflow = !resolvedJob.outsideStage && (profile.touchesRepo || stage === "review");
379
+ const workflow = takesWorkflow
380
+ ? this.db.getStageWorkflow(stage)
381
+ : emptyWorkflow();
382
+ const snapshot = hasWorkflow(workflow) ? { stage, workflow } : null;
383
+ // The row carries the conversation, not just the attempt: a resume is given
384
+ // the id it already had, and a fresh run seeds one so the next restart has
385
+ // something to reopen.
386
+ const record = this.db.startAgentRun(ticket.id, attempt, snapshot, {
387
+ id: resolvedJob.sessionId ?? null,
388
+ resumeCount: resolvedJob.resumes ?? 0,
389
+ profile: resolvedJob.profile,
390
+ harness: command,
391
+ source: resolvedJob.source,
392
+ prompt: resolvedJob.originalPrompt ?? resolvedJob.prompt,
393
+ systemPrompt: resolvedJob.systemPrompt ?? null,
394
+ seedId,
395
+ });
396
+ const statusToken = randomBytes(24).toString("hex");
397
+ // A verified ticket's developer is told the board checks and publishes: it
398
+ // never commits, pushes or reports Review, so it gets its own doctrine.
399
+ const verified = resolvedJob.profile === "developer" &&
400
+ stage === "in_progress" &&
401
+ !resolvedJob.outsideStage &&
402
+ (ticket.verify ?? []).length > 0;
403
+ const defaultPrompt = verified ? VERIFIED_CODING_AGENT_PROMPT : CODING_AGENT_PROMPT;
404
+ const basePrompt = resolvedJob.systemPrompt ?? defaultPrompt;
405
+ // Empty extra prompt must leave the prompt untouched, including "undefined"
406
+ // so the runtime applies its own default exactly as before. A verified run
407
+ // always names its prompt, because the runtime default is the unverified one.
408
+ const profilePrompt = profile.extraPrompt.trim()
409
+ ? withExtraInstructions(basePrompt, profile.extraPrompt)
410
+ : (resolvedJob.systemPrompt ?? (verified ? VERIFIED_CODING_AGENT_PROMPT : undefined));
411
+ // The repository's own AGENTS.md/CLAUDE.md comes before the workflow: it is
412
+ // the person's standing word on this repo, and it is read at run time, so a
413
+ // change to it takes effect on the next run without touching the board.
414
+ const instructions = profile.touchesRepo
415
+ ? readRepoInstructions(this.repoRoot)
416
+ : { files: [], text: "" };
417
+ // The workflow section goes last: it closes by restating the board rules no
418
+ // standing instruction may override, so it has to be the final thing the run
419
+ // reads. With nothing configured it is a no-op and the prompt is untouched.
420
+ const systemPrompt = hasWorkflow(workflow) || instructions.text
421
+ ? buildRunSystemPrompt(profilePrompt ?? defaultPrompt, stage, workflow, instructions, {
422
+ verified,
423
+ })
424
+ : profilePrompt;
425
+ const status = {
426
+ ticketId: ticket.id,
427
+ runId: record.id,
428
+ label: resolvedJob.label ?? "Starting",
429
+ tool: null,
430
+ startedAt: Date.now(),
431
+ phase: "running",
432
+ ...(resolvedJob.profile === "developer" ? { executionPhase: "inspect" } : {}),
433
+ profile: resolvedJob.profile,
434
+ ...(resolvedJob.sourceCommentId ? { requestCommentId: resolvedJob.sourceCommentId } : {}),
435
+ attempt,
436
+ attempts: this.retry.maxAttempts,
437
+ tail: [],
438
+ actions: [],
439
+ ...(snapshot ? { workflow: workflowSummary(stage, workflow) } : {}),
440
+ };
441
+ let run;
442
+ try {
443
+ const boardUrl = this.statusBaseUrl.replace(/\/$/, "");
444
+ const env = {
445
+ ZELIO_TICKET_ID: ticket.id,
446
+ ZELIO_BOARD_URL: boardUrl,
447
+ ZELIO_STATUS_URL: `${boardUrl}/api/tickets/${encodeURIComponent(ticket.id)}/status`,
448
+ ZELIO_TICKET_TOKEN: statusToken,
449
+ };
450
+ if (this.agentPath)
451
+ env.PATH = `${this.agentPath}:${process.env.PATH ?? ""}`;
452
+ // A harness may create its own session directory; making it first costs
453
+ // one syscall and removes the chance that every run fails on a missing
454
+ // parent under `.zelio`.
455
+ const sessionDir = this.sessionDir;
456
+ mkdirSync(sessionDir, { recursive: true });
457
+ const prompt = resolvedJob.profile === "developer" &&
458
+ resolvedJob.source === "ticket" &&
459
+ !resolvedJob.sessionId
460
+ ? `${resolvedJob.prompt}\n\n${buildDeveloperContextPack(worktree.path, ticket)}`
461
+ : resolvedJob.prompt;
462
+ run = this.runtime.spawn(worktree.path, prompt, {
463
+ env,
464
+ thinking: ticket.thinking ?? profile.thinking,
465
+ model: model || undefined,
466
+ command,
467
+ readOnly: !profile.touchesRepo,
468
+ systemPrompt,
469
+ shellGuard: resolvedJob.profile === "developer",
470
+ reporting: resolvedJob.profile === "developer" && !resolvedJob.outsideStage,
471
+ ...(resolvedJob.profile === "developer" &&
472
+ stage === "in_progress" &&
473
+ !resolvedJob.outsideStage
474
+ ? { continuationPrompt: () => this.continuationPrompt(ticket.id, record.id) }
475
+ : {}),
476
+ // The session lives beside the board's database, never in the person's
477
+ // home directory: a board is one repo, and its conversations go with it.
478
+ sessionId: record.session_id ?? (seedId ? record.id : undefined),
479
+ sessionDir,
480
+ });
481
+ }
482
+ catch (cause) {
483
+ const error = cause instanceof Error ? cause.message : "the agent could not start";
484
+ this.finishRecord(record.id, "failed", null, null, null, error);
485
+ const failed = {
486
+ ...status,
487
+ label: "Run failed",
488
+ phase: "failed",
489
+ endedAt: Date.now(),
490
+ error,
491
+ };
492
+ this.statuses.set(ticket.id, failed);
493
+ this.onStatus(failed);
494
+ return failed;
495
+ }
496
+ const active = {
497
+ run,
498
+ job: resolvedJob,
499
+ command,
500
+ status,
501
+ statusToken,
502
+ startHead: worktreeHead(worktree.path),
503
+ cancelled: false,
504
+ settled: false,
505
+ continuations: 0,
506
+ emittedCommits: new Set(),
507
+ emittedPrUrl: null,
508
+ output: [],
509
+ partial: "",
510
+ actions: [],
511
+ toolCalls: new Map(),
512
+ commandEvidence: [...(resolvedJob.resumeEvidence ?? [])],
513
+ checks: stage === "in_progress" && !resolvedJob.outsideStage
514
+ ? workflow.checks.map((check) => ({ label: check.label, command: check.command }))
515
+ : [],
516
+ verifyRounds: 0,
517
+ verified: ticket.verify.length > 0,
518
+ repeat: { key: "", count: 0 },
519
+ nudged: false,
520
+ gating: false,
521
+ gateAbort: new AbortController(),
522
+ worktreePath: worktree.path,
523
+ tokens: null,
524
+ ...(resolvedJob.profile === "developer" ? { executionPhase: "inspect" } : {}),
525
+ };
526
+ if (active.commandEvidence.length)
527
+ this.db.recordCommandEvidence(record.id, active.commandEvidence);
528
+ this.active.set(ticket.id, active);
529
+ this.statuses.set(ticket.id, status);
530
+ this.onStatus(status);
531
+ void this.execute(ticket.id, worktree, record.id, active);
532
+ return status;
533
+ }
534
+ async continuationPrompt(ticketId, runId) {
535
+ const gate = await this.completionGate(ticketId, runId, false);
536
+ if (gate.kind === "completed" || gate.kind === "escalated")
537
+ return undefined;
538
+ if (gate.kind === "continue") {
539
+ const current = this.active.get(ticketId);
540
+ if (current?.status.runId === runId) {
541
+ this.update(ticketId, current, {
542
+ label: `Fixing checks (round ${current.verifyRounds}/${MAX_VERIFY_ROUNDS})`,
543
+ tool: null,
544
+ });
545
+ }
546
+ return gate.prompt;
547
+ }
548
+ const active = this.active.get(ticketId);
549
+ if (!active ||
550
+ active.status.runId !== runId ||
551
+ active.cancelled ||
552
+ active.settled ||
553
+ active.continuations >= MAX_TURN_CONTINUATIONS ||
554
+ this.db.getTicket(ticketId)?.state !== "in_progress")
555
+ return undefined;
556
+ active.continuations += 1;
557
+ this.update(ticketId, active, {
558
+ label: `Continuing (${active.continuations}/${MAX_TURN_CONTINUATIONS})`,
559
+ tool: null,
560
+ });
561
+ return CONTINUATION_PROMPT;
562
+ }
563
+ /**
564
+ * The board's own completion check for a verified In Progress ticket. The
565
+ * ticket's verify commands and the stage checks run in the worktree; when they
566
+ * pass, the board commits, pushes, opens the pull request and records the
567
+ * result. Anything else is a skip, which leaves the run to the ordinary flow.
568
+ */
569
+ async completionGate(ticketId, runId, final) {
570
+ const active = this.active.get(ticketId);
571
+ const ticket = this.db.getTicket(ticketId);
572
+ const job = active?.job;
573
+ if (!active ||
574
+ !ticket ||
575
+ !job ||
576
+ active.status.runId !== runId ||
577
+ active.cancelled ||
578
+ active.settled ||
579
+ active.gating ||
580
+ job.profile !== "developer" ||
581
+ job.outsideStage ||
582
+ (job.stage ?? "in_progress") !== "in_progress" ||
583
+ ticket.state !== "in_progress" ||
584
+ ticket.verify.length === 0)
585
+ return { kind: "skip" };
586
+ active.gating = true;
587
+ this.update(ticketId, active, { label: "Verifying", tool: null });
588
+ try {
589
+ return await this.verifyTicket(ticketId, runId, active, ticket, final);
590
+ }
591
+ catch (cause) {
592
+ const message = cause instanceof Error ? cause.message : String(cause);
593
+ this.db.addComment({
594
+ ticket_id: ticketId,
595
+ type: "system",
596
+ author: "zelio",
597
+ text: `The board could not verify this run: ${message}`,
598
+ });
599
+ return { kind: "skip" };
600
+ }
601
+ finally {
602
+ active.gating = false;
603
+ }
604
+ }
605
+ async verifyTicket(ticketId, runId, active, ticket, final) {
606
+ const cwd = active.worktreePath;
607
+ const max = MAX_VERIFY_ROUNDS;
608
+ const changed = await hasTicketChanges(cwd);
609
+ if (!this.isLive(ticketId, active))
610
+ return { kind: "skip" };
611
+ if (!changed) {
612
+ return this.failRound(ticketId, runId, active, final, {
613
+ prompt: NO_CHANGES_PROMPT,
614
+ summary: "no changes for the ticket",
615
+ blocked: {
616
+ summary: `The ticket still has no changes after ${max} verification rounds.`,
617
+ reason: `the worktree still has no changes for the ticket after ${max} verification rounds`,
618
+ unblock: "Implement the ticket so its Verify commands pass, then mention @developer to continue.",
619
+ detail: "",
620
+ },
621
+ });
622
+ }
623
+ const checks = [...ticket.verify, ...active.checks];
624
+ const env = this.agentPath
625
+ ? { ...process.env, PATH: `${this.agentPath}:${process.env.PATH ?? ""}` }
626
+ : process.env;
627
+ const results = await runChecks(cwd, checks, {
628
+ env,
629
+ signal: active.gateAbort.signal,
630
+ rerunFailed: true,
631
+ });
632
+ if (!this.isLive(ticketId, active))
633
+ return { kind: "skip" };
634
+ for (const result of results.filter((item) => item.flaky)) {
635
+ this.db.addComment({
636
+ ticket_id: ticketId,
637
+ type: "system",
638
+ author: "zelio",
639
+ text: `Check "${result.label}" failed once and passed on rerun, so the board counted it as passed. It looks flaky: \`${result.command}\`.`,
640
+ });
641
+ }
642
+ for (const result of results) {
643
+ active.commandEvidence.push({
644
+ id: randomUUID(),
645
+ command: result.command,
646
+ outcome: result.passed ? "passed" : "failed",
647
+ revision: null,
648
+ });
649
+ }
650
+ active.commandEvidence = active.commandEvidence.slice(-64);
651
+ this.db.recordCommandEvidence(runId, active.commandEvidence);
652
+ const failed = results.find((result) => !result.passed);
653
+ if (failed) {
654
+ const detail = failureReport(results);
655
+ const fingerprint = await worktreeFingerprint(cwd);
656
+ if (!this.isLive(ticketId, active))
657
+ return { kind: "skip" };
658
+ return this.failRound(ticketId, runId, active, final, {
659
+ prompt: `${VERIFY_FAILED_PROMPT}\n\n${detail}`,
660
+ summary: failed.label,
661
+ check: failed.label,
662
+ fingerprint,
663
+ blocked: {
664
+ summary: `The board's checks still fail after ${max} rounds.`,
665
+ reason: `Check "${failed.label}" still fails after ${max} verification rounds: ${failed.command}`,
666
+ unblock: "Fix the failing check or correct the ticket's verify commands, then mention @developer to continue.",
667
+ detail,
668
+ },
669
+ });
670
+ }
671
+ const branch = ticket.branch?.trim() || (await currentBranch(cwd));
672
+ if (!this.isLive(ticketId, active))
673
+ return { kind: "skip" };
674
+ const commit = await commitTicketWork(cwd, commitMessage(ticket.title, branch));
675
+ if (!this.isLive(ticketId, active))
676
+ return { kind: "skip" };
677
+ if (commit.error) {
678
+ const hook = `The commit hook failed:\n\n\`\`\`text\n${commit.error}\n\`\`\``;
679
+ return this.failRound(ticketId, runId, active, final, {
680
+ prompt: `${VERIFY_FAILED_PROMPT}\n\n${hook}`,
681
+ summary: "the commit hook failed",
682
+ blocked: {
683
+ summary: `The commit hook still fails after ${max} rounds.`,
684
+ reason: `The commit hook still fails after ${max} verification rounds`,
685
+ unblock: "Fix the commit hook failure, then mention @developer to continue.",
686
+ detail: hook,
687
+ },
688
+ });
689
+ }
690
+ const prBody = [
691
+ `## Goal\n\n${ticket.goal.trim() || ticket.title}`,
692
+ `## Acceptance\n\n${ticket.acceptance.trim() || "See the ticket."}`,
693
+ [
694
+ "## Verified by Zelio",
695
+ ...results.map((result) => `- ${result.label}: \`${result.command}\` — passed in ${seconds(result.durationMs)}s`),
696
+ ].join("\n"),
697
+ ].join("\n\n");
698
+ const publish = branch
699
+ ? await publishBranch(cwd, branch, { title: ticket.title, body: prBody }, { gh: this.ghCommand })
700
+ : { pushed: false, prUrl: null, error: "the worktree is not on a branch" };
701
+ if (!this.isLive(ticketId, active))
702
+ return { kind: "skip" };
703
+ const summary = [
704
+ `Verified by the board: ${results.length} ${results.length === 1 ? "check" : "checks"} passed.`,
705
+ publish.prUrl ? `Pull request: ${publish.prUrl}.` : "",
706
+ publish.error
707
+ ? `Publishing failed: ${publish.error}. The work is committed on ${branch} at ${commit.head?.slice(0, 7) ?? "an unknown commit"}.`
708
+ : "",
709
+ commit.refused.length ? `Not committed (secret-looking): ${commit.refused.join(", ")}.` : "",
710
+ ]
711
+ .filter(Boolean)
712
+ .join(" ");
713
+ const report = {
714
+ outcome: "ready_for_review",
715
+ summary,
716
+ required_evidence: results.map((result) => ({
717
+ requirement: result.label,
718
+ result: "met",
719
+ evidence: `exit 0 in ${seconds(result.durationMs)}s`,
720
+ command: result.command,
721
+ })),
722
+ remaining_assurance: [],
723
+ };
724
+ this.db.recordAgentResult(runId, report, resultComment(report));
725
+ if (publish.prUrl)
726
+ this.db.setPullRequest(ticketId, publish.prUrl);
727
+ active.settled = true;
728
+ this.update(ticketId, active, { label: "Finishing", tool: null });
729
+ return { kind: "completed" };
730
+ }
731
+ /** One failed round: send the run back while rounds remain, otherwise block the ticket. */
732
+ failRound(ticketId, runId, active, final, round) {
733
+ active.verifyRounds += 1;
734
+ // The same check failing again on work that did not change is the developer
735
+ // repeating itself: the lead is asked now, not after the rounds run out.
736
+ const previous = active.lastFailure;
737
+ const repeated = round.check !== undefined &&
738
+ round.fingerprint != null &&
739
+ previous?.check === round.check &&
740
+ previous.fingerprint === round.fingerprint;
741
+ active.lastFailure =
742
+ round.check === undefined
743
+ ? undefined
744
+ : { check: round.check, fingerprint: round.fingerprint ?? null };
745
+ const exhausted = active.verifyRounds > MAX_VERIFY_ROUNDS;
746
+ if (exhausted || repeated) {
747
+ const { blocked } = round;
748
+ const current = this.db.getTicket(ticketId);
749
+ if (current && this.canConsultLead(current)) {
750
+ active.leadRequest = {
751
+ trigger: "checks_failing",
752
+ reason: exhausted
753
+ ? blocked.reason
754
+ : `Check "${round.check}" failed again and the work did not change between the rounds.`,
755
+ failure: blocked.detail,
756
+ };
757
+ active.settled = true;
758
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
759
+ return { kind: "escalated" };
760
+ }
761
+ }
762
+ if (exhausted) {
763
+ const { blocked } = round;
764
+ const current = this.db.getTicket(ticketId);
765
+ const report = {
766
+ outcome: "blocked",
767
+ summary: blocked.summary,
768
+ required_evidence: [],
769
+ remaining_assurance: [],
770
+ reason: `${current ? this.leadLimitNote(current) : ""}${blocked.reason}`,
771
+ unblock: blocked.unblock,
772
+ };
773
+ const text = [resultComment(report), blocked.detail].filter(Boolean).join("\n\n");
774
+ this.db.recordAgentResult(runId, report, text);
775
+ active.settled = true;
776
+ this.update(ticketId, active, { label: "Finishing", tool: null });
777
+ return { kind: "escalated" };
778
+ }
779
+ // After the process has gone there is no session to send the prompt to.
780
+ if (final)
781
+ this.update(ticketId, active, { label: "Checks failed", tool: null });
782
+ return { kind: "continue", prompt: round.prompt, summary: round.summary };
783
+ }
784
+ /** Counts identical tool calls in a row; the fourth one sends the nudge, once per run. */
785
+ noteRepeat(active, tool, args) {
786
+ if (!active.verified || active.nudged || !active.run.sendMessage)
787
+ return;
788
+ const key = `${tool} ${stableJson(args)}`;
789
+ active.repeat = { key, count: active.repeat.key === key ? active.repeat.count + 1 : 1 };
790
+ if (active.repeat.count < REPEAT_NUDGE_AT)
791
+ return;
792
+ active.nudged = true;
793
+ void active.run.sendMessage(REPEAT_NUDGE).catch(() => false);
794
+ }
795
+ isLive(ticketId, active) {
796
+ return (this.active.get(ticketId) === active &&
797
+ !active.cancelled &&
798
+ !active.settled &&
799
+ this.db.getTicket(ticketId)?.state === "in_progress");
800
+ }
801
+ cancel(ticketId) {
802
+ const active = this.active.get(ticketId);
803
+ if (!active)
804
+ return false;
805
+ active.cancelled = true;
806
+ this.update(ticketId, active, { label: "Cancelling", tool: null });
807
+ active.gateAbort.abort();
808
+ active.run.abort();
809
+ return true;
810
+ }
811
+ /**
812
+ * The agent said what happened, so the process has done its job. Stop it
813
+ * without recording a user cancellation; the ticket move is the record.
814
+ */
815
+ settle(ticketId) {
816
+ const active = this.active.get(ticketId);
817
+ if (!active || active.settled || active.cancelled)
818
+ return false;
819
+ active.settled = true;
820
+ this.update(ticketId, active, { label: "Finishing", tool: null });
821
+ active.run.abort();
822
+ return true;
823
+ }
824
+ async reportResult(ticketId, report) {
825
+ const active = this.active.get(ticketId);
826
+ if (!active || active.cancelled || active.job.outsideStage || active.job.stage === "review") {
827
+ return { ok: false, error: "no writable ticket run is accepting results" };
828
+ }
829
+ if (report.outcome === "ready_for_review" &&
830
+ (this.db.getTicket(ticketId)?.verify.length ?? 0) > 0) {
831
+ return {
832
+ ok: false,
833
+ 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.",
834
+ };
835
+ }
836
+ const recorded = this.db.getAgentRun(active.status.runId)?.result_report;
837
+ if (recorded) {
838
+ const ticket = this.db.getTicket(ticketId);
839
+ return JSON.stringify(recorded) === JSON.stringify(report) && ticket
840
+ ? { ok: true, ticket }
841
+ : { ok: false, error: "this run already accepted a different result" };
842
+ }
843
+ if (active.settled || this.db.getTicket(ticketId)?.state !== "in_progress") {
844
+ return { ok: false, error: "this run is no longer In Progress" };
845
+ }
846
+ if (report.outcome === "ready_for_review") {
847
+ const revision = await evidenceRevision(active.worktreePath);
848
+ if (!revision)
849
+ return {
850
+ ok: false,
851
+ error: "could not identify current worktree inputs; verification evidence cannot be confirmed",
852
+ };
853
+ for (const item of report.required_evidence) {
854
+ if (!item.command)
855
+ continue;
856
+ const command = stripWorktreeCd(item.command);
857
+ const observed = active.commandEvidence.findLast((entry) => entry.command === command);
858
+ if (!observed || observed.outcome !== "passed" || observed.revision !== revision) {
859
+ return {
860
+ ok: false,
861
+ error: `No current passed evidence for: ${command}. A running, failed, stale, or unobserved command cannot establish this requirement. Continue the required implementation/verification.`,
862
+ };
863
+ }
864
+ }
865
+ }
866
+ // Hashing yields; cancellation or another accepted report must still win.
867
+ if (this.active.get(ticketId) !== active ||
868
+ active.cancelled ||
869
+ active.settled ||
870
+ this.db.getTicket(ticketId)?.state !== "in_progress") {
871
+ return { ok: false, error: "the run changed while this result was being validated" };
872
+ }
873
+ if (report.outcome === "blocked") {
874
+ // A verified ticket's blocker goes to the lead first; the run ends here
875
+ // either way, so the developer's report becomes the lead's question.
876
+ const current = this.db.getTicket(ticketId);
877
+ if (current && this.canConsultLead(current)) {
878
+ this.db.addComment({
879
+ ticket_id: ticketId,
880
+ type: "comment",
881
+ author: active.job.profile || "developer",
882
+ text: resultComment(report),
883
+ run_id: active.status.runId,
884
+ });
885
+ active.leadRequest = {
886
+ trigger: "developer_blocked",
887
+ reason: report.reason ?? report.summary,
888
+ failure: report.unblock ?? "",
889
+ };
890
+ active.settled = true;
891
+ this.update(ticketId, active, { label: "Asking the lead", tool: null });
892
+ return { ok: true, ticket: current, escalated: true };
893
+ }
894
+ }
895
+ const ticket = this.db.recordAgentResult(active.status.runId, report, resultComment(report));
896
+ active.settled = true;
897
+ this.update(ticketId, active, { label: "Finishing", tool: null });
898
+ // Let the reporting tool receive its receipt; tool_end/settled then stops the process.
899
+ return { ok: true, ticket };
900
+ }
901
+ /** Current-run verification only; a successful command is not acceptance by itself. */
902
+ recordVerification(ticketId, evidence) {
903
+ const active = this.active.get(ticketId);
904
+ if (!active)
905
+ return false;
906
+ if (evidence.outcome === "passed" &&
907
+ !active.actions.some((action) => action.tool === "bash" &&
908
+ action.state === "done" &&
909
+ action.detail.includes(evidence.command.trim()))) {
910
+ return false;
911
+ }
912
+ active.verification = evidence;
913
+ return true;
914
+ }
915
+ reviewVerification(ticketId) {
916
+ return this.active.get(ticketId)?.verification;
917
+ }
918
+ runStartedAt(ticketId) {
919
+ return this.active.get(ticketId)?.status.startedAt;
920
+ }
921
+ /** A status token only belongs to the one run it was minted for. */
922
+ verifyStatusToken(ticketId, token) {
923
+ const expected = this.active.get(ticketId)?.statusToken;
924
+ if (!expected || !token || expected.length !== token.length)
925
+ return false;
926
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(token));
927
+ }
928
+ /** Deliver only when the current run belongs to the mentioned profile and its adapter accepts steering. */
929
+ async sendMessage(ticketId, profile, text, commentId) {
930
+ const active = this.active.get(ticketId);
931
+ if (!active ||
932
+ active.status.profile !== profile ||
933
+ active.status.phase !== "running" ||
934
+ active.cancelled ||
935
+ active.settled ||
936
+ !active.run.sendMessage)
937
+ return false;
938
+ try {
939
+ const accepted = await active.run.sendMessage(text);
940
+ if (accepted) {
941
+ if (this.active.get(ticketId) === active &&
942
+ active.status.phase === "running" &&
943
+ !active.cancelled &&
944
+ !active.settled) {
945
+ this.update(ticketId, active, { requestCommentId: commentId });
946
+ }
947
+ }
948
+ return accepted;
949
+ }
950
+ catch {
951
+ return false;
952
+ }
953
+ }
954
+ activeIdentity(ticketId) {
955
+ const active = this.active.get(ticketId);
956
+ return active
957
+ ? { profile: active.status.profile ?? "agent", runId: active.status.runId }
958
+ : null;
959
+ }
960
+ tailOf(active) {
961
+ const partial = outputLine(active.partial);
962
+ return [...active.output, ...(partial ? [partial] : [])].slice(-TAIL_LINES);
963
+ }
964
+ publishOutput(ticketId, active) {
965
+ if (active.outputTimer) {
966
+ clearTimeout(active.outputTimer);
967
+ active.outputTimer = undefined;
968
+ }
969
+ this.update(ticketId, active, { tail: this.tailOf(active) });
970
+ }
971
+ appendLine(ticketId, active, line) {
972
+ const text = outputLine(line);
973
+ if (!text)
974
+ return;
975
+ active.output.push(text);
976
+ active.output = active.output.slice(-OUTPUT_LINES);
977
+ this.publishOutput(ticketId, active);
978
+ }
979
+ appendText(ticketId, active, text) {
980
+ active.partial += text;
981
+ const lines = active.partial.split("\n");
982
+ // A file being printed without a newline must not grow without bound; the
983
+ // part that matters is the end, which is what a terminal would show.
984
+ active.partial = (lines.pop() ?? "").slice(-2000);
985
+ for (const line of lines) {
986
+ const clipped = outputLine(line);
987
+ if (clipped)
988
+ active.output.push(clipped);
989
+ }
990
+ active.output = active.output.slice(-OUTPUT_LINES);
991
+ if (lines.length > 0) {
992
+ this.publishOutput(ticketId, active);
993
+ return;
994
+ }
995
+ if (active.outputTimer)
996
+ return;
997
+ active.outputTimer = setTimeout(() => {
998
+ active.outputTimer = undefined;
999
+ this.publishOutput(ticketId, active);
1000
+ }, OUTPUT_DELAY_MS);
1001
+ }
1002
+ update(ticketId, active, patch) {
1003
+ active.status = { ...active.status, ...patch };
1004
+ this.statuses.set(ticketId, active.status);
1005
+ this.onStatus(active.status);
1006
+ }
1007
+ /**
1008
+ * Send the total so far to the board and write it to the run row. The row
1009
+ * matters as much as the stream: reopening the ticket, or reloading the tab,
1010
+ * reads the stored row rather than replaying events it never saw.
1011
+ */
1012
+ publishTokens(ticketId, runId, active) {
1013
+ active.tokenTimer = undefined;
1014
+ if (!active.tokens)
1015
+ return;
1016
+ this.db.updateAgentRunTokens(runId, active.tokens, active.tokens.cost);
1017
+ this.update(ticketId, active, { tokens: active.tokens });
1018
+ }
1019
+ /**
1020
+ * Commits and pull requests are facts the runtime can observe, so they land
1021
+ * in the timeline even if the agent forgot to say them in a comment.
1022
+ */
1023
+ recordFacts(ticketId, facts, active) {
1024
+ for (const commit of facts.commits) {
1025
+ if (active.emittedCommits.has(commit.sha))
1026
+ continue;
1027
+ active.emittedCommits.add(commit.sha);
1028
+ this.db.addComment({
1029
+ ticket_id: ticketId,
1030
+ type: "system",
1031
+ author: "git",
1032
+ text: `Committed ${commit.sha.slice(0, 7)} ${commit.subject} on ${facts.branch ?? "the ticket branch"}`,
1033
+ });
1034
+ }
1035
+ if (facts.prUrl && facts.prUrl !== active.emittedPrUrl) {
1036
+ active.emittedPrUrl = facts.prUrl;
1037
+ this.db.setPullRequest(ticketId, facts.prUrl);
1038
+ const text = `Pull request opened: ${facts.prUrl}`;
1039
+ // Run-local state resets on retries, resumes, and server restarts. The
1040
+ // timeline is the durable record of which PRs were already announced.
1041
+ const announced = this.db
1042
+ .listComments(ticketId)
1043
+ .some((comment) => comment.type === "system" && comment.text === text);
1044
+ if (!announced) {
1045
+ this.db.addComment({
1046
+ ticket_id: ticketId,
1047
+ type: "system",
1048
+ author: "github",
1049
+ text,
1050
+ });
1051
+ }
1052
+ }
1053
+ }
1054
+ async captureFacts(ticketId, worktree, active) {
1055
+ // A conflict repair commits a merge, not the ticket's work: "Committed …"
1056
+ // and "Pull request opened …" would describe a PR that already existed.
1057
+ if (active.job.outsideStage)
1058
+ return;
1059
+ try {
1060
+ const facts = await captureRunFacts(worktree.path, active.startHead, this.ghCommand);
1061
+ this.recordFacts(ticketId, facts, active);
1062
+ }
1063
+ catch {
1064
+ // Facts are an observation, not a reason to fail the run.
1065
+ }
1066
+ }
1067
+ /** One poll at a time: an in-flight capture already describes the worktree. */
1068
+ pollFacts(ticketId, worktree, active) {
1069
+ if (active.factsPoll)
1070
+ return active.factsPoll;
1071
+ active.factsPoll = this.captureFacts(ticketId, worktree, active).finally(() => {
1072
+ active.factsPoll = undefined;
1073
+ });
1074
+ return active.factsPoll;
1075
+ }
1076
+ /**
1077
+ * The run is over, so let any in-flight poll land and then read the worktree
1078
+ * once more: a commit made just before exit could predate that poll.
1079
+ */
1080
+ async finalFacts(ticketId, worktree, active) {
1081
+ await active.factsPoll;
1082
+ await this.captureFacts(ticketId, worktree, active);
1083
+ }
1084
+ finishRecord(runId, state, exitCode, gitStatus, gitDiff, error, tokens = null) {
1085
+ this.db.finishAgentRun(runId, {
1086
+ state,
1087
+ exit_code: exitCode,
1088
+ git_status: gitStatus,
1089
+ git_diff: gitDiff,
1090
+ error,
1091
+ input_tokens: tokens?.input ?? null,
1092
+ output_tokens: tokens?.output ?? null,
1093
+ cost: tokens?.cost ?? null,
1094
+ });
1095
+ }
1096
+ /**
1097
+ * Ask the separate manager pass whether this run's evidence argues for a
1098
+ * better standing instruction. Gated by deterministic waste signals so a
1099
+ * clean run costs nothing; the result is a proposal, never a workflow edit.
1100
+ */
1101
+ reviewRun(ticketId, runId, state, attempt, actions, durationMs, harness) {
1102
+ if (!this.retro)
1103
+ return;
1104
+ // The trace keeps 12 rows; the full history is what shows repeated reads
1105
+ // and guard blocks, so the manager reads every call the run recorded.
1106
+ const details = wasteSignalDetails(actions, durationMs, this.db.listToolCalls(runId));
1107
+ if (details.length === 0)
1108
+ return;
1109
+ const signals = details.map((signal) => signal.text);
1110
+ const signalCauses = Object.fromEntries(details.map((signal) => [signal.text, signal.cause]));
1111
+ const record = this.db.latestAgentRun(ticketId);
1112
+ const workflow = record?.workflow ?? emptyWorkflow();
1113
+ void this.retro({
1114
+ ticketId,
1115
+ state,
1116
+ attempt,
1117
+ durationMs,
1118
+ actions,
1119
+ workflow,
1120
+ signals,
1121
+ signalCauses,
1122
+ harness,
1123
+ })
1124
+ .then((result) => {
1125
+ if (!result)
1126
+ return;
1127
+ const evidence = result.evidence.length > 0 ? result.evidence : signals;
1128
+ const suggestion = this.db.addWorkflowSuggestion({
1129
+ stage: record?.workflow_stage ?? "in_progress",
1130
+ ticket_id: ticketId,
1131
+ evidence,
1132
+ notes: result.notes,
1133
+ });
1134
+ // The suggestion lives beside the workflow, but the person meets it
1135
+ // where they review the run. The comment is the pointer; applying still
1136
+ // happens in Workflows, so a system message cannot rewrite config.
1137
+ if (suggestion) {
1138
+ this.db.addComment({
1139
+ ticket_id: ticketId,
1140
+ type: "system",
1141
+ author: "manager",
1142
+ text: [
1143
+ "Workflow suggestion for In Progress",
1144
+ "",
1145
+ result.notes,
1146
+ "",
1147
+ "Why:",
1148
+ ...evidence.map((line) => `- ${line}`),
1149
+ "",
1150
+ "Apply or dismiss it in Workflows.",
1151
+ ].join("\n"),
1152
+ actions: commentActionsFor(result, details),
1153
+ });
1154
+ }
1155
+ })
1156
+ // A manager that fails is a missing suggestion, not a failed run.
1157
+ .catch(() => { });
1158
+ }
1159
+ async execute(ticketId, worktree, runId, active) {
1160
+ let exitCode = null;
1161
+ let stderr = "";
1162
+ let timedOut = false;
1163
+ let spawnError = false;
1164
+ let error = null;
1165
+ const factsTimer = setInterval(() => {
1166
+ void this.pollFacts(ticketId, worktree, active);
1167
+ }, this.factsPollMs);
1168
+ try {
1169
+ for await (const event of active.run.events) {
1170
+ if (event.type === "tool_start") {
1171
+ if (active.executionPhase) {
1172
+ active.executionPhase = phaseForTool(active.executionPhase, event.tool, event.args);
1173
+ }
1174
+ // The label already says what is starting, so the tail stays output:
1175
+ // the assistant's prose and whatever the command prints.
1176
+ active.actions = startAction(active.actions, {
1177
+ tool: event.tool,
1178
+ label: event.label,
1179
+ detail: actionDetail(event.tool, event.args),
1180
+ callId: event.callId,
1181
+ });
1182
+ this.noteRepeat(active, event.tool, event.args);
1183
+ const id = active.actions.at(-1)?.id;
1184
+ if (id) {
1185
+ const args = event.args;
1186
+ active.toolCalls.set(id, {
1187
+ output: "",
1188
+ tool: event.tool,
1189
+ detail: actionDetail(event.tool, event.args),
1190
+ path: actionPath(event.tool, event.args),
1191
+ startedAt: Date.now(),
1192
+ ...(event.tool === "bash" &&
1193
+ typeof args?.command === "string" &&
1194
+ args.command.length <= 3_000
1195
+ ? { command: stripWorktreeCd(args.command) }
1196
+ : {}),
1197
+ });
1198
+ }
1199
+ this.update(ticketId, active, {
1200
+ label: event.label,
1201
+ tool: event.tool,
1202
+ actions: active.actions,
1203
+ ...(active.executionPhase ? { executionPhase: active.executionPhase } : {}),
1204
+ });
1205
+ }
1206
+ else if (event.type === "tool_output") {
1207
+ // Only the failed row keeps this; the cap is the memory the run pays
1208
+ // for evidence it may never need.
1209
+ const id = event.callId ??
1210
+ active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
1211
+ const call = id ? active.toolCalls.get(id) : undefined;
1212
+ if (call)
1213
+ call.output = (call.output + event.text).slice(-MAX_ACTION_OUTPUT);
1214
+ this.appendText(ticketId, active, event.text);
1215
+ }
1216
+ else if (event.type === "tool_end") {
1217
+ if (active.executionPhase) {
1218
+ active.executionPhase = phaseForTool(active.executionPhase, "", {}, event.isError);
1219
+ }
1220
+ const id = event.callId ??
1221
+ active.actions.findLast((action) => action.state === "running" && action.tool === event.tool)?.id;
1222
+ const call = id ? active.toolCalls.get(id) : undefined;
1223
+ active.actions = finishAction(active.actions, {
1224
+ isError: event.isError,
1225
+ output: call?.output,
1226
+ callId: id,
1227
+ });
1228
+ // The full history keeps every completed call, not just the trace's
1229
+ // tail. A refused bash command is still a call, marked as blocked.
1230
+ const endedAt = Date.now();
1231
+ this.db.recordToolCall({
1232
+ runId,
1233
+ tool: call?.tool ?? event.tool,
1234
+ detail: call?.detail ?? "",
1235
+ path: call?.path ?? null,
1236
+ state: event.isError ? "failed" : "done",
1237
+ blocked: event.isError && bashGuardBlockedReader(call?.output) !== null,
1238
+ startedAt: call?.startedAt ?? endedAt,
1239
+ endedAt,
1240
+ output: call?.output,
1241
+ });
1242
+ if (call?.command && id) {
1243
+ active.commandEvidence.push({
1244
+ id,
1245
+ command: call.command,
1246
+ outcome: event.isError ? "failed" : "passed",
1247
+ revision: event.isError ? null : await evidenceRevision(worktree.path),
1248
+ });
1249
+ active.commandEvidence = active.commandEvidence.slice(-64);
1250
+ this.db.recordCommandEvidence(runId, active.commandEvidence);
1251
+ }
1252
+ if (id)
1253
+ active.toolCalls.delete(id);
1254
+ this.update(ticketId, active, {
1255
+ label: "Thinking",
1256
+ tool: null,
1257
+ actions: active.actions,
1258
+ ...(active.executionPhase ? { executionPhase: active.executionPhase } : {}),
1259
+ });
1260
+ const reported = event.tool === "report_result" ||
1261
+ (event.tool === "bash" && /\bzelio\s+ticket\s+report\b/.test(call?.command ?? ""));
1262
+ if (active.settled && !active.cancelled && reported)
1263
+ active.run.abort();
1264
+ }
1265
+ else if (event.type === "settled") {
1266
+ if (active.settled && !active.cancelled)
1267
+ active.run.abort();
1268
+ }
1269
+ else if (event.type === "text") {
1270
+ this.appendText(ticketId, active, event.text);
1271
+ }
1272
+ else if (event.type === "session") {
1273
+ this.db.setAgentRunSessionId(runId, event.id);
1274
+ }
1275
+ else if (event.type === "usage") {
1276
+ // The harness may report usage more than once per run; the run is the
1277
+ // sum of what it said, never a guess from the transcript.
1278
+ active.tokens = {
1279
+ input: (active.tokens?.input ?? 0) + event.input,
1280
+ output: (active.tokens?.output ?? 0) + event.output,
1281
+ // A harness that reports no price on one message must not erase the
1282
+ // prices it did report: silence is null, and null plus a number is
1283
+ // that number.
1284
+ cost: event.cost === null
1285
+ ? (active.tokens?.cost ?? null)
1286
+ : (active.tokens?.cost ?? 0) + event.cost,
1287
+ };
1288
+ // Publish on a timer instead of per message: one report is a turn,
1289
+ // not a number a person needs to see change mid-sentence.
1290
+ if (!active.tokenTimer) {
1291
+ active.tokenTimer = setTimeout(() => {
1292
+ this.publishTokens(ticketId, runId, active);
1293
+ }, this.tokenPublishMs);
1294
+ }
1295
+ }
1296
+ else if (event.type === "exit") {
1297
+ exitCode = event.code;
1298
+ stderr = event.stderr;
1299
+ timedOut = event.timedOut;
1300
+ spawnError = event.spawnError === true;
1301
+ }
1302
+ }
1303
+ }
1304
+ catch (cause) {
1305
+ error = cause instanceof Error ? cause.message : "the agent run failed";
1306
+ }
1307
+ clearInterval(factsTimer);
1308
+ if (active.tokenTimer) {
1309
+ clearTimeout(active.tokenTimer);
1310
+ active.tokenTimer = undefined;
1311
+ }
1312
+ let gitStatus = null;
1313
+ let gitDiff = null;
1314
+ try {
1315
+ const captured = await captureWorktree(worktree.path, active.startHead);
1316
+ gitStatus = captured.status;
1317
+ gitDiff = captured.diff;
1318
+ }
1319
+ catch (cause) {
1320
+ error ??= `could not capture the worktree diff: ${cause instanceof Error ? cause.message : "git failed"}`;
1321
+ }
1322
+ await this.finalFacts(ticketId, worktree, active);
1323
+ if (active.outputTimer) {
1324
+ clearTimeout(active.outputTimer);
1325
+ active.outputTimer = undefined;
1326
+ }
1327
+ const cancelled = active.cancelled;
1328
+ // A settled run is the agent saying it is done, so the SIGTERM that follows
1329
+ // is our own abort. Its exit code describes how we stopped pi, not how the
1330
+ // work went: a clean run would otherwise be recorded as `failed` with
1331
+ // "the agent exited with code 143".
1332
+ const stoppedByUs = active.settled || cancelled;
1333
+ const cleanExit = stoppedByUs || exitCode === null || exitCode === 0;
1334
+ const failed = !cancelled && (error !== null || timedOut || spawnError || !cleanExit);
1335
+ if (!cancelled && failed) {
1336
+ error ??= spawnError
1337
+ ? "the harness could not start"
1338
+ : timedOut
1339
+ ? "the agent timed out"
1340
+ : `the agent exited with code ${exitCode ?? "unknown"}`;
1341
+ const detail = tail(stderr);
1342
+ if (detail)
1343
+ error = `${error}: ${detail}`;
1344
+ }
1345
+ // The agent reports *before* it stops: the status route moves the ticket and
1346
+ // then settles the process. So a run that ends while its ticket still says
1347
+ // `in_progress` did not report, and the card keeps claiming a job nobody is
1348
+ // doing. The run says so instead of letting that pass, and the ticket is
1349
+ // left untouched: only the agent or a person moves it.
1350
+ // A run that ended without its ticket moving may still have finished its
1351
+ // work: the board runs the gate here for harnesses with no in-session hook.
1352
+ let gate = { kind: "skip" };
1353
+ if (!cancelled && !failed && this.db.getTicket(ticketId)?.state === "in_progress") {
1354
+ gate = await this.completionGate(ticketId, runId, true);
1355
+ }
1356
+ // A request to the lead leaves the ticket In Progress while the lead reads
1357
+ // it; that is the board's own question, not a stall.
1358
+ const open = !cancelled && !failed && this.db.getTicket(ticketId)?.state === "in_progress";
1359
+ const stalled = open && !active.leadRequest;
1360
+ const attempt = active.status.attempt ?? 1;
1361
+ const job = active.job;
1362
+ // Recorded before the decision, so the breaker counts the failure that just
1363
+ // happened and not only the earlier ones. A comment run that opted out of
1364
+ // retries never inherits the ticket's original brief.
1365
+ const decision = stalled && job.retry !== false ? this.retryDecision(attempt) : "none";
1366
+ if (stalled) {
1367
+ const cause = gate.kind === "continue" ? `checks failed: ${gate.summary}` : stallReason(exitCode);
1368
+ error =
1369
+ decision === "hold"
1370
+ ? `${cause}; not retrying, because ${this.stalls.length} runs stalled recently and the harness looks unhealthy`
1371
+ : cause;
1372
+ }
1373
+ // Attempts are spent: a verified ticket goes to the lead before the person.
1374
+ if (decision === "escalate") {
1375
+ const current = this.db.getTicket(ticketId);
1376
+ if (current && this.canConsultLead(current)) {
1377
+ const failedAction = active.actions.findLast((action) => action.state === "failed");
1378
+ active.leadRequest = {
1379
+ trigger: "no_status",
1380
+ reason: error ?? stallReason(exitCode),
1381
+ failure: failedAction?.output ?? "",
1382
+ };
1383
+ }
1384
+ }
1385
+ const state = cancelled ? "cancelled" : failed ? "failed" : stalled ? "stalled" : "completed";
1386
+ this.finishRecord(runId, state, exitCode, gitStatus, gitDiff, error, active.tokens);
1387
+ this.active.delete(ticketId);
1388
+ // A retry starts before the finishing status is published, so the card never
1389
+ // blinks through "finished" and the allocator never sees a free slot and
1390
+ // hands it to another ticket. The next attempt owns the status line from
1391
+ // here; if it cannot start, the stall is published below.
1392
+ if (decision === "retry") {
1393
+ const failedAction = active.actions.findLast((action) => action.state === "failed");
1394
+ const summary = [
1395
+ error ?? stallReason(exitCode),
1396
+ failedAction
1397
+ ? `Last failed tool: ${failedAction.detail}. ${failedAction.output ?? ""}`
1398
+ : "",
1399
+ gate.kind === "continue" ? gate.prompt : "",
1400
+ "Worktree and commits are preserved.",
1401
+ ]
1402
+ .filter(Boolean)
1403
+ .join(" ");
1404
+ if (await this.retryNow(ticketId, worktree, attempt, job, {
1405
+ comment: `Attempt ${attempt} of ${this.retry.maxAttempts} ended without an accepted status. Observed outcome: ${summary}`,
1406
+ wip: `wip: attempt ${attempt} ended without reporting`,
1407
+ }))
1408
+ return;
1409
+ }
1410
+ const label = cancelled
1411
+ ? "Run cancelled"
1412
+ : failed
1413
+ ? "Run failed"
1414
+ : active.leadRequest
1415
+ ? "Asking the lead"
1416
+ : stalled
1417
+ ? "No status reported"
1418
+ : "Run finished";
1419
+ const final = {
1420
+ ...active.status,
1421
+ label,
1422
+ tool: null,
1423
+ endedAt: Date.now(),
1424
+ phase: cancelled ? "cancelled" : failed ? "failed" : stalled ? "stalled" : "done",
1425
+ // A call that was still live when the process ended did not finish; the
1426
+ // row says how the run ended instead of staying a spinner forever.
1427
+ actions: closeActions(active.actions, cancelled ? "cancelled" : failed || stalled ? "failed" : "done", Date.now(), error ?? undefined),
1428
+ error,
1429
+ tokens: active.tokens ?? undefined,
1430
+ };
1431
+ this.statuses.set(ticketId, final);
1432
+ this.onStatus(final);
1433
+ // The run is over and its trace is final. Anything waiting on this ticket's
1434
+ // run — a conflict repair reconciling its own outcome — is told now.
1435
+ this.wakeSettleWaiters(ticketId, final);
1436
+ // The run is over, so the manager pass can read its trail without holding
1437
+ // the slot or the card. It never blocks the finish and never moves a card.
1438
+ // A conflict repair is not In Progress work, so it proposes nothing there.
1439
+ if (!active.job.outsideStage) {
1440
+ this.reviewRun(ticketId, runId, final.phase, attempt, final.actions ?? [], Math.max(0, (final.endedAt ?? Date.now()) - active.status.startedAt), active.command);
1441
+ }
1442
+ if (decision === "escalate" && !active.leadRequest)
1443
+ this.escalate(ticketId, attempt);
1444
+ if (active.leadRequest)
1445
+ void this.runLead(ticketId, worktree, active, active.leadRequest);
1446
+ }
1447
+ /**
1448
+ * Retry, escalate, or leave the card with its stall badge. The numbers live in
1449
+ * §21 of the design notes: two attempts per ticket, and the breaker shuts
1450
+ * retrying down after three stalls in ten minutes.
1451
+ */
1452
+ retryDecision(attempt) {
1453
+ const now = Date.now();
1454
+ const cutoff = now - this.retry.breakerWindowMs;
1455
+ while (this.stalls.length > 0 && (this.stalls[0] ?? now) < cutoff)
1456
+ this.stalls.shift();
1457
+ this.stalls.push(now);
1458
+ if (attempt >= this.retry.maxAttempts)
1459
+ return "escalate";
1460
+ // A downed provider or a dead key fails every ticket the same way. Retrying
1461
+ // past that pays twice for the same outage, so the board stops and says so.
1462
+ return this.stalls.length >= this.retry.breakerStalls ? "hold" : "retry";
1463
+ }
1464
+ /**
1465
+ * The retry itself: commit what the failed attempt left behind, say so on the
1466
+ * timeline, then start again in the same worktree. Work is never lost to a
1467
+ * retry, and the attempt is never invisible.
1468
+ */
1469
+ async retryNow(ticketId, worktree, attempt, job, notice = {
1470
+ comment: `Attempt ${attempt} of ${this.retry.maxAttempts} ended without reporting a status. Retrying in the same worktree.`,
1471
+ wip: `wip: attempt ${attempt} ended without reporting`,
1472
+ }) {
1473
+ this.db.addComment({
1474
+ ticket_id: ticketId,
1475
+ type: "system",
1476
+ author: "zelio",
1477
+ text: notice.comment,
1478
+ });
1479
+ await commitAttempt(worktree.path, notice.wip);
1480
+ // The person may have moved or cancelled the card while the attempt was
1481
+ // settling. A retry never overrules them.
1482
+ const ticket = this.db.getTicket(ticketId);
1483
+ if (!ticket || ticket.state !== "in_progress" || this.active.has(ticketId))
1484
+ return false;
1485
+ try {
1486
+ if (job?.source === "comment") {
1487
+ // Keep the original task and add a factual lifecycle handoff: a fresh
1488
+ // comment turn must not have to rediscover why its predecessor ended.
1489
+ this.start(ticket, worktree, attempt + 1, {
1490
+ ...job,
1491
+ prompt: `${job.prompt}\n\n## Recovery handoff\n${notice.comment}\nContinue the original goal, acceptance, constraints, and authorizations above; inspect the previous run's output/trace, identify what remains, and do not repeat completed work without a reason.${notice.comment.includes("interrupted by a server restart") ? " The process was interrupted by a server restart; resume is unavailable or exhausted, so continue in this same worktree without claiming the work was lost." : " This was a normal turn completion without an accepted status report, not a process interruption."}`,
1492
+ });
1493
+ }
1494
+ else {
1495
+ // Rebuild the same authoritative brief and add the observed lifecycle
1496
+ // failure. A fresh session cannot see the prior conversation or trace.
1497
+ const retryPrompt = buildTicketPrompt(ticket, { number: attempt + 1, of: this.retry.maxAttempts }, this.db.listComments(ticketId), absoluteAttachments(this.repoRoot, ticket.attachments));
1498
+ this.start(ticket, worktree, attempt + 1, {
1499
+ prompt: `${retryPrompt}\n\n## Recovery handoff\n${notice.comment}\nInspect the preserved work and run only checks that remain necessary.`,
1500
+ profile: job?.profile ?? ticket.profile ?? "developer",
1501
+ retry: true,
1502
+ source: "ticket",
1503
+ command: job?.command,
1504
+ systemPrompt: job?.systemPrompt,
1505
+ });
1506
+ }
1507
+ return true;
1508
+ }
1509
+ catch {
1510
+ // The slot went somewhere else in the meantime; the stall badge stands.
1511
+ return false;
1512
+ }
1513
+ }
1514
+ leadConsults(ticketId) {
1515
+ return this.db.listComments(ticketId).filter((comment) => comment.author === "lead").length;
1516
+ }
1517
+ canConsultLead(ticket) {
1518
+ return (!!this.lead && ticket.verify.length > 0 && this.leadConsults(ticket.id) < MAX_LEAD_CONSULTS);
1519
+ }
1520
+ /** Said ahead of a block or an escalation once a verified ticket has used up its lead consults. */
1521
+ leadLimitNote(ticket) {
1522
+ return this.lead &&
1523
+ ticket.verify.length > 0 &&
1524
+ this.leadConsults(ticket.id) >= MAX_LEAD_CONSULTS
1525
+ ? `The lead already intervened ${MAX_LEAD_CONSULTS} times. `
1526
+ : "";
1527
+ }
1528
+ /**
1529
+ * One read-only consult of the lead, after the run has ended. The ticket stays
1530
+ * In Progress with no process behind it until the answer is applied here. This
1531
+ * never throws: an unanswered or broken consult blocks the ticket as before.
1532
+ */
1533
+ async runLead(ticketId, worktree, active, request) {
1534
+ const lead = this.lead;
1535
+ const current = this.db.getTicket(ticketId);
1536
+ if (!lead || !current || current.state !== "in_progress" || this.active.has(ticketId))
1537
+ return;
1538
+ try {
1539
+ const consult = this.leadConsults(ticketId) + 1;
1540
+ this.db.addComment({
1541
+ ticket_id: ticketId,
1542
+ type: "system",
1543
+ author: "zelio",
1544
+ text: `Asking the lead to look (consult ${consult} of ${MAX_LEAD_CONSULTS}): ${request.reason}`,
1545
+ });
1546
+ let decision = null;
1547
+ let problem = null;
1548
+ try {
1549
+ const input = {
1550
+ ticketId,
1551
+ title: current.title,
1552
+ goal: current.goal,
1553
+ outOfScope: current.out_of_scope,
1554
+ acceptance: current.acceptance,
1555
+ verify: current.verify,
1556
+ trigger: request.trigger,
1557
+ reason: request.reason,
1558
+ failure: request.failure,
1559
+ diff: await ticketDiff(worktree.path),
1560
+ actions: active.actions
1561
+ .slice(-25)
1562
+ .map((action) => `[${action.state === "failed" ? "FAILED" : action.state}] ${action.detail}`),
1563
+ consult,
1564
+ worktreePath: worktree.path,
1565
+ };
1566
+ decision = await lead(input).catch(() => null);
1567
+ }
1568
+ catch (cause) {
1569
+ problem = cause instanceof Error ? cause.message : String(cause);
1570
+ }
1571
+ const live = this.db.getTicket(ticketId);
1572
+ if (!live || live.state !== "in_progress" || this.active.has(ticketId)) {
1573
+ this.db.addComment({
1574
+ ticket_id: ticketId,
1575
+ type: "system",
1576
+ author: "zelio",
1577
+ text: "The lead answered after the ticket moved; its answer was not applied.",
1578
+ });
1579
+ return;
1580
+ }
1581
+ if (!decision) {
1582
+ this.blockForLead(ticketId, request, problem === null ? null : `The lead failed: ${problem}`);
1583
+ return;
1584
+ }
1585
+ try {
1586
+ this.applyLead(ticketId, worktree, decision);
1587
+ }
1588
+ catch (cause) {
1589
+ const message = cause instanceof Error ? cause.message : String(cause);
1590
+ this.blockForLead(ticketId, request, `The lead's answer could not be applied: ${message}`);
1591
+ }
1592
+ }
1593
+ catch (cause) {
1594
+ const message = cause instanceof Error ? cause.message : String(cause);
1595
+ this.db.addComment({
1596
+ ticket_id: ticketId,
1597
+ type: "system",
1598
+ author: "zelio",
1599
+ text: `The board could not consult the lead: ${message}`,
1600
+ });
1601
+ }
1602
+ }
1603
+ applyLead(ticketId, worktree, decision) {
1604
+ if (decision.decision === "guide") {
1605
+ this.db.addComment({
1606
+ ticket_id: ticketId,
1607
+ type: "decision",
1608
+ author: "lead",
1609
+ text: `Lead guidance:\n\n${decision.guidance}`,
1610
+ });
1611
+ const ticket = this.db.getTicket(ticketId);
1612
+ if (ticket)
1613
+ this.restartWithLead(ticket, worktree, decision.guidance);
1614
+ return;
1615
+ }
1616
+ if (decision.decision === "revise") {
1617
+ const updated = this.db.updateSpec(ticketId, {
1618
+ ...(decision.verify ? { verify: decision.verify } : {}),
1619
+ ...(decision.acceptance ? { acceptance: decision.acceptance } : {}),
1620
+ });
1621
+ if (!updated)
1622
+ return;
1623
+ const changed = [decision.verify ? "verify" : "", decision.acceptance ? "acceptance" : ""]
1624
+ .filter(Boolean)
1625
+ .join(" and ");
1626
+ const verify = decision.verify
1627
+ ? `\n\nVerify:\n${decision.verify.map((check) => `- ${check.label}: ${check.command}`).join("\n")}`
1628
+ : "";
1629
+ const acceptance = decision.acceptance ? `\n\nAcceptance:\n${decision.acceptance}` : "";
1630
+ this.db.addComment({
1631
+ ticket_id: ticketId,
1632
+ type: "decision",
1633
+ author: "lead",
1634
+ text: `Lead revised the ticket (${changed}):\n\n${decision.guidance}${verify}${acceptance}`,
1635
+ });
1636
+ this.restartWithLead(updated, worktree, decision.guidance);
1637
+ return;
1638
+ }
1639
+ const options = decision.options.map((option, index) => `${index + 1}) ${option}`);
1640
+ this.db.transition(ticketId, "blocked", {
1641
+ blocker_kind: "needs_human",
1642
+ blocker_reason: decision.question,
1643
+ blocker_unblock: `Reply with one of: ${options.join("; ")} — then mention @developer.`,
1644
+ });
1645
+ this.db.addComment({
1646
+ ticket_id: ticketId,
1647
+ type: "blocker",
1648
+ author: "lead",
1649
+ blocker_kind: "needs_human",
1650
+ text: [decision.question, options.join("\n")].join("\n\n"),
1651
+ });
1652
+ }
1653
+ /** The lead could not decide: the ticket blocks with the reason it was asked about. */
1654
+ blockForLead(ticketId, request, note) {
1655
+ this.db.transition(ticketId, "blocked", {
1656
+ blocker_kind: "decision",
1657
+ blocker_reason: request.reason,
1658
+ blocker_unblock: "The lead could not decide. Fix the failing check or answer the developer's question, then mention @developer to continue.",
1659
+ });
1660
+ const text = [
1661
+ `The lead could not decide. ${request.reason}${request.failure ? `\n\n${request.failure}` : ""}`,
1662
+ note,
1663
+ ]
1664
+ .filter(Boolean)
1665
+ .join("\n\n");
1666
+ this.db.addComment({ ticket_id: ticketId, type: "blocker", author: "zelio", text });
1667
+ }
1668
+ /** The developer again, from the start, with the lead's guidance added to the brief. */
1669
+ restartWithLead(ticket, worktree, guidance) {
1670
+ try {
1671
+ this.start(ticket, worktree, 1, {
1672
+ prompt: `${buildTicketPrompt(ticket, { number: 1, of: this.retry.maxAttempts }, this.db.listComments(ticket.id), absoluteAttachments(this.repoRoot, ticket.attachments))}\n\n## Guidance from the lead\n\n${guidance}`,
1673
+ profile: ticket.profile ?? "developer",
1674
+ label: "Following the lead",
1675
+ retry: true,
1676
+ source: "ticket",
1677
+ });
1678
+ }
1679
+ catch (cause) {
1680
+ const message = cause instanceof Error ? cause.message : String(cause);
1681
+ this.db.addComment({
1682
+ ticket_id: ticket.id,
1683
+ type: "system",
1684
+ author: "zelio",
1685
+ text: `Could not restart the developer: ${message}`,
1686
+ });
1687
+ this.db.transition(ticket.id, "blocked", {
1688
+ blocker_kind: "decision",
1689
+ blocker_reason: "the developer could not be restarted with the lead's guidance",
1690
+ blocker_unblock: "Check the server log, then mention @developer to continue.",
1691
+ });
1692
+ }
1693
+ }
1694
+ /** Exhaustion is an execution stall, not an agent-declared human blocker. */
1695
+ escalate(ticketId, attempt) {
1696
+ const ticket = this.db.getTicket(ticketId);
1697
+ if (!ticket || ticket.state !== "in_progress")
1698
+ return;
1699
+ const reason = `the agent ended ${attempt} ${attempt === 1 ? "time" : "times"} without reporting a status`;
1700
+ 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.";
1701
+ this.db.addComment({
1702
+ ticket_id: ticketId,
1703
+ type: "system",
1704
+ author: "zelio",
1705
+ text: `${this.leadLimitNote(ticket)}Execution needs attention: ${reason}. ${unblock} Mention @developer to continue the preserved work.`,
1706
+ });
1707
+ }
1708
+ }
1709
+ //# sourceMappingURL=manager.js.map