zelio-cli 0.1.0-beta.1 → 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 (137) hide show
  1. package/README.md +41 -148
  2. package/dist/cli-main.js +521 -0
  3. package/dist/cli-main.js.map +1 -0
  4. package/dist/cli.js +17 -464
  5. package/dist/cli.js.map +1 -1
  6. package/dist/cloud/account.js +109 -0
  7. package/dist/cloud/account.js.map +1 -0
  8. package/dist/cloud/command.js +7 -2
  9. package/dist/cloud/command.js.map +1 -1
  10. package/dist/cloud/login.js +2 -1
  11. package/dist/cloud/login.js.map +1 -1
  12. package/dist/cloud/push-nudge.js +5 -3
  13. package/dist/cloud/push-nudge.js.map +1 -1
  14. package/dist/cloud/relay.js +5 -0
  15. package/dist/cloud/relay.js.map +1 -1
  16. package/dist/cloud/tunnel.js +65 -1
  17. package/dist/cloud/tunnel.js.map +1 -1
  18. package/dist/db/db.js +381 -157
  19. package/dist/db/db.js.map +1 -1
  20. package/dist/db/lifecycle.js +18 -5
  21. package/dist/db/lifecycle.js.map +1 -1
  22. package/dist/limits.js +1 -1
  23. package/dist/orchestrator/area-notes.js +87 -0
  24. package/dist/orchestrator/area-notes.js.map +1 -0
  25. package/dist/orchestrator/codex-session.js +10 -9
  26. package/dist/orchestrator/codex-session.js.map +1 -1
  27. package/dist/orchestrator/contract.js +30 -22
  28. package/dist/orchestrator/contract.js.map +1 -1
  29. package/dist/orchestrator/new-task-prompt.js +4 -4
  30. package/dist/orchestrator/pi-session.js +6 -0
  31. package/dist/orchestrator/pi-session.js.map +1 -1
  32. package/dist/orchestrator/prompt.js +4 -4
  33. package/dist/orchestrator/research.js +28 -13
  34. package/dist/orchestrator/research.js.map +1 -1
  35. package/dist/orchestrator/retrieval.js +333 -0
  36. package/dist/orchestrator/retrieval.js.map +1 -0
  37. package/dist/orchestrator/runtime.js +199 -36
  38. package/dist/orchestrator/runtime.js.map +1 -1
  39. package/dist/repo/code-map.js +152 -0
  40. package/dist/repo/code-map.js.map +1 -0
  41. package/dist/repo/instructions.js +9 -3
  42. package/dist/repo/instructions.js.map +1 -1
  43. package/dist/repo/linked-boards.js +20 -123
  44. package/dist/repo/linked-boards.js.map +1 -1
  45. package/dist/repo/project-repos.js +78 -0
  46. package/dist/repo/project-repos.js.map +1 -0
  47. package/dist/run/actions.js +24 -0
  48. package/dist/run/actions.js.map +1 -1
  49. package/dist/run/auto-review.js +116 -0
  50. package/dist/run/auto-review.js.map +1 -0
  51. package/dist/run/claude-runtime.js +54 -12
  52. package/dist/run/claude-runtime.js.map +1 -1
  53. package/dist/run/codex-client.js +17 -4
  54. package/dist/run/codex-client.js.map +1 -1
  55. package/dist/run/codex-planner-config.js +26 -0
  56. package/dist/run/codex-planner-config.js.map +1 -0
  57. package/dist/run/codex-runtime.js +200 -97
  58. package/dist/run/codex-runtime.js.map +1 -1
  59. package/dist/run/consult.js +109 -0
  60. package/dist/run/consult.js.map +1 -0
  61. package/dist/run/developer-sandbox.js +67 -0
  62. package/dist/run/developer-sandbox.js.map +1 -0
  63. package/dist/run/diff.js +42 -0
  64. package/dist/run/diff.js.map +1 -1
  65. package/dist/run/finish.js +53 -16
  66. package/dist/run/finish.js.map +1 -1
  67. package/dist/run/handoff.js +51 -0
  68. package/dist/run/handoff.js.map +1 -0
  69. package/dist/run/harness-runtime.js +4 -1
  70. package/dist/run/harness-runtime.js.map +1 -1
  71. package/dist/run/harnesses.js +20 -0
  72. package/dist/run/harnesses.js.map +1 -1
  73. package/dist/run/lead.js +65 -82
  74. package/dist/run/lead.js.map +1 -1
  75. package/dist/run/manager.js +1096 -68
  76. package/dist/run/manager.js.map +1 -1
  77. package/dist/run/merge-watch.js +48 -17
  78. package/dist/run/merge-watch.js.map +1 -1
  79. package/dist/run/pi-packages.js +72 -0
  80. package/dist/run/pi-packages.js.map +1 -0
  81. package/dist/run/pi-rpc.js +61 -9
  82. package/dist/run/pi-rpc.js.map +1 -1
  83. package/dist/run/piped-check.js +56 -0
  84. package/dist/run/piped-check.js.map +1 -0
  85. package/dist/run/pr-checks.js +67 -0
  86. package/dist/run/pr-checks.js.map +1 -0
  87. package/dist/run/prompt.js +64 -4
  88. package/dist/run/prompt.js.map +1 -1
  89. package/dist/run/red-check.js +130 -0
  90. package/dist/run/red-check.js.map +1 -0
  91. package/dist/run/retro.js +2 -2
  92. package/dist/run/retro.js.map +1 -1
  93. package/dist/run/settings.js +5 -2
  94. package/dist/run/settings.js.map +1 -1
  95. package/dist/run/skills.js +146 -0
  96. package/dist/run/skills.js.map +1 -0
  97. package/dist/run/tests-first.js +146 -0
  98. package/dist/run/tests-first.js.map +1 -0
  99. package/dist/run/watchdog.js +266 -0
  100. package/dist/run/watchdog.js.map +1 -0
  101. package/dist/run/workflow.js +17 -6
  102. package/dist/run/workflow.js.map +1 -1
  103. package/dist/server/app.js +1083 -300
  104. package/dist/server/app.js.map +1 -1
  105. package/dist/server/principal.js +5 -2
  106. package/dist/server/principal.js.map +1 -1
  107. package/dist/server/provider-auth.js +206 -0
  108. package/dist/server/provider-auth.js.map +1 -0
  109. package/dist/server/repo-picker.js +18 -0
  110. package/dist/server/repo-picker.js.map +1 -0
  111. package/dist/server/terminal.js +2 -2
  112. package/dist/server/terminal.js.map +1 -1
  113. package/dist/setup/config.js +0 -31
  114. package/dist/setup/config.js.map +1 -1
  115. package/dist/setup/ink-ui.js +1 -0
  116. package/dist/setup/ink-ui.js.map +1 -1
  117. package/dist/setup/onboarding.js +12 -38
  118. package/dist/setup/onboarding.js.map +1 -1
  119. package/dist/setup/run.js +4 -5
  120. package/dist/setup/run.js.map +1 -1
  121. package/dist/skills.js +151 -0
  122. package/dist/skills.js.map +1 -0
  123. package/dist/ticket-cli.js +41 -0
  124. package/dist/ticket-cli.js.map +1 -1
  125. package/dist/version.js +13 -0
  126. package/dist/version.js.map +1 -0
  127. package/dist/web/assets/index-TN5sUF2z.css +1 -0
  128. package/dist/web/assets/index-vB3Cucuc.js +258 -0
  129. package/dist/web/index.html +2 -2
  130. package/dist/web/sw.js +3 -1
  131. package/media/board.png +0 -0
  132. package/media/mobile.png +0 -0
  133. package/media/new-task.png +0 -0
  134. package/media/review.png +0 -0
  135. package/package.json +16 -7
  136. package/dist/web/assets/index-ChuS3qKc.js +0 -254
  137. package/dist/web/assets/index-DR6WkmzI.css +0 -1
