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

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