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,2503 @@
1
+ import { Hono } from "hono";
2
+ import { streamSSE } from "hono/streaming";
3
+ import { existsSync } from "node:fs";
4
+ import { readFile } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import QRCode from "qrcode";
7
+ import { normaliseVerify, } from "../db/db.js";
8
+ import { AttachmentError, absoluteAttachments, attachmentPaths, deleteAttachments, imageMime, readAttachmentImages, saveAttachment, sniffImage, } from "../attachments.js";
9
+ import { MAX_IMAGE_BYTES, MAX_MESSAGE_CHARS, PLAN_TURN_DEADLINE_MS } from "../limits.js";
10
+ import { newTaskTurns, summariseTurns } from "../metrics.js";
11
+ import { TransitionError, canTransition, checkSpec, describeRefusal, reviewEvidence, } from "../db/lifecycle.js";
12
+ import { MAX_CARDS, MAX_QUESTIONS, OrchestratorError, EMPTY_TURN_STATS, INTAKE_THINKING_CAP, assignIds, fallbackHandoff, normaliseCard, normaliseQuestions, runOrchestrator, summarizeConversation, } from "../orchestrator/runtime.js";
13
+ import { linkedBoardQuestion, runResearch, taskResearchQuestions, } from "../orchestrator/research.js";
14
+ import { fileOnLinkedBoard, LinkedBoardError } from "../repo/linked-boards.js";
15
+ import { buildIndex, readHead, readRepoName, renderBrief } from "../repo/index.js";
16
+ import { RunAlreadyActiveError, RunManager, } from "../run/manager.js";
17
+ import { MergeWatcher } from "../run/merge-watch.js";
18
+ import { normaliseRunResult } from "../run/result.js";
19
+ import { mergeBlockReason, mergePullRequest, readMergeOptions, readPullRequestSnapshot, } from "../run/pr-merge.js";
20
+ import { parseUnifiedDiff } from "../run/diff.js";
21
+ import { pullRequestUrlIn } from "../run/pull-request.js";
22
+ import { createIssue, prepareIssue } from "../run/issue.js";
23
+ import { hasMentionInstruction, mentionedProfiles } from "../run/mentions.js";
24
+ import { HarnessRuntime } from "../run/harness-runtime.js";
25
+ import { consultLead } from "../run/lead.js";
26
+ import { buildCommentPrompt, buildConflictPrompt, buildReviewPrompt, COMMENT_AGENT_PROMPT, CONFLICT_AGENT_PROMPT, REVIEW_AGENT_PROMPT, VERIFIED_CODING_AGENT_PROMPT, } from "../run/prompt.js";
27
+ import { listCodexModels } from "../run/codex-client.js";
28
+ import { listHarnessModels } from "../run/harnesses.js";
29
+ import { profileFor } from "../run/profiles.js";
30
+ import { asMaxAgents, asPlannerThinking } from "../run/settings.js";
31
+ import { capThinking, parseThinkingLevel, THINKING_LEVELS, } from "../run/thinking.js";
32
+ import { WORKFLOW_STAGES, isWorkflowStage, normaliseWorkflow, } from "../run/workflow.js";
33
+ import { WorktreeError, ensureWorktree, retireWorktree, worktreePath, } from "../run/worktree.js";
34
+ import { createPlanner } from "../orchestrator/codex-session.js";
35
+ import { memorySetupStore } from "../setup/config.js";
36
+ import { MAX_AUDIO_BYTES, VoiceError, createVoice } from "../voice/index.js";
37
+ import { createAuth } from "./auth.js";
38
+ import { createIdempotency } from "./idempotency.js";
39
+ import { capabilitiesFor } from "./principal.js";
40
+ import { MAX_TERMINAL_COLS, MAX_TERMINAL_ROWS, MIN_TERMINAL_COLS, MIN_TERMINAL_ROWS, NoSuchTerminalError, TerminalExitedError, TerminalLimitError, TerminalManager, } from "./terminal.js";
41
+ /** How long a settled reading waits for its answer turn before it is dropped. */
42
+ const PENDING_RESEARCH_TTL_MS = 15 * 60_000;
43
+ const BOARD_COLUMNS = ["todo", "in_progress", "blocked", "review", "done"];
44
+ /** Only strings survive into the database; anything else becomes an empty spec field. */
45
+ const asText = (value) => (typeof value === "string" ? value.trim() : "");
46
+ /** A pty dimension from the client: absent or invalid is `null`, so a route can judge it. */
47
+ const asDimension = (value) => typeof value === "number" && Number.isInteger(value) ? value : null;
48
+ /** A card count from the client: anything but a non-negative integer is zero. */
49
+ const asCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : 0;
50
+ /** A RIFF/WAVE container, which is the only thing whisper-cli is given here. */
51
+ function isWav(bytes) {
52
+ if (bytes.byteLength < 44)
53
+ return false;
54
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
55
+ return view.getUint32(0, false) === 0x52494646 && view.getUint32(8, false) === 0x57415645;
56
+ }
57
+ /**
58
+ * Which conversation a write was addressed to. Absent means the panel's own
59
+ * chat, which is what every route did before there were two surfaces.
60
+ */
61
+ const asConversationId = (value) => typeof value === "string" && value.trim() ? value.trim() : undefined;
62
+ /**
63
+ * The two answers a turn can refuse with. Everything else is a real failure and
64
+ * belongs in the log rather than in a status code someone has to interpret.
65
+ */
66
+ function turnRefusal(c, cause) {
67
+ if (cause instanceof AlreadyPlanningError) {
68
+ return c.json({ error: "the orchestrator is already planning" }, 409);
69
+ }
70
+ if (cause instanceof UnknownConversationError) {
71
+ return c.json({ error: "no such conversation" }, 404);
72
+ }
73
+ throw cause;
74
+ }
75
+ /**
76
+ * The bottom panel's shells are local only: a pseudoterminal is a shell on the
77
+ * Mac, so the tunnel allowlist does not carry these routes, and the routes
78
+ * refuse a tunnel principal even if one is ever let through by mistake.
79
+ */
80
+ function terminalOnly(c) {
81
+ if (c.get("principal").kind === "local")
82
+ return null;
83
+ return c.json({ error: "the terminal is local only", code: "forbidden" }, 403);
84
+ }
85
+ /** A shell that is gone or has ended is a refusal, not a server failure. */
86
+ function terminalRefusal(c, cause) {
87
+ if (cause instanceof NoSuchTerminalError)
88
+ return c.json({ error: "no such session" }, 404);
89
+ if (cause instanceof TerminalExitedError) {
90
+ return c.json({ error: "the shell has exited", code: "terminal_exited" }, 409);
91
+ }
92
+ if (cause instanceof TerminalLimitError) {
93
+ return c.json({ error: cause.message, code: "terminal_limit" }, 429);
94
+ }
95
+ throw cause;
96
+ }
97
+ /** A pass never gets less than this, so a late draft still has room to write one card. */
98
+ const MIN_PASS_MS = 20_000;
99
+ const MAX_MESSAGES = 20;
100
+ /** One keystroke, a paste, or a paste of a file: bigger than this is not typing. */
101
+ const MAX_TERMINAL_INPUT_CHARS = 64_000;
102
+ /** A turn is already in flight, so this one is refused rather than queued. */
103
+ class AlreadyPlanningError extends Error {
104
+ constructor() {
105
+ super("the orchestrator is already planning");
106
+ this.name = "AlreadyPlanningError";
107
+ }
108
+ }
109
+ /** Whatever went wrong, said in one line for the log. */
110
+ const describeError = (cause) => cause instanceof Error ? cause.message.slice(0, 300) : "the turn failed";
111
+ /** The conversation a turn was addressed to is gone, or was never created. */
112
+ class UnknownConversationError extends Error {
113
+ constructor(id) {
114
+ super(`no conversation ${id}`);
115
+ this.name = "UnknownConversationError";
116
+ }
117
+ }
118
+ const EMPTY_ANSWERS = { decided: [], block: "" };
119
+ /** Answers as they arrive from the panel: anything unreadable is simply not an answer. */
120
+ function asAnswers(value) {
121
+ if (!Array.isArray(value))
122
+ return [];
123
+ const answers = [];
124
+ for (const raw of value) {
125
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
126
+ continue;
127
+ const body = raw;
128
+ const questionId = asText(body.questionId);
129
+ if (!questionId)
130
+ continue;
131
+ const optionId = asText(body.optionId);
132
+ const text = asText(body.text);
133
+ answers.push({
134
+ questionId,
135
+ ...(optionId ? { optionId } : {}),
136
+ ...(text ? { text } : {}),
137
+ });
138
+ }
139
+ return answers;
140
+ }
141
+ /** Absent is `undefined`; present but invalid is `null`, so a route can refuse it. */
142
+ function asThinking(value) {
143
+ if (value === undefined)
144
+ return undefined;
145
+ return typeof value === "string" ? (parseThinkingLevel(value) ?? null) : null;
146
+ }
147
+ /**
148
+ * An answer is resolved against the questions the person was actually looking
149
+ * at. The model sees the same lines in their turn, but the cards get the record
150
+ * from here, because a model that forgets is exactly what this avoids.
151
+ */
152
+ function resolveAnswers(previous, answers) {
153
+ const lines = [];
154
+ const decided = [];
155
+ for (const answer of answers) {
156
+ const question = previous?.questions.find((item) => item.id === answer.questionId);
157
+ if (!question)
158
+ continue;
159
+ const option = question.options.find((item) => item.id === answer.optionId);
160
+ const chosen = option?.label ?? asText(answer.text);
161
+ if (!chosen)
162
+ continue;
163
+ lines.push(`- ${question.text} → ${chosen}`);
164
+ decided.push(option ? `person chose ${option.label}` : `person said: ${chosen}`);
165
+ }
166
+ if (lines.length === 0)
167
+ return EMPTY_ANSWERS;
168
+ return {
169
+ decided: [...new Set(decided)],
170
+ block: `Answers to your questions:\n${lines.join("\n")}`,
171
+ };
172
+ }
173
+ /** The board's own question about a linked board, so its answer is never a model's paraphrase. */
174
+ const BOARD_QUESTION = "board-";
175
+ /** More than two other repositories in one task is a project, not a card set. */
176
+ const MAX_BOARD_QUESTIONS = 2;
177
+ function boardQuestion(board) {
178
+ const about = board.description ? ` (${board.description})` : "";
179
+ return {
180
+ id: `${BOARD_QUESTION}${board.name}`,
181
+ text: `This also looks like it needs a change in ${board.name}${about}. Include a card for the ${board.name} board?`,
182
+ derived: false,
183
+ options: [
184
+ {
185
+ id: "include",
186
+ label: `Include ${board.name}`,
187
+ cost: `adds a card that runs on the ${board.name} board, in that repository`,
188
+ recommended: true,
189
+ },
190
+ {
191
+ id: "skip",
192
+ label: "This repo only",
193
+ cost: `the ${board.name} part is named in the reply, not carded`,
194
+ recommended: false,
195
+ },
196
+ ],
197
+ };
198
+ }
199
+ /** What the planner is told about a linked board: no port, no liveness. */
200
+ function briefOf(board) {
201
+ return { name: board.name, root: board.root, description: board.description };
202
+ }
203
+ /**
204
+ * The linked boards the person agreed to: the ones already on the draft, plus
205
+ * a "yes" to the board's own question in this turn, minus a "no". A board that
206
+ * left the registry is no longer one the work can be filed on.
207
+ */
208
+ function includedBoards(previous, answers, known) {
209
+ const included = new Set((previous?.boards ?? []).filter((name) => known.has(name)));
210
+ for (const answer of answers) {
211
+ if (!answer.questionId.startsWith(BOARD_QUESTION))
212
+ continue;
213
+ if (!previous?.questions.some((question) => question.id === answer.questionId))
214
+ continue;
215
+ const name = answer.questionId.slice(BOARD_QUESTION.length);
216
+ if (!known.has(name))
217
+ continue;
218
+ if (answer.optionId === "include")
219
+ included.add(name);
220
+ else if (answer.optionId === "skip")
221
+ included.delete(name);
222
+ }
223
+ return [...included];
224
+ }
225
+ /** A decision was made about the plan in front of the person, so it lands on its cards. */
226
+ function applyDecided(cards, decided) {
227
+ const out = [];
228
+ for (const card of cards) {
229
+ const merged = [...card.decided];
230
+ for (const entry of decided)
231
+ if (!merged.includes(entry))
232
+ merged.push(entry);
233
+ out.push({ ...card, decided: merged });
234
+ }
235
+ return out;
236
+ }
237
+ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize, harness, setup, listModels, plannerThinking, plannerToolBudget, summaryTimeoutMs, runtime, runTimeoutMs, retro, lead, leadEnabled, research, researchEnabled, maxRunning, prepare, prepareTicket, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, mergePollMs, index: indexOverride, indexOnStart, onRunsChange, voice: voiceOverride, build: buildOption, phone, terminals: terminalOverride, onLiveChange, linkedBoards: listLinked, boardFetch, }) {
238
+ const app = new Hono();
239
+ const auth = createAuth({ token, port });
240
+ const idempotency = createIdempotency(db);
241
+ const build = buildOption?.trim() || process.env.ZELIO_BUILD_HASH?.trim() || "dev";
242
+ const voice = voiceOverride ?? createVoice();
243
+ const root = repoRoot ?? process.cwd();
244
+ const setupStore = setup ?? memorySetupStore({ harness: "pi", modelChosen: true });
245
+ const effectiveHarness = () => harness?.trim() || process.env.ZELIO_HARNESS?.trim() || setupStore.read().harness || "pi";
246
+ const effectivePlannerModel = () => {
247
+ const saved = setupStore.read();
248
+ return effectiveHarness() === saved.harness ? saved.plannerModel : "";
249
+ };
250
+ const effectiveDeveloperModel = () => {
251
+ const saved = setupStore.read();
252
+ return effectiveHarness() === saved.harness ? saved.developerModel : "";
253
+ };
254
+ // The bottom panel's shells live in the repo root, never in a worktree.
255
+ const terminals = terminalOverride ?? new TerminalManager({ root });
256
+ // Config, not a constant: the person can raise the ceiling while the board
257
+ // runs. An explicit option (tests, a future CLI flag) still wins.
258
+ const maxConcurrentRuns = () => maxRunning ?? db.getBoardSettings().maxAgents;
259
+ // Likewise for the planner: a CLI flag beats the saved choice; the saved
260
+ // choice beats the runtime's env/default.
261
+ const plannerThinkingForTurn = () => plannerThinking ?? db.getBoardSettings().plannerThinking;
262
+ const prepareOverride = prepare ?? prepareTicket;
263
+ // One planning run at a time. Two in flight would cost twice and race on
264
+ // creating the same cards.
265
+ let planning = false;
266
+ /**
267
+ * What the turn in flight is doing. Ephemeral on purpose: it describes a
268
+ * subprocess that is running right now, so it lives in memory and dies with
269
+ * the turn instead of becoming a row nobody reads.
270
+ */
271
+ let turnStatus = null;
272
+ // The turn's own clock. Stamped here rather than in the panel, so a window
273
+ // opened halfway through a turn still counts the turn.
274
+ let turnStartedAt = 0;
275
+ const turnWatchers = new Set();
276
+ // Ephemeral state is part of the snapshot's ETag too. A status line that
277
+ // changes without a board write still has to reach a refetching client.
278
+ let liveRev = 0;
279
+ const publish = (status) => {
280
+ liveRev += 1;
281
+ if (status === null) {
282
+ turnStatus = null;
283
+ turnStartedAt = 0;
284
+ }
285
+ else {
286
+ if (turnStartedAt === 0)
287
+ turnStartedAt = Date.now();
288
+ turnStatus = { ...status, startedAt: turnStartedAt };
289
+ }
290
+ for (const watcher of turnWatchers)
291
+ watcher(turnStatus);
292
+ onLiveChange?.();
293
+ };
294
+ const runWatchers = new Set();
295
+ // Only a change is worth reporting: a token total or a tool label also moves
296
+ // through here, and waking the CLI every seven seconds to re-hold an
297
+ // assertion it already holds is churn, not information.
298
+ let liveRuns = 0;
299
+ const publishRun = (status) => {
300
+ liveRev += 1;
301
+ for (const watcher of runWatchers)
302
+ watcher(status);
303
+ onLiveChange?.();
304
+ const running = runs.runningCount();
305
+ if (running !== liveRuns) {
306
+ liveRuns = running;
307
+ onRunsChange?.(running);
308
+ }
309
+ // A finished process frees a slot. Ask the allocator for the next ticket,
310
+ // but never derive ticket state from this event.
311
+ if (status.phase !== "running")
312
+ void scheduleTickets();
313
+ };
314
+ const agentRuntime = runtime ?? new HarnessRuntime({ timeoutMs: runTimeoutMs });
315
+ // Resolved once. A test injects `research`; the CLI turns the scouts on with
316
+ // `researchEnabled`; otherwise an intake never has research to start.
317
+ const researchRunner = research ??
318
+ (researchEnabled
319
+ ? (questions, onFinding) => runResearch(questions, {
320
+ runtime: agentRuntime,
321
+ cwd: root,
322
+ cwdFor: (name) => linkedBoards().find((board) => board.name === name)?.root,
323
+ command: effectiveHarness(),
324
+ model: effectiveDeveloperModel() || undefined,
325
+ onFinding,
326
+ })
327
+ : undefined);
328
+ // Readings started by an intake, keyed by the conversation they belong to. The
329
+ // answer turn takes its own; a reading nobody asks for is dropped after a while.
330
+ const pendingResearch = new Map();
331
+ const startResearch = (conversationId, questions) => {
332
+ if (!researchRunner || questions.length === 0)
333
+ return undefined;
334
+ const startedAt = Date.now();
335
+ const reading = {
336
+ promise: Promise.resolve([]),
337
+ done: 0,
338
+ total: questions.length,
339
+ };
340
+ // One row per reading, like a planner turn. It never throws.
341
+ const record = (ok, error) => {
342
+ try {
343
+ db.recordPlannerTurn({
344
+ conversation_id: conversationId,
345
+ kind: "task",
346
+ mode: "research",
347
+ ok,
348
+ error,
349
+ duration_ms: Date.now() - startedAt,
350
+ index_ms: 0,
351
+ first_event_ms: null,
352
+ harness_ms: Date.now() - startedAt,
353
+ tool_calls: 0,
354
+ tool_errors: 0,
355
+ tool_budget: 0,
356
+ capped: null,
357
+ prompt_chars: 0,
358
+ output_chars: 0,
359
+ questions: questions.length,
360
+ cards: 0,
361
+ started_at: new Date(startedAt).toISOString(),
362
+ });
363
+ }
364
+ catch {
365
+ // The log is diagnostics only.
366
+ }
367
+ };
368
+ reading.promise = runReading(reading, questions).then((findings) => {
369
+ record(true, null);
370
+ return findings;
371
+ }, (cause) => {
372
+ record(false, describeError(cause));
373
+ return [];
374
+ });
375
+ pendingResearch.set(conversationId, reading);
376
+ void reading.promise.then(() => {
377
+ const timer = setTimeout(() => {
378
+ if (pendingResearch.get(conversationId) === reading) {
379
+ pendingResearch.delete(conversationId);
380
+ }
381
+ }, PENDING_RESEARCH_TTL_MS);
382
+ timer.unref();
383
+ });
384
+ return reading;
385
+ };
386
+ /** One batch of scouts on a reading; `done` counts across every batch it has. */
387
+ function runReading(reading, questions) {
388
+ return Promise.resolve().then(() => researchRunner(questions, () => {
389
+ reading.done += 1;
390
+ reading.listener?.(reading.done, reading.total);
391
+ }));
392
+ }
393
+ /**
394
+ * Adds scouts to a reading already under way, for the linked boards the
395
+ * intake named. The answer turn waits for both batches as one reading.
396
+ */
397
+ const extendResearch = (conversationId, questions) => {
398
+ if (!researchRunner || questions.length === 0)
399
+ return;
400
+ const reading = pendingResearch.get(conversationId);
401
+ if (!reading) {
402
+ startResearch(conversationId, questions);
403
+ return;
404
+ }
405
+ reading.total += questions.length;
406
+ const extra = runReading(reading, questions).catch(() => []);
407
+ reading.promise = Promise.all([reading.promise, extra]).then(([first, second]) => [
408
+ ...first,
409
+ ...second,
410
+ ]);
411
+ };
412
+ /** Other boards, never throwing: a broken registry is no linked boards. */
413
+ function linkedBoards() {
414
+ try {
415
+ return listLinked?.() ?? [];
416
+ }
417
+ catch {
418
+ return [];
419
+ }
420
+ }
421
+ /** Shows the reading as it goes, and waits for all of it. */
422
+ const awaitReading = async (reading) => {
423
+ const status = (done, total) => publish({ label: `Reading the repo (${done}/${total})`, tool: "explore" });
424
+ status(reading.done, reading.total);
425
+ reading.listener = status;
426
+ try {
427
+ return await reading.promise;
428
+ }
429
+ finally {
430
+ reading.listener = undefined;
431
+ }
432
+ };
433
+ const leadConsultant = lead ??
434
+ (leadEnabled
435
+ ? (input) => consultLead(input, {
436
+ runtime: agentRuntime,
437
+ command: effectiveHarness(),
438
+ model: effectivePlannerModel() || undefined,
439
+ })
440
+ : undefined);
441
+ const runs = new RunManager(db, agentRuntime, publishRun, `http://127.0.0.1:${port}`, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, root, retro, () => ({ harness: effectiveHarness(), model: effectiveDeveloperModel() }), leadConsultant);
442
+ /**
443
+ * The ticket's checkout, with its branch recorded on the row the first time.
444
+ * Every path that starts work goes through here: a branch that exists on disk
445
+ * but not on the card is a fact the drawer and the review cannot see.
446
+ */
447
+ async function checkoutFor(ticket) {
448
+ const worktree = await ensureWorktree(root, ticket.id, ticket.title, ticket.branch);
449
+ if (!ticket.branch)
450
+ db.setBranch(ticket.id, worktree.branch);
451
+ return worktree;
452
+ }
453
+ // A restart empties the run map, so any ticket that was mid-run comes back
454
+ // claiming `in_progress` with nothing behind it. A run the restart killed is
455
+ // started again as the next attempt in its own worktree; anything else quiet
456
+ // is adopted, because nobody is working on those cards and the board has to
457
+ // say so rather than leave them looking busy. This runs before the first
458
+ // client connects, and the worktree may have to be recreated on disk, so it
459
+ // completes on its own rather than holding up the server.
460
+ void runs.reconcileOrphans((ticketId) => {
461
+ const ticket = db.getTicket(ticketId);
462
+ return ticket ? checkoutFor(ticket) : ensureWorktree(root, ticketId);
463
+ });
464
+ // Observing a merge is not running anything: the card is in `review`, no
465
+ // process is alive, and the only question is whether GitHub finished the
466
+ // step the person owns. The watcher moves the card and retires the checkout
467
+ // and branch; it never merges, so `main` still only changes by a human's hand.
468
+ //
469
+ // A pull request that no longer merges is the one case the board repairs: it
470
+ // starts one run in the ticket's own worktree, which merges main and pushes.
471
+ // The card stays in Review, and the runner never merges the PR or rebases.
472
+ const mergeWatcher = new MergeWatcher({
473
+ db,
474
+ root,
475
+ ghCommand,
476
+ intervalMs: mergePollMs,
477
+ onMergeabilityChange: () => {
478
+ liveRev += 1;
479
+ onLiveChange?.();
480
+ },
481
+ isBusy: (ticketId) => runs.isRunning(ticketId),
482
+ resolveConflict: async (ticket, conflict) => {
483
+ // A repair is a run like any other: it waits for a slot rather than
484
+ // overfilling the board. `null` asks the watcher to try on a later pass.
485
+ if (runs.isRunning(ticket.id) || runs.runningCount() >= maxConcurrentRuns())
486
+ return null;
487
+ let worktree;
488
+ try {
489
+ worktree = await checkoutFor(ticket);
490
+ }
491
+ catch {
492
+ return null;
493
+ }
494
+ // Git took a moment; the person may have moved the card since.
495
+ const current = db.getTicket(ticket.id);
496
+ if (!current || current.state !== "review")
497
+ return null;
498
+ let status;
499
+ try {
500
+ status = runs.start(current, worktree, 1, {
501
+ prompt: buildConflictPrompt(current, {
502
+ branch: conflict.baseBranch,
503
+ baseRefOid: conflict.baseRefOid,
504
+ headRefOid: conflict.headRefOid,
505
+ }),
506
+ profile: "developer",
507
+ systemPrompt: CONFLICT_AGENT_PROMPT,
508
+ label: "Resolving a merge conflict",
509
+ // One attempt per main commit, and the card is not In Progress.
510
+ retry: false,
511
+ source: "conflict",
512
+ outsideStage: true,
513
+ });
514
+ }
515
+ catch {
516
+ return null;
517
+ }
518
+ if (status.phase !== "running")
519
+ return null;
520
+ return runs.whenSettled(current.id);
521
+ },
522
+ });
523
+ const mergeInFlight = new Set();
524
+ const issueInFlight = new Set();
525
+ if (mergePollMs !== 0)
526
+ mergeWatcher.start();
527
+ let scheduling = null;
528
+ let scheduleRequested = false;
529
+ /** The card the planner sees while filling a parked ticket's gaps. */
530
+ function draftOf(ticket) {
531
+ return {
532
+ id: ticket.id,
533
+ title: ticket.title,
534
+ goal: ticket.goal,
535
+ out_of_scope: ticket.out_of_scope,
536
+ acceptance: ticket.acceptance,
537
+ likely_files: [...ticket.likely_files],
538
+ context: [...(ticket.context ?? [])],
539
+ verify: [...ticket.verify],
540
+ rationale: "",
541
+ assumed: [],
542
+ decided: [],
543
+ ...(ticket.thinking ? { thinking: ticket.thinking } : {}),
544
+ };
545
+ }
546
+ function fieldsOf(value) {
547
+ if (!value)
548
+ return {};
549
+ return {
550
+ ...(typeof value.goal === "string" ? { goal: value.goal } : {}),
551
+ ...(typeof value.out_of_scope === "string" ? { out_of_scope: value.out_of_scope } : {}),
552
+ ...(typeof value.acceptance === "string" ? { acceptance: value.acceptance } : {}),
553
+ ...(Array.isArray(value.likely_files) ? { likely_files: value.likely_files } : {}),
554
+ ...(Array.isArray(value.context) ? { context: value.context } : {}),
555
+ // Only a non-empty list is carried. The prepare pass hands back a card that
556
+ // always has a verify array (an omitted one reads as []), so an empty one
557
+ // here means "not said", and a prepare pass must not wipe checks a person set.
558
+ ...(Array.isArray(value.verify) && value.verify.length > 0
559
+ ? { verify: normaliseVerify(value.verify) }
560
+ : {}),
561
+ };
562
+ }
563
+ /**
564
+ * A quick ticket may be confirmed with gaps. Nothing runs until a planner
565
+ * pass fills them; a failed pass leaves the ticket in Todo with the reason on
566
+ * it, so the next allocation pass can try again instead of losing the card.
567
+ */
568
+ async function runPrepare(ticket) {
569
+ const missing = checkSpec(ticket).missing;
570
+ try {
571
+ const filled = prepareOverride
572
+ ? await prepareOverride(ticket, missing)
573
+ : await (async () => {
574
+ const index = await ensureIndex(false);
575
+ const requested = missing.length
576
+ ? missing.join(", ")
577
+ : "anything the prepare pass finds uncheckable";
578
+ const prepared = await runPlan([
579
+ {
580
+ role: "user",
581
+ content: `(prepare) The ticket below was captured with Quick and is parked in Todo ` +
582
+ `until its spec is complete. Fill ${requested}. Keep the person's existing ` +
583
+ `wording and add only what is missing: an outcome in the goal, a real ` +
584
+ `exclusion in out_of_scope, checkable acceptance (including a failure case), ` +
585
+ `and likely files read from the repo. Return the complete card, same id.\n\n` +
586
+ `${ticket.title}\n${ticket.goal}\n${ticket.out_of_scope}\n` +
587
+ `${ticket.acceptance}\n${ticket.likely_files.join(", ")}\n` +
588
+ `${(ticket.context ?? []).join("\n")}`,
589
+ },
590
+ ], index ? renderBrief(index) : "", { reply: "", questions: [], cards: [draftOf(ticket)] }, db.listTickets().map((item) => ({
591
+ id: item.id,
592
+ title: item.title,
593
+ state: item.state,
594
+ })), undefined, null, "new-task");
595
+ return (prepared.cards.find((card) => card.id === ticket.id) ?? prepared.cards[0] ?? null);
596
+ })();
597
+ const next = db.updateSpec(ticket.id, fieldsOf(filled));
598
+ if (!next)
599
+ throw new Error(`no ticket ${ticket.id}`);
600
+ const check = checkSpec(next);
601
+ if (!check.ok) {
602
+ throw new Error(`spec is still incomplete: ${check.missing.join(", ")}`);
603
+ }
604
+ return next;
605
+ }
606
+ catch (cause) {
607
+ db.setPrepareError(ticket.id, describeError(cause));
608
+ return db.getTicket(ticket.id) ?? ticket;
609
+ }
610
+ }
611
+ async function fillSlots() {
612
+ // A parked quick ticket is not queued until its spec is checkable. This is
613
+ // also the retry: every allocation pass gives a failed prepare another go.
614
+ for (const ticket of db.listTickets()) {
615
+ if (ticket.state !== "todo" || !ticket.quick)
616
+ continue;
617
+ let current = ticket;
618
+ if (!checkSpec(current).ok) {
619
+ // oxlint-disable-next-line no-await-in-loop
620
+ current = await runPrepare(current);
621
+ }
622
+ if (current.state !== "todo" || !checkSpec(current).ok)
623
+ continue;
624
+ try {
625
+ // oxlint-disable-next-line no-await-in-loop
626
+ db.transition(current.id, "queued", { profile: current.profile ?? "developer" });
627
+ }
628
+ catch {
629
+ // A card the person moved in the meantime is not this pass's business.
630
+ }
631
+ }
632
+ const queued = db.listTickets().filter((ticket) => ticket.state === "queued");
633
+ for (const ticket of queued) {
634
+ if (runs.runningCount() >= maxConcurrentRuns())
635
+ return;
636
+ if (runs.isRunning(ticket.id))
637
+ continue;
638
+ try {
639
+ // Slots are filled in board order; parallel checkout creation would make
640
+ // the order depend on git timing instead.
641
+ // oxlint-disable-next-line no-await-in-loop
642
+ const worktree = await checkoutFor(ticket);
643
+ // Git may have taken a while; the person could have moved it since.
644
+ const current = db.getTicket(ticket.id);
645
+ if (!current || current.state !== "queued")
646
+ continue;
647
+ const started = db.transition(ticket.id, "in_progress");
648
+ runs.start(started, worktree);
649
+ }
650
+ catch {
651
+ // A ticket that cannot get a worktree stays queued rather than wearing
652
+ // a false in_progress badge. Try the next one, if there is one.
653
+ }
654
+ }
655
+ }
656
+ /**
657
+ * The PR's URL, as the ticket stores it. An agent that opened the PR outside
658
+ * the ticket worktree reports it in a done comment, so a board written before
659
+ * `pr_url` existed still has a readable answer in its timeline.
660
+ */
661
+ function latestPullRequestUrl(ticketId) {
662
+ const stored = db.getTicket(ticketId)?.pr_url;
663
+ if (stored)
664
+ return stored;
665
+ for (const comment of db.listComments(ticketId).toReversed()) {
666
+ if (comment.type !== "system" && comment.type !== "done")
667
+ continue;
668
+ const url = pullRequestUrlIn(comment.text);
669
+ if (url)
670
+ return url;
671
+ }
672
+ return null;
673
+ }
674
+ /**
675
+ * A PR URL is a fact whether the manager observed it or a person typed it.
676
+ * Recording it on the ticket is what the drawer and the reviewer read.
677
+ */
678
+ function notePullRequest(ticketId, text) {
679
+ const url = pullRequestUrlIn(text);
680
+ if (url)
681
+ db.setPullRequest(ticketId, url);
682
+ }
683
+ /**
684
+ * A person mentioning an agent is a request for a second pass in the same
685
+ * worktree. A reviewer stays in Review and only writes a comment; a developer
686
+ * or tester is a send-back, so the card moves to In Progress while it works.
687
+ */
688
+ async function startMentionRun(ticket, comment) {
689
+ const [name] = mentionedProfiles(comment.text);
690
+ if (!name)
691
+ return;
692
+ const profile = profileFor(name);
693
+ const note = (text) => db.addComment({ ticket_id: ticket.id, type: "system", author: "zelio", text });
694
+ if (!hasMentionInstruction(comment.text)) {
695
+ note(`@${name} was mentioned, but there is no question or instruction to act on. Add one to start a run.`);
696
+ return;
697
+ }
698
+ if (runs.isRunning(ticket.id)) {
699
+ const delivered = await runs.sendMessage(ticket.id, profile.name, `${comment.text}\n\nReply in the shared thread using zelio ticket comment "$ZELIO_TICKET_ID" --type comment --reply-to "${comment.id}" --text "...". This is an intermediate update; keep working and do not change ticket status just because you replied.`, comment.id);
700
+ if (delivered) {
701
+ note(`Mention delivered to @${name}; awaiting response. The agent continues its current task.`);
702
+ }
703
+ else {
704
+ note(`@${name} cannot receive messages during this run. Your comment is saved; mention @${name} again after the current run finishes.`);
705
+ }
706
+ return;
707
+ }
708
+ if (runs.runningCount() >= maxConcurrentRuns()) {
709
+ note(`All agent slots are busy; @${name} has not started yet.`);
710
+ return;
711
+ }
712
+ if (profile.name === "reviewer" && ticket.state !== "review") {
713
+ note(`@${name} reviews only tickets in Review; this ticket is ${ticket.state}.`);
714
+ return;
715
+ }
716
+ if (ticket.state !== "review" && ticket.state !== "blocked" && ticket.state !== "in_progress") {
717
+ note(`Mention runs start from Review, Blocked, or In Progress; this ticket is ${ticket.state}. The comment is saved for its next run.`);
718
+ return;
719
+ }
720
+ let worktree;
721
+ try {
722
+ worktree = await checkoutFor(ticket);
723
+ }
724
+ catch (cause) {
725
+ note(`@${name} could not start: ${cause instanceof Error ? cause.message : "the worktree could not be prepared"}`);
726
+ return;
727
+ }
728
+ const reviewer = profile.name === "reviewer";
729
+ const job = {
730
+ prompt: reviewer
731
+ ? buildReviewPrompt(ticket, comment, latestPullRequestUrl(ticket.id), absoluteAttachments(root, ticket.attachments))
732
+ : buildCommentPrompt(ticket, comment, absoluteAttachments(root, ticket.attachments)),
733
+ profile: profile.name,
734
+ // A verified ticket's developer never commits or reports Review: the board
735
+ // checks and publishes, so its comment runs get the verified doctrine.
736
+ systemPrompt: reviewer
737
+ ? REVIEW_AGENT_PROMPT
738
+ : (ticket.verify ?? []).length > 0
739
+ ? VERIFIED_CODING_AGENT_PROMPT
740
+ : COMMENT_AGENT_PROMPT,
741
+ // The reviewer reads the Review column's standing instructions; a comment
742
+ // run by the developer stays on In Progress, where the ticket is worked.
743
+ ...(reviewer ? { stage: "review" } : {}),
744
+ label: reviewer ? "Reviewing the diff" : "Working on your comment",
745
+ retry: !reviewer,
746
+ source: "comment",
747
+ sourceCommentId: comment.id,
748
+ };
749
+ let status;
750
+ try {
751
+ status = runs.start(ticket, worktree, 1, job);
752
+ }
753
+ catch (cause) {
754
+ note(`@${name} could not start: ${cause instanceof Error ? cause.message : "the run was refused"}`);
755
+ return;
756
+ }
757
+ if (status.phase !== "running") {
758
+ note(`@${name} could not start: ${status.error ?? "the run failed"}`);
759
+ return;
760
+ }
761
+ // A review comment is a read: the card stays in Review while the reviewer
762
+ // looks. A developer mention is a send-back, so the card becomes truthful
763
+ // as soon as the run exists.
764
+ if (!reviewer && ticket.state !== "in_progress") {
765
+ try {
766
+ db.transition(ticket.id, "in_progress");
767
+ }
768
+ catch (cause) {
769
+ runs.cancel(ticket.id);
770
+ note(`@${name} started but the ticket could not move: ${cause instanceof Error ? cause.message : "the transition was refused"}`);
771
+ }
772
+ }
773
+ }
774
+ /**
775
+ * One allocator, so two confirms arriving together cannot both see a free
776
+ * slot and start three agents. A request that lands mid-pass asks for one
777
+ * more pass instead of running beside it.
778
+ */
779
+ function scheduleTickets() {
780
+ if (scheduling) {
781
+ scheduleRequested = true;
782
+ return scheduling;
783
+ }
784
+ scheduling = (async () => {
785
+ do {
786
+ scheduleRequested = false;
787
+ // oxlint-disable-next-line no-await-in-loop
788
+ await fillSlots();
789
+ } while (scheduleRequested);
790
+ })().finally(() => {
791
+ scheduling = null;
792
+ });
793
+ return scheduling;
794
+ }
795
+ const runPlan = plan ??
796
+ ((messages, brief, draft, board, onStatus, handoff, mode, onStats, attachments = [], images = [], thinking, findings, timeoutMs, linked) => runOrchestrator({
797
+ repoRoot: root,
798
+ messages,
799
+ brief,
800
+ plan: draft,
801
+ board,
802
+ handoff,
803
+ // The door changes the directive. Dropping it here silently gave every
804
+ // real turn the chat prompt while tests saw the new-task one.
805
+ mode,
806
+ attachments,
807
+ images,
808
+ command: effectiveHarness(),
809
+ planner: createPlanner(effectiveHarness(), effectivePlannerModel()),
810
+ model: effectivePlannerModel() || undefined,
811
+ thinking: thinking ?? plannerThinkingForTurn(),
812
+ budget: plannerToolBudget,
813
+ // The planner and the run it writes for must agree on what "done" means;
814
+ // otherwise every ticket it drafts asks for a check the run will skip.
815
+ workflow: db.getStageWorkflow("in_progress"),
816
+ onStatus,
817
+ onStats,
818
+ research: findings,
819
+ timeoutMs,
820
+ linkedBoards: linked,
821
+ }));
822
+ // A test that injected the planner explicitly asked for no subprocess. Only
823
+ // an explicitly named harness (or a summary injection) opts back in.
824
+ const harnessNamed = harness !== undefined || process.env.ZELIO_HARNESS !== undefined;
825
+ const runSummary = summarize ??
826
+ (plan && !harnessNamed
827
+ ? async () => {
828
+ throw new OrchestratorError("harness", "no summary harness in this test");
829
+ }
830
+ : (request) => summarizeConversation({
831
+ repoRoot: root,
832
+ messages: request.messages,
833
+ plan: request.plan,
834
+ board: request.board,
835
+ priorSummary: request.priorSummary,
836
+ command: effectiveHarness(),
837
+ planner: createPlanner(effectiveHarness(), effectivePlannerModel()),
838
+ model: effectivePlannerModel() || undefined,
839
+ timeoutMs: summaryTimeoutMs,
840
+ thinking: plannerThinkingForTurn(),
841
+ onStatus: request.onStatus,
842
+ }));
843
+ /**
844
+ * The repo map, cached against `git HEAD`. Built once at startup, rebuilt
845
+ * when the commit changes, and never allowed to fail a plan: a stale map is
846
+ * better than a refused message.
847
+ */
848
+ let indexing = null;
849
+ /**
850
+ * `onBuild` fires only when the map is really being built — not when the
851
+ * cached one is current — so a caller can say so without guessing. It also
852
+ * fires when this call joins a build already in flight, because from the
853
+ * person's side the wait is the same one.
854
+ */
855
+ function ensureIndex(force = false, onBuild) {
856
+ if (indexing) {
857
+ onBuild?.();
858
+ return indexing;
859
+ }
860
+ indexing = (async () => {
861
+ try {
862
+ if (indexOverride) {
863
+ onBuild?.();
864
+ const built = await indexOverride();
865
+ db.saveRepoIndex(built);
866
+ return built;
867
+ }
868
+ const stored = db.getRepoIndex();
869
+ const head = await readHead(root);
870
+ if (!force && stored && stored.head === head)
871
+ return stored;
872
+ onBuild?.();
873
+ const built = await buildIndex(root);
874
+ db.saveRepoIndex(built);
875
+ return built;
876
+ }
877
+ catch {
878
+ return db.getRepoIndex();
879
+ }
880
+ finally {
881
+ indexing = null;
882
+ }
883
+ })();
884
+ return indexing;
885
+ }
886
+ if (indexOnStart)
887
+ void ensureIndex();
888
+ // The name is separate from the index: the pill can say which repo it is
889
+ // before (or without) a map being built. Asked once, then remembered.
890
+ let repoName = null;
891
+ const ensureRepoName = () => (repoName ??= readRepoName(root));
892
+ const repoStatus = async () => {
893
+ const stored = db.getRepoIndex();
894
+ return {
895
+ name: stored?.name ?? (await ensureRepoName()),
896
+ indexing: indexing !== null,
897
+ index: stored
898
+ ? {
899
+ head: stored.head,
900
+ indexed_at: stored.indexed_at,
901
+ file_count: stored.file_count,
902
+ duration_ms: stored.duration_ms,
903
+ }
904
+ : null,
905
+ };
906
+ };
907
+ app.onError((error, c) => {
908
+ if (error instanceof AttachmentError)
909
+ return c.json({ error: error.message }, 400);
910
+ if (error instanceof TransitionError) {
911
+ return c.json({ error: error.message, from: error.from, to: error.to }, 409);
912
+ }
913
+ if (error instanceof OrchestratorError) {
914
+ const status = error.kind === "timeout" ? 504 : 502;
915
+ return c.json({ error: error.message, kind: error.kind }, status);
916
+ }
917
+ if (error instanceof WorktreeError) {
918
+ return c.json({ error: error.message, kind: error.kind }, 409);
919
+ }
920
+ if (error instanceof RunAlreadyActiveError) {
921
+ return c.json({ error: error.message }, 409);
922
+ }
923
+ if (error instanceof VoiceError) {
924
+ const status = error.kind === "unavailable" ? 503 : error.kind === "timeout" ? 504 : 502;
925
+ return c.json({ error: error.message, kind: error.kind }, status);
926
+ }
927
+ return c.json({ error: error.message }, 500);
928
+ });
929
+ app.get("/api/health", (c) => c.json({ ok: true, columns: BOARD_COLUMNS }));
930
+ /**
931
+ * Board-scoped settings. They are read by the server on every allocation and
932
+ * planner turn, so a save takes effect without a restart.
933
+ */
934
+ app.get("/api/settings", (c) => c.json({ settings: db.getBoardSettings() }));
935
+ const setupResponse = () => ({
936
+ ...setupStore.read(),
937
+ effectiveHarness: effectiveHarness(),
938
+ effectiveDeveloperModel: effectiveDeveloperModel(),
939
+ });
940
+ app.get("/api/setup", (c) => c.json({ setup: setupResponse() }));
941
+ app.put("/api/setup", async (c) => {
942
+ const body = await c.req
943
+ .json()
944
+ .catch(() => ({}));
945
+ const legacy = typeof body.model === "string" ? body.model.trim() : undefined;
946
+ const plannerModel = typeof body.plannerModel === "string" ? body.plannerModel.trim() : legacy;
947
+ const developerModel = typeof body.developerModel === "string" ? body.developerModel.trim() : legacy;
948
+ if (plannerModel === undefined || developerModel === undefined) {
949
+ return c.json({ error: "plannerModel and developerModel must be strings" }, 400);
950
+ }
951
+ if (plannerModel.length > 200 || developerModel.length > 200) {
952
+ return c.json({ error: "model is too long" }, 400);
953
+ }
954
+ db.clearProfileRuntimeOverrides();
955
+ setupStore.save({
956
+ ...(legacy === undefined ? {} : { model: legacy }),
957
+ plannerModel,
958
+ developerModel,
959
+ modelChosen: true,
960
+ });
961
+ return c.json({ setup: setupResponse() });
962
+ });
963
+ app.put("/api/settings", async (c) => {
964
+ const body = await c.req
965
+ .json()
966
+ .catch(() => ({}));
967
+ const patch = {};
968
+ if (body.maxAgents !== undefined) {
969
+ const maxAgents = asMaxAgents(body.maxAgents);
970
+ if (maxAgents === null)
971
+ return c.json({ error: "maxAgents must be 2 through 6" }, 400);
972
+ patch.maxAgents = maxAgents;
973
+ }
974
+ if (body.plannerThinking !== undefined) {
975
+ const chosen = asPlannerThinking(body.plannerThinking);
976
+ if (!chosen)
977
+ return c.json({ error: "unknown thinking level" }, 400);
978
+ patch.plannerThinking = chosen;
979
+ }
980
+ if (Object.keys(patch).length === 0)
981
+ return c.json({ error: "nothing to save" }, 400);
982
+ const settings = db.setBoardSettings(patch);
983
+ // Raising the cap should start queued work now, not at the next unrelated
984
+ // event. Lowering it never kills a run; it only stops new ones.
985
+ if (patch.maxAgents !== undefined)
986
+ void scheduleTickets();
987
+ return c.json({ settings });
988
+ });
989
+ /**
990
+ * The agent's own door to the board. It is authenticated by a per-run ticket
991
+ * token, not the server token, so a process can move only its own ticket and
992
+ * only to a state it is allowed to claim. Status is never inferred from
993
+ * stdout; this request is the status.
994
+ */
995
+ app.post("/api/tickets/:id/report", async (c) => {
996
+ const id = c.req.param("id");
997
+ if (!runs.verifyStatusToken(id, c.req.header("x-zelio-ticket-token") ?? "")) {
998
+ return c.json({ error: "invalid ticket token" }, 401);
999
+ }
1000
+ const parsed = normaliseRunResult(await c.req.json().catch(() => null));
1001
+ if (!parsed.ok)
1002
+ return c.json({ error: parsed.error }, 400);
1003
+ const result = await runs.reportResult(id, parsed.report);
1004
+ if (!result.ok)
1005
+ return c.json({ error: result.error }, 409);
1006
+ notePullRequest(id, parsed.report.summary);
1007
+ // The lead now reads the blocker; the run ends with the report as its outcome.
1008
+ if (result.escalated)
1009
+ return c.json({ accepted: true, state: "blocked", escalated: true, ticket: result.ticket });
1010
+ return c.json({ accepted: true, state: result.ticket.state, ticket: result.ticket });
1011
+ });
1012
+ app.post("/api/tickets/:id/status", async (c) => {
1013
+ const id = c.req.param("id");
1014
+ const ticketToken = c.req.header("x-zelio-ticket-token") ?? "";
1015
+ if (!runs.verifyStatusToken(id, ticketToken)) {
1016
+ return c.json({ error: "invalid ticket token" }, 401);
1017
+ }
1018
+ const body = await c.req
1019
+ .json()
1020
+ .catch(() => ({}));
1021
+ const to = body.to;
1022
+ if (to !== "review" && to !== "blocked") {
1023
+ return c.json({
1024
+ error: "status must be review or blocked. Starting a run already establishes In Progress; no progress/keepalive update is needed. Use report_result to report completion or a genuine blocker. Done belongs to human review.",
1025
+ code: "invalid_status_target",
1026
+ allowed: ["review", "blocked"],
1027
+ current_state: db.getTicket(id)?.state ?? null,
1028
+ }, 400);
1029
+ }
1030
+ const reason = typeof body.reason === "string" ? body.reason.trim() : "";
1031
+ const unblock = typeof body.unblock === "string" ? body.unblock.trim() : "";
1032
+ if (to === "blocked" && !reason) {
1033
+ return c.json({ error: "a blocked ticket needs a reason" }, 400);
1034
+ }
1035
+ const ticket = db.getTicket(id);
1036
+ if (!ticket)
1037
+ return c.json({ error: "no such ticket" }, 404);
1038
+ if (ticket.state !== "in_progress") {
1039
+ return c.json({ error: `ticket is ${ticket.state}` }, 409);
1040
+ }
1041
+ if (to === "review" && (ticket.verify ?? []).length > 0) {
1042
+ return c.json({
1043
+ 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.",
1044
+ code: "verified_by_board",
1045
+ }, 409);
1046
+ }
1047
+ if (to === "review") {
1048
+ const startedAt = runs.runStartedAt(id) ?? Date.now();
1049
+ const runComments = db
1050
+ .listComments(id)
1051
+ .filter((comment) => Date.parse(comment.created_at) >= startedAt);
1052
+ const evidence = reviewEvidence(runComments, runs.reviewVerification(id));
1053
+ if (!evidence.ok) {
1054
+ return c.json({ error: evidence.note ?? "review needs evidence" }, 409);
1055
+ }
1056
+ }
1057
+ const next = db.transition(id, to, {
1058
+ blocker_kind: to === "blocked" ? "decision" : null,
1059
+ blocker_reason: to === "blocked" ? reason : null,
1060
+ blocker_unblock: to === "blocked" && unblock ? unblock : null,
1061
+ });
1062
+ // The agent has said what happened, so the process can stop. The ticket is
1063
+ // already in its new state; this is not a user cancellation.
1064
+ runs.settle(id);
1065
+ return c.json({ ticket: next });
1066
+ });
1067
+ /**
1068
+ * Explicit verification for the active run. A command passing is distinct
1069
+ * from the agent confirming that required behavioral acceptance was checked.
1070
+ * This records evidence only; status still moves through the status endpoint.
1071
+ */
1072
+ app.post("/api/tickets/:id/verification", async (c) => {
1073
+ const id = c.req.param("id");
1074
+ const ticketToken = c.req.header("x-zelio-ticket-token") ?? "";
1075
+ if (!runs.verifyStatusToken(id, ticketToken)) {
1076
+ return c.json({ error: "invalid ticket token" }, 401);
1077
+ }
1078
+ const body = await c.req
1079
+ .json()
1080
+ .catch(() => ({}));
1081
+ const command = typeof body.command === "string" ? body.command.trim() : "";
1082
+ const outcomes = ["passed", "failed", "skipped", "not_run"];
1083
+ const acceptance = ["verified", "unverified"];
1084
+ if (!command)
1085
+ return c.json({ error: "command is required" }, 400);
1086
+ if (!outcomes.includes(String(body.outcome))) {
1087
+ return c.json({ error: "outcome must be passed, failed, skipped or not_run" }, 400);
1088
+ }
1089
+ if (!acceptance.includes(String(body.acceptance))) {
1090
+ return c.json({ error: "acceptance must be verified or unverified" }, 400);
1091
+ }
1092
+ const recorded = runs.recordVerification(id, {
1093
+ command,
1094
+ outcome: body.outcome,
1095
+ acceptance: body.acceptance,
1096
+ });
1097
+ if (!recorded) {
1098
+ return c.json({
1099
+ error: "no completed successful command matching this verification was observed in the current run",
1100
+ }, 409);
1101
+ }
1102
+ return c.json({ recorded: true });
1103
+ });
1104
+ /**
1105
+ * Typed events from the agent working the ticket. Same per-run token as the
1106
+ * status endpoint, so a process can only write to its own card.
1107
+ */
1108
+ app.post("/api/tickets/:id/agent-comments", async (c) => {
1109
+ const id = c.req.param("id");
1110
+ const ticketToken = c.req.header("x-zelio-ticket-token") ?? "";
1111
+ if (!runs.verifyStatusToken(id, ticketToken)) {
1112
+ return c.json({ error: "invalid ticket token" }, 401);
1113
+ }
1114
+ const body = await c.req
1115
+ .json()
1116
+ .catch(() => ({}));
1117
+ const type = body.type;
1118
+ const text = typeof body.text === "string" ? body.text.trim() : "";
1119
+ if (type !== "comment" &&
1120
+ type !== "decision" &&
1121
+ type !== "blocker" &&
1122
+ type !== "done" &&
1123
+ type !== "review") {
1124
+ return c.json({ error: "type must be comment, decision, blocker, done or review" }, 400);
1125
+ }
1126
+ const replyTo = typeof body.reply_to === "string" ? body.reply_to : null;
1127
+ if (replyTo && !db.listComments(id).some((candidate) => candidate.id === replyTo)) {
1128
+ return c.json({ error: "reply_to must identify a comment on this ticket" }, 400);
1129
+ }
1130
+ if (!text)
1131
+ return c.json({ error: "text is required" }, 400);
1132
+ const blockerKind = body.blocker_kind === "needs_human" ? "needs_human" : "decision";
1133
+ if (type !== "blocker" && body.blocker_kind !== undefined) {
1134
+ return c.json({ error: "only a blocker comment carries a kind" }, 400);
1135
+ }
1136
+ const ticket = db.getTicket(id);
1137
+ if (!ticket)
1138
+ return c.json({ error: "no such ticket" }, 404);
1139
+ const identity = runs.activeIdentity(id);
1140
+ if (!identity)
1141
+ return c.json({ error: "the run has finished" }, 409);
1142
+ const comment = db.addComment({
1143
+ ticket_id: id,
1144
+ type,
1145
+ text,
1146
+ author: identity.profile,
1147
+ blocker_kind: type === "blocker" ? blockerKind : null,
1148
+ reply_to: replyTo,
1149
+ run_id: identity.runId,
1150
+ });
1151
+ notePullRequest(id, text);
1152
+ return c.json({ comment }, 201);
1153
+ });
1154
+ app.use("/api/*", auth, idempotency);
1155
+ /**
1156
+ * Who the caller is and what it may do. The phone uses this to hide controls
1157
+ * the tunnel allowlist would refuse anyway; the server stays the authority.
1158
+ */
1159
+ app.get("/api/me", (c) => {
1160
+ const principal = c.get("principal");
1161
+ return c.json({
1162
+ principal: principal.kind === "tunnel"
1163
+ ? { kind: "tunnel", boardId: principal.boardId }
1164
+ : { kind: "local" },
1165
+ capabilities: capabilitiesFor(principal),
1166
+ build,
1167
+ });
1168
+ });
1169
+ /** Version skew: the phone compares this with the build in the tunnel hello. */
1170
+ app.get("/api/version", (c) => c.json({ version: "1", protocol: 1, build }, 200, { "Cache-Control": "no-store" }));
1171
+ /**
1172
+ * The whole board in one read. `rev` is the persisted board revision; the
1173
+ * ETag adds the in-memory live counter so a turn or run status change also
1174
+ * invalidates a cached snapshot. A matching If-None-Match is a 304 with no
1175
+ * ticket content, which is what makes the tick-then-refetch path cheap.
1176
+ */
1177
+ app.get("/api/snapshot", (c) => {
1178
+ const rev = db.revision();
1179
+ const etag = `"${rev}-${liveRev}"`;
1180
+ if (c.req.header("if-none-match") === etag) {
1181
+ return c.body(null, 304, { ETag: etag, "Cache-Control": "no-store" });
1182
+ }
1183
+ const commentCounts = db.ticketCommentCounts();
1184
+ return c.json({
1185
+ rev,
1186
+ tickets: db.listTickets().map((ticket) => ({
1187
+ ...ticket,
1188
+ comment_count: commentCounts[ticket.id] ?? 0,
1189
+ ...(ticket.state === "review" && ticket.pr_url
1190
+ ? { mergeability: mergeWatcher.getMergeability(ticket.id) }
1191
+ : {}),
1192
+ })),
1193
+ // Off the board, but still readable: ⌘K searches these and opens one
1194
+ // in the same read-only drawer.
1195
+ archived: db.listArchivedTickets(),
1196
+ runs: db.latestAgentRuns(),
1197
+ // The card chip shows a ticket's whole spend, not only its latest run's.
1198
+ costs: db.ticketCostTotals(),
1199
+ turnStatus,
1200
+ runStatuses: runs.listStatuses(),
1201
+ serverTime: new Date().toISOString(),
1202
+ }, 200, { ETag: etag, "Cache-Control": "no-store" });
1203
+ });
1204
+ /**
1205
+ * The phone's read-only surface. Deliberately narrower than `/api/tickets`:
1206
+ * the board list and one ticket's comments, with no agent run record and no
1207
+ * diff. The Mac relay client only forwards these two paths.
1208
+ */
1209
+ app.get("/api/mobile/board", (c) => c.json({ tickets: db.listTickets() }));
1210
+ app.get("/api/mobile/tickets/:id", (c) => {
1211
+ const ticket = db.getTicket(c.req.param("id"));
1212
+ if (!ticket)
1213
+ return c.json({ error: "no such ticket" }, 404);
1214
+ return c.json({ ticket, comments: db.listComments(ticket.id) });
1215
+ });
1216
+ /**
1217
+ * The board's Pair phone dialog. The tunnel is the only thing that can register
1218
+ * a one-time code with the DO, so this route asks it for a fresh link and
1219
+ * renders the QR. Nothing long-lived is minted here, and the code expires.
1220
+ */
1221
+ app.post("/api/cloud/pair", async (c) => {
1222
+ const link = phone?.pair() ?? null;
1223
+ if (!link) {
1224
+ return c.json({
1225
+ error: "The phone tunnel is not connected yet. Keep zelio running, signed in, and try again.",
1226
+ code: "tunnel_offline",
1227
+ }, 409);
1228
+ }
1229
+ const qr = await QRCode.toDataURL(link.url, { margin: 1, width: 320 });
1230
+ return c.json({ ...link, qr });
1231
+ });
1232
+ app.get("/api/profiles", (c) => c.json({ profiles: db.listProfiles() }));
1233
+ /**
1234
+ * The editable half of a profile. Permissions (whether it touches the repo and
1235
+ * shares the writer cap) are deliberately not in this body: changing what an
1236
+ * agent may do is a code decision, not a form field.
1237
+ */
1238
+ app.put("/api/profiles/:name", async (c) => {
1239
+ const name = c.req.param("name");
1240
+ if (!db.getProfile(name))
1241
+ return c.json({ error: "no such profile" }, 404);
1242
+ const body = await c.req
1243
+ .json()
1244
+ .catch(() => ({}));
1245
+ const patch = {};
1246
+ for (const field of ["model", "harness", "extraPrompt"]) {
1247
+ if (body[field] === undefined)
1248
+ continue;
1249
+ if (typeof body[field] !== "string") {
1250
+ return c.json({ error: `${field} must be a string` }, 400);
1251
+ }
1252
+ patch[field] = body[field];
1253
+ }
1254
+ if (body.thinking !== undefined) {
1255
+ const level = typeof body.thinking === "string" ? parseThinkingLevel(body.thinking) : undefined;
1256
+ if (!level) {
1257
+ return c.json({ error: `thinking must be one of ${THINKING_LEVELS.join(", ")}` }, 400);
1258
+ }
1259
+ patch.thinking = level;
1260
+ }
1261
+ return c.json({ profile: db.updateProfile(name, patch) });
1262
+ });
1263
+ /** Back to the seed rows. The only way an edited profile forgets its edits. */
1264
+ app.post("/api/profiles/reset", (c) => c.json({ profiles: db.resetProfiles() }));
1265
+ /**
1266
+ * What a harness says it can run. Discovery is a suggestion for the model
1267
+ * field, never a gate: a harness that is missing, slow or broken returns an
1268
+ * error payload and the page keeps its free-text field.
1269
+ */
1270
+ app.get("/api/agent-models", async (c) => {
1271
+ const command = asText(c.req.query("harness")) || effectiveHarness();
1272
+ const result = await (listModels ?? ((value) => listHarnessModels(value, { listCodex: listCodexModels })))(command);
1273
+ return c.json({ harness: command, models: result.models, error: result.error });
1274
+ });
1275
+ /**
1276
+ * Standing instructions per stage. This is config, not board state: the
1277
+ * person writes it once and every run started from that stage receives it.
1278
+ * It is read when a run starts and never copied onto the ticket.
1279
+ */
1280
+ app.get("/api/workflows", (c) => {
1281
+ const workflows = Object.fromEntries(Object.keys(WORKFLOW_STAGES).map((stage) => [
1282
+ stage,
1283
+ db.getStageWorkflow(stage),
1284
+ ]));
1285
+ return c.json({ workflows });
1286
+ });
1287
+ /**
1288
+ * Pending manager proposals. They are evidence beside the workflow, never the
1289
+ * workflow itself: the person applies one or refuses it, and either way the
1290
+ * row keeps what was proposed.
1291
+ */
1292
+ app.get("/api/workflows/suggestions", (c) => {
1293
+ const stage = c.req.query("stage") ?? "in_progress";
1294
+ if (!isWorkflowStage(stage))
1295
+ return c.json({ error: `no such stage: ${stage}` }, 400);
1296
+ return c.json({ suggestions: db.listWorkflowSuggestions(stage) });
1297
+ });
1298
+ app.post("/api/workflows/suggestions/:id/apply", (c) => {
1299
+ const applied = db.applyWorkflowSuggestion(c.req.param("id"));
1300
+ if (!applied)
1301
+ return c.json({ error: "no such pending suggestion" }, 404);
1302
+ return c.json(applied);
1303
+ });
1304
+ app.post("/api/workflows/suggestions/:id/dismiss", (c) => {
1305
+ const dismissed = db.dismissWorkflowSuggestion(c.req.param("id"));
1306
+ if (!dismissed)
1307
+ return c.json({ error: "no such pending suggestion" }, 404);
1308
+ return c.json({ suggestion: dismissed });
1309
+ });
1310
+ app.put("/api/workflows/:stage", async (c) => {
1311
+ const stage = c.req.param("stage");
1312
+ if (!isWorkflowStage(stage))
1313
+ return c.json({ error: `no such stage: ${stage}` }, 400);
1314
+ const body = await c.req
1315
+ .json()
1316
+ .catch(() => ({}));
1317
+ const parsed = normaliseWorkflow(body.workflow);
1318
+ if (!parsed.ok)
1319
+ return c.json({ error: parsed.error }, 400);
1320
+ return c.json({ workflow: db.setStageWorkflow(stage, parsed.workflow) });
1321
+ });
1322
+ /**
1323
+ * A person's comment. Mentions are resolved here, not in the browser, so a
1324
+ * comment is still a durable instruction even if the tab closes before the
1325
+ * agent starts.
1326
+ */
1327
+ app.post("/api/tickets/:id/comments", async (c) => {
1328
+ const id = c.req.param("id");
1329
+ const ticket = db.getTicket(id);
1330
+ if (!ticket)
1331
+ return c.json({ error: "no such ticket" }, 404);
1332
+ const body = await c.req.json().catch(() => ({}));
1333
+ const text = asText(body.text);
1334
+ if (!text)
1335
+ return c.json({ error: "text is required" }, 400);
1336
+ if (text.length > MAX_MESSAGE_CHARS) {
1337
+ return c.json({ error: `text is limited to ${MAX_MESSAGE_CHARS} characters` }, 400);
1338
+ }
1339
+ const comment = db.addComment({
1340
+ ticket_id: id,
1341
+ type: "comment",
1342
+ author: "user",
1343
+ text,
1344
+ });
1345
+ notePullRequest(id, text);
1346
+ await startMentionRun(ticket, comment);
1347
+ return c.json({ comment }, 201);
1348
+ });
1349
+ /**
1350
+ * What recent planner turns cost. This is a diagnostic surface, not a board
1351
+ * one: it reads the log and changes nothing. Percentiles, because the p90 is
1352
+ * the number a person actually feels — the average hides the turn that hit a
1353
+ * cold map after a week away.
1354
+ */
1355
+ app.get("/api/metrics", (c) => {
1356
+ const limit = Math.min(500, Math.max(1, Number(c.req.query("limit") ?? 200) || 200));
1357
+ const turns = db.listPlannerTurns(limit);
1358
+ const forDoor = (kind) => turns.filter((turn) => turn.kind === kind);
1359
+ return c.json({
1360
+ all: summariseTurns(turns),
1361
+ panel: summariseTurns(forDoor("panel")),
1362
+ task: summariseTurns(forDoor("task")),
1363
+ newTask: summariseTurns(newTaskTurns(turns)),
1364
+ // The two aggregates on Insights that are read from runs rather than
1365
+ // turns. Existing fields keep their shape; these are additions.
1366
+ tokens: db.tokenTotals(),
1367
+ cost: db.costTotal(),
1368
+ recent: turns.slice(0, 20),
1369
+ });
1370
+ });
1371
+ app.get("/api/tickets", (c) => c.json({ tickets: db.listTickets() }));
1372
+ /**
1373
+ * What each card's latest run did, in one read. The board renders every
1374
+ * column from this, so a card can say how long its last run took and what it
1375
+ * cost without anyone opening its timeline first.
1376
+ */
1377
+ app.get("/api/runs/latest", (c) => c.json({ runs: db.latestAgentRuns(), costs: db.ticketCostTotals() }));
1378
+ app.get("/api/tickets/:id", (c) => {
1379
+ const ticket = db.getTicket(c.req.param("id"));
1380
+ if (!ticket)
1381
+ return c.json({ error: "no such ticket" }, 404);
1382
+ return c.json({
1383
+ ticket,
1384
+ comments: db.listComments(ticket.id),
1385
+ run: db.latestAgentRun(ticket.id),
1386
+ });
1387
+ });
1388
+ /** Stop a live run and wait for its process before touching its worktree. */
1389
+ async function stopRun(ticketId, mode) {
1390
+ if (!runs.isRunning(ticketId))
1391
+ return;
1392
+ const settled = runs.whenSettled(ticketId);
1393
+ if (mode === "settle")
1394
+ runs.settle(ticketId);
1395
+ else
1396
+ runs.cancel(ticketId);
1397
+ await settled;
1398
+ }
1399
+ /**
1400
+ * A person's own way off the board. The card, its comments and its runs go
1401
+ * in one step, and the ticket's checkout and branch go with them: a row nobody
1402
+ * can open must not keep a claim on disk or on origin. A cancelled ticket is
1403
+ * the ending that keeps its checkout.
1404
+ */
1405
+ app.delete("/api/tickets/:id", async (c) => {
1406
+ const id = c.req.param("id");
1407
+ const ticket = db.getTicket(id);
1408
+ if (!ticket)
1409
+ return c.json({ error: "no such ticket" }, 404);
1410
+ await stopRun(id, "cancel");
1411
+ const removed = db.deleteTicket(id);
1412
+ if (!removed)
1413
+ return c.json({ error: "no such ticket" }, 404);
1414
+ await retireWorktree(root, removed.id, removed.branch);
1415
+ return c.json({ ticket: removed });
1416
+ });
1417
+ app.get("/api/tickets/:id/diff", (c) => {
1418
+ const ticket = db.getTicket(c.req.param("id"));
1419
+ if (!ticket)
1420
+ return c.json({ error: "no such ticket" }, 404);
1421
+ const run = db.latestAgentRunWithDiff(ticket.id);
1422
+ return c.json(parseUnifiedDiff(run?.git_diff));
1423
+ });
1424
+ /** The local polling fallback: a board revision, never ticket content. */
1425
+ app.get("/api/rev", (c) => c.json({ rev: db.revision(), live: liveRev }, 200, { "Cache-Control": "no-store" }));
1426
+ /**
1427
+ * Content-free ticks. A ticket write and a live status change both bump a
1428
+ * counter; the page responds by refetching /api/snapshot with its ETag. No
1429
+ * ticket text, comment text or tool output rides this stream.
1430
+ */
1431
+ app.get("/api/ticks", (c) => streamSSE(c, async (stream) => {
1432
+ let closed = false;
1433
+ const write = () => {
1434
+ if (closed)
1435
+ return;
1436
+ void stream.writeSSE({
1437
+ event: "tick",
1438
+ data: JSON.stringify({ rev: db.revision(), live: liveRev }),
1439
+ });
1440
+ };
1441
+ const unsubscribe = db.onChange(write);
1442
+ turnWatchers.add(write);
1443
+ runWatchers.add(write);
1444
+ stream.onAbort(() => {
1445
+ closed = true;
1446
+ unsubscribe();
1447
+ turnWatchers.delete(write);
1448
+ runWatchers.delete(write);
1449
+ });
1450
+ await stream.writeSSE({
1451
+ event: "hello",
1452
+ data: JSON.stringify({ rev: db.revision(), live: liveRev }),
1453
+ });
1454
+ // Keep the connection open; stream.onAbort is what ends it. The heartbeat
1455
+ // carries no data, which is the point.
1456
+ for (;;) {
1457
+ // oxlint-disable-next-line no-await-in-loop
1458
+ await stream.sleep(15_000);
1459
+ if (closed)
1460
+ return;
1461
+ // oxlint-disable-next-line no-await-in-loop
1462
+ await stream.writeSSE({ event: "ping", data: "{}" });
1463
+ }
1464
+ }));
1465
+ app.get("/api/terminal/sessions", (c) => {
1466
+ const denied = terminalOnly(c);
1467
+ if (denied)
1468
+ return denied;
1469
+ return c.json({ sessions: terminals.list() }, 200, { "Cache-Control": "no-store" });
1470
+ });
1471
+ app.post("/api/terminal/sessions", async (c) => {
1472
+ const denied = terminalOnly(c);
1473
+ if (denied)
1474
+ return denied;
1475
+ const body = (await c.req.json().catch(() => ({})));
1476
+ try {
1477
+ const session = terminals.create({
1478
+ cols: asDimension(body.cols) ?? undefined,
1479
+ rows: asDimension(body.rows) ?? undefined,
1480
+ });
1481
+ return c.json({ session }, 201);
1482
+ }
1483
+ catch (cause) {
1484
+ return terminalRefusal(c, cause);
1485
+ }
1486
+ });
1487
+ app.post("/api/terminal/sessions/:id/input", async (c) => {
1488
+ const denied = terminalOnly(c);
1489
+ if (denied)
1490
+ return denied;
1491
+ const body = (await c.req.json().catch(() => ({})));
1492
+ if (typeof body.data !== "string" || body.data.length === 0) {
1493
+ return c.json({ error: "data is required" }, 400);
1494
+ }
1495
+ if (body.data.length > MAX_TERMINAL_INPUT_CHARS) {
1496
+ return c.json({ error: "that is too much to type at once" }, 413);
1497
+ }
1498
+ try {
1499
+ terminals.input(c.req.param("id"), body.data);
1500
+ }
1501
+ catch (cause) {
1502
+ return terminalRefusal(c, cause);
1503
+ }
1504
+ return c.body(null, 204);
1505
+ });
1506
+ app.post("/api/terminal/sessions/:id/resize", async (c) => {
1507
+ const denied = terminalOnly(c);
1508
+ if (denied)
1509
+ return denied;
1510
+ const body = (await c.req.json().catch(() => ({})));
1511
+ const cols = asDimension(body.cols);
1512
+ const rows = asDimension(body.rows);
1513
+ if (cols === null ||
1514
+ rows === null ||
1515
+ cols < MIN_TERMINAL_COLS ||
1516
+ cols > MAX_TERMINAL_COLS ||
1517
+ rows < MIN_TERMINAL_ROWS ||
1518
+ rows > MAX_TERMINAL_ROWS) {
1519
+ return c.json({ error: "cols and rows must be whole numbers that fit a window" }, 400);
1520
+ }
1521
+ try {
1522
+ terminals.resize(c.req.param("id"), cols, rows);
1523
+ }
1524
+ catch (cause) {
1525
+ return terminalRefusal(c, cause);
1526
+ }
1527
+ return c.json({ session: terminals.get(c.req.param("id")) });
1528
+ });
1529
+ app.delete("/api/terminal/sessions/:id", (c) => {
1530
+ const denied = terminalOnly(c);
1531
+ if (denied)
1532
+ return denied;
1533
+ if (!terminals.delete(c.req.param("id")))
1534
+ return c.json({ error: "no such session" }, 404);
1535
+ return c.body(null, 204);
1536
+ });
1537
+ /**
1538
+ * The session's screen as it happens: a replay of what a reattaching reader
1539
+ * missed, then live bytes, then the shell's ending. One reader per tab is
1540
+ * normal, so every reader gets the same events.
1541
+ */
1542
+ app.get("/api/terminal/sessions/:id/output", (c) => {
1543
+ const denied = terminalOnly(c);
1544
+ if (denied)
1545
+ return denied;
1546
+ const id = c.req.param("id");
1547
+ if (!terminals.has(id))
1548
+ return c.json({ error: "no such session" }, 404);
1549
+ return streamSSE(c, async (stream) => {
1550
+ let closed = false;
1551
+ let finish = () => { };
1552
+ const ended = new Promise((resolve) => {
1553
+ finish = resolve;
1554
+ });
1555
+ let unsubscribe = () => { };
1556
+ try {
1557
+ unsubscribe = terminals.subscribe(id, (event) => {
1558
+ if (closed)
1559
+ return;
1560
+ void stream.writeSSE({ event: event.type, data: JSON.stringify(event) });
1561
+ // A shell that has ended has nothing left to say; the panel shows
1562
+ // "exited" and stops reconnecting.
1563
+ if (event.type === "exit")
1564
+ finish();
1565
+ });
1566
+ }
1567
+ catch {
1568
+ closed = true;
1569
+ return;
1570
+ }
1571
+ stream.onAbort(() => {
1572
+ closed = true;
1573
+ unsubscribe();
1574
+ finish();
1575
+ });
1576
+ await ended;
1577
+ closed = true;
1578
+ unsubscribe();
1579
+ });
1580
+ });
1581
+ // Programmatic surface. The board has no creation UI in M1; the orchestrator
1582
+ // and the tests are the only callers.
1583
+ /** What the person said in the conversation a card came from, as one line for the run. */
1584
+ const originalIntentOf = (conversationId) => {
1585
+ const conversation = typeof conversationId === "string" ? db.getConversation(conversationId) : null;
1586
+ return conversation?.messages
1587
+ .filter((message) => message.role === "user")
1588
+ .map((message) => message.content.replace(/\s+/g, " ").trim())
1589
+ .filter(Boolean)
1590
+ .join(" | ")
1591
+ .slice(0, 2_000);
1592
+ };
1593
+ app.post("/api/tickets", async (c) => {
1594
+ const body = await c.req.json().catch(() => ({}));
1595
+ if (!body.title?.trim())
1596
+ return c.json({ error: "title is required" }, 400);
1597
+ const attachments = attachmentPaths(body.attachments);
1598
+ if (!attachments)
1599
+ return c.json({ error: "those screenshots are not the board's" }, 400);
1600
+ const draft = body;
1601
+ // A card drafted for another repository must never run in this one.
1602
+ if (typeof draft.board === "string" && draft.board.trim()) {
1603
+ return c.json({ error: `that card belongs on the ${draft.board.trim()} board` }, 400);
1604
+ }
1605
+ const originalIntent = originalIntentOf(draft.conversationId);
1606
+ const ticket = db.createTicket({
1607
+ title: body.title.trim(),
1608
+ goal: asText(body.goal),
1609
+ out_of_scope: asText(body.out_of_scope),
1610
+ acceptance: asText(body.acceptance),
1611
+ attachments,
1612
+ verify: normaliseVerify(body.verify),
1613
+ likely_files: Array.isArray(body.likely_files)
1614
+ ? body.likely_files.filter((file) => typeof file === "string")
1615
+ : [],
1616
+ context: [
1617
+ ...(Array.isArray(body.context)
1618
+ ? body.context.filter((line) => typeof line === "string")
1619
+ : []),
1620
+ ...(originalIntent ? [`Original user intent: ${originalIntent}`] : []),
1621
+ ...["decided", "assumed"].flatMap((field) => {
1622
+ const values = draft[field];
1623
+ return Array.isArray(values)
1624
+ ? values
1625
+ .filter((line) => typeof line === "string" && Boolean(line.trim()))
1626
+ .map((line) => `Planner ${field === "decided" ? "decision" : "assumption"}: ${line}`)
1627
+ : [];
1628
+ }),
1629
+ ...(typeof draft.rationale === "string" && draft.rationale.trim()
1630
+ ? [`User intent: ${draft.rationale.trim()}`]
1631
+ : []),
1632
+ ],
1633
+ quick: body.quick === true,
1634
+ thinking: asThinking(body.thinking) ?? null,
1635
+ });
1636
+ return c.json({ ticket }, 201);
1637
+ });
1638
+ /** Other boards on this machine a new-task card can be filed on. */
1639
+ app.get("/api/boards", (c) => c.json({
1640
+ boards: linkedBoards().map((board) => ({
1641
+ name: board.name,
1642
+ root: board.root,
1643
+ description: board.description,
1644
+ running: board.running,
1645
+ })),
1646
+ }));
1647
+ /**
1648
+ * Files a confirmed card on a linked board: created and confirmed there,
1649
+ * through that board's own API, so it runs in that repository under that
1650
+ * board's allocator and rules. Nothing is written to this board.
1651
+ */
1652
+ app.post("/api/boards/:name/tickets", async (c) => {
1653
+ const name = c.req.param("name");
1654
+ const board = linkedBoards().find((item) => item.name === name);
1655
+ if (!board)
1656
+ return c.json({ error: `there is no linked board named ${name}` }, 404);
1657
+ const body = await c.req
1658
+ .json()
1659
+ .catch(() => ({}));
1660
+ const card = normaliseCard(body);
1661
+ if (!card.title)
1662
+ return c.json({ error: "title is required" }, 400);
1663
+ const intent = originalIntentOf(body.conversationId);
1664
+ const here = await ensureRepoName();
1665
+ try {
1666
+ const ticket = await fileOnLinkedBoard(board, {
1667
+ title: card.title,
1668
+ goal: card.goal,
1669
+ out_of_scope: card.out_of_scope,
1670
+ acceptance: card.acceptance,
1671
+ likely_files: card.likely_files,
1672
+ verify: card.verify ?? [],
1673
+ context: [
1674
+ ...(card.context ?? []),
1675
+ `Drafted on the ${here} board's new-task dialog; companion work there is a separate ticket.`,
1676
+ ...(intent ? [`Original user intent: ${intent}`] : []),
1677
+ ],
1678
+ rationale: card.rationale,
1679
+ assumed: card.assumed,
1680
+ decided: card.decided,
1681
+ ...(card.thinking ? { thinking: card.thinking } : {}),
1682
+ }, boardFetch);
1683
+ return c.json({ ticket, board: board.name }, 201);
1684
+ }
1685
+ catch (cause) {
1686
+ if (cause instanceof LinkedBoardError)
1687
+ return c.json({ error: cause.message }, cause.status);
1688
+ throw cause;
1689
+ }
1690
+ });
1691
+ /**
1692
+ * Run the parked-spec pass now. The allocator does this on its own; the route
1693
+ * exists for a person or a client that wants to retry without waiting for
1694
+ * another card to move.
1695
+ */
1696
+ app.post("/api/tickets/:id/prepare", async (c) => {
1697
+ const id = c.req.param("id");
1698
+ const ticket = db.getTicket(id);
1699
+ if (!ticket)
1700
+ return c.json({ error: `no ticket ${id}` }, 404);
1701
+ if (ticket.state !== "todo") {
1702
+ return c.json({ error: "only a ticket in Todo can be prepared" }, 409);
1703
+ }
1704
+ if (!ticket.quick)
1705
+ db.markQuick(id);
1706
+ await scheduleTickets();
1707
+ return c.json({ ticket: db.getTicket(id) ?? ticket });
1708
+ });
1709
+ app.post("/api/tickets/:id/confirm", async (c) => {
1710
+ const body = await c.req.json().catch(() => ({}));
1711
+ const id = c.req.param("id");
1712
+ const existing = db.getTicket(id);
1713
+ if (!existing)
1714
+ return c.json({ error: `no ticket ${id}` }, 404);
1715
+ // Quick is a property of the ticket, but a caller may set it on the confirm
1716
+ // request when the card was created moments earlier. Everything else keeps
1717
+ // the ordinary spec gate.
1718
+ const quick = existing.quick || body.quick === true;
1719
+ if (quick && !existing.quick)
1720
+ db.markQuick(id);
1721
+ const current = db.getTicket(id) ?? existing;
1722
+ if (quick && !checkSpec(current).ok) {
1723
+ // Park in Todo without queueing. The allocation pass fills the gaps and
1724
+ // only then moves it to Queued, so a gapped card never claims a slot.
1725
+ const parked = db.confirmTicket(id, { allowIncomplete: true });
1726
+ // Start the prepare pass after this response, so the person sees the card
1727
+ // parked first and a slow planner cannot fail the confirm.
1728
+ setTimeout(() => void scheduleTickets(), 0);
1729
+ return c.json({ ticket: db.getTicket(id) ?? parked });
1730
+ }
1731
+ const confirmed = db.confirmTicket(id);
1732
+ // Confirming is permission to run, so the ticket enters the allocation
1733
+ // queue immediately. The allocator starts it if a slot is free.
1734
+ const queued = db.transition(confirmed.id, "queued", {
1735
+ profile: confirmed.profile ?? "developer",
1736
+ });
1737
+ await scheduleTickets();
1738
+ return c.json({ ticket: db.getTicket(confirmed.id) ?? queued });
1739
+ });
1740
+ app.get("/api/orchestrator", (c) => c.json({ conversation: db.activeConversation() }));
1741
+ app.get("/api/repo", async (c) => c.json(await repoStatus()));
1742
+ /** Manual rebuild, for when the map is wrong and the person knows better. */
1743
+ app.post("/api/repo/reindex", async (c) => {
1744
+ await ensureIndex(true);
1745
+ return c.json(await repoStatus());
1746
+ });
1747
+ /**
1748
+ * What dictation can do right now. The board asks when the dialog opens,
1749
+ * because "the model is not downloaded" and "whisper.cpp is not installed"
1750
+ * are different sentences and only one of them has a button.
1751
+ */
1752
+ app.get("/api/voice", async (c) => c.json(await voice.status()));
1753
+ /**
1754
+ * The one-time model fetch, on its own route. It is the only part of
1755
+ * dictation that touches the network, and 142 MB is not something a
1756
+ * transcription request should do while somebody waits with a sentence
1757
+ * already in their head.
1758
+ */
1759
+ app.post("/api/voice/prepare", async (c) => c.json(await voice.prepare()));
1760
+ /**
1761
+ * A recorded WAV in, the words out. The audio is written to a temp file and
1762
+ * deleted in a `finally`, so nothing said into the microphone outlives the
1763
+ * request that carried it.
1764
+ */
1765
+ app.post("/api/voice/transcribe", async (c) => {
1766
+ if (!(c.req.header("content-type") ?? "").toLowerCase().startsWith("audio/")) {
1767
+ return c.json({ error: "send audio/wav" }, 415);
1768
+ }
1769
+ // Checked before the body is read: a 200 MB upload should cost the sender
1770
+ // bandwidth, not this process's memory.
1771
+ const declared = Number(c.req.header("content-length"));
1772
+ if (Number.isFinite(declared) && declared > MAX_AUDIO_BYTES) {
1773
+ return c.json({ error: "that recording is too long" }, 413);
1774
+ }
1775
+ const body = new Uint8Array(await c.req.arrayBuffer());
1776
+ if (body.byteLength > MAX_AUDIO_BYTES) {
1777
+ return c.json({ error: "that recording is too long" }, 413);
1778
+ }
1779
+ if (!isWav(body)) {
1780
+ return c.json({ error: "only WAV is accepted; the board sends 16 kHz mono" }, 415);
1781
+ }
1782
+ return c.json({ text: await voice.transcribe(body) });
1783
+ });
1784
+ /**
1785
+ * A screenshot on its way to a planner turn. The browser sends the file's own
1786
+ * bytes; the bytes decide whether it is an image, not the content-type. The
1787
+ * file lands in the board's state directory, because a later ticket run needs
1788
+ * a path a process can read in a worktree it does not share with this request.
1789
+ */
1790
+ app.post("/api/attachments", async (c) => {
1791
+ const declared = imageMime(c.req.header("content-type"));
1792
+ if (!declared) {
1793
+ return c.json({ error: "send a png, jpeg, webp or gif" }, 415);
1794
+ }
1795
+ // Checked before the body is read, for the same reason the audio route does:
1796
+ // a huge upload should cost the sender bandwidth, not this process's memory.
1797
+ const length = Number(c.req.header("content-length"));
1798
+ if (Number.isFinite(length) && length > MAX_IMAGE_BYTES) {
1799
+ return c.json({ error: "that image is too large" }, 413);
1800
+ }
1801
+ const bytes = new Uint8Array(await c.req.arrayBuffer());
1802
+ if (bytes.byteLength > MAX_IMAGE_BYTES) {
1803
+ return c.json({ error: "that image is too large" }, 413);
1804
+ }
1805
+ if (bytes.byteLength === 0)
1806
+ return c.json({ error: "the image is empty" }, 400);
1807
+ const sniffed = sniffImage(bytes);
1808
+ if (!sniffed)
1809
+ return c.json({ error: "that file is not an image" }, 415);
1810
+ return c.json({ attachment: await saveAttachment(root, bytes, sniffed) }, 201);
1811
+ });
1812
+ /**
1813
+ * Screenshots a person decided not to use. Only the board's own paths are
1814
+ * touched, so a malformed body cannot turn this into a file-delete endpoint.
1815
+ */
1816
+ app.delete("/api/attachments", async (c) => {
1817
+ const body = await c.req.json().catch(() => ({}));
1818
+ const paths = attachmentPaths(body.paths);
1819
+ if (!paths)
1820
+ return c.json({ error: "those screenshots are not the board's" }, 400);
1821
+ await deleteAttachments(root, paths);
1822
+ return c.json({ deleted: paths.length });
1823
+ });
1824
+ /**
1825
+ * One planner turn, whichever door the person came through. Both doors share
1826
+ * it because the rules that matter — the message cap, the handoff, one turn in
1827
+ * flight, the transcript — are rules about the turn, not about the route.
1828
+ */
1829
+ /**
1830
+ * The conversation a route was told to act on, or the panel's own chat when it
1831
+ * was not told. `null` means the id was given and is not there.
1832
+ */
1833
+ const addressedConversation = (value) => {
1834
+ const id = asConversationId(value);
1835
+ return id ? db.getConversation(id) : db.activeConversation();
1836
+ };
1837
+ const planTurn = async (text, options = {}) => {
1838
+ // Read before the turn takes the lock: a screenshot that vanished is this
1839
+ // request's error, not a turn that has to be waited out by the next person.
1840
+ const attachments = options.attachments ?? [];
1841
+ const images = attachments.length > 0 ? await readAttachmentImages(root, attachments) : [];
1842
+ if (planning)
1843
+ throw new AlreadyPlanningError();
1844
+ planning = true;
1845
+ publish({ label: "Thinking", tool: null });
1846
+ const startedAt = Date.now();
1847
+ // The intake and the draft are two rows; each one is timed from its own start.
1848
+ let rowStartedAt = startedAt;
1849
+ let indexMs = 0;
1850
+ let stats = EMPTY_TURN_STATS;
1851
+ let kind = "panel";
1852
+ let door = options.mode ?? null;
1853
+ let session = options.conversationId ?? "";
1854
+ /**
1855
+ * One row per turn. It never throws: a measurement that can fail a turn is a
1856
+ * measurement that changes the thing it measures.
1857
+ */
1858
+ const measure = (outcome) => {
1859
+ try {
1860
+ db.recordPlannerTurn({
1861
+ conversation_id: session,
1862
+ kind,
1863
+ mode: door,
1864
+ ok: outcome.ok,
1865
+ error: outcome.error ?? null,
1866
+ duration_ms: Date.now() - rowStartedAt,
1867
+ index_ms: indexMs,
1868
+ first_event_ms: stats.firstEventMs,
1869
+ harness_ms: stats.harnessMs,
1870
+ tool_calls: stats.toolCalls,
1871
+ tool_errors: stats.toolErrors,
1872
+ tool_budget: stats.toolBudget,
1873
+ capped: stats.capped,
1874
+ prompt_chars: stats.promptChars,
1875
+ output_chars: stats.outputChars,
1876
+ questions: outcome.questions ?? 0,
1877
+ cards: outcome.cards ?? 0,
1878
+ started_at: new Date(rowStartedAt).toISOString(),
1879
+ });
1880
+ }
1881
+ catch {
1882
+ // The log is diagnostics; losing one row must never lose the turn.
1883
+ }
1884
+ };
1885
+ try {
1886
+ // Which chat this turn belongs to. The panel writes into the board's active
1887
+ // conversation; a wizard writes into its own session, so a person drafting
1888
+ // a ticket never finds the questions they answered sitting in the chat
1889
+ // they have with the orchestrator.
1890
+ const target = options.conversationId
1891
+ ? db.getConversation(options.conversationId)
1892
+ : db.activeConversation();
1893
+ if (!target)
1894
+ throw new UnknownConversationError(options.conversationId ?? "");
1895
+ kind = target.kind ?? "panel";
1896
+ session = target.id;
1897
+ // The route cannot see the door the person came through, so a wizard's
1898
+ // answer turn takes its doctrine from the conversation it writes into.
1899
+ const mode = options.mode ?? (kind === "task" ? "new-task" : undefined);
1900
+ door = mode ?? null;
1901
+ // Other repositories matter only to the new-task dialog. The intake hears
1902
+ // about every candidate; the draft only about the ones the person said yes to.
1903
+ const candidates = kind === "task" ? linkedBoards() : [];
1904
+ const included = includedBoards(target.plan, options.answers ?? [], new Set(candidates.map((board) => board.name)));
1905
+ const includedBriefs = candidates
1906
+ .filter((board) => included.includes(board.name))
1907
+ .map(briefOf);
1908
+ // A scout that read a board the person turned down is not reading the draft gets.
1909
+ const forDraft = (findings) => findings?.filter((finding) => !finding.board || included.includes(finding.board));
1910
+ // What the person chose travels in their own turn, so the planner reads it
1911
+ // and the cards are written from the same source below.
1912
+ const answered = options.answers && options.answers.length > 0
1913
+ ? resolveAnswers(target.plan, options.answers)
1914
+ : EMPTY_ANSWERS;
1915
+ const said = answered.block ? `${text}\n\n${answered.block}` : text;
1916
+ let conversation = target;
1917
+ // Accepted cards are tickets. Without them the planner re-proposes
1918
+ // work the person already said yes to, in the same words.
1919
+ const board = db.listTickets().map((ticket) => ({
1920
+ id: ticket.id,
1921
+ title: ticket.title,
1922
+ state: ticket.state,
1923
+ }));
1924
+ let draft = conversation.plan;
1925
+ let handoff = conversation.summary && conversation.summaryFrom
1926
+ ? { conversationId: conversation.summaryFrom, summary: conversation.summary }
1927
+ : null;
1928
+ if (conversation.messages.length >= MAX_MESSAGES) {
1929
+ const ended = conversation;
1930
+ const count = ended.messages.length;
1931
+ let summary;
1932
+ // The summary is an optimisation, never a gate. A failed or slow pass
1933
+ // still hands the new chat a deterministic record and lets the turn run.
1934
+ try {
1935
+ summary = await runSummary({
1936
+ messages: ended.messages,
1937
+ plan: ended.plan,
1938
+ board,
1939
+ conversationId: ended.id,
1940
+ priorSummary: ended.summaryFrom ? (ended.summary ?? null) : null,
1941
+ onStatus: publish,
1942
+ });
1943
+ if (!summary.trim()) {
1944
+ throw new OrchestratorError("output", "the summariser returned nothing");
1945
+ }
1946
+ }
1947
+ catch {
1948
+ summary = fallbackHandoff({
1949
+ messages: ended.messages,
1950
+ plan: ended.plan,
1951
+ board,
1952
+ conversationId: ended.id,
1953
+ priorSummary: ended.summaryFrom ? (ended.summary ?? null) : null,
1954
+ });
1955
+ }
1956
+ // The old row keeps its own final summary. The new row inherits it so
1957
+ // every later turn in this chat still knows what carried over. A wizard
1958
+ // session hands off as a wizard session: the continuation is still not
1959
+ // the panel's chat.
1960
+ db.setSummary(ended.id, summary, null);
1961
+ const fresh = db.newConversation({ summary, from: ended.id }, ended.kind ?? "panel");
1962
+ db.appendMessage("assistant", `Continuing in a new chat — ${count} messages carried over.`, "note", fresh.id);
1963
+ conversation = db.appendMessage("user", said, "message", fresh.id);
1964
+ draft = ended.plan;
1965
+ handoff = { conversationId: ended.id, summary, messageCount: count };
1966
+ }
1967
+ else {
1968
+ conversation = db.appendMessage("user", said, "message", conversation.id);
1969
+ }
1970
+ // Start scouts before the index and intake, using only the original description.
1971
+ const intakeReading = mode === "intake" ? startResearch(conversation.id, taskResearchQuestions(text)) : undefined;
1972
+ // Waiting here is usually free: the index is built at startup and the
1973
+ // head check is one git call. When it is not free — a first run, or a
1974
+ // checkout that just changed — the build is minutes of silence with no
1975
+ // harness to report anything, so the turn says what it is waiting for.
1976
+ const indexStarted = Date.now();
1977
+ const index = await ensureIndex(false, () => publish({ label: "Indexing the repo", tool: "index" }));
1978
+ indexMs = Date.now() - indexStarted;
1979
+ const brief = index ? renderBrief(index) : "";
1980
+ // One planner run. Its stats are its own, so the row it writes is too.
1981
+ const planOnce = (passMode, findings) => {
1982
+ stats = EMPTY_TURN_STATS;
1983
+ // The intake decides, it does not read at length: its level is capped in
1984
+ // this one place so the injected test planner and the real one agree.
1985
+ const level = options.thinking ?? plannerThinkingForTurn();
1986
+ const passThinking = passMode === "intake" ? capThinking(level, INTAKE_THINKING_CAP) : level;
1987
+ return runPlan(conversation.messages, brief, draft, board, publish, handoff, passMode, (measured) => {
1988
+ stats = measured;
1989
+ }, attachments, images, passThinking, findings,
1990
+ // What is left of the request, not a fresh clock per pass: the intake,
1991
+ // the scouts and the draft share one deadline, and the planner is told it.
1992
+ Math.max(MIN_PASS_MS, PLAN_TURN_DEADLINE_MS - (Date.now() - startedAt)), passMode === "intake" ? candidates.map(briefOf) : includedBriefs);
1993
+ };
1994
+ // Saves what the planner decided. Research is a planner input, not part of
1995
+ // the plan the dialog reads, so it is not stored.
1996
+ const store = (drafted) => {
1997
+ // Card identity is the server's, not the model's: the draft it just wrote
1998
+ // has to line up with the draft a person may already be editing.
1999
+ const assigned = assignIds(drafted, draft);
2000
+ // Clamped again here on purpose: a fifth question costs the person attention.
2001
+ const next = { ...assigned, questions: normaliseQuestions(assigned.questions) };
2002
+ // A card for a board the person did not include would run where nobody
2003
+ // agreed to it. It is dropped, and the reply says so.
2004
+ const strays = next.cards.filter((card) => card.board && !included.includes(card.board));
2005
+ const kept = next.cards.filter((card) => !card.board || included.includes(card.board));
2006
+ const cards = answered.decided.length > 0 ? applyDecided(kept, answered.decided) : kept;
2007
+ const reply = strays.length > 0
2008
+ ? `${next.reply} (Left out ${strays.length === 1 ? "a card" : `${strays.length} cards`} for ${[
2009
+ ...new Set(strays.map((card) => card.board)),
2010
+ ].join(", ")}: that board was not included.)`.trim()
2011
+ : next.reply;
2012
+ // The assistant turn is the prose. Questions live in `plan` and are drawn as cards.
2013
+ if (reply)
2014
+ db.appendMessage("assistant", reply, "message", conversation.id);
2015
+ const saved = db.setPlan({
2016
+ reply,
2017
+ questions: next.questions,
2018
+ cards,
2019
+ ...(included.length > 0 ? { boards: included } : {}),
2020
+ }, conversation.id);
2021
+ return { saved, questions: next.questions.length, cards: cards.length };
2022
+ };
2023
+ // An answer turn in the wizard reads what its intake started, first.
2024
+ let findings;
2025
+ if (mode === "new-task") {
2026
+ const reading = pendingResearch.get(target.id);
2027
+ if (reading) {
2028
+ pendingResearch.delete(target.id);
2029
+ findings = forDraft(await awaitReading(reading));
2030
+ }
2031
+ }
2032
+ let drafted = await planOnce(mode, findings);
2033
+ if (mode === "intake") {
2034
+ // The intake names boards; the board asks the person, in its own words,
2035
+ // and a scout starts reading that repository while they decide.
2036
+ const byName = new Map(candidates.map((linked) => [linked.name, linked]));
2037
+ const suspected = [...new Set(drafted.boards ?? [])]
2038
+ .map((name) => byName.get(name))
2039
+ .filter((linked) => linked !== undefined)
2040
+ .filter((linked) => !included.includes(linked.name))
2041
+ .slice(0, MAX_BOARD_QUESTIONS);
2042
+ if (suspected.length > 0) {
2043
+ extendResearch(conversation.id, suspected.map((linked) => linkedBoardQuestion(linked.name, text)));
2044
+ drafted = {
2045
+ ...drafted,
2046
+ questions: [
2047
+ ...suspected.map(boardQuestion),
2048
+ ...normaliseQuestions(drafted.questions),
2049
+ ].slice(0, MAX_QUESTIONS),
2050
+ };
2051
+ }
2052
+ }
2053
+ let outcome;
2054
+ if (mode !== "intake") {
2055
+ outcome = store(drafted);
2056
+ }
2057
+ else {
2058
+ // Scouts have been running since the request arrived.
2059
+ if (normaliseQuestions(drafted.questions).length > 0) {
2060
+ outcome = store({ ...drafted, cards: [] });
2061
+ }
2062
+ else {
2063
+ // Nothing to ask and nothing drafted: the intake's row is recorded, then
2064
+ // the draft waits for the reading in this same request.
2065
+ measure({ ok: true });
2066
+ pendingResearch.delete(conversation.id);
2067
+ const readFirst = intakeReading ? forDraft(await awaitReading(intakeReading)) : undefined;
2068
+ door = "new-task";
2069
+ rowStartedAt = Date.now();
2070
+ indexMs = 0;
2071
+ outcome = store(await planOnce("new-task", readFirst));
2072
+ }
2073
+ }
2074
+ session = conversation.id;
2075
+ measure({ ok: true, questions: outcome.questions, cards: outcome.cards });
2076
+ return outcome.saved;
2077
+ }
2078
+ catch (cause) {
2079
+ // A failed turn is the most interesting row in the log: it is the only one
2080
+ // that says how long the person waited for nothing.
2081
+ measure({ ok: false, error: describeError(cause) });
2082
+ throw cause;
2083
+ }
2084
+ finally {
2085
+ planning = false;
2086
+ publish(null);
2087
+ }
2088
+ };
2089
+ /**
2090
+ * The server owns the transcript. The client sends one message and gets the
2091
+ * whole conversation back, so a second tab, a reload, or a failed run all end
2092
+ * up reading the same record instead of a client-side copy of it.
2093
+ */
2094
+ app.post("/api/orchestrator/messages", async (c) => {
2095
+ const body = await c.req
2096
+ .json()
2097
+ .catch(() => ({}));
2098
+ const text = typeof body.text === "string" ? body.text.trim() : "";
2099
+ const thinking = asThinking(body.thinking);
2100
+ if (!text)
2101
+ return c.json({ error: "text is required" }, 400);
2102
+ if (thinking === null)
2103
+ return c.json({ error: "unknown thinking level" }, 400);
2104
+ if (text.length > MAX_MESSAGE_CHARS)
2105
+ return c.json({ error: "message too long" }, 400);
2106
+ const attachments = attachmentPaths(body.attachments);
2107
+ if (!attachments)
2108
+ return c.json({ error: "those screenshots are not the board's" }, 400);
2109
+ try {
2110
+ return c.json({
2111
+ conversation: await planTurn(text, {
2112
+ answers: asAnswers(body.answers),
2113
+ conversationId: asConversationId(body.conversationId),
2114
+ attachments,
2115
+ thinking: thinking ?? undefined,
2116
+ }),
2117
+ });
2118
+ }
2119
+ catch (cause) {
2120
+ return turnRefusal(c, cause);
2121
+ }
2122
+ });
2123
+ /**
2124
+ * The way into the planner from the new-task wizard: a description, not a
2125
+ * title. It is one message to the planner — the wizard holds the person in
2126
+ * the dialog and the turn comes back with questions and cards — so it carries
2127
+ * one message's cap rather than a title's.
2128
+ */
2129
+ app.post("/api/orchestrator/intent", async (c) => {
2130
+ const body = await c.req
2131
+ .json()
2132
+ .catch(() => ({}));
2133
+ const text = typeof body.text === "string" ? body.text.trim() : "";
2134
+ const thinking = asThinking(body.thinking);
2135
+ if (!text)
2136
+ return c.json({ error: "a description is required" }, 400);
2137
+ if (thinking === null)
2138
+ return c.json({ error: "unknown thinking level" }, 400);
2139
+ if (text.length > MAX_MESSAGE_CHARS) {
2140
+ return c.json({ error: "that description is too long" }, 400);
2141
+ }
2142
+ const attachments = attachmentPaths(body.attachments);
2143
+ if (!attachments)
2144
+ return c.json({ error: "those screenshots are not the board's" }, 400);
2145
+ // A fresh session, not the panel's chat. The wizard's questions and the
2146
+ // card it drafts belong to this description, and the person confirming it
2147
+ // is not having a conversation with the orchestrator while they do it.
2148
+ // The row is kept afterwards: it is the record of why the ticket exists.
2149
+ const session = db.newTaskConversation();
2150
+ try {
2151
+ return c.json({
2152
+ conversation: await planTurn(`(new task) ${text}`, {
2153
+ mode: "intake",
2154
+ conversationId: session.id,
2155
+ attachments,
2156
+ thinking: thinking ?? undefined,
2157
+ }),
2158
+ });
2159
+ }
2160
+ catch (cause) {
2161
+ // The client never got this session's id, so nothing can ever address it.
2162
+ // A failed first turn leaves a row nobody can see and nobody can close.
2163
+ pendingResearch.delete(session.id);
2164
+ db.deleteConversation(session.id);
2165
+ return turnRefusal(c, cause);
2166
+ }
2167
+ });
2168
+ /**
2169
+ * Edits made while reviewing a draft. They are part of the draft: a person
2170
+ * who corrects an acceptance criterion has decided it, so the next turn must
2171
+ * see their wording, not the model's.
2172
+ */
2173
+ app.put("/api/orchestrator/plan", async (c) => {
2174
+ const body = await c.req
2175
+ .json()
2176
+ .catch(() => ({}));
2177
+ const conversation = addressedConversation(body.conversationId);
2178
+ if (!conversation)
2179
+ return c.json({ error: "no such conversation" }, 404);
2180
+ if (!conversation.plan)
2181
+ return c.json({ error: "there is no draft to edit" }, 409);
2182
+ if (!Array.isArray(body.cards))
2183
+ return c.json({ error: "cards must be a list" }, 400);
2184
+ const cards = body.cards.map((card) => normaliseCard((card ?? {})));
2185
+ if (cards.length > MAX_CARDS)
2186
+ return c.json({ error: "too many cards" }, 400);
2187
+ // Ids stay the server's: an edit is not a new card, so a card without a
2188
+ // known id is refused rather than silently minted a fresh one.
2189
+ const known = new Set(conversation.plan.cards.map((card) => card.id));
2190
+ if (cards.some((card) => !known.has(card.id))) {
2191
+ return c.json({ error: "a card lost its id" }, 409);
2192
+ }
2193
+ return c.json({
2194
+ conversation: db.setPlan({ ...conversation.plan, cards }, conversation.id),
2195
+ });
2196
+ });
2197
+ /** "New chat": a new row, so the old transcript can still be read later. */
2198
+ app.post("/api/orchestrator/reset", (c) => c.json({ conversation: db.newConversation() }));
2199
+ /**
2200
+ * The cards were created (or kept as drafts), so the review is over. Say so in
2201
+ * the transcript: the panel goes back to being a chat, and six weeks later the
2202
+ * conversation explains where those tickets came from.
2203
+ */
2204
+ app.post("/api/orchestrator/confirmed", async (c) => {
2205
+ const body = await c.req
2206
+ .json()
2207
+ .catch(() => ({}));
2208
+ const conversation = addressedConversation(body.conversationId);
2209
+ if (!conversation)
2210
+ return c.json({ error: "no such conversation" }, 404);
2211
+ const created = asCount(body.created);
2212
+ const kept = asCount(body.kept);
2213
+ const parts = [];
2214
+ if (created > 0)
2215
+ parts.push(`Started ${created} card${created === 1 ? "" : "s"}.`);
2216
+ if (kept > 0)
2217
+ parts.push(`Kept ${kept} as draft${kept === 1 ? "" : "s"}.`);
2218
+ if (parts.length === 0)
2219
+ parts.push("Nothing was selected; the plan was dropped.");
2220
+ db.appendMessage("assistant", parts.join(" "), "message", conversation.id);
2221
+ return c.json({ conversation: db.setPlan(null, conversation.id) });
2222
+ });
2223
+ /**
2224
+ * Empties Complete without deleting anything. It is a second, narrower write
2225
+ * beside the state machine: only done goes, and the rows stay.
2226
+ */
2227
+ app.post("/api/tickets/archive-done", (c) => {
2228
+ const archived = db.archiveDone();
2229
+ return c.json({ archived: archived.length });
2230
+ });
2231
+ app.get("/api/tickets/:id/merge", async (c) => {
2232
+ if (c.get("principal").kind !== "local") {
2233
+ return c.json({ error: "merging is available from the local board only" }, 403);
2234
+ }
2235
+ const ticket = db.getTicket(c.req.param("id"));
2236
+ if (!ticket)
2237
+ return c.json({ error: "no such ticket" }, 404);
2238
+ if (ticket.state !== "review")
2239
+ return c.json({ error: `ticket is ${ticket.state}` }, 409);
2240
+ if (runs.isRunning(ticket.id))
2241
+ return c.json({ error: "ticket has a run in progress" }, 409);
2242
+ if (!ticket.pr_url || !ticket.branch) {
2243
+ return c.json({ error: "ticket has no linked pull request and branch" }, 409);
2244
+ }
2245
+ const checkout = worktreePath(root, ticket.id);
2246
+ if (!existsSync(join(checkout, ".git")))
2247
+ return c.json({ error: "ticket checkout is missing" }, 409);
2248
+ try {
2249
+ const [pr, options] = await Promise.all([
2250
+ readPullRequestSnapshot(checkout, ticket.pr_url, ghCommand),
2251
+ readMergeOptions(checkout, ticket.pr_url, ghCommand),
2252
+ ]);
2253
+ if (pr.headRefName !== ticket.branch) {
2254
+ return c.json({ error: "linked pull request does not match the ticket branch" }, 409);
2255
+ }
2256
+ const current = db.getTicket(ticket.id);
2257
+ if (!current ||
2258
+ current.state !== "review" ||
2259
+ runs.isRunning(ticket.id) ||
2260
+ current.branch !== ticket.branch ||
2261
+ current.pr_url !== ticket.pr_url) {
2262
+ return c.json({ error: "ticket changed while merge status was loading" }, 409);
2263
+ }
2264
+ const reason = mergeBlockReason(pr);
2265
+ return c.json({
2266
+ ready: reason === null && options.methods.length > 0,
2267
+ reason: reason ??
2268
+ (options.methods.length === 0 ? "Repository has disabled all merge methods" : null),
2269
+ headSha: pr.headRefOid,
2270
+ mergeStateStatus: pr.mergeStateStatus,
2271
+ checksWarning: pr.mergeStateStatus === "BLOCKED" || pr.mergeStateStatus === "UNSTABLE"
2272
+ ? "Checks (or required reviews) are not passing"
2273
+ : null,
2274
+ methods: options.methods,
2275
+ defaultMethod: options.defaultMethod,
2276
+ });
2277
+ }
2278
+ catch (cause) {
2279
+ return c.json({ error: cause instanceof Error ? cause.message : "could not read pull request status" }, 502);
2280
+ }
2281
+ });
2282
+ app.post("/api/tickets/:id/merge", async (c) => {
2283
+ if (c.get("principal").kind !== "local") {
2284
+ return c.json({ error: "merging is available from the local board only" }, 403);
2285
+ }
2286
+ const ticket = db.getTicket(c.req.param("id"));
2287
+ if (!ticket)
2288
+ return c.json({ error: "no such ticket" }, 404);
2289
+ if (ticket.state !== "review")
2290
+ return c.json({ error: `ticket is ${ticket.state}` }, 409);
2291
+ if (runs.isRunning(ticket.id))
2292
+ return c.json({ error: "ticket has a run in progress" }, 409);
2293
+ if (!ticket.pr_url || !ticket.branch) {
2294
+ return c.json({ error: "ticket has no linked pull request and branch" }, 409);
2295
+ }
2296
+ if (mergeInFlight.has(ticket.id))
2297
+ return c.json({ error: "a merge is already in progress" }, 409);
2298
+ const checkout = worktreePath(root, ticket.id);
2299
+ if (!existsSync(join(checkout, ".git")))
2300
+ return c.json({ error: "ticket checkout is missing" }, 409);
2301
+ const body = await c.req
2302
+ .json()
2303
+ .catch(() => ({}));
2304
+ const method = body.method;
2305
+ const headSha = typeof body.headSha === "string" ? body.headSha : "";
2306
+ if (method !== "merge" && method !== "squash" && method !== "rebase") {
2307
+ return c.json({ error: "choose a supported merge method" }, 400);
2308
+ }
2309
+ if (!/^[a-f0-9]{7,64}$/i.test(headSha)) {
2310
+ return c.json({ error: "refresh the pull request status before merging" }, 400);
2311
+ }
2312
+ if (mergeInFlight.has(ticket.id))
2313
+ return c.json({ error: "a merge is already in progress" }, 409);
2314
+ mergeInFlight.add(ticket.id);
2315
+ try {
2316
+ const before = await readPullRequestSnapshot(checkout, ticket.pr_url, ghCommand);
2317
+ if (before.headRefName !== ticket.branch) {
2318
+ return c.json({ error: "linked pull request does not match the ticket branch" }, 409);
2319
+ }
2320
+ const current = db.getTicket(ticket.id);
2321
+ if (!current ||
2322
+ current.state !== "review" ||
2323
+ runs.isRunning(ticket.id) ||
2324
+ current.branch !== ticket.branch ||
2325
+ current.pr_url !== ticket.pr_url) {
2326
+ return c.json({ error: "ticket changed while merge status was loading" }, 409);
2327
+ }
2328
+ const merged = await mergePullRequest(checkout, ticket.pr_url, method, headSha, ghCommand, () => {
2329
+ const latest = db.getTicket(ticket.id);
2330
+ if (!latest ||
2331
+ latest.state !== "review" ||
2332
+ runs.isRunning(ticket.id) ||
2333
+ latest.branch !== ticket.branch ||
2334
+ latest.pr_url !== ticket.pr_url ||
2335
+ !mergeInFlight.has(ticket.id)) {
2336
+ throw new Error("ticket changed before the pull request could be merged");
2337
+ }
2338
+ });
2339
+ // The watcher remains the only writer of Review -> Done. It independently
2340
+ // observes GitHub's merged state before retiring the checkout and branch.
2341
+ await mergeWatcher.poll().catch(() => { });
2342
+ return c.json({ merged: true, mergedAt: merged.mergedAt, headSha: merged.headRefOid });
2343
+ }
2344
+ catch (cause) {
2345
+ return c.json({
2346
+ error: cause instanceof Error ? cause.message : "GitHub could not merge this pull request",
2347
+ }, 409);
2348
+ }
2349
+ finally {
2350
+ mergeInFlight.delete(ticket.id);
2351
+ }
2352
+ });
2353
+ app.post("/api/tickets/:id/comments/:commentId/issue", async (c) => {
2354
+ if (c.get("principal").kind !== "local") {
2355
+ return c.json({ error: "filing issues is available from the local board only" }, 403);
2356
+ }
2357
+ const ticket = db.getTicket(c.req.param("id"));
2358
+ if (!ticket)
2359
+ return c.json({ error: "no such ticket" }, 404);
2360
+ const commentId = c.req.param("commentId");
2361
+ const comment = db.listComments(ticket.id).find((item) => item.id === commentId);
2362
+ if (!comment)
2363
+ return c.json({ error: "no such comment" }, 404);
2364
+ if (!comment.actions?.issue) {
2365
+ return c.json({ error: "this comment has no issue to file" }, 409);
2366
+ }
2367
+ if (comment.actions.issue.url) {
2368
+ return c.json({ error: "this issue is already filed", url: comment.actions.issue.url }, 409);
2369
+ }
2370
+ const body = await c.req
2371
+ .json()
2372
+ .catch(() => ({}));
2373
+ if (typeof body.title !== "string" ||
2374
+ !body.title.trim() ||
2375
+ typeof body.body !== "string" ||
2376
+ !body.body.trim()) {
2377
+ return c.json({ error: "title and body are required" }, 400);
2378
+ }
2379
+ const issue = prepareIssue(body.title, body.body);
2380
+ if (!issue)
2381
+ return c.json({ error: "the issue has no text left to file" }, 400);
2382
+ // No await between the check and the add: a second submit sees the first.
2383
+ if (issueInFlight.has(comment.id)) {
2384
+ return c.json({ error: "this issue is already being filed" }, 409);
2385
+ }
2386
+ issueInFlight.add(comment.id);
2387
+ try {
2388
+ const filed = await createIssue({
2389
+ ghCommand: ghCommand ?? "gh",
2390
+ title: issue.title,
2391
+ body: issue.body,
2392
+ });
2393
+ const updated = db.setCommentIssueUrl(comment.id, filed.url);
2394
+ return c.json({ url: filed.url, comment: updated });
2395
+ }
2396
+ catch (cause) {
2397
+ return c.json({ error: cause instanceof Error ? cause.message : "GitHub could not create the issue" }, 409);
2398
+ }
2399
+ finally {
2400
+ issueInFlight.delete(comment.id);
2401
+ }
2402
+ });
2403
+ app.post("/api/tickets/:id/transition", async (c) => {
2404
+ const body = await c.req
2405
+ .json()
2406
+ .catch(() => ({}));
2407
+ const to = body.to;
2408
+ if (typeof to !== "string")
2409
+ return c.json({ error: "to is required" }, 400);
2410
+ const id = c.req.param("id");
2411
+ // A ticket works inside its own worktree, so a start gets one before the
2412
+ // state moves. The refusal is checked first on purpose: a start that is
2413
+ // going to be rejected must not leave a branch and a checkout behind.
2414
+ let worktree = null;
2415
+ if (to === "in_progress") {
2416
+ const current = db.getTicket(id);
2417
+ if (!current)
2418
+ return c.json({ error: "no such ticket" }, 404);
2419
+ if (!canTransition(current.state, "in_progress")) {
2420
+ throw new TransitionError(current.state, "in_progress", describeRefusal(current.state, "in_progress"));
2421
+ }
2422
+ if (runs.isRunning(id))
2423
+ throw new RunAlreadyActiveError(id);
2424
+ if (runs.runningCount() >= maxConcurrentRuns()) {
2425
+ return c.json({ error: "all agent slots are busy; queue the ticket instead" }, 409);
2426
+ }
2427
+ worktree = await checkoutFor(current);
2428
+ }
2429
+ const moved = db.transition(id, to, {
2430
+ blocker_kind: body.blocker_kind ?? null,
2431
+ blocker_reason: body.blocker_reason ?? null,
2432
+ blocker_unblock: body.blocker_unblock ?? null,
2433
+ });
2434
+ // Cancel is a board action, so it also stops the process behind it. Review
2435
+ // and blocked mean the agent has said what happened, so its process stops
2436
+ // too; those endings keep the checkout. Done and a delete are endings that
2437
+ // retire it: the ticket's claim on disk and on origin goes with the card.
2438
+ if (to === "cancelled")
2439
+ runs.cancel(id);
2440
+ else if (to === "review" || to === "blocked")
2441
+ runs.settle(id);
2442
+ if (to === "done") {
2443
+ await stopRun(id, "settle");
2444
+ await retireWorktree(root, id, moved.branch);
2445
+ }
2446
+ const run = to === "in_progress" && worktree ? runs.start(moved, worktree) : null;
2447
+ if (to === "queued")
2448
+ await scheduleTickets();
2449
+ return c.json({ ticket: db.getTicket(id) ?? moved, worktree, run });
2450
+ });
2451
+ // Static app. index.html is served without the token: a page navigation
2452
+ // can't carry a header, and the app strips `?t=` from the URL on first load,
2453
+ // so gating the document turns every reload into a 401 wall. The document
2454
+ // holds no data; every /api/* call below still requires the token.
2455
+ if (webRoot) {
2456
+ app.get("/", async (c) => {
2457
+ const html = await readFile(join(webRoot, "index.html"), "utf8");
2458
+ return c.html(html);
2459
+ });
2460
+ app.get("/assets/*", async (c) => {
2461
+ const path = c.req.path.replace(/^\/+/, "");
2462
+ const file = await readFileSafe(join(webRoot, path));
2463
+ if (!file)
2464
+ return c.notFound();
2465
+ return c.body(file.body, 200, { "content-type": file.type });
2466
+ });
2467
+ // The manifest and icon set are part of the built document. The Mac is
2468
+ // plain http, so it never registers sw.js, but serving the file keeps the
2469
+ // build-inspection path honest and avoids a 404 from a stray tab.
2470
+ for (const path of ["/manifest.webmanifest", "/sw.js", "/icons/*"]) {
2471
+ app.get(path, async (c) => {
2472
+ const file = await readFileSafe(join(webRoot, c.req.path.replace(/^\/+/, "")));
2473
+ if (!file)
2474
+ return c.notFound();
2475
+ return c.body(file.body, 200, { "content-type": file.type });
2476
+ });
2477
+ }
2478
+ }
2479
+ return app;
2480
+ }
2481
+ const TYPES = {
2482
+ js: "text/javascript; charset=utf-8",
2483
+ css: "text/css; charset=utf-8",
2484
+ svg: "image/svg+xml",
2485
+ png: "image/png",
2486
+ woff2: "font/woff2",
2487
+ webmanifest: "application/manifest+json",
2488
+ };
2489
+ async function readFileSafe(path) {
2490
+ // Reject traversal before touching the disk.
2491
+ if (path.includes(".."))
2492
+ return null;
2493
+ try {
2494
+ const buffer = await readFile(path);
2495
+ const ext = path.split(".").pop() ?? "";
2496
+ const bytes = new Uint8Array(buffer);
2497
+ return { body: bytes.buffer, type: TYPES[ext] ?? "application/octet-stream" };
2498
+ }
2499
+ catch {
2500
+ return null;
2501
+ }
2502
+ }
2503
+ //# sourceMappingURL=app.js.map