zelio-cli 0.1.0-beta.1 → 0.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +9 -2
  2. package/dist/cli.js +34 -7
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cloud/command.js +23 -2
  5. package/dist/cloud/command.js.map +1 -1
  6. package/dist/cloud/push-nudge.js +5 -3
  7. package/dist/cloud/push-nudge.js.map +1 -1
  8. package/dist/cloud/relay.js +5 -0
  9. package/dist/cloud/relay.js.map +1 -1
  10. package/dist/cloud/tunnel.js +65 -1
  11. package/dist/cloud/tunnel.js.map +1 -1
  12. package/dist/db/db.js +273 -146
  13. package/dist/db/db.js.map +1 -1
  14. package/dist/db/lifecycle.js +18 -5
  15. package/dist/db/lifecycle.js.map +1 -1
  16. package/dist/orchestrator/contract.js +22 -19
  17. package/dist/orchestrator/contract.js.map +1 -1
  18. package/dist/orchestrator/research.js +1 -1
  19. package/dist/orchestrator/research.js.map +1 -1
  20. package/dist/orchestrator/runtime.js +180 -27
  21. package/dist/orchestrator/runtime.js.map +1 -1
  22. package/dist/repo/instructions.js +9 -3
  23. package/dist/repo/instructions.js.map +1 -1
  24. package/dist/repo/linked-boards.js +8 -123
  25. package/dist/repo/linked-boards.js.map +1 -1
  26. package/dist/repo/project-repos.js +78 -0
  27. package/dist/repo/project-repos.js.map +1 -0
  28. package/dist/run/actions.js +24 -0
  29. package/dist/run/actions.js.map +1 -1
  30. package/dist/run/auto-review.js +102 -0
  31. package/dist/run/auto-review.js.map +1 -0
  32. package/dist/run/claude-runtime.js +37 -9
  33. package/dist/run/claude-runtime.js.map +1 -1
  34. package/dist/run/codex-client.js +3 -1
  35. package/dist/run/codex-client.js.map +1 -1
  36. package/dist/run/codex-runtime.js +190 -96
  37. package/dist/run/codex-runtime.js.map +1 -1
  38. package/dist/run/consult.js +105 -0
  39. package/dist/run/consult.js.map +1 -0
  40. package/dist/run/diff.js +42 -0
  41. package/dist/run/diff.js.map +1 -1
  42. package/dist/run/finish.js +22 -7
  43. package/dist/run/finish.js.map +1 -1
  44. package/dist/run/handoff.js +51 -0
  45. package/dist/run/handoff.js.map +1 -0
  46. package/dist/run/harness-runtime.js +4 -1
  47. package/dist/run/harness-runtime.js.map +1 -1
  48. package/dist/run/lead.js +42 -83
  49. package/dist/run/lead.js.map +1 -1
  50. package/dist/run/manager.js +896 -59
  51. package/dist/run/manager.js.map +1 -1
  52. package/dist/run/merge-watch.js +48 -17
  53. package/dist/run/merge-watch.js.map +1 -1
  54. package/dist/run/pi-rpc.js +32 -5
  55. package/dist/run/pi-rpc.js.map +1 -1
  56. package/dist/run/piped-check.js +56 -0
  57. package/dist/run/piped-check.js.map +1 -0
  58. package/dist/run/pr-checks.js +67 -0
  59. package/dist/run/pr-checks.js.map +1 -0
  60. package/dist/run/prompt.js +45 -2
  61. package/dist/run/prompt.js.map +1 -1
  62. package/dist/run/red-check.js +130 -0
  63. package/dist/run/red-check.js.map +1 -0
  64. package/dist/run/retro.js +2 -2
  65. package/dist/run/retro.js.map +1 -1
  66. package/dist/run/settings.js +4 -2
  67. package/dist/run/settings.js.map +1 -1
  68. package/dist/run/skills.js +146 -0
  69. package/dist/run/skills.js.map +1 -0
  70. package/dist/run/tests-first.js +146 -0
  71. package/dist/run/tests-first.js.map +1 -0
  72. package/dist/run/watchdog.js +259 -0
  73. package/dist/run/watchdog.js.map +1 -0
  74. package/dist/run/workflow.js +17 -6
  75. package/dist/run/workflow.js.map +1 -1
  76. package/dist/server/app.js +644 -201
  77. package/dist/server/app.js.map +1 -1
  78. package/dist/server/principal.js +5 -2
  79. package/dist/server/principal.js.map +1 -1
  80. package/dist/server/repo-picker.js +18 -0
  81. package/dist/server/repo-picker.js.map +1 -0
  82. package/dist/setup/ink-ui.js +1 -0
  83. package/dist/setup/ink-ui.js.map +1 -1
  84. package/dist/setup/onboarding.js +0 -16
  85. package/dist/setup/onboarding.js.map +1 -1
  86. package/dist/skills.js +151 -0
  87. package/dist/skills.js.map +1 -0
  88. package/dist/ticket-cli.js +41 -0
  89. package/dist/ticket-cli.js.map +1 -1
  90. package/dist/version.js +13 -0
  91. package/dist/version.js.map +1 -0
  92. package/dist/web/assets/index-CCQMrUIF.js +255 -0
  93. package/dist/web/assets/index-lzGSgTRQ.css +1 -0
  94. package/dist/web/index.html +2 -2
  95. package/dist/web/sw.js +3 -1
  96. package/package.json +1 -1
  97. package/dist/web/assets/index-ChuS3qKc.js +0 -254
  98. package/dist/web/assets/index-DR6WkmzI.css +0 -1
@@ -1,20 +1,25 @@
1
1
  import { Hono } from "hono";
2
2
  import { streamSSE } from "hono/streaming";
3
+ import { randomBytes } from "node:crypto";
3
4
  import { existsSync } from "node:fs";
4
5
  import { readFile } from "node:fs/promises";
5
- import { join } from "node:path";
6
+ import { basename, join } from "node:path";
6
7
  import QRCode from "qrcode";
7
8
  import { normaliseVerify, } from "../db/db.js";
9
+ import { checkSkillName, checkSkillText, fetchSkillText, githubSkillLink } from "../skills.js";
8
10
  import { AttachmentError, absoluteAttachments, attachmentPaths, deleteAttachments, imageMime, readAttachmentImages, saveAttachment, sniffImage, } from "../attachments.js";
9
11
  import { MAX_IMAGE_BYTES, MAX_MESSAGE_CHARS, PLAN_TURN_DEADLINE_MS } from "../limits.js";
10
12
  import { newTaskTurns, summariseTurns } from "../metrics.js";
11
13
  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";
14
+ import { MAX_CARDS, OrchestratorError, EMPTY_TURN_STATS, INTAKE_THINKING_CAP, assignIds, cardVerify, fallbackHandoff, keepListedModels, normaliseCard, normaliseQuestions, runOrchestrator, summarizeConversation, } from "../orchestrator/runtime.js";
13
15
  import { linkedBoardQuestion, runResearch, taskResearchQuestions, } from "../orchestrator/research.js";
14
- import { fileOnLinkedBoard, LinkedBoardError } from "../repo/linked-boards.js";
16
+ import { describeRepo } from "../repo/linked-boards.js";
17
+ import { ProjectRepoError, validateRepoFolder } from "../repo/project-repos.js";
18
+ import { pickRepoFolder } from "./repo-picker.js";
15
19
  import { buildIndex, readHead, readRepoName, renderBrief } from "../repo/index.js";
16
20
  import { RunAlreadyActiveError, RunManager, } from "../run/manager.js";
17
21
  import { MergeWatcher } from "../run/merge-watch.js";
22
+ import { readPullRequestChecks } from "../run/pr-checks.js";
18
23
  import { normaliseRunResult } from "../run/result.js";
19
24
  import { mergeBlockReason, mergePullRequest, readMergeOptions, readPullRequestSnapshot, } from "../run/pr-merge.js";
20
25
  import { parseUnifiedDiff } from "../run/diff.js";
@@ -22,11 +27,15 @@ import { pullRequestUrlIn } from "../run/pull-request.js";
22
27
  import { createIssue, prepareIssue } from "../run/issue.js";
23
28
  import { hasMentionInstruction, mentionedProfiles } from "../run/mentions.js";
