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
package/dist/db/db.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
2
  import { mkdirSync } from "node:fs";
3
3
  import { dirname } from "node:path";
4
- import { randomUUID } from "node:crypto";
4
+ import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
5
5
  import { attachmentPaths } from "../attachments.js";
6
6
  import { MAX_ACTION_OUTPUT } from "../run/actions.js";
7
7
  import { PROFILES } from "../run/profiles.js";
8
8
  import { normaliseRunResult } from "../run/result.js";
9
- import { asMaxAgents, asPlannerThinking, DEFAULT_MAX_AGENTS, DEFAULT_PLANNER_THINKING, } from "../run/settings.js";
9
+ import { asMaxAgents, asPlannerThinking, DEFAULT_MAX_AGENTS, DEFAULT_TESTS_FIRST_ENABLED, DEFAULT_PLANNER_THINKING, } from "../run/settings.js";
10
+ import { skillIds } from "../run/skills.js";
10
11
  import { parseThinkingLevel } from "../run/thinking.js";
11
12
  import { emptyWorkflow, hasWorkflow, isWorkflowStage, normaliseWorkflow, } from "../run/workflow.js";
12
13
  import { canTransition, checkSpec, describeRefusal, TransitionError, } from "./lifecycle.js";
@@ -64,8 +65,6 @@ function parseCommentActions(raw) {
64
65
  return undefined;
65
66
  const value = parsed;
66
67
  const actions = {};
67
- if (typeof value.workflows === "boolean")
68
- actions.workflows = value.workflows;
69
68
  if (typeof value.fixPrompt === "string")
70
69
  actions.fixPrompt = value.fixPrompt;
71
70
  const issue = value.issue;
@@ -207,7 +206,9 @@ const MIGRATIONS = [
207
206
  output_chars INTEGER NOT NULL DEFAULT 0,
208
207
  questions INTEGER NOT NULL DEFAULT 0,
209
208
  cards INTEGER NOT NULL DEFAULT 0,
210
- started_at TEXT NOT NULL
209
+ started_at TEXT NOT NULL,
210
+ -- What the model wrote, kept only when the turn failed on that text.
211
+ output TEXT
211
212
  );
212
213
 
213
214
  CREATE INDEX IF NOT EXISTS idx_planner_turns_started
@@ -242,22 +243,9 @@ const MIGRATIONS = [
242
243
  );
243
244
  `,
244
245
  `
245
- -- A manager's proposal is evidence beside the workflow, not the workflow.
246
- -- Pending rows are what the Workflows page shows; applying or dismissing
247
- -- stamps the row rather than deleting it, so a bad suggestion stays visible in
248
- -- the record after it was refused.
249
- CREATE TABLE IF NOT EXISTS workflow_suggestions (
250
- id TEXT PRIMARY KEY,
251
- stage TEXT NOT NULL,
252
- ticket_id TEXT NOT NULL,
253
- evidence TEXT NOT NULL DEFAULT '[]',
254
- notes TEXT NOT NULL,
255
- created_at TEXT NOT NULL,
256
- applied_at TEXT,
257
- dismissed_at TEXT
258
- );
259
- CREATE INDEX IF NOT EXISTS idx_workflow_suggestions_stage
260
- ON workflow_suggestions(stage, created_at);
246
+ -- Manager notes used to queue here for the Workflows page, one near-identical
247
+ -- rewrite per run. They are a comment on the ticket now; the queue is gone.
248
+ DROP TABLE IF EXISTS workflow_suggestions;
261
249
  `,
262
250
  `
263
251
  -- The board's revision is a counter, not a timestamp: a client that saw
@@ -301,10 +289,57 @@ const MIGRATIONS = [
301
289
  output TEXT,
302
290
  PRIMARY KEY (run_id, seq)
303
291
  );
292
+ `,
293
+ `
294
+ -- Repositories attached to this board besides the home repo. A card with a
295
+ -- non-null tickets.repo works in that repository's checkout.
296
+ CREATE TABLE IF NOT EXISTS project_repos (
297
+ name TEXT PRIMARY KEY,
298
+ root TEXT NOT NULL UNIQUE,
299
+ added_at TEXT NOT NULL
300
+ );
301
+ `,
302
+ `
303
+ -- How long each Verify or workflow-check command took the last time the board
304
+ -- ran it, keyed by the exact command string. The developer prompt quotes it,
305
+ -- so an agent knows a slow command is slow before its shell returns early.
306
+ -- repo is '' for the home repo and the project_repos name otherwise.
307
+ CREATE TABLE IF NOT EXISTS command_durations (
308
+ repo TEXT NOT NULL DEFAULT '',
309
+ command TEXT NOT NULL,
310
+ duration_ms INTEGER NOT NULL,
311
+ measured_at TEXT NOT NULL,
312
+ PRIMARY KEY (repo, command)
313
+ );
314
+ `,
315
+ `
316
+ -- Reusable agent guidance a person keeps on the board. Config, not record: it
317
+ -- survives a board reset. The name is the key, so a skill is found by what it
318
+ -- is called. source is the GitHub link it was loaded from, or '' when typed.
319
+ CREATE TABLE IF NOT EXISTS skills (
320
+ name TEXT PRIMARY KEY,
321
+ body TEXT NOT NULL,
322
+ source TEXT NOT NULL DEFAULT '',
323
+ enabled INTEGER NOT NULL DEFAULT 1,
324
+ created_at TEXT NOT NULL
325
+ );
304
326
  `,
305
327
  ];
306
328
  /** A run keeps at most this many tool-call rows; later calls are not recorded. */
307
329
  export const MAX_RUN_TOOL_CALLS = 500;
330
+ /**
331
+ * A failed turn keeps at most this much of what the model wrote. The tail is
332
+ * kept, because the plan block is the last thing it writes.
333
+ */
334
+ export const MAX_PLANNER_OUTPUT_CHARS = 100_000;
335
+ function toSkill(row) {
336
+ return {
337
+ name: String(row.name),
338
+ text: String(row.body ?? ""),
339
+ source: String(row.source ?? ""),
340
+ enabled: Number(row.enabled) === 1,
341
+ };
342
+ }
308
343
  function toProfile(row) {
309
344
  return {
310
345
  name: String(row.name),
@@ -329,6 +364,8 @@ function toTicket(row) {
329
364
  state: String(row.state),
330
365
  profile: row.profile === null ? null : String(row.profile),
331
366
  thinking: parseThinkingLevel(row.thinking === null ? null : String(row.thinking)) ?? null,
367
+ model: typeof row.model === "string" && row.model.trim() ? row.model : null,
368
+ skills: parseSkills(row.skills),
332
369
  blocker_kind: (row.blocker_kind ?? null),
333
370
  blocker_reason: row.blocker_reason === null ? null : String(row.blocker_reason),
334
371
  blocker_unblock: row.blocker_unblock === null ? null : String(row.blocker_unblock),
@@ -337,11 +374,33 @@ function toTicket(row) {
337
374
  pr_url: row.pr_url === null || row.pr_url === undefined ? null : String(row.pr_url),
338
375
  branch: row.branch === null || row.branch === undefined ? null : String(row.branch),
339
376
  archived_at: row.archived_at === null || row.archived_at === undefined ? null : String(row.archived_at),
377
+ repo: row.repo === null || row.repo === undefined ? null : String(row.repo),
378
+ handoff: typeof row.handed_off_at === "string" && typeof row.handoff_harness === "string"
379
+ ? {
380
+ harness: row.handoff_harness,
381
+ session: typeof row.handoff_session === "string" ? row.handoff_session : null,
382
+ at: row.handed_off_at,
383
+ }
384
+ : null,
340
385
  created_at: String(row.created_at),
341
386
  updated_at: String(row.updated_at),
342
387
  confirmed_at: row.confirmed_at === null ? null : String(row.confirmed_at),
343
388
  };
344
389
  }
390
+ function hashHandoffToken(token) {
391
+ return createHash("sha256").update(token).digest("hex");
392
+ }
393
+ /** A malformed column reads as "no skills chosen", never as a crash. */
394
+ function parseSkills(value) {
395
+ if (typeof value !== "string")
396
+ return [];
397
+ try {
398
+ return skillIds(JSON.parse(value));
399
+ }
400
+ catch {
401
+ return [];
402
+ }
403
+ }
345
404
  /** A malformed or hostile column reads as "no screenshots", never as a crash. */
346
405
  function parseAttachments(value) {
347
406
  if (typeof value !== "string")
@@ -410,7 +469,10 @@ function toAgentRun(row) {
410
469
  resume_count: Number(row.resume_count) || 0,
411
470
  profile: row.profile === null || row.profile === undefined ? null : String(row.profile),
412
471
  harness: row.harness === null || row.harness === undefined ? null : String(row.harness),
413
- job_source: row.job_source === "comment" || row.job_source === "conflict" ? row.job_source : "ticket",
472
+ model: row.model === null || row.model === undefined ? null : String(row.model),
473
+ job_source: row.job_source === "comment" || row.job_source === "conflict" || row.job_source === "check"
474
+ ? row.job_source
475
+ : "ticket",
414
476
  job_prompt: row.job_prompt === null || row.job_prompt === undefined ? null : String(row.job_prompt),
415
477
  job_system_prompt: row.job_system_prompt === null || row.job_system_prompt === undefined
416
478
  ? null
@@ -508,11 +570,18 @@ export class ZelioDb {
508
570
  this.ensureColumn("tickets", "context", "TEXT NOT NULL DEFAULT '[]'");
509
571
  this.ensureColumn("tickets", "quick", "INTEGER NOT NULL DEFAULT 0");
510
572
  this.ensureColumn("tickets", "thinking", "TEXT");
573
+ this.ensureColumn("tickets", "model", "TEXT");
574
+ this.ensureColumn("tickets", "skills", "TEXT NOT NULL DEFAULT '[]'");
511
575
  this.ensureColumn("tickets", "prepare_error", "TEXT");
512
576
  this.ensureColumn("tickets", "pr_url", "TEXT");
513
577
  this.ensureColumn("tickets", "branch", "TEXT");
514
578
  this.ensureColumn("tickets", "archived_at", "TEXT");
515
579
  this.ensureColumn("tickets", "verify", "TEXT NOT NULL DEFAULT '[]'");
580
+ this.ensureColumn("tickets", "repo", "TEXT");
581
+ this.ensureColumn("tickets", "handoff_harness", "TEXT");
582
+ this.ensureColumn("tickets", "handoff_session", "TEXT");
583
+ this.ensureColumn("tickets", "handed_off_at", "TEXT");
584
+ this.ensureColumn("tickets", "handoff_token", "TEXT");
516
585
  this.ensureColumn("conversations", "summary", "TEXT");
517
586
  this.ensureColumn("conversations", "summary_from", "TEXT");
518
587
  this.ensureColumn("conversations", "kind", "TEXT NOT NULL DEFAULT 'panel'");
@@ -529,6 +598,7 @@ export class ZelioDb {
529
598
  this.ensureColumn("agent_runs", "resume_count", "INTEGER NOT NULL DEFAULT 0");
530
599
  this.ensureColumn("agent_runs", "profile", "TEXT");
531
600
  this.ensureColumn("agent_runs", "harness", "TEXT");
601
+ this.ensureColumn("agent_runs", "model", "TEXT");
532
602
  this.ensureColumn("agent_runs", "job_source", "TEXT NOT NULL DEFAULT 'ticket'");
533
603
  this.ensureColumn("agent_runs", "job_prompt", "TEXT");
534
604
  this.ensureColumn("agent_runs", "job_system_prompt", "TEXT");
@@ -538,11 +608,8 @@ export class ZelioDb {
538
608
  this.ensureColumn("agent_runs", "workflow", "TEXT");
539
609
  this.ensureColumn("planner_turns", "tool_budget", "INTEGER NOT NULL DEFAULT 0");
540
610
  this.ensureColumn("planner_turns", "capped", "TEXT");
611
+ this.ensureColumn("planner_turns", "output", "TEXT");
541
612
  this.seedProfiles();
542
- // A model written before harnesses were paired to profiles belonged to the
543
- // only runtime that existed then. Record that instead of letting a later
544
- // machine default send a pi model to Codex.
545
- this.db.exec("UPDATE agent_profiles SET harness = 'pi' WHERE model <> '' AND (harness IS NULL OR harness = '')");
546
613
  }
547
614
  /**
548
615
  * Seed once, then leave the rows alone: a restart must not undo an edit, and
@@ -691,10 +758,40 @@ export class ZelioDb {
691
758
  this.seedProfiles();
692
759
  return this.listProfiles();
693
760
  }
761
+ /** Oldest first, so a skill keeps its place in the list once saved. */
762
+ listSkills() {
763
+ const rows = this.db
764
+ .prepare("SELECT * FROM skills ORDER BY created_at ASC, name ASC")
765
+ .all();
766
+ return rows.map(toSkill);
767
+ }
768
+ getSkill(name) {
769
+ const row = this.db.prepare("SELECT * FROM skills WHERE name = ?").get(name);
770
+ return row ? toSkill(row) : null;
771
+ }
772
+ addSkill(input) {
773
+ this.db
774
+ .prepare("INSERT INTO skills (name, body, source, enabled, created_at) VALUES (?, ?, ?, ?, ?)")
775
+ .run(input.name, input.text, input.source ?? "", input.enabled === false ? 0 : 1, new Date().toISOString());
776
+ return this.getSkill(input.name);
777
+ }
778
+ /** Edits the text or the enabled switch; the name is the key and stays. */
779
+ updateSkill(name, patch) {
780
+ const current = this.getSkill(name);
781
+ if (!current)
782
+ return null;
783
+ const next = { ...current, ...patch };
784
+ this.db
785
+ .prepare("UPDATE skills SET body = ?, enabled = ? WHERE name = ?")
786
+ .run(next.text, next.enabled ? 1 : 0, name);
787
+ return this.getSkill(name);
788
+ }
694
789
  createTicket(input) {
695
790
  const now = new Date().toISOString();
696
791
  const state = input.state ?? "proposed";
697
792
  const thinking = parseThinkingLevel(input.thinking ?? null) ?? null;
793
+ const model = input.model?.trim() || null;
794
+ const skills = skillIds(input.skills);
698
795
  const ticket = {
699
796
  id: `T-${randomUUID().slice(0, 8)}`,
700
797
  title: input.title,
@@ -708,6 +805,8 @@ export class ZelioDb {
708
805
  state,
709
806
  profile: input.profile ?? null,
710
807
  thinking,
808
+ model,
809
+ skills,
711
810
  blocker_kind: null,
712
811
  blocker_reason: null,
713
812
  blocker_unblock: null,
@@ -715,16 +814,18 @@ export class ZelioDb {
715
814
  prepare_error: null,
716
815
  pr_url: null,
717
816
  branch: null,
817
+ archived_at: null,
818
+ repo: input.repo?.trim() || null,
718
819
  created_at: now,
719
820
  updated_at: now,
720
821
  confirmed_at: state === "todo" ? now : null,
721
822
  };
722
823
  this.db
723
824
  .prepare(`INSERT INTO tickets (id, title, goal, out_of_scope, acceptance, likely_files, context, attachments,
724
- verify, state, profile, thinking, blocker_kind, blocker_reason, blocker_unblock, quick,
725
- prepare_error, created_at, updated_at, confirmed_at)
726
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
727
- .run(ticket.id, ticket.title, ticket.goal, ticket.out_of_scope, ticket.acceptance, JSON.stringify(ticket.likely_files), JSON.stringify(ticket.context), JSON.stringify(ticket.attachments), JSON.stringify(ticket.verify), ticket.state, ticket.profile, thinking, null, null, null, ticket.quick ? 1 : 0, null, ticket.created_at, ticket.updated_at, ticket.confirmed_at);
825
+ verify, state, profile, thinking, model, skills, blocker_kind, blocker_reason, blocker_unblock,
826
+ quick, prepare_error, repo, created_at, updated_at, confirmed_at)
827
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
828
+ .run(ticket.id, ticket.title, ticket.goal, ticket.out_of_scope, ticket.acceptance, JSON.stringify(ticket.likely_files), JSON.stringify(ticket.context), JSON.stringify(ticket.attachments), JSON.stringify(ticket.verify), ticket.state, ticket.profile, thinking, model, JSON.stringify(skills), null, null, null, ticket.quick ? 1 : 0, null, ticket.repo ?? null, ticket.created_at, ticket.updated_at, ticket.confirmed_at);
728
829
  this.emit({ type: "ticket_created", ticket });