@@ -1,20 +1,31 @@
1
1
  import { Hono } from "hono";
2
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";
3
6
  import { existsSync } from "node:fs";
4
7
  import { readFile } from "node:fs/promises";
5
- import { join } from "node:path";
8
+ import { basename, join } from "node:path";
6
9
  import QRCode from "qrcode";
7
10
  import { normaliseVerify, } from "../db/db.js";
11
+ import { checkSkillName, checkSkillText, fetchSkillText, githubSkillLink } from "../skills.js";
8
12
  import { AttachmentError, absoluteAttachments, attachmentPaths, deleteAttachments, imageMime, readAttachmentImages, saveAttachment, sniffImage, } from "../attachments.js";
9
13
  import { MAX_IMAGE_BYTES, MAX_MESSAGE_CHARS, PLAN_TURN_DEADLINE_MS } from "../limits.js";
10
14
  import { newTaskTurns, summariseTurns } from "../metrics.js";
15
+ import { ProviderKeyError, ProviderSignIns, SignInBusyError, isKeyId, isSignInId, saveProviderKey, } from "./provider-auth.js";
11
16
  import { TransitionError, canTransition, checkSpec, describeRefusal, reviewEvidence, } from "../db/lifecycle.js";
12
- import { MAX_CARDS, MAX_QUESTIONS, OrchestratorError, EMPTY_TURN_STATS, INTAKE_THINKING_CAP, assignIds, fallbackHandoff, normaliseCard, normaliseQuestions, runOrchestrator, summarizeConversation, } from "../orchestrator/runtime.js";
13
- import { linkedBoardQuestion, runResearch, taskResearchQuestions, } from "../orchestrator/research.js";
14
- import { fileOnLinkedBoard, LinkedBoardError } from "../repo/linked-boards.js";
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";
15
25
  import { buildIndex, readHead, readRepoName, renderBrief } from "../repo/index.js";
16
26
  import { RunAlreadyActiveError, RunManager, } from "../run/manager.js";
17
27
  import { MergeWatcher } from "../run/merge-watch.js";
28
+ import { readPullRequestChecks } from "../run/pr-checks.js";
18
29
  import { normaliseRunResult } from "../run/result.js";
19
30
  import { mergeBlockReason, mergePullRequest, readMergeOptions, readPullRequestSnapshot, } from "../run/pr-merge.js";
20
31
  import { parseUnifiedDiff } from "../run/diff.js";
@@ -22,11 +33,15 @@ import { pullRequestUrlIn } from "../run/pull-request.js";
22
33
  import { createIssue, prepareIssue } from "../run/issue.js";
23
34
  import { hasMentionInstruction, mentionedProfiles } from "../run/mentions.js";
24
35
  import { HarnessRuntime } from "../run/harness-runtime.js";
36
+ import { handoffBrief, handoffCommand, handoffHarness, shellQuote } from "../run/handoff.js";
25
37
  import { consultLead } from "../run/lead.js";
26
- import { buildCommentPrompt, buildConflictPrompt, buildReviewPrompt, COMMENT_AGENT_PROMPT, CONFLICT_AGENT_PROMPT, REVIEW_AGENT_PROMPT, VERIFIED_CODING_AGENT_PROMPT, } from "../run/prompt.js";
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";
27
41
  import { listCodexModels } from "../run/codex-client.js";
28
- import { listHarnessModels } from "../run/harnesses.js";
42
+ import { HARNESSES, checkHarnessAuth, checkPiModelAuth, detectHarnesses, installHarness, listHarnessModels, modelFitsHarness, } from "../run/harnesses.js";
29
43
  import { profileFor } from "../run/profiles.js";
44
+ import { readSkills, skillBriefs, skillStoreOf } from "../run/skills.js";
30
45
  import { asMaxAgents, asPlannerThinking } from "../run/settings.js";
31
46
  import { capThinking, parseThinkingLevel, THINKING_LEVELS, } from "../run/thinking.js";
32
47
  import { WORKFLOW_STAGES, isWorkflowStage, normaliseWorkflow, } from "../run/workflow.js";
@@ -40,6 +55,8 @@ import { capabilitiesFor } from "./principal.js";
40
55
  import { MAX_TERMINAL_COLS, MAX_TERMINAL_ROWS, MIN_TERMINAL_COLS, MIN_TERMINAL_ROWS, NoSuchTerminalError, TerminalExitedError, TerminalLimitError, TerminalManager, } from "./terminal.js";
41
56
  /** How long a settled reading waits for its answer turn before it is dropped. */
42
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;
43
60
  const BOARD_COLUMNS = ["todo", "in_progress", "blocked", "review", "done"];
44
61
  /** Only strings survive into the database; anything else becomes an empty spec field. */
45
62
  const asText = (value) => (typeof value === "string" ? value.trim() : "");
@@ -72,6 +89,13 @@ function turnRefusal(c, cause) {
72
89
  }
73
90
  throw cause;
74
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
+ }
75
99
  /**
76
100
  * The bottom panel's shells are local only: a pseudoterminal is a shell on the
77
101
  * Mac, so the tunnel allowlist does not carry these routes, and the routes
@@ -116,6 +140,12 @@ class UnknownConversationError extends Error {
116
140
  }
117
141
  }
118
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;
119
149
  /** Answers as they arrive from the panel: anything unreadable is simply not an answer. */
