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

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