729
830
  return ticket;
730
831
  }
@@ -829,6 +930,39 @@ export class ZelioDb {
829
930
  this.emit({ type: "ticket_updated", ticket: next });
830
931
  return next;
831
932
  }
933
+ /**
934
+ * Moves the ticket to `handed_off` and records who has it, in one statement:
935
+ * a token that outlived its state, or a state with no token, would be a card
936
+ * nobody can write to or one an old agent still can.
937
+ */
938
+ handOff(id, input) {
939
+ const ticket = this.getTicket(id);
940
+ if (!ticket)
941
+ throw new TransitionError("todo", "handed_off", `no ticket ${id}`);
942
+ if (!canTransition(ticket.state, "handed_off")) {
943
+ throw new TransitionError(ticket.state, "handed_off", describeRefusal(ticket.state, "handed_off"));
944
+ }
945
+ const now = new Date().toISOString();
946
+ this.db
947
+ .prepare(`UPDATE tickets SET state = 'handed_off', blocker_kind = NULL, blocker_reason = NULL,
948
+ blocker_unblock = NULL, handoff_harness = ?, handoff_session = ?, handed_off_at = ?,
949
+ handoff_token = ?, updated_at = ? WHERE id = ?`)
950
+ .run(input.harness, input.session, now, hashHandoffToken(input.token), now, id);
951
+ const next = this.getTicket(id);
952
+ this.emit({ type: "ticket_updated", ticket: next });
953
+ return next;
954
+ }
955
+ /** The handed-off agent's token, valid only while the card is still handed off. */
956
+ verifyHandoffToken(id, token) {
957
+ if (!token)
958
+ return false;
959
+ const row = this.db.prepare("SELECT state, handoff_token FROM tickets WHERE id = ?").get(id);
960
+ if (!row || row.state !== "handed_off" || typeof row.handoff_token !== "string")
961
+ return false;
962
+ const expected = Buffer.from(row.handoff_token);
963
+ const actual = Buffer.from(hashHandoffToken(token));
964
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
965
+ }
832
966
  transition(id, to, extra = {}) {
833
967
  const ticket = this.getTicket(id);
834
968
  if (!ticket)
@@ -848,9 +982,68 @@ export class ZelioDb {
848
982
  .prepare(`UPDATE tickets SET state = ?, profile = ?, blocker_kind = ?, blocker_reason = ?,
849
983
  blocker_unblock = ?, updated_at = ?, confirmed_at = ? WHERE id = ?`)
850
984
  .run(next.state, next.profile, next.blocker_kind, next.blocker_reason, next.blocker_unblock, next.updated_at, next.confirmed_at, id);
985
+ // Leaving `handed_off` ends that agent's access; the record of who had it stays.
986
+ if (ticket.state === "handed_off" && to !== "handed_off") {
987
+ this.db.prepare("UPDATE tickets SET handoff_token = NULL WHERE id = ?").run(id);
988
+ }
851
989
  this.emit({ type: "ticket_updated", ticket: next });
852
990
  return next;
853
991
  }
992
+ /** Attached repositories, oldest first. */
993
+ listRepos() {
994
+ const rows = this.db
995
+ .prepare("SELECT name, root, added_at FROM project_repos ORDER BY added_at ASC, name ASC")
996
+ .all();
997
+ return rows.map((row) => ({
998
+ name: String(row.name),
999
+ root: String(row.root),
1000
+ added_at: String(row.added_at),
1001
+ }));
1002
+ }
1003
+ addRepo(input) {
1004
+ const repo = {
1005
+ name: input.name,
1006
+ root: input.root,
1007
+ added_at: new Date().toISOString(),
1008
+ };
1009
+ this.db
1010
+ .prepare("INSERT INTO project_repos (name, root, added_at) VALUES (?, ?, ?)")
1011
+ .run(repo.name, repo.root, repo.added_at);
1012
+ this.emit({ type: "repo_changed", name: repo.name });
1013
+ return repo;
1014
+ }
1015
+ /** Detaches a repository row. Its tickets are the caller's to archive or refuse first. */
1016
+ removeRepo(name) {
1017
+ const result = this.db.prepare("DELETE FROM project_repos WHERE name = ?").run(name);
1018
+ if (Number(result.changes) === 0)
1019
+ return false;
1020
+ this.emit({ type: "repo_changed", name });
1021
+ return true;
1022
+ }
1023
+ /**
1024
+ * Takes every card of one added repository off the board, the same way
1025
+ * archiveDone() does: rows, comments and runs stay.
1026
+ */
1027
+ archiveRepoTickets(name) {
1028
+ const rows = this.db
1029
+ .prepare("SELECT * FROM tickets WHERE repo = ? AND archived_at IS NULL")
1030
+ .all(name);
1031
+ if (rows.length === 0)
1032
+ return [];
1033
+ const now = new Date().toISOString();
1034
+ this.db
1035
+ .prepare("UPDATE tickets SET archived_at = ?, updated_at = ? WHERE repo = ? AND archived_at IS NULL")
1036
+ .run(now, now, name);
1037
+ const archived = rows.map((row) => {
1038
+ const ticket = toTicket(row);
1039
+ ticket.archived_at = now;
1040
+ ticket.updated_at = now;
1041
+ return ticket;
1042
+ });
1043
+ for (const ticket of archived)
1044
+ this.emit({ type: "ticket_updated", ticket });
1045
+ return archived;
1046
+ }
854
1047
  /**
855
1048
  * Takes every completed card off the board without deleting anything: the
856
1049
  * rows, their comments and their runs stay, and only listTickets() stops
@@ -1103,6 +1296,7 @@ export class ZelioDb {
1103
1296
  resume_count: session.resumeCount ?? 0,
1104
1297
  profile: session.profile ?? null,
1105
1298
  harness: session.harness ?? null,
1299
+ model: session.model ?? null,
1106
1300
  job_source: session.source ?? "ticket",
1107
1301
  job_prompt: session.prompt ?? null,
1108
1302
  job_system_prompt: session.systemPrompt ?? null,
@@ -1114,9 +1308,9 @@ export class ZelioDb {
1114
1308
  this.db
1115
1309
  .prepare(`INSERT INTO agent_runs (id, ticket_id, attempt, state, started_at, ended_at, exit_code,
1116
1310
  git_status, git_diff, error, input_tokens, output_tokens, cost, workflow_stage, workflow,
1117
- session_id, resume_count, profile, harness, job_source, job_prompt, job_system_prompt)
1118
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1119
- .run(run.id, run.ticket_id, run.attempt, run.state, run.started_at, null, null, null, null, null, null, null, null, run.workflow_stage, run.workflow ? JSON.stringify(run.workflow) : null, run.session_id, run.resume_count, run.profile, run.harness, run.job_source, run.job_prompt, run.job_system_prompt);
1311
+ session_id, resume_count, profile, harness, model, job_source, job_prompt, job_system_prompt)
1312
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1313
+ .run(run.id, run.ticket_id, run.attempt, run.state, run.started_at, null, null, null, null, null, null, null, null, run.workflow_stage, run.workflow ? JSON.stringify(run.workflow) : null, run.session_id, run.resume_count, run.profile, run.harness, run.model, run.job_source, run.job_prompt, run.job_system_prompt);
1120
1314
  return run;
1121
1315
  }
1122
1316
  finishAgentRun(id, input) {
@@ -1135,6 +1329,26 @@ export class ZelioDb {
1135
1329
  .prepare("UPDATE agent_runs SET input_tokens = ?, output_tokens = ?, cost = ? WHERE id = ? AND state = 'running'")
1136
1330
  .run(tokens.input, tokens.output, cost, id);
1137
1331
  }
1332
+ /** Keep the latest measured duration of one check command; a later run replaces it. */
1333
+ recordCommandDuration(repo, command, durationMs) {
1334
+ this.db
1335
+ .prepare(`INSERT INTO command_durations (repo, command, duration_ms, measured_at)
1336
+ VALUES (?, ?, ?, ?)
1337
+ ON CONFLICT(repo, command) DO UPDATE SET
1338
+ duration_ms = excluded.duration_ms, measured_at = excluded.measured_at`)
1339
+ .run(repo ?? "", command, Math.max(0, Math.round(durationMs)), new Date().toISOString());
1340
+ }
1341
+ /** The last measured duration of each command that has one, in milliseconds. */
1342
+ commandDurations(repo, commands) {
1343
+ const found = new Map();
1344
+ const read = this.db.prepare("SELECT duration_ms FROM command_durations WHERE repo = ? AND command = ?");
1345
+ for (const command of new Set(commands)) {
1346
+ const row = read.get(repo ?? "", command);
1347
+ if (typeof row?.duration_ms === "number")
1348
+ found.set(command, row.duration_ms);
1349
+ }
1350
+ return found;
1351
+ }
1138
1352
  recordCommandEvidence(id, evidence) {
1139
1353
  this.db
1140
1354
  .prepare("UPDATE agent_runs SET command_evidence = ? WHERE id = ? AND state = 'running'")
@@ -1350,17 +1564,29 @@ export class ZelioDb {
1350
1564
  duration_ms = excluded.duration_ms, json = excluded.json`)
1351
1565
  .run(index.head, index.indexed_at, index.duration_ms, JSON.stringify(index));
1352
1566
  }
1353
- /** One row per planner turn. Append-only: a turn is a fact that already ended. */
1354
- recordPlannerTurn(turn) {
1567
+ /**
1568
+ * One row per planner turn. Append-only: a turn is a fact that already ended.
1569
+ * `output` is what the model wrote, kept only for a turn that failed on it;
1570
+ * it stays out of `listPlannerTurns`, so the metrics payload does not carry it.
1571
+ */
1572
+ recordPlannerTurn(turn, output = null) {
1355
1573
  const row = { ...turn, id: randomUUID() };
1574
+ const kept = output === null || output.length <= MAX_PLANNER_OUTPUT_CHARS
1575
+ ? output
1576
+ : output.slice(-MAX_PLANNER_OUTPUT_CHARS);
1356
1577
  this.db
1357
1578
  .prepare(`INSERT INTO planner_turns (id, conversation_id, kind, mode, ok, error, duration_ms,
1358
1579
  index_ms, first_event_ms, harness_ms, tool_calls, tool_errors, tool_budget, capped,
1359
- prompt_chars, output_chars, questions, cards, started_at)
1360
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1361
- .run(row.id, row.conversation_id, row.kind, row.mode, row.ok ? 1 : 0, row.error, row.duration_ms, row.index_ms, row.first_event_ms, row.harness_ms, row.tool_calls, row.tool_errors, row.tool_budget, row.capped, row.prompt_chars, row.output_chars, row.questions, row.cards, row.started_at);
1580
+ prompt_chars, output_chars, questions, cards, started_at, output)
1581
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1582
+ .run(row.id, row.conversation_id, row.kind, row.mode, row.ok ? 1 : 0, row.error, row.duration_ms, row.index_ms, row.first_event_ms, row.harness_ms, row.tool_calls, row.tool_errors, row.tool_budget, row.capped, row.prompt_chars, row.output_chars, row.questions, row.cards, row.started_at, kept);
1362
1583
  return row;
1363
1584
  }
1585
+ /** What the model wrote on a failed turn, or null when nothing was kept. */
1586
+ plannerTurnOutput(id) {
1587
+ const row = this.db.prepare("SELECT output FROM planner_turns WHERE id = ?").get(id);
1588
+ return typeof row?.output === "string" ? row.output : null;
1589
+ }
1364
1590
  /** Newest first. The reader only ever wants recent turns. */
1365
1591
  listPlannerTurns(limit = 50) {
1366
1592
  const rows = this.db
@@ -1395,9 +1621,15 @@ export class ZelioDb {
1395
1621
  getBoardSettings() {
1396
1622
  const maxAgents = this.metaValue("max_agents");
1397
1623
  const plannerThinking = this.metaValue("planner_thinking");
1624
+ const testsFirstEnabled = this.metaValue("tests_first_enabled");
1398
1625
  return {
1399
1626
  maxAgents: asMaxAgents(maxAgents) ?? DEFAULT_MAX_AGENTS,
1400
1627
  plannerThinking: asPlannerThinking(plannerThinking) ?? DEFAULT_PLANNER_THINKING,
1628
+ testsFirstEnabled: testsFirstEnabled === "true"
1629
+ ? true
1630
+ : testsFirstEnabled === "false"
1631
+ ? false
1632
+ : DEFAULT_TESTS_FIRST_ENABLED,
1401
1633
  };
1402
1634
  }
1403
1635
  setBoardSettings(patch) {
@@ -1407,6 +1639,9 @@ export class ZelioDb {
1407
1639
  if (patch.plannerThinking !== undefined) {
1408
1640
  this.writeMeta("planner_thinking", patch.plannerThinking);
1409
1641
  }
1642
+ if (patch.testsFirstEnabled !== undefined) {
1643
+ this.writeMeta("tests_first_enabled", String(patch.testsFirstEnabled));
1644
+ }
1410
1645
  return this.getBoardSettings();
1411
1646
  }
1412
1647
  metaValue(key) {
@@ -1454,114 +1689,6 @@ export class ZelioDb {
1454
1689
  .run(stage, JSON.stringify(workflow.checks), 1, workflow.notes, JSON.stringify(workflow.askFirst), new Date().toISOString());
1455
1690
  return this.getStageWorkflow(stage);
1456
1691
  }
1457
- /** One row as the API sees it: evidence is JSON in the row, an array outside. */
1458
- readSuggestion(row) {
1459
- let evidence = [];
1460
- try {
1461
- const parsed = JSON.parse(String(row.evidence ?? "[]"));
1462
- if (Array.isArray(parsed)) {
1463
- evidence = parsed.filter((entry) => typeof entry === "string");
1464
- }
1465
- }
1466
- catch {
1467
- evidence = [];
1468
- }
1469
- return {
1470
- id: String(row.id),
1471
- stage: row.stage,
1472
- ticket_id: String(row.ticket_id),
1473
- evidence,
1474
- notes: String(row.notes ?? ""),
1475
- created_at: String(row.created_at),
1476
- applied_at: row.applied_at === null || row.applied_at === undefined ? null : String(row.applied_at),
1477
- dismissed_at: row.dismissed_at === null || row.dismissed_at === undefined
1478
- ? null
1479
- : String(row.dismissed_at),
1480
- };
1481
- }
1482
- /**
1483
- * A pending proposal. Duplicates are dropped: the same notes for the same
1484
- * stage is one decision, however many runs reached it.
1485
- */
1486
- addWorkflowSuggestion(input) {
1487
- const notes = input.notes.trim();
1488
- if (!notes)
1489
- return null;
1490
- const duplicate = this.db
1491
- .prepare(`SELECT 1 FROM workflow_suggestions
1492
- WHERE stage = ? AND notes = ? AND applied_at IS NULL AND dismissed_at IS NULL`)
1493
- .get(input.stage, notes);
1494
- if (duplicate)
1495
- return null;
1496
- const suggestion = {
1497
- id: randomUUID(),
1498
- stage: input.stage,
1499
- ticket_id: input.ticket_id,
1500
- evidence: input.evidence
1501
- .map((entry) => entry.trim())
1502
- .filter(Boolean)
1503
- .slice(0, 12),
1504
- notes,
1505
- created_at: new Date().toISOString(),
1506
- applied_at: null,
1507
- dismissed_at: null,
1508
- };
1509
- this.db
1510
- .prepare(`INSERT INTO workflow_suggestions
1511
- (id, stage, ticket_id, evidence, notes, created_at, applied_at, dismissed_at)
1512
- VALUES (?, ?, ?, ?, ?, ?, NULL, NULL)`)
1513
- .run(suggestion.id, suggestion.stage, suggestion.ticket_id, JSON.stringify(suggestion.evidence), suggestion.notes, suggestion.created_at);
1514
- this.emit({ type: "workflow_suggestion", suggestion });
1515
- return suggestion;
1516
- }
1517
- /** Pending proposals for a stage, newest first. */
1518
- listWorkflowSuggestions(stage) {
1519
- const rows = this.db
1520
- .prepare(`SELECT * FROM workflow_suggestions
1521
- WHERE stage = ? AND applied_at IS NULL AND dismissed_at IS NULL
1522
- ORDER BY created_at DESC`)
1523
- .all(stage);
1524
- return rows.map((row) => this.readSuggestion(row));
1525
- }
1526
- pendingSuggestion(id) {
1527
- const row = this.db
1528
- .prepare(`SELECT * FROM workflow_suggestions
1529
- WHERE id = ? AND applied_at IS NULL AND dismissed_at IS NULL`)
1530
- .get(id);
1531
- return row ? this.readSuggestion(row) : null;
1532
- }
1533
- /**
1534
- * Applies the notes to the stage, keeping checks and ask-first as they are.
1535
- * A person applying a proposal is the only way it reaches future runs.
1536
- */
1537
- applyWorkflowSuggestion(id) {
1538
- const suggestion = this.pendingSuggestion(id);
1539
- if (!suggestion)
1540
- return null;
1541
- const current = this.getStageWorkflow(suggestion.stage);
1542
- const workflow = this.setStageWorkflow(suggestion.stage, {
1543
- ...current,
1544
- notes: suggestion.notes,
1545
- });
1546
- this.db
1547
- .prepare("UPDATE workflow_suggestions SET applied_at = ? WHERE id = ?")
1548
- .run(new Date().toISOString(), id);
1549
- return {
1550
- suggestion: { ...suggestion, applied_at: new Date().toISOString() },
1551
- workflow,
1552
- };
1553
- }
1554
- /** Refuses a proposal without touching the workflow. */
1555
- dismissWorkflowSuggestion(id) {
1556
- const suggestion = this.pendingSuggestion(id);
1557
- if (!suggestion)
1558
- return null;
1559
- const dismissed_at = new Date().toISOString();
1560
- this.db
1561
- .prepare("UPDATE workflow_suggestions SET dismissed_at = ? WHERE id = ?")
1562
- .run(dismissed_at, id);
1563
- return { ...suggestion, dismissed_at };
1564
- }
1565
1692
  /** Tickets in a state where something is (or is about to be) running. */
1566
1693
  runningTickets() {
1567
1694
  const rows = this.db