120
150
  function asAnswers(value) {
121
151
  if (!Array.isArray(value))
@@ -149,6 +179,8 @@ function asThinking(value) {
149
179
  * at. The model sees the same lines in their turn, but the cards get the record
150
180
  * from here, because a model that forgets is exactly what this avoids.
151
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:";
152
184
  function resolveAnswers(previous, answers) {
153
185
  const lines = [];
154
186
  const decided = [];
@@ -167,61 +199,13 @@ function resolveAnswers(previous, answers) {
167
199
  return EMPTY_ANSWERS;
168
200
  return {
169
201
  decided: [...new Set(decided)],
170
- block: `Answers to your questions:\n${lines.join("\n")}`,
171
- };
172
- }
173
- /** The board's own question about a linked board, so its answer is never a model's paraphrase. */
174
- const BOARD_QUESTION = "board-";
175
- /** More than two other repositories in one task is a project, not a card set. */
176
- const MAX_BOARD_QUESTIONS = 2;
177
- function boardQuestion(board) {
178
- const about = board.description ? ` (${board.description})` : "";
179
- return {
180
- id: `${BOARD_QUESTION}${board.name}`,
181
- text: `This also looks like it needs a change in ${board.name}${about}. Include a card for the ${board.name} board?`,
182
- derived: false,
183
- options: [
184
- {
185
- id: "include",
186
- label: `Include ${board.name}`,
187
- cost: `adds a card that runs on the ${board.name} board, in that repository`,
188
- recommended: true,
189
- },
190
- {
191
- id: "skip",
192
- label: "This repo only",
193
- cost: `the ${board.name} part is named in the reply, not carded`,
194
- recommended: false,
195
- },
196
- ],
202
+ block: `${ANSWERS_HEADING}\n${lines.join("\n")}`,
197
203
  };
198
204
  }
199
205
  /** What the planner is told about a linked board: no port, no liveness. */
200
206
  function briefOf(board) {
201
207
  return { name: board.name, root: board.root, description: board.description };
202
208
  }
203
- /**
204
- * The linked boards the person agreed to: the ones already on the draft, plus
205
- * a "yes" to the board's own question in this turn, minus a "no". A board that
206
- * left the registry is no longer one the work can be filed on.
207
- */
208
- function includedBoards(previous, answers, known) {
209
- const included = new Set((previous?.boards ?? []).filter((name) => known.has(name)));
210
- for (const answer of answers) {
211
- if (!answer.questionId.startsWith(BOARD_QUESTION))
212
- continue;
213
- if (!previous?.questions.some((question) => question.id === answer.questionId))
214
- continue;
215
- const name = answer.questionId.slice(BOARD_QUESTION.length);
216
- if (!known.has(name))
217
- continue;
218
- if (answer.optionId === "include")
219
- included.add(name);
220
- else if (answer.optionId === "skip")
221
- included.delete(name);
222
- }
223
- return [...included];
224
- }
225
209
  /** A decision was made about the plan in front of the person, so it lands on its cards. */
226
210
  function applyDecided(cards, decided) {
227
211
  const out = [];
@@ -234,23 +218,26 @@ function applyDecided(cards, decided) {
234
218
  }
235
219
  return out;
236
220
  }
237
- export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize, harness, setup, listModels, plannerThinking, plannerToolBudget, summaryTimeoutMs, runtime, runTimeoutMs, retro, lead, leadEnabled, research, researchEnabled, maxRunning, prepare, prepareTicket, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, mergePollMs, index: indexOverride, indexOnStart, onRunsChange, voice: voiceOverride, build: buildOption, phone, terminals: terminalOverride, onLiveChange, linkedBoards: listLinked, boardFetch, }) {
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 }, }) {
238
222
  const app = new Hono();
239
223
  const auth = createAuth({ token, port });
240
224
  const idempotency = createIdempotency(db);
241
225
  const build = buildOption?.trim() || process.env.ZELIO_BUILD_HASH?.trim() || "dev";
242
226
  const voice = voiceOverride ?? createVoice();
243
227
  const root = repoRoot ?? process.cwd();
244
- const setupStore = setup ?? memorySetupStore({ harness: "pi", modelChosen: true });
228
+ const skills = skillStore ?? skillStoreOf(db);
229
+ const setupStore = setup ?? memorySetupStore({ harness: "pi" });
245
230
  const effectiveHarness = () => harness?.trim() || process.env.ZELIO_HARNESS?.trim() || setupStore.read().harness || "pi";
246
- const effectivePlannerModel = () => {
247
- const saved = setupStore.read();
248
- return effectiveHarness() === saved.harness ? saved.plannerModel : "";
249
- };
250
- const effectiveDeveloperModel = () => {
251
- const saved = setupStore.read();
252
- return effectiveHarness() === saved.harness ? saved.developerModel : "";
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() : "";
253
239
  };
240
+ const effectivePlannerModel = () => plannerModelFor(boardPlannerHarness());
254
241
  // The bottom panel's shells live in the repo root, never in a worktree.
255
242
  const terminals = terminalOverride ?? new TerminalManager({ root });
256
243
  // Config, not a constant: the person can raise the ceiling while the board
@@ -259,6 +246,19 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
259
246
  // Likewise for the planner: a CLI flag beats the saved choice; the saved
260
247
  // choice beats the runtime's env/default.
261
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
262
  const prepareOverride = prepare ?? prepareTicket;
263
263
  // One planning run at a time. Two in flight would cost twice and race on
264
264
  // creating the same cards.
@@ -316,26 +316,111 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
316
316
  // `researchEnabled`; otherwise an intake never has research to start.
317
317
  const researchRunner = research ??
318
318
  (researchEnabled
319
- ? (questions, onFinding) => runResearch(questions, {
319
+ ? (questions, onFinding, choice) => runResearch(questions, {
320
320
  runtime: agentRuntime,
321
321
  cwd: root,
322
322
  cwdFor: (name) => linkedBoards().find((board) => board.name === name)?.root,
323
- command: effectiveHarness(),
324
- model: effectiveDeveloperModel() || undefined,
323
+ command: choice?.command || effectiveHarness(),
324
+ model: choice ? choice.model || undefined : undefined,
325
325
  onFinding,
326
326
  })
327
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
+ ];
328
413
  // Readings started by an intake, keyed by the conversation they belong to. The
329
414
  // answer turn takes its own; a reading nobody asks for is dropped after a while.
330
415
  const pendingResearch = new Map();
331
- const startResearch = (conversationId, questions) => {
332
- if (!researchRunner || questions.length === 0)
333
- return undefined;
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) => {
334
418
  const startedAt = Date.now();
335
419
  const reading = {
336
420
  promise: Promise.resolve([]),
337
421
  done: 0,
338
- total: questions.length,
422
+ total,
423
+ choice,
339
424
  };
340
425
  // One row per reading, like a planner turn. It never throws.
341
426
  const record = (ok, error) => {
@@ -356,7 +441,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
356
441
  capped: null,
357
442
  prompt_chars: 0,
358
443
  output_chars: 0,
359
- questions: questions.length,
444
+ questions: total,
360
445
  cards: 0,
361
446
  started_at: new Date(startedAt).toISOString(),
362
447
  });
@@ -365,7 +450,9 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
365
450
  // The log is diagnostics only.
366
451
  }
367
452
  };
368
- reading.promise = runReading(reading, questions).then((findings) => {
453
+ reading.promise = Promise.resolve()
454
+ .then(() => read(reading))
455
+ .then((findings) => {
369
456
  record(true, null);
370
457
  return findings;
371
458
  }, (cause) => {
@@ -383,23 +470,39 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
383
470
  });
384
471
  return reading;
385
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;
386
489
  /** One batch of scouts on a reading; `done` counts across every batch it has. */
387
490
  function runReading(reading, questions) {
388
491
  return Promise.resolve().then(() => researchRunner(questions, () => {
389
492
  reading.done += 1;
390
493
  reading.listener?.(reading.done, reading.total);
391
- }));
494
+ }, reading.choice));
392
495
  }
393
496
  /**
394
497
  * Adds scouts to a reading already under way, for the linked boards the
395
498
  * intake named. The answer turn waits for both batches as one reading.
396
499
  */
397
- const extendResearch = (conversationId, questions) => {
500
+ const extendResearch = (conversationId, questions, choice) => {
398
501
  if (!researchRunner || questions.length === 0)
399
502
  return;
400
503
  const reading = pendingResearch.get(conversationId);
401
504
  if (!reading) {
402
- startResearch(conversationId, questions);
505
+ startResearch(conversationId, questions, choice);
403
506
  return;
404
507
  }
405
508
  reading.total += questions.length;
@@ -409,10 +512,19 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
409
512
  ...second,
410
513
  ]);
411
514
  };
412
- /** Other boards, never throwing: a broken registry is no linked boards. */
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
+ */
413
519
  function linkedBoards() {
414
520
  try {
415
- return listLinked?.() ?? [];
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
+ }));
416
528
  }
417
529
  catch {
418
530
  return [];
@@ -432,20 +544,53 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
432
544
  };
433
545
  const leadConsultant = lead ??