24
29
  import { HarnessRuntime } from "../run/harness-runtime.js";
30
+ import { handoffBrief, handoffCommand, handoffHarness } from "../run/handoff.js";
25
31
  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";
32
+ import { consultWatchdog } from "../run/watchdog.js";
33
+ import { consultReviewer } from "../run/auto-review.js";
34
+ import { buildCheckFixPrompt, buildCommentPrompt, buildConflictPrompt, buildReviewPrompt, COMMENT_AGENT_PROMPT, CONFLICT_AGENT_PROMPT, REVIEW_AGENT_PROMPT, VERIFIED_CODING_AGENT_PROMPT, } from "../run/prompt.js";
27
35
  import { listCodexModels } from "../run/codex-client.js";
28
36
  import { listHarnessModels } from "../run/harnesses.js";
29
37
  import { profileFor } from "../run/profiles.js";
38
+ import { readSkills, skillBriefs, skillStoreOf } from "../run/skills.js";
30
39
  import { asMaxAgents, asPlannerThinking } from "../run/settings.js";
31
40
  import { capThinking, parseThinkingLevel, THINKING_LEVELS, } from "../run/thinking.js";
32
41
  import { WORKFLOW_STAGES, isWorkflowStage, normaliseWorkflow, } from "../run/workflow.js";
@@ -40,6 +49,8 @@ import { capabilitiesFor } from "./principal.js";
40
49
  import { MAX_TERMINAL_COLS, MAX_TERMINAL_ROWS, MIN_TERMINAL_COLS, MIN_TERMINAL_ROWS, NoSuchTerminalError, TerminalExitedError, TerminalLimitError, TerminalManager, } from "./terminal.js";
41
50
  /** How long a settled reading waits for its answer turn before it is dropped. */
42
51
  const PENDING_RESEARCH_TTL_MS = 15 * 60_000;
52
+ /** How long a harness's model list is trusted before the planner asks again. */
53
+ const MODEL_LIST_TTL_MS = 5 * 60_000;
43
54
  const BOARD_COLUMNS = ["todo", "in_progress", "blocked", "review", "done"];
44
55
  /** Only strings survive into the database; anything else becomes an empty spec field. */
45
56
  const asText = (value) => (typeof value === "string" ? value.trim() : "");
@@ -116,6 +127,8 @@ class UnknownConversationError extends Error {
116
127
  }
117
128
  }
118
129
  const EMPTY_ANSWERS = { decided: [], block: "" };
130
+ /** Repos one intake may send a scout into; more than this is a project, not a card set. */
131
+ const MAX_REPO_SCOUTS = 2;
119
132
  /** Answers as they arrive from the panel: anything unreadable is simply not an answer. */
120
133
  function asAnswers(value) {
121
134
  if (!Array.isArray(value))
@@ -149,6 +162,8 @@ function asThinking(value) {
149
162
  * at. The model sees the same lines in their turn, but the cards get the record
150
163
  * from here, because a model that forgets is exactly what this avoids.
151
164
  */
165
+ /** Starts the block an answer adds to the person's message; a card's intent line stops at it. */
166
+ const ANSWERS_HEADING = "Answers to your questions:";
152
167
  function resolveAnswers(previous, answers) {
153
168
  const lines = [];
154
169
  const decided = [];
@@ -167,61 +182,13 @@ function resolveAnswers(previous, answers) {
167
182
  return EMPTY_ANSWERS;
168
183
  return {
169
184
  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
- ],
185
+ block: `${ANSWERS_HEADING}\n${lines.join("\n")}`,
197
186
  };
198
187
  }
199
188
  /** What the planner is told about a linked board: no port, no liveness. */
200
189
  function briefOf(board) {
201
190
  return { name: board.name, root: board.root, description: board.description };
202
191
  }
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
192
  /** A decision was made about the plan in front of the person, so it lands on its cards. */
226
193
  function applyDecided(cards, decided) {
227
194
  const out = [];
@@ -234,13 +201,14 @@ function applyDecided(cards, decided) {
234
201
  }
235
202
  return out;
236
203
  }
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, }) {
204
+ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl, plan, summarize, harness, setup, listModels, skills: skillStore, plannerThinking, plannerToolBudget, summaryTimeoutMs, runtime, runTimeoutMs, retro, lead, leadEnabled, watchdog, watchdogEnabled, watchdogTickMs, watchdogBackstopMs, autoReview, autoReviewEnabled, redCheckEnabled, testsFirstEnabled, research, researchEnabled, maxRunning, prepare, prepareTicket, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, mergePollMs, index: indexOverride, indexOnStart, onRunsChange, voice: voiceOverride, build: buildOption, phone, terminals: terminalOverride, onLiveChange, repoRegistryFile, repoPicker = { available: process.platform === "darwin", pick: pickRepoFolder }, }) {
238
205
  const app = new Hono();
239
206
  const auth = createAuth({ token, port });
240
207
  const idempotency = createIdempotency(db);
241
208
  const build = buildOption?.trim() || process.env.ZELIO_BUILD_HASH?.trim() || "dev";
242
209
  const voice = voiceOverride ?? createVoice();
243
210
  const root = repoRoot ?? process.cwd();
211
+ const skills = skillStore ?? skillStoreOf(db);
244
212
  const setupStore = setup ?? memorySetupStore({ harness: "pi", modelChosen: true });
245
213
  const effectiveHarness = () => harness?.trim() || process.env.ZELIO_HARNESS?.trim() || setupStore.read().harness || "pi";
246
214
  const effectivePlannerModel = () => {
@@ -259,6 +227,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
259
227
  // Likewise for the planner: a CLI flag beats the saved choice; the saved
260
228
  // choice beats the runtime's env/default.
261
229
  const plannerThinkingForTurn = () => plannerThinking ?? db.getBoardSettings().plannerThinking;
230
+ const testsFirstForcedOff = () => testsFirstEnabled === false || process.env.ZELIO_TESTS_FIRST === "off";
231
+ const testsFirstForRun = () => !testsFirstForcedOff() && db.getBoardSettings().testsFirstEnabled;
262
232
  const prepareOverride = prepare ?? prepareTicket;
263
233
  // One planning run at a time. Two in flight would cost twice and race on
264
234
  // creating the same cards.
@@ -409,10 +379,19 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
409
379
  ...second,
410
380
  ]);
411
381
  };
412
- /** Other boards, never throwing: a broken registry is no linked boards. */
382
+ /**
383
+ * The project repos on this board, as the planner and the scouts see them.
384
+ * Never throwing: a repo that cannot be read is simply not a candidate.
385
+ */
413
386
  function linkedBoards() {
414
387
  try {
415
- return listLinked?.() ?? [];
388
+ return db.listRepos().map((repo) => ({
389
+ name: repo.name,
390
+ root: repo.root,
391
+ description: describeRepo(repo.root),
392
+ port: 0,
393
+ running: true,
394
+ }));
416
395
  }
417
396
  catch {
418
397
  return [];
@@ -438,14 +417,68 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
438
417
  model: effectivePlannerModel() || undefined,
439
418
  })
440
419
  : 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);