434
546
  (leadEnabled
435
- ? (input) => consultLead(input, {
436
- runtime: agentRuntime,
437
- command: effectiveHarness(),
438
- model: effectivePlannerModel() || undefined,
439
- })
547
+ ? (input) => consultLead(input, { runtime: agentRuntime, ...plannerSetup() })
548
+ : undefined);
549
+ const watchdogConsultant = watchdog ??
550
+ (watchdogEnabled
551
+ ? (input) => consultWatchdog(input, { runtime: agentRuntime, ...plannerSetup() })
440
552
  : undefined);
441
- const runs = new RunManager(db, agentRuntime, publishRun, `http://127.0.0.1:${port}`, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, root, retro, () => ({ harness: effectiveHarness(), model: effectiveDeveloperModel() }), leadConsultant);
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);
442
587
  /**
443
588
  * The ticket's checkout, with its branch recorded on the row the first time.
444
589
  * Every path that starts work goes through here: a branch that exists on disk
445
590
  * but not on the card is a fact the drawer and the review cannot see.
446
591
  */
447
592
  async function checkoutFor(ticket) {
448
- const worktree = await ensureWorktree(root, ticket.id, ticket.title, ticket.branch);
593
+ const worktree = await ensureWorktree(rootFor(ticket), ticket.id, ticket.title, ticket.branch);
449
594
  if (!ticket.branch)
450
595
  db.setBranch(ticket.id, worktree.branch);
451
596
  return worktree;
@@ -472,6 +617,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
472
617
  const mergeWatcher = new MergeWatcher({
473
618
  db,
474
619
  root,
620
+ rootFor,
475
621
  ghCommand,
476
622
  intervalMs: mergePollMs,
477
623
  onMergeabilityChange: () => {
@@ -497,7 +643,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
497
643
  return null;
498
644
  let status;
499
645
  try {
500
- status = runs.start(current, worktree, 1, {
646
+ status = await runs.begin(current, worktree, 1, {
501
647
  prompt: buildConflictPrompt(current, {
502
648
  branch: conflict.baseBranch,
503
649
  baseRefOid: conflict.baseRefOid,
@@ -536,6 +682,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
536
682
  acceptance: ticket.acceptance,
537
683
  likely_files: [...ticket.likely_files],
538
684
  context: [...(ticket.context ?? [])],
685
+ plan: ticket.plan ?? undefined,
539
686
  verify: [...ticket.verify],
540
687
  rationale: "",
541
688
  assumed: [],
@@ -552,6 +699,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
552
699
  ...(typeof value.acceptance === "string" ? { acceptance: value.acceptance } : {}),
553
700
  ...(Array.isArray(value.likely_files) ? { likely_files: value.likely_files } : {}),
554
701
  ...(Array.isArray(value.context) ? { context: value.context } : {}),
702
+ ...(typeof value.plan === "string" ? { plan: value.plan } : {}),
555
703
  // Only a non-empty list is carried. The prepare pass hands back a card that
556
704
  // always has a verify array (an omitted one reads as []), so an empty one
557
705
  // here means "not said", and a prepare pass must not wipe checks a person set.
@@ -565,8 +713,34 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
565
713
  * pass fills them; a failed pass leaves the ticket in Todo with the reason on
566
714
  * it, so the next allocation pass can try again instead of losing the card.
567
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
+ }
568
741
  async function runPrepare(ticket) {
569
742
  const missing = checkSpec(ticket).missing;
743
+ const planned = [];
570
744
  try {
571
745
  const filled = prepareOverride
572
746
  ? await prepareOverride(ticket, missing)
@@ -575,12 +749,21 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
575
749
  const requested = missing.length
576
750
  ? missing.join(", ")
577
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
+ }
578
757
  const prepared = await runPlan([
579
758
  {
580
759
  role: "user",
581
760
  content: `(prepare) The ticket below was captured with Quick and is parked in Todo ` +
582
- `until its spec is complete. Fill ${requested}. Keep the person's existing ` +
583
- `wording and add only what is missing: an outcome in the goal, a real ` +
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 ` +
584
767
  `exclusion in out_of_scope, checkable acceptance (including a failure case), ` +
585
768
  `and likely files read from the repo. Return the complete card, same id.\n\n` +
586
769
  `${ticket.title}\n${ticket.goal}\n${ticket.out_of_scope}\n` +
@@ -591,7 +774,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
591
774
  id: item.id,
592
775
  title: item.title,
593
776
  state: item.state,
594
- })), undefined, null, "new-task");
777
+ })), undefined, null, "new-task", undefined, undefined, undefined, undefined, undefined, undefined, undefined, choice.model, choice.command);
778
+ planned.push(...prepared.cards);
595
779
  return (prepared.cards.find((card) => card.id === ticket.id) ?? prepared.cards[0] ?? null);
596
780
  })();
597
781
  const next = db.updateSpec(ticket.id, fieldsOf(filled));
@@ -601,6 +785,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
601
785
  if (!check.ok) {
602
786
  throw new Error(`spec is still incomplete: ${check.missing.join(", ")}`);
603
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();
604
795
  return next;
605
796
  }
606
797
  catch (cause) {
@@ -645,7 +836,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
645
836
  if (!current || current.state !== "queued")
646
837
  continue;
647
838
  const started = db.transition(ticket.id, "in_progress");
648
- runs.start(started, worktree);
839
+ // oxlint-disable-next-line no-await-in-loop
840
+ await runs.begin(started, worktree);
649
841
  }
650
842
  catch {
651
843
  // A ticket that cannot get a worktree stays queued rather than wearing
@@ -726,11 +918,14 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
726
918
  return;
727
919
  }
728
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;
729
923
  const job = {
730
924
  prompt: reviewer
731
925
  ? buildReviewPrompt(ticket, comment, latestPullRequestUrl(ticket.id), absoluteAttachments(root, ticket.attachments))
732
926
  : buildCommentPrompt(ticket, comment, absoluteAttachments(root, ticket.attachments)),
733
927
  profile: profile.name,
928
+ ...(reviewerSetup ? { ...reviewerSetup, model: reviewerSetup.model ?? "" } : {}),
734
929
  // A verified ticket's developer never commits or reports Review: the board
735
930
  // checks and publishes, so its comment runs get the verified doctrine.
736
931
  systemPrompt: reviewer
@@ -745,10 +940,12 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
745
940
  retry: !reviewer,
746
941
  source: "comment",
747
942
  sourceCommentId: comment.id,
943
+ // A send-back asks for a change; the reviewer only reads.
944
+ expectsChange: !reviewer,
748
945
  };
749
946
  let status;
750
947
  try {
751
- status = runs.start(ticket, worktree, 1, job);
948
+ status = await runs.begin(ticket, worktree, 1, job);
752
949
  }
753
950
  catch (cause) {
754
951
  note(`@${name} could not start: ${cause instanceof Error ? cause.message : "the run was refused"}`);
@@ -792,33 +989,85 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
792
989
  });
793
990
  return scheduling;
794
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
+ };
795
1036
  const runPlan = plan ??
796
- ((messages, brief, draft, board, onStatus, handoff, mode, onStats, attachments = [], images = [], thinking, findings, timeoutMs, linked) => runOrchestrator({
797
- repoRoot: root,
798
- messages,
799
- brief,
800
- plan: draft,
801
- board,
802
- handoff,
803
- // The door changes the directive. Dropping it here silently gave every
804
- // real turn the chat prompt while tests saw the new-task one.
805
- mode,
806
- attachments,
807
- images,
808
- command: effectiveHarness(),
809
- planner: createPlanner(effectiveHarness(), effectivePlannerModel()),
810
- model: effectivePlannerModel() || undefined,
811
- thinking: thinking ?? plannerThinkingForTurn(),
812
- budget: plannerToolBudget,
813
- // The planner and the run it writes for must agree on what "done" means;
814
- // otherwise every ticket it drafts asks for a check the run will skip.
815
- workflow: db.getStageWorkflow("in_progress"),
816
- onStatus,
817
- onStats,
818
- research: findings,
819
- timeoutMs,
820
- linkedBoards: linked,
821
- }));
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
+ });
822
1071
  // A test that injected the planner explicitly asked for no subprocess. Only
823
1072
  // an explicitly named harness (or a summary injection) opts back in.
824
1073
  const harnessNamed = harness !== undefined || process.env.ZELIO_HARNESS !== undefined;
@@ -833,8 +1082,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
833
1082
  plan: request.plan,
834
1083
  board: request.board,
835
1084
  priorSummary: request.priorSummary,
836
- command: effectiveHarness(),
837
- planner: createPlanner(effectiveHarness(), effectivePlannerModel()),
1085
+ command: boardPlannerHarness(),
1086
+ planner: createPlanner(boardPlannerHarness(), effectivePlannerModel()),
838
1087
  model: effectivePlannerModel() || undefined,
839
1088
  timeoutMs: summaryTimeoutMs,
840
1089
  thinking: plannerThinkingForTurn(),
@@ -931,36 +1180,70 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
931
1180
  * Board-scoped settings. They are read by the server on every allocation and
932
1181
  * planner turn, so a save takes effect without a restart.
933
1182
  */
934
- app.get("/api/settings", (c) => c.json({ settings: db.getBoardSettings() }));
935
- const setupResponse = () => ({
936
- ...setupStore.read(),
937
- effectiveHarness: effectiveHarness(),
938
- effectiveDeveloperModel: effectiveDeveloperModel(),
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
+ });
939
1204
  });
940
- app.get("/api/setup", (c) => c.json({ setup: setupResponse() }));
941
- app.put("/api/setup", async (c) => {
942
- const body = await c.req
943
- .json()
944
- .catch(() => ({}));
945
- const legacy = typeof body.model === "string" ? body.model.trim() : undefined;
946
- const plannerModel = typeof body.plannerModel === "string" ? body.plannerModel.trim() : legacy;
947
- const developerModel = typeof body.developerModel === "string" ? body.developerModel.trim() : legacy;
948
- if (plannerModel === undefined || developerModel === undefined) {
949
- return c.json({ error: "plannerModel and developerModel must be strings" }, 400);
950
- }
951
- if (plannerModel.length > 200 || developerModel.length > 200) {
952
- return c.json({ error: "model is too long" }, 400);
953
- }
954
- db.clearProfileRuntimeOverrides();
955
- setupStore.save({
956
- ...(legacy === undefined ? {} : { model: legacy }),
957
- plannerModel,
958
- developerModel,
959
- modelChosen: true,
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
+ },
960
1231
  });
961
- return c.json({ setup: setupResponse() });
962
1232
  });
963
- app.put("/api/settings", async (c) => {
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) => {
964
1247
  const body = await c.req
965
1248
  .json()
966
1249
  .catch(() => ({}));
@@ -977,9 +1260,41 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
977
1260
  return c.json({ error: "unknown thinking level" }, 400);
978
1261
  patch.plannerThinking = chosen;
979
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
+ }
980
1294
  if (Object.keys(patch).length === 0)
981
1295
  return c.json({ error: "nothing to save" }, 400);
982
- const settings = db.setBoardSettings(patch);
1296
+ db.setBoardSettings(patch);
1297
+ const settings = effectiveBoardSettings();
983
1298
  // Raising the cap should start queued work now, not at the next unrelated
984
1299
  // event. Lowering it never kills a run; it only stops new ones.
985
1300
  if (patch.maxAgents !== undefined)
@@ -1012,7 +1327,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1012
1327
  app.post("/api/tickets/:id/status", async (c) => {
1013
1328
  const id = c.req.param("id");
1014
1329
  const ticketToken = c.req.header("x-zelio-ticket-token") ?? "";
1015
- if (!runs.verifyStatusToken(id, ticketToken)) {
1330
+ if (!agentTokenOk(id, ticketToken)) {
1016
1331
  return c.json({ error: "invalid ticket token" }, 401);
1017
1332
  }
1018
1333
  const body = await c.req
@@ -1035,9 +1350,29 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1035
1350
  const ticket = db.getTicket(id);
1036
1351
  if (!ticket)
1037
1352
  return c.json({ error: "no such ticket" }, 404);
1038
- if (ticket.state !== "in_progress") {
1353
+ if (ticket.state !== "in_progress" && ticket.state !== "handed_off") {
1039
1354
  return c.json({ error: `ticket is ${ticket.state}` }, 409);
1040
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
+ }
1041
1376
  if (to === "review" && (ticket.verify ?? []).length > 0) {
1042
1377
  return c.json({
1043
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.",
@@ -1108,7 +1443,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1108
1443
  app.post("/api/tickets/:id/agent-comments", async (c) => {
1109
1444
  const id = c.req.param("id");
1110
1445
  const ticketToken = c.req.header("x-zelio-ticket-token") ?? "";
1111
- if (!runs.verifyStatusToken(id, ticketToken)) {
1446
+ if (!agentTokenOk(id, ticketToken)) {
1112
1447
  return c.json({ error: "invalid ticket token" }, 401);
1113
1448
  }
1114
1449
  const body = await c.req
@@ -1136,7 +1471,9 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1136
1471
  const ticket = db.getTicket(id);
1137
1472
  if (!ticket)
1138
1473
  return c.json({ error: "no such ticket" }, 404);
1139
- const identity = runs.activeIdentity(id);
1474
+ const identity = ticket.state === "handed_off"
1475
+ ? { profile: ticket.handoff?.harness ?? "agent", runId: null }
1476
+ : runs.activeIdentity(id);
1140
1477
  if (!identity)
1141
1478
  return c.json({ error: "the run has finished" }, 409);
1142
1479
  const comment = db.addComment({
@@ -1152,6 +1489,52 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1152
1489
  return c.json({ comment }, 201);
1153
1490
  });
1154
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
+ });
1155
1538
  /**
1156
1539
  * Who the caller is and what it may do. The phone uses this to hide controls
1157
1540
  * the tunnel allowlist would refuse anyway; the server stays the authority.
@@ -1166,8 +1549,21 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1166
1549
  build,
1167
1550
  });
1168
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
+ });
1169
1563
  /** Version skew: the phone compares this with the build in the tunnel hello. */
1170
- app.get("/api/version", (c) => c.json({ version: "1", protocol: 1, build }, 200, { "Cache-Control": "no-store" }));
1564
+ app.get("/api/version", (c) => c.json({ version: "1", protocol: 1, build, cliVersion }, 200, {
1565
+ "Cache-Control": "no-store",
1566
+ }));
1171
1567
  /**
1172
1568
  * The whole board in one read. `rev` is the persisted board revision; the
1173
1569
  * ETag adds the in-memory live counter so a turn or run status change also
@@ -1262,6 +1658,82 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1262
1658
  });
1263
1659
  /** Back to the seed rows. The only way an edited profile forgets its edits. */
1264
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
+ });
1265
1737
  /**
1266
1738
  * What a harness says it can run. Discovery is a suggestion for the model
1267
1739
  * field, never a gate: a harness that is missing, slow or broken returns an
@@ -1269,8 +1741,14 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1269
1741
  */
1270
1742
  app.get("/api/agent-models", async (c) => {
1271
1743
  const command = asText(c.req.query("harness")) || effectiveHarness();
1272
- const result = await (listModels ?? ((value) => listHarnessModels(value, { listCodex: listCodexModels })))(command);
1273
- return c.json({ harness: command, models: result.models, error: result.error });
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
+ });
1274
1752
  });
1275
1753
  /**
1276
1754
  * Standing instructions per stage. This is config, not board state: the
@@ -1284,29 +1762,6 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1284
1762
  ]));
1285
1763
  return c.json({ workflows });
1286
1764
  });
1287
- /**
1288
- * Pending manager proposals. They are evidence beside the workflow, never the
1289
- * workflow itself: the person applies one or refuses it, and either way the
1290
- * row keeps what was proposed.
1291
- */
1292
- app.get("/api/workflows/suggestions", (c) => {
1293
- const stage = c.req.query("stage") ?? "in_progress";
1294
- if (!isWorkflowStage(stage))
1295
- return c.json({ error: `no such stage: ${stage}` }, 400);
1296
- return c.json({ suggestions: db.listWorkflowSuggestions(stage) });
1297
- });
1298
- app.post("/api/workflows/suggestions/:id/apply", (c) => {
1299
- const applied = db.applyWorkflowSuggestion(c.req.param("id"));
1300
- if (!applied)
1301
- return c.json({ error: "no such pending suggestion" }, 404);
1302
- return c.json(applied);
1303
- });
1304
- app.post("/api/workflows/suggestions/:id/dismiss", (c) => {
1305
- const dismissed = db.dismissWorkflowSuggestion(c.req.param("id"));
1306
- if (!dismissed)
1307
- return c.json({ error: "no such pending suggestion" }, 404);
1308
- return c.json({ suggestion: dismissed });
1309
- });
1310
1765
  app.put("/api/workflows/:stage", async (c) => {
1311
1766
  const stage = c.req.param("stage");
1312
1767
  if (!isWorkflowStage(stage))
@@ -1385,6 +1840,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1385
1840
  run: db.latestAgentRun(ticket.id),
1386
1841
  });
1387
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
+ }
1388
1850
  /** Stop a live run and wait for its process before touching its worktree. */
1389
1851
  async function stopRun(ticketId, mode) {
1390
1852
  if (!runs.isRunning(ticketId))
@@ -1411,9 +1873,87 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1411
1873
  const removed = db.deleteTicket(id);
1412
1874
  if (!removed)
1413
1875
  return c.json({ error: "no such ticket" }, 404);
1414
- await retireWorktree(root, removed.id, removed.branch);
1876
+ const checkoutRoot = retireRootFor(removed);
1877
+ if (checkoutRoot)
1878
+ await retireWorktree(checkoutRoot, removed.id, removed.branch);
1415
1879
  return c.json({ ticket: removed });
1416
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
+ });
1417
1957
  app.get("/api/tickets/:id/diff", (c) => {
1418
1958
  const ticket = db.getTicket(c.req.param("id"));
1419
1959
  if (!ticket)
@@ -1580,12 +2120,16 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1580
2120
  });
1581
2121
  // Programmatic surface. The board has no creation UI in M1; the orchestrator
1582
2122
  // and the tests are the only callers.
1583
- /** What the person said in the conversation a card came from, as one line for the run. */
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
+ */
1584
2128
  const originalIntentOf = (conversationId) => {
1585
2129
  const conversation = typeof conversationId === "string" ? db.getConversation(conversationId) : null;
1586
2130
  return conversation?.messages
1587
2131
  .filter((message) => message.role === "user")
1588
- .map((message) => message.content.replace(/\s+/g, " ").trim())
2132
+ .map((message) => (message.content.split(ANSWERS_HEADING)[0] ?? "").replace(/\s+/g, " ").trim())
1589
2133
  .filter(Boolean)
1590
2134
  .join(" | ")
1591
2135
  .slice(0, 2_000);
@@ -1598,14 +2142,24 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1598
2142
  if (!attachments)
1599
2143
  return c.json({ error: "those screenshots are not the board's" }, 400);
1600
2144
  const draft = body;
1601
- // A card drafted for another repository must never run in this one.
1602
- if (typeof draft.board === "string" && draft.board.trim()) {
1603
- return c.json({ error: `that card belongs on the ${draft.board.trim()} board` }, 400);
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);
1604
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);
1605
2158
  const originalIntent = originalIntentOf(draft.conversationId);
2159
+ const goal = asText(body.goal);
1606
2160
  const ticket = db.createTicket({
1607
2161
  title: body.title.trim(),
1608
- goal: asText(body.goal),
2162
+ goal,
1609
2163
  out_of_scope: asText(body.out_of_scope),
1610
2164
  acceptance: asText(body.acceptance),
1611
2165
  attachments,
@@ -1613,11 +2167,16 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1613
2167
  likely_files: Array.isArray(body.likely_files)
1614
2168
  ? body.likely_files.filter((file) => typeof file === "string")
1615
2169
  : [],
2170
+ plan: typeof body.plan === "string" ? body.plan : null,
1616
2171
  context: [
1617
2172
  ...(Array.isArray(body.context)
1618
2173
  ? body.context.filter((line) => typeof line === "string")
1619
2174
  : []),
1620
- ...(originalIntent ? [`Original user intent: ${originalIntent}`] : []),
2175
+ ...(originalIntent
2176
+ ? [`Original user intent: ${originalIntent}`]
2177
+ : body.quick === true && goal
2178
+ ? [`Original user intent: ${goal}`]
2179
+ : []),
1621
2180
  ...["decided", "assumed"].flatMap((field) => {
1622
2181
  const values = draft[field];
1623
2182
  return Array.isArray(values)
@@ -1626,68 +2185,36 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1626
2185
  .map((line) => `Planner ${field === "decided" ? "decision" : "assumption"}: ${line}`)
1627
2186
  : [];
1628
2187
  }),
1629
- ...(typeof draft.rationale === "string" && draft.rationale.trim()
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()
1630
2191
  ? [`User intent: ${draft.rationale.trim()}`]
1631
2192
  : []),
1632
2193
  ],
2194
+ repo: named,
1633
2195
  quick: body.quick === true,
1634
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,
1635
2215
  });
1636
2216
  return c.json({ ticket }, 201);
1637
2217
  });
1638
- /** Other boards on this machine a new-task card can be filed on. */
1639
- app.get("/api/boards", (c) => c.json({
1640
- boards: linkedBoards().map((board) => ({
1641
- name: board.name,
1642
- root: board.root,
1643
- description: board.description,
1644
- running: board.running,
1645
- })),
1646
- }));
1647
- /**
1648
- * Files a confirmed card on a linked board: created and confirmed there,
1649
- * through that board's own API, so it runs in that repository under that
1650
- * board's allocator and rules. Nothing is written to this board.
1651
- */
1652
- app.post("/api/boards/:name/tickets", async (c) => {
1653
- const name = c.req.param("name");
1654
- const board = linkedBoards().find((item) => item.name === name);
1655
- if (!board)
1656
- return c.json({ error: `there is no linked board named ${name}` }, 404);
1657
- const body = await c.req
1658
- .json()
1659
- .catch(() => ({}));
1660
- const card = normaliseCard(body);
1661
- if (!card.title)
1662
- return c.json({ error: "title is required" }, 400);
1663
- const intent = originalIntentOf(body.conversationId);
1664
- const here = await ensureRepoName();
1665
- try {
1666
- const ticket = await fileOnLinkedBoard(board, {
1667
- title: card.title,
1668
- goal: card.goal,
1669
- out_of_scope: card.out_of_scope,
1670
- acceptance: card.acceptance,
1671
- likely_files: card.likely_files,
1672
- verify: card.verify ?? [],
1673
- context: [
1674
- ...(card.context ?? []),
1675
- `Drafted on the ${here} board's new-task dialog; companion work there is a separate ticket.`,
1676
- ...(intent ? [`Original user intent: ${intent}`] : []),
1677
- ],
1678
- rationale: card.rationale,
1679
- assumed: card.assumed,
1680
- decided: card.decided,
1681
- ...(card.thinking ? { thinking: card.thinking } : {}),
1682
- }, boardFetch);
1683
- return c.json({ ticket, board: board.name }, 201);
1684
- }
1685
- catch (cause) {
1686
- if (cause instanceof LinkedBoardError)
1687
- return c.json({ error: cause.message }, cause.status);
1688
- throw cause;
1689
- }
1690
- });
1691
2218
  /**
1692
2219
  * Run the parked-spec pass now. The allocator does this on its own; the route
1693
2220
  * exists for a person or a client that wants to retry without waiting for
@@ -1876,7 +2403,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1876
2403
  questions: outcome.questions ?? 0,
1877
2404
  cards: outcome.cards ?? 0,
1878
2405
  started_at: new Date(rowStartedAt).toISOString(),
1879
- });
2406
+ }, outcome.output ?? null);
1880
2407
  }
1881
2408
  catch {
1882
2409
  // The log is diagnostics; losing one row must never lose the turn.
@@ -1898,14 +2425,11 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1898
2425
  // answer turn takes its doctrine from the conversation it writes into.
1899
2426
  const mode = options.mode ?? (kind === "task" ? "new-task" : undefined);
1900
2427
  door = mode ?? null;
1901
- // Other repositories matter only to the new-task dialog. The intake hears
1902
- // about every candidate; the draft only about the ones the person said yes to.
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.
1903
2430
  const candidates = kind === "task" ? linkedBoards() : [];
1904
- const included = includedBoards(target.plan, options.answers ?? [], new Set(candidates.map((board) => board.name)));
1905
- const includedBriefs = candidates
1906
- .filter((board) => included.includes(board.name))
1907
- .map(briefOf);
1908
- // A scout that read a board the person turned down is not reading the draft gets.
2431
+ const included = candidates.map((repo) => repo.name);
2432
+ const repoBriefs = candidates.map(briefOf);
1909
2433
  const forDraft = (findings) => findings?.filter((finding) => !finding.board || included.includes(finding.board));
1910
2434
  // What the person chose travels in their own turn, so the planner reads it
1911
2435
  // and the cards are written from the same source below.
@@ -1967,8 +2491,18 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1967
2491
  else {
1968
2492
  conversation = db.appendMessage("user", said, "message", conversation.id);
1969
2493
  }
1970
- // Start scouts before the index and intake, using only the original description.
1971
- const intakeReading = mode === "intake" ? startResearch(conversation.id, taskResearchQuestions(text)) : undefined;
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;
1972
2506
  // Waiting here is usually free: the index is built at startup and the
1973
2507
  // head check is one git call. When it is not free — a first run, or a
1974
2508
  // checkout that just changed — the build is minutes of silence with no
@@ -1978,18 +2512,24 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1978
2512
  indexMs = Date.now() - indexStarted;
1979
2513
  const brief = index ? renderBrief(index) : "";
1980
2514
  // One planner run. Its stats are its own, so the row it writes is too.
1981
- const planOnce = (passMode, findings) => {
2515
+ const planOnce = async (passMode, findings) => {
1982
2516
  stats = EMPTY_TURN_STATS;
1983
2517
  // The intake decides, it does not read at length: its level is capped in
1984
2518
  // this one place so the injected test planner and the real one agree.
1985
2519
  const level = options.thinking ?? plannerThinkingForTurn();
1986
2520
  const passThinking = passMode === "intake" ? capThinking(level, INTAKE_THINKING_CAP) : level;
1987
- return runPlan(conversation.messages, brief, draft, board, publish, handoff, passMode, (measured) => {
2521
+ const planned = await runPlan(conversation.messages, brief, draft, board, publish, handoff, passMode, (measured) => {
1988
2522
  stats = measured;
1989
2523
  }, attachments, images, passThinking, findings,
1990
2524
  // What is left of the request, not a fresh clock per pass: the intake,
1991
2525
  // the scouts and the draft share one deadline, and the planner is told it.
1992
- Math.max(MIN_PASS_MS, PLAN_TURN_DEADLINE_MS - (Date.now() - startedAt)), passMode === "intake" ? candidates.map(briefOf) : includedBriefs);
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;
1993
2533
  };
1994
2534
  // Saves what the planner decided. Research is a planner input, not part of
1995
2535
  // the plan the dialog reads, so it is not stored.
@@ -1999,15 +2539,20 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1999
2539
  const assigned = assignIds(drafted, draft);
2000
2540
  // Clamped again here on purpose: a fifth question costs the person attention.
2001
2541
  const next = { ...assigned, questions: normaliseQuestions(assigned.questions) };
2002
- // A card for a board the person did not include would run where nobody
2003
- // agreed to it. It is dropped, and the reply says so.
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.
2004
2544
  const strays = next.cards.filter((card) => card.board && !included.includes(card.board));
2005
- const kept = next.cards.filter((card) => !card.board || included.includes(card.board));
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) });
2006
2551
  const cards = answered.decided.length > 0 ? applyDecided(kept, answered.decided) : kept;
2007
2552
  const reply = strays.length > 0
2008
2553
  ? `${next.reply} (Left out ${strays.length === 1 ? "a card" : `${strays.length} cards`} for ${[
2009
2554
  ...new Set(strays.map((card) => card.board)),
2010
- ].join(", ")}: that board was not included.)`.trim()
2555
+ ].join(", ")}: that repository is not on this board.)`.trim()
2011
2556
  : next.reply;
2012
2557
  // The assistant turn is the prose. Questions live in `plan` and are drawn as cards.
2013
2558
  if (reply)
@@ -2020,42 +2565,36 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2020
2565
  }, conversation.id);
2021
2566
  return { saved, questions: next.questions.length, cards: cards.length };
2022
2567
  };
2023
- // An answer turn in the wizard reads what its intake started, first.
2024
- let findings;
2025
- if (mode === "new-task") {
2026
- const reading = pendingResearch.get(target.id);
2027
- if (reading) {
2028
- pendingResearch.delete(target.id);
2029
- findings = forDraft(await awaitReading(reading));
2030
- }
2031
- }
2032
- let drafted = await planOnce(mode, findings);
2033
- if (mode === "intake") {
2034
- // The intake names boards; the board asks the person, in its own words,
2035
- // and a scout starts reading that repository while they decide.
2036
- const byName = new Map(candidates.map((linked) => [linked.name, linked]));
2037
- const suspected = [...new Set(drafted.boards ?? [])]
2038
- .map((name) => byName.get(name))
2039
- .filter((linked) => linked !== undefined)
2040
- .filter((linked) => !included.includes(linked.name))
2041
- .slice(0, MAX_BOARD_QUESTIONS);
2042
- if (suspected.length > 0) {
2043
- extendResearch(conversation.id, suspected.map((linked) => linkedBoardQuestion(linked.name, text)));
2044
- drafted = {
2045
- ...drafted,
2046
- questions: [
2047
- ...suspected.map(boardQuestion),
2048
- ...normaliseQuestions(drafted.questions),
2049
- ].slice(0, MAX_QUESTIONS),
2050
- };
2051
- }
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);
2052
2591
  }
2053
2592
  let outcome;
2054
- if (mode !== "intake") {
2593
+ if (pass !== "intake") {
2055
2594
  outcome = store(drafted);
2056
2595
  }
2057
2596
  else {
2058
- // Scouts have been running since the request arrived.
2597
+ // The reading has been running since the request arrived.
2059
2598
  if (normaliseQuestions(drafted.questions).length > 0) {
2060
2599
  outcome = store({ ...drafted, cards: [] });
2061
2600
  }
@@ -2063,8 +2602,10 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2063
2602
  // Nothing to ask and nothing drafted: the intake's row is recorded, then
2064
2603
  // the draft waits for the reading in this same request.
2065
2604
  measure({ ok: true });
2066
- pendingResearch.delete(conversation.id);
2067
- const readFirst = intakeReading ? forDraft(await awaitReading(intakeReading)) : undefined;
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;
2068
2609
  door = "new-task";
2069
2610
  rowStartedAt = Date.now();
2070
2611
  indexMs = 0;
@@ -2078,7 +2619,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2078
2619
  catch (cause) {
2079
2620
  // A failed turn is the most interesting row in the log: it is the only one
2080
2621
  // that says how long the person waited for nothing.
2081
- measure({ ok: false, error: describeError(cause) });
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
+ });
2082
2629
  throw cause;
2083
2630
  }
2084
2631
  finally {
@@ -2097,10 +2644,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2097
2644
  .catch(() => ({}));
2098
2645
  const text = typeof body.text === "string" ? body.text.trim() : "";
2099
2646
  const thinking = asThinking(body.thinking);
2647
+ const badHarness = unknownHarness(body.harness);
2100
2648
  if (!text)
2101
2649
  return c.json({ error: "text is required" }, 400);
2102
2650
  if (thinking === null)
2103
2651
  return c.json({ error: "unknown thinking level" }, 400);
2652
+ if (badHarness)
2653
+ return c.json({ error: `unknown harness: ${badHarness}` }, 400);
2104
2654
  if (text.length > MAX_MESSAGE_CHARS)
2105
2655
  return c.json({ error: "message too long" }, 400);
2106
2656
  const attachments = attachmentPaths(body.attachments);
@@ -2113,6 +2663,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2113
2663
  conversationId: asConversationId(body.conversationId),
2114
2664
  attachments,
2115
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,
2116
2668
  }),
2117
2669
  });
2118
2670
  }
@@ -2126,16 +2678,38 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2126
2678
  * the dialog and the turn comes back with questions and cards — so it carries
2127
2679
  * one message's cap rather than a title's.
2128
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
+ });
2129
2700
  app.post("/api/orchestrator/intent", async (c) => {
2130
2701
  const body = await c.req
2131
2702
  .json()
2132
2703
  .catch(() => ({}));
2133
2704
  const text = typeof body.text === "string" ? body.text.trim() : "";
2134
2705
  const thinking = asThinking(body.thinking);
2706
+ const badHarness = unknownHarness(body.harness);
2135
2707
  if (!text)
2136
2708
  return c.json({ error: "a description is required" }, 400);
2137
2709
  if (thinking === null)
2138
2710
  return c.json({ error: "unknown thinking level" }, 400);
2711
+ if (badHarness)
2712
+ return c.json({ error: `unknown harness: ${badHarness}` }, 400);
2139
2713
  if (text.length > MAX_MESSAGE_CHARS) {
2140
2714
  return c.json({ error: "that description is too long" }, 400);
2141
2715
  }
@@ -2154,6 +2728,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2154
2728
  conversationId: session.id,
2155
2729
  attachments,
2156
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,
2157
2733
  }),
2158
2734
  });
2159
2735
  }
@@ -2190,8 +2766,23 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2190
2766
  if (cards.some((card) => !known.has(card.id))) {
2191
2767
  return c.json({ error: "a card lost its id" }, 409);
2192
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 };
2193
2784
  return c.json({
2194
- conversation: db.setPlan({ ...conversation.plan, cards }, conversation.id),
2785
+ conversation: db.setPlan(filteredPlan, conversation.id),
2195
2786
  });
2196
2787
  });
2197
2788
  /** "New chat": a new row, so the old transcript can still be read later. */
@@ -2229,9 +2820,6 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2229
2820
  return c.json({ archived: archived.length });
2230
2821
  });
2231
2822
  app.get("/api/tickets/:id/merge", async (c) => {
2232
- if (c.get("principal").kind !== "local") {
2233
- return c.json({ error: "merging is available from the local board only" }, 403);
2234
- }
2235
2823
  const ticket = db.getTicket(c.req.param("id"));
2236
2824
  if (!ticket)
2237
2825
  return c.json({ error: "no such ticket" }, 404);
@@ -2242,7 +2830,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2242
2830
  if (!ticket.pr_url || !ticket.branch) {
2243
2831
  return c.json({ error: "ticket has no linked pull request and branch" }, 409);
2244
2832
  }
2245
- const checkout = worktreePath(root, ticket.id);
2833
+ const checkout = worktreePath(rootFor(ticket), ticket.id);
2246
2834
  if (!existsSync(join(checkout, ".git")))
2247
2835
  return c.json({ error: "ticket checkout is missing" }, 409);
2248
2836
  try {
@@ -2279,10 +2867,142 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2279
2867
  return c.json({ error: cause instanceof Error ? cause.message : "could not read pull request status" }, 502);
2280
2868
  }
2281
2869
  });
2282
- app.post("/api/tickets/:id/merge", async (c) => {
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) => {
2283
2914
  if (c.get("principal").kind !== "local") {
2284
- return c.json({ error: "merging is available from the local board only" }, 403);
2915
+ return c.json({ error: "checks are available from the local board only" }, 403);
2285
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) => {
2286
3006
  const ticket = db.getTicket(c.req.param("id"));
2287
3007
  if (!ticket)
2288
3008
  return c.json({ error: "no such ticket" }, 404);
@@ -2295,7 +3015,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2295
3015
  }
2296
3016
  if (mergeInFlight.has(ticket.id))
2297
3017
  return c.json({ error: "a merge is already in progress" }, 409);
2298
- const checkout = worktreePath(root, ticket.id);
3018
+ const checkout = worktreePath(rootFor(ticket), ticket.id);
2299
3019
  if (!existsSync(join(checkout, ".git")))
2300
3020
  return c.json({ error: "ticket checkout is missing" }, 409);
2301
3021
  const body = await c.req
@@ -2400,6 +3120,67 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2400
3120
  issueInFlight.delete(comment.id);
2401
3121
  }
2402
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
+ });
2403
3184
  app.post("/api/tickets/:id/transition", async (c) => {
2404
3185
  const body = await c.req
2405
3186
  .json()
@@ -2441,9 +3222,11 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2441
3222
  runs.settle(id);
2442
3223
  if (to === "done") {
2443
3224
  await stopRun(id, "settle");
2444
- await retireWorktree(root, id, moved.branch);
3225
+ const checkoutRoot = retireRootFor(moved);
3226
+ if (checkoutRoot)
3227
+ await retireWorktree(checkoutRoot, id, moved.branch);
2445
3228
  }
2446
- const run = to === "in_progress" && worktree ? runs.start(moved, worktree) : null;
3229
+ const run = to === "in_progress" && worktree ? await runs.begin(moved, worktree) : null;
2447
3230
  if (to === "queued")
2448
3231
  await scheduleTickets();
2449
3232
  return c.json({ ticket: db.getTicket(id) ?? moved, worktree, run });