420
+ const watchdogConsultant = watchdog ??
421
+ (watchdogEnabled
422
+ ? (input) => consultWatchdog(input, {
423
+ runtime: agentRuntime,
424
+ command: effectiveHarness(),
425
+ model: effectivePlannerModel() || undefined,
426
+ })
427
+ : undefined);
428
+ // The reviewer profile, as the person edited it on the Agents page, decides
429
+ // the harness, model and effort; an empty field falls back like a run's does.
430
+ const reviewConsultant = autoReview ??
431
+ (autoReviewEnabled
432
+ ? (input) => {
433
+ const profile = db.getProfile("reviewer") ?? profileFor("reviewer");
434
+ const command = profile.harness.trim() || effectiveHarness();
435
+ const model = profile.model.trim() ||
436
+ (command === effectiveHarness() ? effectiveDeveloperModel() : "");
437
+ return consultReviewer(input, {
438
+ runtime: agentRuntime,
439
+ command,
440
+ thinking: profile.thinking,
441
+ ...(model ? { model } : {}),
442
+ });
443
+ }
444
+ : undefined);
445
+ /**
446
+ * The checkout root a ticket's worktree, branch and merge watch live in: its
447
+ * added repository, or the home repo when it names none. A card whose repo was
448
+ * removed has nowhere to work, so this throws rather than guessing.
449
+ */
450
+ function rootFor(ticket) {
451
+ if (!ticket.repo)
452
+ return root;
453
+ const repo = db.listRepos().find((item) => item.name === ticket.repo);
454
+ if (!repo) {
455
+ throw new Error(`The repository ${ticket.repo} was removed from this board.`);
456
+ }
457
+ return repo.root;
458
+ }
459
+ /** For cleanup only: a removed repo's checkout is unreachable, so there is nothing to retire. */
460
+ function retireRootFor(ticket) {
461
+ try {
462
+ return rootFor(ticket);
463
+ }
464
+ catch {
465
+ return null;
466
+ }
467
+ }
468
+ const runs = new RunManager(db, agentRuntime, publishRun, `http://127.0.0.1:${port}`, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, root, retro, () => ({ harness: effectiveHarness(), model: effectiveDeveloperModel() }), leadConsultant, rootFor, reviewConsultant, redCheckEnabled ?? false, testsFirstForRun, skills, (command) => harnessModels(command), watchdogConsultant
469
+ ? {
470
+ consult: watchdogConsultant,
471
+ ...(watchdogTickMs ? { tickMs: watchdogTickMs } : {}),
472
+ ...(watchdogBackstopMs ? { backstopMs: watchdogBackstopMs } : {}),
473
+ }
474
+ : undefined);
442
475
  /**
443
476
  * The ticket's checkout, with its branch recorded on the row the first time.
444
477
  * Every path that starts work goes through here: a branch that exists on disk
445
478
  * but not on the card is a fact the drawer and the review cannot see.
446
479
  */
447
480
  async function checkoutFor(ticket) {
448
- const worktree = await ensureWorktree(root, ticket.id, ticket.title, ticket.branch);
481
+ const worktree = await ensureWorktree(rootFor(ticket), ticket.id, ticket.title, ticket.branch);
449
482
  if (!ticket.branch)
450
483
  db.setBranch(ticket.id, worktree.branch);
451
484
  return worktree;
@@ -472,6 +505,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
472
505
  const mergeWatcher = new MergeWatcher({
473
506
  db,
474
507
  root,
508
+ rootFor,
475
509
  ghCommand,
476
510
  intervalMs: mergePollMs,
477
511
  onMergeabilityChange: () => {
@@ -497,7 +531,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
497
531
  return null;
498
532
  let status;
499
533
  try {
500
- status = runs.start(current, worktree, 1, {
534
+ status = await runs.begin(current, worktree, 1, {
501
535
  prompt: buildConflictPrompt(current, {
502
536
  branch: conflict.baseBranch,
503
537
  baseRefOid: conflict.baseRefOid,
@@ -565,8 +599,33 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
565
599
  * pass fills them; a failed pass leaves the ticket in Todo with the reason on
566
600
  * it, so the next allocation pass can try again instead of losing the card.
567
601
  */
602
+ /**
603
+ * A card the planner split out of a parked quick ticket becomes its own quick
604
+ * ticket in Todo. It carries the person's original request, so each card still
605
+ * reads as the ask it came from.
606
+ */
607
+ function splitTicket(source, card) {
608
+ const intent = (source.context ?? []).find((line) => line.startsWith("Original user intent: "));
609
+ const context = [...(card.context ?? [])];
610
+ const requested = intent ?? (source.goal ? `Original user intent: ${source.goal}` : null);
611
+ if (requested && !context.includes(requested))
612
+ context.push(requested);
613
+ db.createTicket({
614
+ title: card.title.trim() || source.title,
615
+ goal: card.goal,
616
+ out_of_scope: card.out_of_scope,
617
+ acceptance: card.acceptance,
618
+ likely_files: [...card.likely_files],
619
+ context,
620
+ verify: normaliseVerify(card.verify),
621
+ state: "todo",
622
+ quick: true,
623
+ repo: source.repo,
624
+ });
625
+ }
568
626
  async function runPrepare(ticket) {
569
627
  const missing = checkSpec(ticket).missing;
628
+ const planned = [];
570
629
  try {
571
630
  const filled = prepareOverride
572
631
  ? await prepareOverride(ticket, missing)
@@ -579,8 +638,12 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
579
638
  {
580
639
  role: "user",
581
640
  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 ` +
641
+ `until its spec is complete. Fill ${requested}. Preserve the person's ` +
642
+ `intent and any existing exclusions or checks. Rewrite the goal as ` +
643
+ `Today: <current state>. After: <desired change>. Done when: <observable ` +
644
+ `result>. Use the original request in ticket context when present, otherwise ` +
645
+ `use the existing goal. Do not invent current state or outcomes. Also add ` +
646
+ `only what is missing: a real ` +
584
647
  `exclusion in out_of_scope, checkable acceptance (including a failure case), ` +
585
648
  `and likely files read from the repo. Return the complete card, same id.\n\n` +
586
649
  `${ticket.title}\n${ticket.goal}\n${ticket.out_of_scope}\n` +
@@ -592,6 +655,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
592
655
  title: item.title,
593
656
  state: item.state,
594
657
  })), undefined, null, "new-task");
658
+ planned.push(...prepared.cards);
595
659
  return (prepared.cards.find((card) => card.id === ticket.id) ?? prepared.cards[0] ?? null);
596
660
  })();
597
661
  const next = db.updateSpec(ticket.id, fieldsOf(filled));
@@ -601,6 +665,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
601
665
  if (!check.ok) {
602
666
  throw new Error(`spec is still incomplete: ${check.missing.join(", ")}`);
603
667
  }
668
+ // Only after the original is complete: a failed pass creates nothing, so
669
+ // the retry on the next allocation pass cannot duplicate these cards.
670
+ const extra = planned.filter((card) => card !== filled);
671
+ for (const card of extra)
672
+ splitTicket(ticket, card);
673
+ if (extra.length > 0)
674
+ void scheduleTickets();
604
675
  return next;
605
676
  }
606
677
  catch (cause) {
@@ -645,7 +716,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
645
716
  if (!current || current.state !== "queued")
646
717
  continue;
647
718
  const started = db.transition(ticket.id, "in_progress");
648
- runs.start(started, worktree);
719
+ // oxlint-disable-next-line no-await-in-loop
720
+ await runs.begin(started, worktree);
649
721
  }
650
722
  catch {
651
723
  // A ticket that cannot get a worktree stays queued rather than wearing
@@ -745,10 +817,12 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
745
817
  retry: !reviewer,
746
818
  source: "comment",
747
819
  sourceCommentId: comment.id,
820
+ // A send-back asks for a change; the reviewer only reads.
821
+ expectsChange: !reviewer,
748
822
  };
749
823
  let status;
750
824
  try {
751
- status = runs.start(ticket, worktree, 1, job);
825
+ status = await runs.begin(ticket, worktree, 1, job);
752
826
  }
753
827
  catch (cause) {
754
828
  note(`@${name} could not start: ${cause instanceof Error ? cause.message : "the run was refused"}`);
@@ -792,8 +866,37 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
792
866
  });
793
867
  return scheduling;
794
868
  }
869
+ /**
870
+ * What a card's developer run is: the developer profile's harness, the models
871
+ * that harness lists, and its own model and effort. Listing spawns the
872
+ * harness, so a list is kept for a few minutes per harness; a list that
873
+ * failed is kept too, as empty, so a broken harness is not asked every turn.
874
+ */
875
+ const discover = listModels ?? ((value) => listHarnessModels(value, { listCodex: listCodexModels }));
876
+ const listedModels = new Map();
877
+ const harnessModels = (command) => {
878
+ const cached = listedModels.get(command);
879
+ if (cached && Date.now() - cached.at < MODEL_LIST_TTL_MS)
880
+ return cached.models;
881
+ const models = discover(command)
882
+ .then((result) => result.models)
883
+ .catch(() => []);
884
+ listedModels.set(command, { at: Date.now(), models });
885
+ return models;
886
+ };
887
+ const developerBrief = async () => {
888
+ const profile = db.getProfile("developer") ?? profileFor("developer");
889
+ const command = profile.harness.trim() || effectiveHarness();
890
+ return {
891
+ harness: command,
892
+ models: await harnessModels(command),
893
+ model: profile.model.trim() || (command === effectiveHarness() ? effectiveDeveloperModel() : ""),
894
+ thinking: profile.thinking,
895
+ skills: skillBriefs(readSkills(skills)),
896
+ };
897
+ };
795
898
  const runPlan = plan ??
796
- ((messages, brief, draft, board, onStatus, handoff, mode, onStats, attachments = [], images = [], thinking, findings, timeoutMs, linked) => runOrchestrator({
899
+ (async (messages, brief, draft, board, onStatus, handoff, mode, onStats, attachments = [], images = [], thinking, findings, timeoutMs, linked, turnModel) => runOrchestrator({
797
900
  repoRoot: root,
798
901
  messages,
799
902
  brief,
@@ -806,8 +909,9 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
806
909
  attachments,
807
910
  images,
808
911
  command: effectiveHarness(),
809
- planner: createPlanner(effectiveHarness(), effectivePlannerModel()),
810
- model: effectivePlannerModel() || undefined,
912
+ // The dialog's choice for this turn, else the saved planner model.
913
+ planner: createPlanner(effectiveHarness(), turnModel || effectivePlannerModel()),
914
+ model: turnModel || effectivePlannerModel() || undefined,
811
915
  thinking: thinking ?? plannerThinkingForTurn(),
812
916
  budget: plannerToolBudget,
813
917
  // The planner and the run it writes for must agree on what "done" means;
@@ -818,6 +922,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
818
922
  research: findings,
819
923
  timeoutMs,
820
924
  linkedBoards: linked,
925
+ // The intake drafts no run, so it does not wait on a model list.
926
+ developer: mode === "intake" ? null : await developerBrief(),
821
927
  }));
822
928
  // A test that injected the planner explicitly asked for no subprocess. Only
823
929
  // an explicitly named harness (or a summary injection) opts back in.
@@ -931,7 +1037,16 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
931
1037
  * Board-scoped settings. They are read by the server on every allocation and
932
1038
  * planner turn, so a save takes effect without a restart.
933
1039
  */
934
- app.get("/api/settings", (c) => c.json({ settings: db.getBoardSettings() }));
1040
+ const effectiveBoardSettings = () => {
1041
+ const settings = db.getBoardSettings();
1042
+ const forcedOff = testsFirstForcedOff();
1043
+ return {
1044
+ ...settings,
1045
+ testsFirstEnabled: forcedOff ? false : settings.testsFirstEnabled,
1046
+ testsFirstForcedOff: forcedOff,
1047
+ };
1048
+ };
1049
+ app.get("/api/settings", (c) => c.json({ settings: effectiveBoardSettings() }));
935
1050
  const setupResponse = () => ({
936
1051
  ...setupStore.read(),
937
1052
  effectiveHarness: effectiveHarness(),
@@ -945,6 +1060,12 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
945
1060
  const legacy = typeof body.model === "string" ? body.model.trim() : undefined;
946
1061
  const plannerModel = typeof body.plannerModel === "string" ? body.plannerModel.trim() : legacy;
947
1062
  const developerModel = typeof body.developerModel === "string" ? body.developerModel.trim() : legacy;
1063
+ if (plannerModel !== undefined && developerModel === undefined && legacy === undefined) {
1064
+ if (plannerModel.length > 200)
1065
+ return c.json({ error: "model is too long" }, 400);
1066
+ setupStore.save({ plannerModel, modelChosen: true });
1067
+ return c.json({ setup: setupResponse() });
1068
+ }
948
1069
  if (plannerModel === undefined || developerModel === undefined) {
949
1070
  return c.json({ error: "plannerModel and developerModel must be strings" }, 400);
950
1071
  }
@@ -977,9 +1098,15 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
977
1098
  return c.json({ error: "unknown thinking level" }, 400);
978
1099
  patch.plannerThinking = chosen;
979
1100
  }
1101
+ if (body.testsFirstEnabled !== undefined) {
1102
+ if (typeof body.testsFirstEnabled !== "boolean")
1103
+ return c.json({ error: "testsFirstEnabled must be a boolean" }, 400);
1104
+ patch.testsFirstEnabled = body.testsFirstEnabled;
1105
+ }
980
1106
  if (Object.keys(patch).length === 0)
981
1107
  return c.json({ error: "nothing to save" }, 400);
982
- const settings = db.setBoardSettings(patch);
1108
+ db.setBoardSettings(patch);
1109
+ const settings = effectiveBoardSettings();
983
1110
  // Raising the cap should start queued work now, not at the next unrelated
984
1111
  // event. Lowering it never kills a run; it only stops new ones.
985
1112
  if (patch.maxAgents !== undefined)
@@ -1012,7 +1139,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1012
1139
  app.post("/api/tickets/:id/status", async (c) => {
1013
1140
  const id = c.req.param("id");
1014
1141
  const ticketToken = c.req.header("x-zelio-ticket-token") ?? "";
1015
- if (!runs.verifyStatusToken(id, ticketToken)) {
1142
+ if (!agentTokenOk(id, ticketToken)) {
1016
1143
  return c.json({ error: "invalid ticket token" }, 401);
1017
1144
  }
1018
1145
  const body = await c.req
@@ -1035,9 +1162,29 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1035
1162
  const ticket = db.getTicket(id);
1036
1163
  if (!ticket)
1037
1164
  return c.json({ error: "no such ticket" }, 404);
1038
- if (ticket.state !== "in_progress") {
1165
+ if (ticket.state !== "in_progress" && ticket.state !== "handed_off") {
1039
1166
  return c.json({ error: `ticket is ${ticket.state}` }, 409);
1040
1167
  }
1168
+ // A handed-off ticket has no board run to observe commands in, and the
1169
+ // person drove the agent that did the work, so the review they are about
1170
+ // to do is the gate. The board still wants the done report on the card.
1171
+ if (ticket.state === "handed_off") {
1172
+ if (to === "review") {
1173
+ const since = Date.parse(ticket.handoff?.at ?? "") || 0;
1174
+ const reported = db
1175
+ .listComments(id)
1176
+ .some((comment) => comment.type === "done" && Date.parse(comment.created_at) >= since);
1177
+ if (!reported) {
1178
+ return c.json({ error: "post a done comment with what changed and how you verified it first" }, 409);
1179
+ }
1180
+ }
1181
+ const next = db.transition(id, to, {
1182
+ blocker_kind: to === "blocked" ? "decision" : null,
1183
+ blocker_reason: to === "blocked" ? reason : null,
1184
+ blocker_unblock: to === "blocked" && unblock ? unblock : null,
1185
+ });
1186
+ return c.json({ ticket: next });
1187
+ }
1041
1188
  if (to === "review" && (ticket.verify ?? []).length > 0) {
1042
1189
  return c.json({
1043
1190
  error: "This ticket is verified by the board. End your turn instead: the board runs its checks and, if they pass, commits, pushes, opens the pull request and moves the ticket to Review.",
@@ -1108,7 +1255,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1108
1255
  app.post("/api/tickets/:id/agent-comments", async (c) => {
1109
1256
  const id = c.req.param("id");
1110
1257
  const ticketToken = c.req.header("x-zelio-ticket-token") ?? "";
1111
- if (!runs.verifyStatusToken(id, ticketToken)) {
1258
+ if (!agentTokenOk(id, ticketToken)) {
1112
1259
  return c.json({ error: "invalid ticket token" }, 401);
1113
1260
  }
1114
1261
  const body = await c.req
@@ -1136,7 +1283,9 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1136
1283
  const ticket = db.getTicket(id);
1137
1284
  if (!ticket)
1138
1285
  return c.json({ error: "no such ticket" }, 404);
1139
- const identity = runs.activeIdentity(id);
1286
+ const identity = ticket.state === "handed_off"
1287
+ ? { profile: ticket.handoff?.harness ?? "agent", runId: null }
1288
+ : runs.activeIdentity(id);
1140
1289
  if (!identity)
1141
1290
  return c.json({ error: "the run has finished" }, 409);
1142
1291
  const comment = db.addComment({
@@ -1164,6 +1313,8 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1164
1313
  : { kind: "local" },
1165
1314
  capabilities: capabilitiesFor(principal),
1166
1315
  build,
1316
+ // The account is the Mac's: a phone tunnel never gets its picture.
1317
+ avatarUrl: principal.kind === "local" ? (accountAvatarUrl?.() ?? null) : null,
1167
1318
  });
1168
1319
  });
1169
1320
  /** Version skew: the phone compares this with the build in the tunnel hello. */
@@ -1262,6 +1413,82 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1262
1413
  });
1263
1414
  /** Back to the seed rows. The only way an edited profile forgets its edits. */
1264
1415
  app.post("/api/profiles/reset", (c) => c.json({ profiles: db.resetProfiles() }));
1416
+ /**
1417
+ * Skills a person keeps on the board. Like the profiles this is config: it
1418
+ * survives a board reset, and a skill keeps its enabled switch across restarts.
1419
+ */
1420
+ app.get("/api/skills", (c) => c.json({ skills: db.listSkills() }));
1421
+ app.post("/api/skills", async (c) => {
1422
+ const body = await c.req
1423
+ .json()
1424
+ .catch(() => ({}));
1425
+ const name = checkSkillName(body.name);
1426
+ if (!name.ok)
1427
+ return c.json({ error: name.error }, 400);
1428
+ const text = checkSkillText(body.text);
1429
+ if (!text.ok)
1430
+ return c.json({ error: text.error }, 400);
1431
+ if (body.enabled !== undefined && typeof body.enabled !== "boolean") {
1432
+ return c.json({ error: "enabled must be true or false" }, 400);
1433
+ }
1434
+ // A source is a label the page links to, so only a GitHub file link is kept.
1435
+ let source = "";
1436
+ if (body.source !== undefined && body.source !== "") {
1437
+ const link = githubSkillLink(body.source);
1438
+ if (!link.ok)
1439
+ return c.json({ error: link.error }, 400);
1440
+ source = link.value.source;
1441
+ }
1442
+ if (db.getSkill(name.value)) {
1443
+ return c.json({ error: `a skill named ${name.value} already exists` }, 409);
1444
+ }
1445
+ const skill = db.addSkill({
1446
+ name: name.value,
1447
+ text: text.value,
1448
+ source,
1449
+ enabled: body.enabled !== false,
1450
+ });
1451
+ return c.json({ skill }, 201);
1452
+ });
1453
+ /**
1454
+ * Reads a GitHub file and answers with what saving it would store. Nothing is
1455
+ * written here: the page shows the draft, and the person's confirm is the POST.
1456
+ */
1457
+ app.post("/api/skills/import", async (c) => {
1458
+ const body = await c.req.json().catch(() => ({}));
1459
+ const link = githubSkillLink(body.url);
1460
+ if (!link.ok)
1461
+ return c.json({ error: link.error }, 400);
1462
+ const loaded = await fetchSkillText(link.value.rawUrl);
1463
+ if (!loaded.ok)
1464
+ return c.json({ error: loaded.error }, loaded.status);
1465
+ return c.json({
1466
+ skill: { name: link.value.name, text: loaded.value.text, source: link.value.source },
1467
+ });
1468
+ });
1469
+ /** Edits the text, or flips the enabled switch. The name is the key and stays. */
1470
+ app.put("/api/skills/:name", async (c) => {
1471
+ const name = c.req.param("name");
1472
+ if (!db.getSkill(name))
1473
+ return c.json({ error: "no such skill" }, 404);
1474
+ const body = await c.req
1475
+ .json()
1476
+ .catch(() => ({}));
1477
+ const patch = {};
1478
+ if (body.text !== undefined) {
1479
+ const text = checkSkillText(body.text);
1480
+ if (!text.ok)
1481
+ return c.json({ error: text.error }, 400);
1482
+ patch.text = text.value;
1483
+ }
1484
+ if (body.enabled !== undefined) {
1485
+ if (typeof body.enabled !== "boolean") {
1486
+ return c.json({ error: "enabled must be true or false" }, 400);
1487
+ }
1488
+ patch.enabled = body.enabled;
1489
+ }
1490
+ return c.json({ skill: db.updateSkill(name, patch) });
1491
+ });
1265
1492
  /**
1266
1493
  * What a harness says it can run. Discovery is a suggestion for the model
1267
1494
  * field, never a gate: a harness that is missing, slow or broken returns an
@@ -1269,7 +1496,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1269
1496
  */
1270
1497
  app.get("/api/agent-models", async (c) => {
1271
1498
  const command = asText(c.req.query("harness")) || effectiveHarness();
1272
- const result = await (listModels ?? ((value) => listHarnessModels(value, { listCodex: listCodexModels })))(command);
1499
+ const result = await discover(command);
1273
1500
  return c.json({ harness: command, models: result.models, error: result.error });
1274
1501
  });
1275
1502
  /**
@@ -1284,29 +1511,6 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1284
1511
  ]));
1285
1512
  return c.json({ workflows });
1286
1513
  });
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
1514
  app.put("/api/workflows/:stage", async (c) => {
1311
1515
  const stage = c.req.param("stage");
1312
1516
  if (!isWorkflowStage(stage))
@@ -1385,6 +1589,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1385
1589
  run: db.latestAgentRun(ticket.id),
1386
1590
  });
1387
1591
  });
1592
+ /**
1593
+ * The agent working a ticket: the board's run, or the terminal agent the
1594
+ * person took it into. Either token opens only that one ticket.
1595
+ */
1596
+ function agentTokenOk(ticketId, token) {
1597
+ return runs.verifyStatusToken(ticketId, token) || db.verifyHandoffToken(ticketId, token);
1598
+ }
1388
1599
  /** Stop a live run and wait for its process before touching its worktree. */
1389
1600
  async function stopRun(ticketId, mode) {
1390
1601
  if (!runs.isRunning(ticketId))
@@ -1411,9 +1622,76 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1411
1622
  const removed = db.deleteTicket(id);
1412
1623
  if (!removed)
1413
1624
  return c.json({ error: "no such ticket" }, 404);
1414
- await retireWorktree(root, removed.id, removed.branch);
1625
+ const checkoutRoot = retireRootFor(removed);
1626
+ if (checkoutRoot)
1627
+ await retireWorktree(checkoutRoot, removed.id, removed.branch);
1415
1628
  return c.json({ ticket: removed });
1416
1629
  });
1630
+ /** The home repo and the repos attached to this board. */
1631
+ app.get("/api/repos", (c) => c.json({
1632
+ home: { name: basename(root), root },
1633
+ repos: db.listRepos(),
1634
+ folderPicker: repoPicker.available && c.get("principal").kind === "local",
1635
+ }));
1636
+ app.post("/api/repos/pick-folder", async (c) => {
1637
+ if (c.get("principal").kind !== "local") {
1638
+ return c.json({ error: "choosing a repository is available from the local board only" }, 403);
1639
+ }
1640
+ if (!repoPicker.available)
1641
+ return c.json({ error: "Folder picking is available on macOS only." }, 400);
1642
+ try {
1643
+ return c.json({ path: await repoPicker.pick() });
1644
+ }
1645
+ catch {
1646
+ return c.json({ error: "Could not open the folder picker. Please try again." }, 500);
1647
+ }
1648
+ });
1649
+ app.post("/api/repos", async (c) => {
1650
+ if (c.get("principal").kind !== "local") {
1651
+ return c.json({ error: "adding a repository is available from the local board only" }, 403);
1652
+ }
1653
+ const body = await c.req.json().catch(() => ({}));
1654
+ try {
1655
+ const folder = await validateRepoFolder(typeof body.path === "string" ? body.path : "", {
1656
+ home: root,
1657
+ existing: db.listRepos(),
1658
+ registryFile: repoRegistryFile,
1659
+ });
1660
+ const repo = db.addRepo({ name: folder.name, root: folder.root });
1661
+ return c.json({ repo }, 201);
1662
+ }
1663
+ catch (error) {
1664
+ if (error instanceof ProjectRepoError)
1665
+ return c.json({ error: error.message }, error.status);
1666
+ throw error;
1667
+ }
1668
+ });
1669
+ /**
1670
+ * Detaches an added repo. Its cards are archived, not deleted, so their runs
1671
+ * and comments stay readable. Refused while one of them is in flight, because
1672
+ * its worktree lives in the repo being detached.
1673
+ */
1674
+ app.delete("/api/repos/:name", (c) => {
1675
+ if (c.get("principal").kind !== "local") {
1676
+ return c.json({ error: "removing a repository is available from the local board only" }, 403);
1677
+ }
1678
+ const name = c.req.param("name");
1679
+ if (!db.listRepos().some((repo) => repo.name === name)) {
1680
+ return c.json({ error: "no such repository" }, 404);
1681
+ }
1682
+ const busy = db
1683
+ .listTickets()
1684
+ .filter((ticket) => ticket.repo === name)
1685
+ .filter((ticket) => ticket.state === "in_progress" || runs.isRunning(ticket.id));
1686
+ if (busy.length > 0) {
1687
+ return c.json({
1688
+ error: `${busy.length} ticket${busy.length === 1 ? " is" : "s are"} in progress in ${name}; stop ${busy.length === 1 ? "it" : "them"} before removing the repository`,
1689
+ }, 409);
1690
+ }
1691
+ const archived = db.archiveRepoTickets(name);
1692
+ db.removeRepo(name);
1693
+ return c.json({ removed: name, archived: archived.length });
1694
+ });
1417
1695
  app.get("/api/tickets/:id/diff", (c) => {
1418
1696
  const ticket = db.getTicket(c.req.param("id"));
1419
1697
  if (!ticket)
@@ -1580,12 +1858,16 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1580
1858
  });
1581
1859
  // Programmatic surface. The board has no creation UI in M1; the orchestrator
1582
1860
  // 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. */
1861
+ /**
1862
+ * What the person said in the conversation a card came from, as one line for
1863
+ * the run. Their answers to the planner's questions are cut off each message:
1864
+ * the card already carries each one as a "Planner decision" line.
1865
+ */
1584
1866
  const originalIntentOf = (conversationId) => {
1585
1867
  const conversation = typeof conversationId === "string" ? db.getConversation(conversationId) : null;
1586
1868
  return conversation?.messages
1587
1869
  .filter((message) => message.role === "user")
1588
- .map((message) => message.content.replace(/\s+/g, " ").trim())
1870
+ .map((message) => (message.content.split(ANSWERS_HEADING)[0] ?? "").replace(/\s+/g, " ").trim())
1589
1871
  .filter(Boolean)
1590
1872
  .join(" | ")
1591
1873
  .slice(0, 2_000);
@@ -1598,14 +1880,21 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1598
1880
  if (!attachments)
1599
1881
  return c.json({ error: "those screenshots are not the board's" }, 400);
1600
1882
  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);
1883
+ // A card for a project repo runs in that repo's checkout. A name this board
1884
+ // does not have is refused: the card would have nowhere to run.
1885
+ const named = typeof draft.board === "string" && draft.board.trim()
1886
+ ? draft.board.trim()
1887
+ : typeof body.repo === "string" && body.repo.trim()
1888
+ ? body.repo.trim()
1889
+ : null;
1890
+ if (named && !db.listRepos().some((repo) => repo.name === named)) {
1891
+ return c.json({ error: `${named} is not a repository on this board` }, 400);
1604
1892
  }
1605
1893
  const originalIntent = originalIntentOf(draft.conversationId);
1894
+ const goal = asText(body.goal);
1606
1895
  const ticket = db.createTicket({
1607
1896
  title: body.title.trim(),
1608
- goal: asText(body.goal),
1897
+ goal,
1609
1898
  out_of_scope: asText(body.out_of_scope),
1610
1899
  acceptance: asText(body.acceptance),
1611
1900
  attachments,
@@ -1617,7 +1906,11 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1617
1906
  ...(Array.isArray(body.context)
1618
1907
  ? body.context.filter((line) => typeof line === "string")
1619
1908
  : []),
1620
- ...(originalIntent ? [`Original user intent: ${originalIntent}`] : []),
1909
+ ...(originalIntent
1910
+ ? [`Original user intent: ${originalIntent}`]
1911
+ : body.quick === true && goal
1912
+ ? [`Original user intent: ${goal}`]
1913
+ : []),
1621
1914
  ...["decided", "assumed"].flatMap((field) => {
1622
1915
  const values = draft[field];
1623
1916
  return Array.isArray(values)
@@ -1626,68 +1919,20 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1626
1919
  .map((line) => `Planner ${field === "decided" ? "decision" : "assumption"}: ${line}`)
1627
1920
  : [];
1628
1921
  }),
1629
- ...(typeof draft.rationale === "string" && draft.rationale.trim()
1922
+ // The planner's one-line paraphrase, only when the person's own words
1923
+ // are not on the card already.
1924
+ ...(!originalIntent && typeof draft.rationale === "string" && draft.rationale.trim()
1630
1925
  ? [`User intent: ${draft.rationale.trim()}`]
1631
1926
  : []),
1632
1927
  ],
1928
+ repo: named,
1633
1929
  quick: body.quick === true,
1634
1930
  thinking: asThinking(body.thinking) ?? null,
1931
+ model: typeof body.model === "string" ? body.model.trim().slice(0, 200) || null : null,
1932
+ skills: body.skills,
1635
1933
  });
1636
1934
  return c.json({ ticket }, 201);
1637
1935
  });
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
1936
  /**
1692
1937
  * Run the parked-spec pass now. The allocator does this on its own; the route
1693
1938
  * exists for a person or a client that wants to retry without waiting for
@@ -1876,7 +2121,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1876
2121
  questions: outcome.questions ?? 0,
1877
2122
  cards: outcome.cards ?? 0,
1878
2123
  started_at: new Date(rowStartedAt).toISOString(),
1879
- });
2124
+ }, outcome.output ?? null);
1880
2125
  }
1881
2126
  catch {
1882
2127
  // The log is diagnostics; losing one row must never lose the turn.
@@ -1898,14 +2143,11 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1898
2143
  // answer turn takes its doctrine from the conversation it writes into.
1899
2144
  const mode = options.mode ?? (kind === "task" ? "new-task" : undefined);
1900
2145
  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.
2146
+ // Project repos matter only to the new-task dialog. Every repo on this board
2147
+ // is a candidate for the intake and for the draft: there is nothing to ask.
1903
2148
  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.
2149
+ const included = candidates.map((repo) => repo.name);
2150
+ const repoBriefs = candidates.map(briefOf);
1909
2151
  const forDraft = (findings) => findings?.filter((finding) => !finding.board || included.includes(finding.board));
1910
2152
  // What the person chose travels in their own turn, so the planner reads it
1911
2153
  // and the cards are written from the same source below.
@@ -1989,7 +2231,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1989
2231
  }, attachments, images, passThinking, findings,
1990
2232
  // What is left of the request, not a fresh clock per pass: the intake,
1991
2233
  // 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);
2234
+ Math.max(MIN_PASS_MS, PLAN_TURN_DEADLINE_MS - (Date.now() - startedAt)), repoBriefs, options.model);
1993
2235
  };
1994
2236
  // Saves what the planner decided. Research is a planner input, not part of
1995
2237
  // the plan the dialog reads, so it is not stored.
@@ -1999,15 +2241,20 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
1999
2241
  const assigned = assignIds(drafted, draft);
2000
2242
  // Clamped again here on purpose: a fifth question costs the person attention.
2001
2243
  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.
2244
+ // A card for a repository that is not on this board has nowhere to run.
2245
+ // It is dropped, and the reply says so.
2004
2246
  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));
2247
+ // The workflow's checks run after every turn on this board; a card that
2248
+ // repeats them reports each one twice. A linked board has its own workflow.
2249
+ const workflowCommands = (db.getStageWorkflow("in_progress")?.checks ?? []).map((check) => check.command);
2250
+ const kept = next.cards
2251
+ .filter((card) => !card.board || included.includes(card.board))
2252
+ .map((card) => card.board ? card : { ...card, verify: cardVerify(card.verify, workflowCommands) });
2006
2253
  const cards = answered.decided.length > 0 ? applyDecided(kept, answered.decided) : kept;
2007
2254
  const reply = strays.length > 0
2008
2255
  ? `${next.reply} (Left out ${strays.length === 1 ? "a card" : `${strays.length} cards`} for ${[
2009
2256
  ...new Set(strays.map((card) => card.board)),
2010
- ].join(", ")}: that board was not included.)`.trim()
2257
+ ].join(", ")}: that repository is not on this board.)`.trim()
2011
2258
  : next.reply;
2012
2259
  // The assistant turn is the prose. Questions live in `plan` and are drawn as cards.
2013
2260
  if (reply)
@@ -2029,26 +2276,17 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2029
2276
  findings = forDraft(await awaitReading(reading));
2030
2277
  }
2031
2278
  }
2032
- let drafted = await planOnce(mode, findings);
2279
+ const drafted = await planOnce(mode, findings);
2033
2280
  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
- }
2281
+ // The intake names the repos the work may touch. A scout starts reading
2282
+ // each one now, so the draft has its findings without asking the person.
2283
+ const onBoard = new Set(candidates.map((repo) => repo.name));
2284
+ // Capped: a request that names more repos than this is a project, and
2285
+ // each scout is a model run the person waits on.
2286
+ const named = [...new Set(drafted.boards ?? [])]
2287
+ .filter((name) => onBoard.has(name))
2288
+ .slice(0, MAX_REPO_SCOUTS);
2289
+ extendResearch(conversation.id, named.map((name) => linkedBoardQuestion(name, text)));
2052
2290
  }
2053
2291
  let outcome;
2054
2292
  if (mode !== "intake") {
@@ -2078,7 +2316,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2078
2316
  catch (cause) {
2079
2317
  // A failed turn is the most interesting row in the log: it is the only one
2080
2318
  // that says how long the person waited for nothing.
2081
- measure({ ok: false, error: describeError(cause) });
2319
+ // The planner's session is ephemeral, so the row is the only place an
2320
+ // unreadable block survives to be looked at.
2321
+ measure({
2322
+ ok: false,
2323
+ error: describeError(cause),
2324
+ output: cause instanceof OrchestratorError ? cause.output : null,
2325
+ });
2082
2326
  throw cause;
2083
2327
  }
2084
2328
  finally {
@@ -2113,6 +2357,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2113
2357
  conversationId: asConversationId(body.conversationId),
2114
2358
  attachments,
2115
2359
  thinking: thinking ?? undefined,
2360
+ model: typeof body.model === "string" ? body.model.trim() || undefined : undefined,
2116
2361
  }),
2117
2362
  });
2118
2363
  }
@@ -2126,6 +2371,25 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2126
2371
  * the dialog and the turn comes back with questions and cards — so it carries
2127
2372
  * one message's cap rather than a title's.
2128
2373
  */
2374
+ app.post("/api/orchestrator/planner-question", async (c) => {
2375
+ const body = await c.req.json().catch(() => ({}));
2376
+ const id = "conversationId" in body && typeof body.conversationId === "string"
2377
+ ? body.conversationId
2378
+ : "";
2379
+ const conversation = id ? db.getConversation(id) : null;
2380
+ if (!conversation?.plan?.questions.some((question) => question.options.length > 0)) {
2381
+ return c.json({ error: "No planner option is waiting" }, 409);
2382
+ }
2383
+ try {
2384
+ if (!phone?.plannerQuestion)
2385
+ return c.json({ error: "Phone alert unavailable: cloud relay is disconnected" }, 503);
2386
+ await phone.plannerQuestion(id);
2387
+ return c.json({ status: "accepted" });
2388
+ }
2389
+ catch (cause) {
2390
+ return c.json({ error: cause instanceof Error ? cause.message : "Phone alert unavailable" }, 503);
2391
+ }
2392
+ });
2129
2393
  app.post("/api/orchestrator/intent", async (c) => {
2130
2394
  const body = await c.req
2131
2395
  .json()
@@ -2154,6 +2418,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2154
2418
  conversationId: session.id,
2155
2419
  attachments,
2156
2420
  thinking: thinking ?? undefined,
2421
+ model: typeof body.model === "string" ? body.model.trim() || undefined : undefined,
2157
2422
  }),
2158
2423
  });
2159
2424
  }
@@ -2190,8 +2455,11 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2190
2455
  if (cards.some((card) => !known.has(card.id))) {
2191
2456
  return c.json({ error: "a card lost its id" }, 409);
2192
2457
  }
2458
+ // A model the developer harness does not list is cleared, as a planner turn
2459
+ // clears it, so the card shows the default instead of a model it cannot run.
2460
+ const plan = keepListedModels({ ...conversation.plan, cards }, await developerBrief());
2193
2461
  return c.json({
2194
- conversation: db.setPlan({ ...conversation.plan, cards }, conversation.id),
2462
+ conversation: db.setPlan(plan, conversation.id),
2195
2463
  });
2196
2464
  });
2197
2465
  /** "New chat": a new row, so the old transcript can still be read later. */
@@ -2229,9 +2497,6 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2229
2497
  return c.json({ archived: archived.length });
2230
2498
  });
2231
2499
  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
2500
  const ticket = db.getTicket(c.req.param("id"));
2236
2501
  if (!ticket)
2237
2502
  return c.json({ error: "no such ticket" }, 404);
@@ -2242,7 +2507,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2242
2507
  if (!ticket.pr_url || !ticket.branch) {
2243
2508
  return c.json({ error: "ticket has no linked pull request and branch" }, 409);
2244
2509
  }
2245
- const checkout = worktreePath(root, ticket.id);
2510
+ const checkout = worktreePath(rootFor(ticket), ticket.id);
2246
2511
  if (!existsSync(join(checkout, ".git")))
2247
2512
  return c.json({ error: "ticket checkout is missing" }, 409);
2248
2513
  try {
@@ -2279,10 +2544,142 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2279
2544
  return c.json({ error: cause instanceof Error ? cause.message : "could not read pull request status" }, 502);
2280
2545
  }
2281
2546
  });
2282
- app.post("/api/tickets/:id/merge", async (c) => {
2547
+ /**
2548
+ * Why a ticket's recorded pull request cannot be read for checks, or null when
2549
+ * it can. The same gate as the merge status: Review only, no run in progress,
2550
+ * and a checkout to read from.
2551
+ */
2552
+ function checksRefusal(ticket) {
2553
+ if (ticket.state !== "review")
2554
+ return `ticket is ${ticket.state}`;
2555
+ if (runs.isRunning(ticket.id))
2556
+ return "ticket has a run in progress";
2557
+ if (!ticket.pr_url || !ticket.branch)
2558
+ return "ticket has no linked pull request and branch";
2559
+ if (!existsSync(join(worktreePath(rootFor(ticket), ticket.id), ".git")))
2560
+ return "ticket checkout is missing";
2561
+ return null;
2562
+ }
2563
+ /**
2564
+ * The checks on the ticket's pull request, once GitHub confirms it is the
2565
+ * ticket's own branch. A checks list GitHub did not return is an error, never
2566
+ * an empty list the panel could mistake for "nothing failed".
2567
+ */
2568
+ async function pullRequestChecksFor(ticket) {
2569
+ const checkout = worktreePath(rootFor(ticket), ticket.id);
2570
+ const prUrl = ticket.pr_url ?? "";
2571
+ try {
2572
+ const [pr, checks] = await Promise.all([
2573
+ readPullRequestSnapshot(checkout, prUrl, ghCommand),
2574
+ readPullRequestChecks(checkout, prUrl, ghCommand),
2575
+ ]);
2576
+ if (pr.headRefName !== ticket.branch) {
2577
+ return { error: "linked pull request does not match the ticket branch", status: 409 };
2578
+ }
2579
+ if (!checks)
2580
+ return { error: "could not read GitHub checks", status: 502 };
2581
+ return { checks };
2582
+ }
2583
+ catch (cause) {
2584
+ return {
2585
+ error: cause instanceof Error ? cause.message : "could not read pull request status",
2586
+ status: 502,
2587
+ };
2588
+ }
2589
+ }
2590
+ app.get("/api/tickets/:id/checks", async (c) => {
2283
2591
  if (c.get("principal").kind !== "local") {
2284
- return c.json({ error: "merging is available from the local board only" }, 403);
2592
+ return c.json({ error: "checks are available from the local board only" }, 403);
2285
2593
  }
2594
+ const ticket = db.getTicket(c.req.param("id"));
2595
+ if (!ticket)
2596
+ return c.json({ error: "no such ticket" }, 404);
2597
+ const refusal = checksRefusal(ticket);
2598
+ if (refusal)
2599
+ return c.json({ error: refusal }, 409);
2600
+ const result = await pullRequestChecksFor(ticket);
2601
+ if ("error" in result)
2602
+ return c.json({ error: result.error }, result.status);
2603
+ return c.json({ checks: result.checks });
2604
+ });
2605
+ /**
2606
+ * Starts one developer run on the ticket's own branch for one failing check.
2607
+ * It is the same start the card's comments use: the run exists first, and only
2608
+ * then does the card move to In Progress.
2609
+ */
2610
+ app.post("/api/tickets/:id/checks/fix", async (c) => {
2611
+ if (c.get("principal").kind !== "local") {
2612
+ return c.json({ error: "fixing checks is available from the local board only" }, 403);
2613
+ }
2614
+ const ticket = db.getTicket(c.req.param("id"));
2615
+ if (!ticket)
2616
+ return c.json({ error: "no such ticket" }, 404);
2617
+ const body = (await c.req.json().catch(() => ({})));
2618
+ const name = typeof body.name === "string" ? body.name : "";
2619
+ if (!name)
2620
+ return c.json({ error: "name the check to fix" }, 400);
2621
+ const refusal = checksRefusal(ticket);
2622
+ if (refusal)
2623
+ return c.json({ error: refusal }, 409);
2624
+ if (runs.runningCount() >= maxConcurrentRuns()) {
2625
+ return c.json({ error: "all agent slots are busy" }, 409);
2626
+ }
2627
+ const result = await pullRequestChecksFor(ticket);
2628
+ if ("error" in result)
2629
+ return c.json({ error: result.error }, result.status);
2630
+ const check = result.checks.find((item) => item.name === name);
2631
+ if (!check)
2632
+ return c.json({ error: `no check named ${name} on this pull request` }, 409);
2633
+ if (check.state !== "failing") {
2634
+ return c.json({ error: `check ${name} is ${check.state}, not failing` }, 409);
2635
+ }
2636
+ // The reads took a moment; the person may have moved the card since.
2637
+ const current = db.getTicket(ticket.id);
2638
+ if (!current ||
2639
+ checksRefusal(current) ||
2640
+ current.branch !== ticket.branch ||
2641
+ current.pr_url !== ticket.pr_url) {
2642
+ return c.json({ error: "ticket changed while checks were loading" }, 409);
2643
+ }
2644
+ let worktree;
2645
+ try {
2646
+ worktree = await checkoutFor(current);
2647
+ }
2648
+ catch {
2649
+ return c.json({ error: "the ticket checkout could not be prepared" }, 409);
2650
+ }
2651
+ let status;
2652
+ try {
2653
+ status = await runs.begin(current, worktree, 1, {
2654
+ prompt: buildCheckFixPrompt(current, {
2655
+ name: check.name,
2656
+ link: check.link,
2657
+ branch: worktree.branch,
2658
+ }),
2659
+ profile: "developer",
2660
+ label: `Fixing check ${check.name}`,
2661
+ // A fix is one attempt; a retry would rebuild the ticket's original brief.
2662
+ retry: false,
2663
+ source: "check",
2664
+ });
2665
+ }
2666
+ catch (cause) {
2667
+ return c.json({ error: cause instanceof Error ? cause.message : "the run was refused" }, 409);
2668
+ }
2669
+ if (status.phase !== "running")
2670
+ return c.json({ error: status.error ?? "the run failed" }, 409);
2671
+ if (current.state !== "in_progress") {
2672
+ try {
2673
+ db.transition(current.id, "in_progress");
2674
+ }
2675
+ catch (cause) {
2676
+ runs.cancel(current.id);
2677
+ return c.json({ error: cause instanceof Error ? cause.message : "the ticket could not move" }, 409);
2678
+ }
2679
+ }
2680
+ return c.json({ started: check.name, run: status }, 202);
2681
+ });
2682
+ app.post("/api/tickets/:id/merge", async (c) => {
2286
2683
  const ticket = db.getTicket(c.req.param("id"));
2287
2684
  if (!ticket)
2288
2685
  return c.json({ error: "no such ticket" }, 404);
@@ -2295,7 +2692,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2295
2692
  }
2296
2693
  if (mergeInFlight.has(ticket.id))
2297
2694
  return c.json({ error: "a merge is already in progress" }, 409);
2298
- const checkout = worktreePath(root, ticket.id);
2695
+ const checkout = worktreePath(rootFor(ticket), ticket.id);
2299
2696
  if (!existsSync(join(checkout, ".git")))
2300
2697
  return c.json({ error: "ticket checkout is missing" }, 409);
2301
2698
  const body = await c.req
@@ -2400,6 +2797,50 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2400
2797
  issueInFlight.delete(comment.id);
2401
2798
  }
2402
2799
  });
2800
+ /**
2801
+ * The person takes the ticket into their own terminal agent. The card moves
2802
+ * to `handed_off` before the run stops, so nothing that watches the run's
2803
+ * end mistakes it for a run to restart. The token in the returned command is
2804
+ * shown once; the database keeps only its hash.
2805
+ */
2806
+ app.post("/api/tickets/:id/handoff", async (c) => {
2807
+ const id = c.req.param("id");
2808
+ const ticket = db.getTicket(id);
2809
+ if (!ticket)
2810
+ return c.json({ error: "no such ticket" }, 404);
2811
+ if (!canTransition(ticket.state, "handed_off")) {
2812
+ return c.json({ error: describeRefusal(ticket.state, "handed_off") }, 409);
2813
+ }
2814
+ const latest = db.latestAgentRun(id);
2815
+ const handoffWith = handoffHarness(latest?.harness || effectiveHarness());
2816
+ if (!handoffWith) {
2817
+ return c.json({
2818
+ error: "only Claude Code and Codex sessions can be taken over in a terminal; this ticket runs on another harness",
2819
+ }, 409);
2820
+ }
2821
+ const session = latest && handoffHarness(latest.harness) === handoffWith ? (latest.session_id ?? null) : null;
2822
+ const worktree = await checkoutFor(ticket);
2823
+ const handoffToken = randomBytes(24).toString("hex");
2824
+ const moved = db.handOff(id, { harness: handoffWith, session, token: handoffToken });
2825
+ await stopRun(id, "cancel");
2826
+ const command = handoffCommand({
2827
+ harness: handoffWith,
2828
+ session,
2829
+ worktree: worktree.path,
2830
+ ticketId: id,
2831
+ boardUrl: `http://127.0.0.1:${port}`,
2832
+ token: handoffToken,
2833
+ agentPath,
2834
+ brief: handoffBrief(ticket, session !== null),
2835
+ });
2836
+ return c.json({
2837
+ ticket: moved,
2838
+ harness: handoffWith,
2839
+ session,
2840
+ worktree: worktree.path,
2841
+ command,
2842
+ });
2843
+ });
2403
2844
  app.post("/api/tickets/:id/transition", async (c) => {
2404
2845
  const body = await c.req
2405
2846
  .json()
@@ -2441,9 +2882,11 @@ export function createApp({ db, token, port, webRoot, repoRoot, plan, summarize,
2441
2882
  runs.settle(id);
2442
2883
  if (to === "done") {
2443
2884
  await stopRun(id, "settle");
2444
- await retireWorktree(root, id, moved.branch);
2885
+ const checkoutRoot = retireRootFor(moved);
2886
+ if (checkoutRoot)
2887
+ await retireWorktree(checkoutRoot, id, moved.branch);
2445
2888
  }
2446
- const run = to === "in_progress" && worktree ? runs.start(moved, worktree) : null;
2889
+ const run = to === "in_progress" && worktree ? await runs.begin(moved, worktree) : null;
2447
2890
  if (to === "queued")
2448
2891
  await scheduleTickets();
2449
2892
  return c.json({ ticket: db.getTicket(id) ?? moved, worktree, run });