zelio-cli 0.0.0-stage → 0.1.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -2
- package/dist/attachments.js +121 -0
- package/dist/attachments.js.map +1 -0
- package/dist/cli-main.js +521 -0
- package/dist/cli-main.js.map +1 -0
- package/dist/cli.js +22 -0
- package/dist/cli.js.map +1 -0
- package/dist/cloud/account.js +109 -0
- package/dist/cloud/account.js.map +1 -0
- package/dist/cloud/board.js +311 -0
- package/dist/cloud/board.js.map +1 -0
- package/dist/cloud/command.js +265 -0
- package/dist/cloud/command.js.map +1 -0
- package/dist/cloud/config.js +132 -0
- package/dist/cloud/config.js.map +1 -0
- package/dist/cloud/credentials.js +134 -0
- package/dist/cloud/credentials.js.map +1 -0
- package/dist/cloud/login.js +166 -0
- package/dist/cloud/login.js.map +1 -0
- package/dist/cloud/pair.js +110 -0
- package/dist/cloud/pair.js.map +1 -0
- package/dist/cloud/pkce.js +16 -0
- package/dist/cloud/pkce.js.map +1 -0
- package/dist/cloud/push-nudge.js +65 -0
- package/dist/cloud/push-nudge.js.map +1 -0
- package/dist/cloud/relay.js +134 -0
- package/dist/cloud/relay.js.map +1 -0
- package/dist/cloud/token.js +66 -0
- package/dist/cloud/token.js.map +1 -0
- package/dist/cloud/tunnel.js +474 -0
- package/dist/cloud/tunnel.js.map +1 -0
- package/dist/db/db.js +1838 -0
- package/dist/db/db.js.map +1 -0
- package/dist/db/lifecycle.js +146 -0
- package/dist/db/lifecycle.js.map +1 -0
- package/dist/limits.js +35 -0
- package/dist/limits.js.map +1 -0
- package/dist/metrics.js +30 -0
- package/dist/metrics.js.map +1 -0
- package/dist/orchestrator/area-notes.js +87 -0
- package/dist/orchestrator/area-notes.js.map +1 -0
- package/dist/orchestrator/claude-session.js +208 -0
- package/dist/orchestrator/claude-session.js.map +1 -0
- package/dist/orchestrator/codex-session.js +327 -0
- package/dist/orchestrator/codex-session.js.map +1 -0
- package/dist/orchestrator/contract.js +189 -0
- package/dist/orchestrator/contract.js.map +1 -0
- package/dist/orchestrator/explore.js +176 -0
- package/dist/orchestrator/explore.js.map +1 -0
- package/dist/orchestrator/new-task-prompt.js +51 -0
- package/dist/orchestrator/new-task-prompt.js.map +1 -0
- package/dist/orchestrator/pi-session.js +234 -0
- package/dist/orchestrator/pi-session.js.map +1 -0
- package/dist/orchestrator/prompt.js +110 -0
- package/dist/orchestrator/prompt.js.map +1 -0
- package/dist/orchestrator/research.js +193 -0
- package/dist/orchestrator/research.js.map +1 -0
- package/dist/orchestrator/retrieval.js +333 -0
- package/dist/orchestrator/retrieval.js.map +1 -0
- package/dist/orchestrator/runtime.js +1217 -0
- package/dist/orchestrator/runtime.js.map +1 -0
- package/dist/orchestrator/session.js +2 -0
- package/dist/orchestrator/session.js.map +1 -0
- package/dist/orchestrator/types.js +2 -0
- package/dist/orchestrator/types.js.map +1 -0
- package/dist/orchestrator/web.js +276 -0
- package/dist/orchestrator/web.js.map +1 -0
- package/dist/repo/code-map.js +152 -0
- package/dist/repo/code-map.js.map +1 -0
- package/dist/repo/index.js +188 -0
- package/dist/repo/index.js.map +1 -0
- package/dist/repo/instructions.js +58 -0
- package/dist/repo/instructions.js.map +1 -0
- package/dist/repo/linked-boards.js +149 -0
- package/dist/repo/linked-boards.js.map +1 -0
- package/dist/repo/project-repos.js +78 -0
- package/dist/repo/project-repos.js.map +1 -0
- package/dist/run/actions.js +257 -0
- package/dist/run/actions.js.map +1 -0
- package/dist/run/auto-review.js +116 -0
- package/dist/run/auto-review.js.map +1 -0
- package/dist/run/bash-guard.js +183 -0
- package/dist/run/bash-guard.js.map +1 -0
- package/dist/run/claude-runtime.js +284 -0
- package/dist/run/claude-runtime.js.map +1 -0
- package/dist/run/claude-stream.js +306 -0
- package/dist/run/claude-stream.js.map +1 -0
- package/dist/run/codex-client.js +213 -0
- package/dist/run/codex-client.js.map +1 -0
- package/dist/run/codex-planner-config.js +26 -0
- package/dist/run/codex-planner-config.js.map +1 -0
- package/dist/run/codex-runtime.js +469 -0
- package/dist/run/codex-runtime.js.map +1 -0
- package/dist/run/consult.js +109 -0
- package/dist/run/consult.js.map +1 -0
- package/dist/run/context.js +87 -0
- package/dist/run/context.js.map +1 -0
- package/dist/run/developer-sandbox.js +67 -0
- package/dist/run/developer-sandbox.js.map +1 -0
- package/dist/run/diff.js +238 -0
- package/dist/run/diff.js.map +1 -0
- package/dist/run/evidence.js +48 -0
- package/dist/run/evidence.js.map +1 -0
- package/dist/run/finish.js +430 -0
- package/dist/run/finish.js.map +1 -0
- package/dist/run/handoff.js +51 -0
- package/dist/run/handoff.js.map +1 -0
- package/dist/run/harness-runtime.js +31 -0
- package/dist/run/harness-runtime.js.map +1 -0
- package/dist/run/harnesses.js +293 -0
- package/dist/run/harnesses.js.map +1 -0
- package/dist/run/issue.js +79 -0
- package/dist/run/issue.js.map +1 -0
- package/dist/run/keep-awake.js +58 -0
- package/dist/run/keep-awake.js.map +1 -0
- package/dist/run/lead.js +183 -0
- package/dist/run/lead.js.map +1 -0
- package/dist/run/manager.js +2737 -0
- package/dist/run/manager.js.map +1 -0
- package/dist/run/mentions.js +35 -0
- package/dist/run/mentions.js.map +1 -0
- package/dist/run/merge-watch.js +425 -0
- package/dist/run/merge-watch.js.map +1 -0
- package/dist/run/models.js +88 -0
- package/dist/run/models.js.map +1 -0
- package/dist/run/phases.js +23 -0
- package/dist/run/phases.js.map +1 -0
- package/dist/run/pi-packages.js +72 -0
- package/dist/run/pi-packages.js.map +1 -0
- package/dist/run/pi-rpc.js +464 -0
- package/dist/run/pi-rpc.js.map +1 -0
- package/dist/run/piped-check.js +56 -0
- package/dist/run/piped-check.js.map +1 -0
- package/dist/run/pr-checks.js +67 -0
- package/dist/run/pr-checks.js.map +1 -0
- package/dist/run/pr-merge.js +121 -0
- package/dist/run/pr-merge.js.map +1 -0
- package/dist/run/profiles.js +43 -0
- package/dist/run/profiles.js.map +1 -0
- package/dist/run/prompt.js +405 -0
- package/dist/run/prompt.js.map +1 -0
- package/dist/run/pull-request.js +23 -0
- package/dist/run/pull-request.js.map +1 -0
- package/dist/run/red-check.js +130 -0
- package/dist/run/red-check.js.map +1 -0
- package/dist/run/result-tool.js +93 -0
- package/dist/run/result-tool.js.map +1 -0
- package/dist/run/result.js +113 -0
- package/dist/run/result.js.map +1 -0
- package/dist/run/retro.js +346 -0
- package/dist/run/retro.js.map +1 -0
- package/dist/run/settings.js +28 -0
- package/dist/run/settings.js.map +1 -0
- package/dist/run/skills.js +146 -0
- package/dist/run/skills.js.map +1 -0
- package/dist/run/tests-first.js +146 -0
- package/dist/run/tests-first.js.map +1 -0
- package/dist/run/thinking.js +41 -0
- package/dist/run/thinking.js.map +1 -0
- package/dist/run/types.js +2 -0
- package/dist/run/types.js.map +1 -0
- package/dist/run/watchdog.js +266 -0
- package/dist/run/watchdog.js.map +1 -0
- package/dist/run/workflow.js +277 -0
- package/dist/run/workflow.js.map +1 -0
- package/dist/run/worktree.js +354 -0
- package/dist/run/worktree.js.map +1 -0
- package/dist/server/app.js +3286 -0
- package/dist/server/app.js.map +1 -0
- package/dist/server/auth.js +93 -0
- package/dist/server/auth.js.map +1 -0
- package/dist/server/demo.js +96 -0
- package/dist/server/demo.js.map +1 -0
- package/dist/server/idempotency.js +104 -0
- package/dist/server/idempotency.js.map +1 -0
- package/dist/server/port.js +36 -0
- package/dist/server/port.js.map +1 -0
- package/dist/server/principal.js +93 -0
- package/dist/server/principal.js.map +1 -0
- package/dist/server/provider-auth.js +206 -0
- package/dist/server/provider-auth.js.map +1 -0
- package/dist/server/repo-picker.js +18 -0
- package/dist/server/repo-picker.js.map +1 -0
- package/dist/server/terminal.js +285 -0
- package/dist/server/terminal.js.map +1 -0
- package/dist/setup/components.js +98 -0
- package/dist/setup/components.js.map +1 -0
- package/dist/setup/config.js +71 -0
- package/dist/setup/config.js.map +1 -0
- package/dist/setup/ink-ui.js +189 -0
- package/dist/setup/ink-ui.js.map +1 -0
- package/dist/setup/onboarding.js +157 -0
- package/dist/setup/onboarding.js.map +1 -0
- package/dist/setup/run.js +69 -0
- package/dist/setup/run.js.map +1 -0
- package/dist/skills.js +151 -0
- package/dist/skills.js.map +1 -0
- package/dist/ticket-cli.js +157 -0
- package/dist/ticket-cli.js.map +1 -0
- package/dist/version.js +13 -0
- package/dist/version.js.map +1 -0
- package/dist/voice/index.js +69 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/voice/moonshine.js +247 -0
- package/dist/voice/moonshine.js.map +1 -0
- package/dist/voice/wav.js +54 -0
- package/dist/voice/wav.js.map +1 -0
- package/dist/voice/whisper.js +491 -0
- package/dist/voice/whisper.js.map +1 -0
- package/dist/web/assets/index-TN5sUF2z.css +1 -0
- package/dist/web/assets/index-vB3Cucuc.js +258 -0
- package/dist/web/icons/apple-touch-icon.png +0 -0
- package/dist/web/icons/icon-192.png +0 -0
- package/dist/web/icons/icon-512.png +0 -0
- package/dist/web/icons/maskable-512.png +0 -0
- package/dist/web/index.html +21 -0
- package/dist/web/manifest.webmanifest +30 -0
- package/dist/web/sw.js +185 -0
- package/media/board.png +0 -0
- package/media/mobile.png +0 -0
- package/media/new-task.png +0 -0
- package/media/review.png +0 -0
- package/package.json +105 -4
package/dist/db/db.js
ADDED
|
@@ -0,0 +1,1838 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
|
+
import { attachmentPaths } from "../attachments.js";
|
|
6
|
+
import { MAX_ACTION_OUTPUT } from "../run/actions.js";
|
|
7
|
+
import { PROFILES } from "../run/profiles.js";
|
|
8
|
+
import { normaliseRunResult } from "../run/result.js";
|
|
9
|
+
import { asMaxAgents, asPlannerThinking, DEFAULT_MAX_AGENTS, DEFAULT_PLANNER_CHOICE_ENABLED, DEFAULT_TESTS_FIRST_ENABLED, DEFAULT_PLANNER_THINKING, } from "../run/settings.js";
|
|
10
|
+
import { skillIds } from "../run/skills.js";
|
|
11
|
+
import { parseThinkingLevel } from "../run/thinking.js";
|
|
12
|
+
import { emptyWorkflow, hasWorkflow, isWorkflowStage, normaliseWorkflow, } from "../run/workflow.js";
|
|
13
|
+
import { canTransition, checkSpec, describeRefusal, TransitionError, } from "./lifecycle.js";
|
|
14
|
+
const MAX_VERIFY_CHECKS = 6;
|
|
15
|
+
/**
|
|
16
|
+
* Keeps only well-formed checks: a label of 1-80 characters and a command of
|
|
17
|
+
* 1-300 characters, both trimmed. Anything else is dropped silently, and the
|
|
18
|
+
* list is capped at six. A non-array reads as no checks.
|
|
19
|
+
*/
|
|
20
|
+
export function normaliseVerify(value) {
|
|
21
|
+
if (!Array.isArray(value))
|
|
22
|
+
return [];
|
|
23
|
+
const checks = [];
|
|
24
|
+
for (const entry of value) {
|
|
25
|
+
if (checks.length >= MAX_VERIFY_CHECKS)
|
|
26
|
+
break;
|
|
27
|
+
if (!entry || typeof entry !== "object")
|
|
28
|
+
continue;
|
|
29
|
+
const { label, command } = entry;
|
|
30
|
+
if (typeof label !== "string" || typeof command !== "string")
|
|
31
|
+
continue;
|
|
32
|
+
const trimmedLabel = label.trim();
|
|
33
|
+
const trimmedCommand = command.trim();
|
|
34
|
+
if (trimmedLabel.length < 1 || trimmedLabel.length > 80)
|
|
35
|
+
continue;
|
|
36
|
+
if (trimmedCommand.length < 1 || trimmedCommand.length > 300)
|
|
37
|
+
continue;
|
|
38
|
+
checks.push({ label: trimmedLabel, command: trimmedCommand });
|
|
39
|
+
}
|
|
40
|
+
return checks;
|
|
41
|
+
}
|
|
42
|
+
/** A malformed or hostile column reads as "no checks", never as a crash. */
|
|
43
|
+
function parseVerify(value) {
|
|
44
|
+
if (typeof value !== "string")
|
|
45
|
+
return [];
|
|
46
|
+
try {
|
|
47
|
+
return normaliseVerify(JSON.parse(value));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Tolerant read of the stored JSON: anything malformed is no actions at all. */
|
|
54
|
+
function parseCommentActions(raw) {
|
|
55
|
+
if (typeof raw !== "string" || !raw.trim())
|
|
56
|
+
return undefined;
|
|
57
|
+
let parsed;
|
|
58
|
+
try {
|
|
59
|
+
parsed = JSON.parse(raw);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
65
|
+
return undefined;
|
|
66
|
+
const value = parsed;
|
|
67
|
+
const actions = {};
|
|
68
|
+
if (typeof value.fixPrompt === "string")
|
|
69
|
+
actions.fixPrompt = value.fixPrompt;
|
|
70
|
+
const issue = value.issue;
|
|
71
|
+
if (issue && typeof issue === "object") {
|
|
72
|
+
if (typeof issue.title === "string" && typeof issue.body === "string") {
|
|
73
|
+
actions.issue = {
|
|
74
|
+
title: issue.title,
|
|
75
|
+
body: issue.body,
|
|
76
|
+
...(typeof issue.url === "string" ? { url: issue.url } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return actions;
|
|
81
|
+
}
|
|
82
|
+
const MIGRATIONS = [
|
|
83
|
+
`
|
|
84
|
+
CREATE TABLE IF NOT EXISTS tickets (
|
|
85
|
+
id TEXT PRIMARY KEY,
|
|
86
|
+
title TEXT NOT NULL,
|
|
87
|
+
goal TEXT NOT NULL DEFAULT '',
|
|
88
|
+
out_of_scope TEXT NOT NULL DEFAULT '',
|
|
89
|
+
acceptance TEXT NOT NULL DEFAULT '',
|
|
90
|
+
likely_files TEXT NOT NULL DEFAULT '[]',
|
|
91
|
+
context TEXT NOT NULL DEFAULT '[]',
|
|
92
|
+
plan TEXT,
|
|
93
|
+
attachments TEXT NOT NULL DEFAULT '[]',
|
|
94
|
+
state TEXT NOT NULL,
|
|
95
|
+
profile TEXT,
|
|
96
|
+
blocker_kind TEXT,
|
|
97
|
+
blocker_reason TEXT,
|
|
98
|
+
blocker_unblock TEXT,
|
|
99
|
+
quick INTEGER NOT NULL DEFAULT 0,
|
|
100
|
+
prepare_error TEXT,
|
|
101
|
+
pr_url TEXT,
|
|
102
|
+
branch TEXT,
|
|
103
|
+
archived_at TEXT,
|
|
104
|
+
created_at TEXT NOT NULL,
|
|
105
|
+
updated_at TEXT NOT NULL,
|
|
106
|
+
confirmed_at TEXT
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
CREATE TABLE IF NOT EXISTS comments (
|
|
110
|
+
id TEXT PRIMARY KEY,
|
|
111
|
+
ticket_id TEXT NOT NULL REFERENCES tickets(id) ON DELETE CASCADE,
|
|
112
|
+
type TEXT NOT NULL,
|
|
113
|
+
text TEXT NOT NULL,
|
|
114
|
+
author TEXT NOT NULL,
|
|
115
|
+
blocker_kind TEXT,
|
|
116
|
+
created_at TEXT NOT NULL
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
CREATE INDEX IF NOT EXISTS idx_tickets_state ON tickets(state);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_comments_ticket ON comments(ticket_id, created_at);
|
|
121
|
+
`,
|
|
122
|
+
`
|
|
123
|
+
-- The orchestrator conversation outlives the tab: a reload, a laptop lid, or
|
|
124
|
+
-- a plan you did not confirm should not be lost. One conversation is active
|
|
125
|
+
-- at a time; "new chat" starts another row rather than deleting the old one.
|
|
126
|
+
--
|
|
127
|
+
-- "kind" keeps two surfaces apart. A "task" conversation belongs to one
|
|
128
|
+
-- new-task wizard session: the person drafting a ticket is not chatting with
|
|
129
|
+
-- the orchestrator, so those turns must never appear in the panel, and the
|
|
130
|
+
-- panel's chat must never be what a wizard's turn writes into.
|
|
131
|
+
CREATE TABLE IF NOT EXISTS conversations (
|
|
132
|
+
id TEXT PRIMARY KEY,
|
|
133
|
+
plan TEXT,
|
|
134
|
+
planner_harness TEXT,
|
|
135
|
+
planner_model TEXT,
|
|
136
|
+
summary TEXT,
|
|
137
|
+
summary_from TEXT,
|
|
138
|
+
kind TEXT NOT NULL DEFAULT 'panel',
|
|
139
|
+
created_at TEXT NOT NULL,
|
|
140
|
+
updated_at TEXT NOT NULL
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
CREATE TABLE IF NOT EXISTS orchestrator_messages (
|
|
144
|
+
id TEXT PRIMARY KEY,
|
|
145
|
+
conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
|
|
146
|
+
role TEXT NOT NULL,
|
|
147
|
+
content TEXT NOT NULL,
|
|
148
|
+
kind TEXT NOT NULL DEFAULT 'message',
|
|
149
|
+
created_at TEXT NOT NULL
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
CREATE INDEX IF NOT EXISTS idx_orchestrator_messages
|
|
153
|
+
ON orchestrator_messages(conversation_id, created_at);
|
|
154
|
+
`,
|
|
155
|
+
`
|
|
156
|
+
-- What each ticket run actually did. The board state stays on the ticket; this
|
|
157
|
+
-- is the evidence beside it: exit code, working-tree status and the diff the
|
|
158
|
+
-- agent left for review.
|
|
159
|
+
CREATE TABLE IF NOT EXISTS agent_runs (
|
|
160
|
+
id TEXT PRIMARY KEY,
|
|
161
|
+
ticket_id TEXT NOT NULL REFERENCES tickets(id) ON DELETE CASCADE,
|
|
162
|
+
state TEXT NOT NULL,
|
|
163
|
+
started_at TEXT NOT NULL,
|
|
164
|
+
ended_at TEXT,
|
|
165
|
+
exit_code INTEGER,
|
|
166
|
+
git_status TEXT,
|
|
167
|
+
git_diff TEXT,
|
|
168
|
+
error TEXT,
|
|
169
|
+
input_tokens INTEGER,
|
|
170
|
+
output_tokens INTEGER,
|
|
171
|
+
cost REAL
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
CREATE INDEX IF NOT EXISTS idx_agent_runs_ticket
|
|
175
|
+
ON agent_runs(ticket_id, started_at);
|
|
176
|
+
`,
|
|
177
|
+
`
|
|
178
|
+
-- A cache, not a record: one row, rewritten whenever the repo moves. Keeping
|
|
179
|
+
-- it in the database means the second message of a session does not pay for
|
|
180
|
+
-- the repo tour the first one already did.
|
|
181
|
+
CREATE TABLE IF NOT EXISTS repo_index (
|
|
182
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
183
|
+
head_sha TEXT,
|
|
184
|
+
indexed_at TEXT NOT NULL,
|
|
185
|
+
duration_ms INTEGER NOT NULL,
|
|
186
|
+
json TEXT NOT NULL
|
|
187
|
+
);
|
|
188
|
+
`,
|
|
189
|
+
`
|
|
190
|
+
-- A cache, not a record: one short note per source folder, written in the
|
|
191
|
+
-- background by a read-only scout and rewritten when the folder's files
|
|
192
|
+
-- change. It survives a board reset because it describes the repo, not the board.
|
|
193
|
+
CREATE TABLE IF NOT EXISTS area_notes (
|
|
194
|
+
path TEXT PRIMARY KEY,
|
|
195
|
+
hash TEXT NOT NULL,
|
|
196
|
+
head TEXT,
|
|
197
|
+
note TEXT NOT NULL,
|
|
198
|
+
written_at TEXT NOT NULL
|
|
199
|
+
);
|
|
200
|
+
`,
|
|
201
|
+
`
|
|
202
|
+
-- What each planner turn cost. A log, not a record: nothing on the board reads
|
|
203
|
+
-- it, so it is written once and never updated. Tokens are absent on purpose —
|
|
204
|
+
-- the harness does not report them, and a guessed number is worse than none.
|
|
205
|
+
CREATE TABLE IF NOT EXISTS planner_turns (
|
|
206
|
+
id TEXT PRIMARY KEY,
|
|
207
|
+
conversation_id TEXT NOT NULL,
|
|
208
|
+
kind TEXT NOT NULL,
|
|
209
|
+
mode TEXT,
|
|
210
|
+
ok INTEGER NOT NULL,
|
|
211
|
+
error TEXT,
|
|
212
|
+
duration_ms INTEGER NOT NULL,
|
|
213
|
+
index_ms INTEGER NOT NULL DEFAULT 0,
|
|
214
|
+
first_event_ms INTEGER,
|
|
215
|
+
harness_ms INTEGER NOT NULL DEFAULT 0,
|
|
216
|
+
tool_calls INTEGER NOT NULL DEFAULT 0,
|
|
217
|
+
tool_errors INTEGER NOT NULL DEFAULT 0,
|
|
218
|
+
tool_budget INTEGER NOT NULL DEFAULT 0,
|
|
219
|
+
capped TEXT,
|
|
220
|
+
prompt_chars INTEGER NOT NULL DEFAULT 0,
|
|
221
|
+
output_chars INTEGER NOT NULL DEFAULT 0,
|
|
222
|
+
questions INTEGER NOT NULL DEFAULT 0,
|
|
223
|
+
cards INTEGER NOT NULL DEFAULT 0,
|
|
224
|
+
started_at TEXT NOT NULL,
|
|
225
|
+
-- What the model wrote, kept only when the turn failed on that text.
|
|
226
|
+
output TEXT
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
CREATE INDEX IF NOT EXISTS idx_planner_turns_started
|
|
230
|
+
ON planner_turns(started_at);
|
|
231
|
+
`,
|
|
232
|
+
`
|
|
233
|
+
-- Agent profiles are configuration, not board record: they survive a board
|
|
234
|
+
-- reset and are only rewritten by the profile routes. The seed rows are
|
|
235
|
+
-- inserted below so a fresh board opens with the four known agents.
|
|
236
|
+
CREATE TABLE IF NOT EXISTS agent_profiles (
|
|
237
|
+
name TEXT PRIMARY KEY,
|
|
238
|
+
model TEXT NOT NULL DEFAULT '',
|
|
239
|
+
harness TEXT NOT NULL DEFAULT '',
|
|
240
|
+
thinking TEXT NOT NULL,
|
|
241
|
+
touches_repo INTEGER NOT NULL DEFAULT 0,
|
|
242
|
+
extra_prompt TEXT NOT NULL DEFAULT '',
|
|
243
|
+
position INTEGER NOT NULL DEFAULT 0
|
|
244
|
+
);
|
|
245
|
+
`,
|
|
246
|
+
`
|
|
247
|
+
-- Standing instructions a person saved against a stage. Config, not a record:
|
|
248
|
+
-- it is read every time a run starts, and it survives a board clear. An empty
|
|
249
|
+
-- stage has no row rather than an empty string, so "using the board defaults"
|
|
250
|
+
-- and "saved as empty" cannot disagree.
|
|
251
|
+
CREATE TABLE IF NOT EXISTS stage_workflows (
|
|
252
|
+
stage TEXT PRIMARY KEY,
|
|
253
|
+
checks TEXT NOT NULL DEFAULT '[]',
|
|
254
|
+
allow_ticket_checks INTEGER NOT NULL DEFAULT 1,
|
|
255
|
+
notes TEXT NOT NULL DEFAULT '',
|
|
256
|
+
ask_first TEXT NOT NULL DEFAULT '[]',
|
|
257
|
+
updated_at TEXT NOT NULL
|
|
258
|
+
);
|
|
259
|
+
`,
|
|
260
|
+
`
|
|
261
|
+
-- Manager notes used to queue here for the Workflows page, one near-identical
|
|
262
|
+
-- rewrite per run. They are a comment on the ticket now; the queue is gone.
|
|
263
|
+
DROP TABLE IF EXISTS workflow_suggestions;
|
|
264
|
+
`,
|
|
265
|
+
`
|
|
266
|
+
-- The board's revision is a counter, not a timestamp: a client that saw
|
|
267
|
+
-- revision 41 asks for 41 and gets a 304, without the server trusting a clock.
|
|
268
|
+
-- It survives a restart because the board it describes does.
|
|
269
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
270
|
+
key TEXT PRIMARY KEY,
|
|
271
|
+
value TEXT NOT NULL
|
|
272
|
+
);
|
|
273
|
+
|
|
274
|
+
-- A retried write is answered with the first attempt's response. The window
|
|
275
|
+
-- is bounded by created_at; a key outside it is simply forgotten, because an
|
|
276
|
+
-- idempotency key is not a durable record of the request.
|
|
277
|
+
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
|
278
|
+
key TEXT PRIMARY KEY,
|
|
279
|
+
method TEXT NOT NULL,
|
|
280
|
+
path TEXT NOT NULL,
|
|
281
|
+
status INTEGER NOT NULL,
|
|
282
|
+
headers TEXT NOT NULL DEFAULT '{}',
|
|
283
|
+
body TEXT NOT NULL DEFAULT '',
|
|
284
|
+
created_at TEXT NOT NULL
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
|
288
|
+
ON idempotency_keys(created_at);
|
|
289
|
+
`,
|
|
290
|
+
`
|
|
291
|
+
-- Every completed tool call of a run, not the 12-row board trace. A manager
|
|
292
|
+
-- pass reads this to see repeats the trace has already dropped. Keyed by the
|
|
293
|
+
-- run and a sequence number, so a run's rows come back in the order they ran.
|
|
294
|
+
CREATE TABLE IF NOT EXISTS run_tool_calls (
|
|
295
|
+
run_id TEXT NOT NULL,
|
|
296
|
+
seq INTEGER NOT NULL,
|
|
297
|
+
tool TEXT NOT NULL,
|
|
298
|
+
detail TEXT NOT NULL DEFAULT '',
|
|
299
|
+
path TEXT,
|
|
300
|
+
state TEXT NOT NULL,
|
|
301
|
+
blocked INTEGER NOT NULL DEFAULT 0,
|
|
302
|
+
started_at INTEGER NOT NULL,
|
|
303
|
+
ended_at INTEGER NOT NULL,
|
|
304
|
+
output TEXT,
|
|
305
|
+
PRIMARY KEY (run_id, seq)
|
|
306
|
+
);
|
|
307
|
+
`,
|
|
308
|
+
`
|
|
309
|
+
-- Repositories attached to this board besides the home repo. A card with a
|
|
310
|
+
-- non-null tickets.repo works in that repository's checkout.
|
|
311
|
+
CREATE TABLE IF NOT EXISTS project_repos (
|
|
312
|
+
name TEXT PRIMARY KEY,
|
|
313
|
+
root TEXT NOT NULL UNIQUE,
|
|
314
|
+
added_at TEXT NOT NULL
|
|
315
|
+
);
|
|
316
|
+
`,
|
|
317
|
+
`
|
|
318
|
+
-- How long each Verify or workflow-check command took the last time the board
|
|
319
|
+
-- ran it, keyed by the exact command string. The developer prompt quotes it,
|
|
320
|
+
-- so an agent knows a slow command is slow before its shell returns early.
|
|
321
|
+
-- repo is '' for the home repo and the project_repos name otherwise.
|
|
322
|
+
CREATE TABLE IF NOT EXISTS command_durations (
|
|
323
|
+
repo TEXT NOT NULL DEFAULT '',
|
|
324
|
+
command TEXT NOT NULL,
|
|
325
|
+
duration_ms INTEGER NOT NULL,
|
|
326
|
+
measured_at TEXT NOT NULL,
|
|
327
|
+
PRIMARY KEY (repo, command)
|
|
328
|
+
);
|
|
329
|
+
`,
|
|
330
|
+
`
|
|
331
|
+
-- Reusable agent guidance a person keeps on the board. Config, not record: it
|
|
332
|
+
-- survives a board reset. The name is the key, so a skill is found by what it
|
|
333
|
+
-- is called. source is the GitHub link it was loaded from, or '' when typed.
|
|
334
|
+
CREATE TABLE IF NOT EXISTS skills (
|
|
335
|
+
name TEXT PRIMARY KEY,
|
|
336
|
+
body TEXT NOT NULL,
|
|
337
|
+
source TEXT NOT NULL DEFAULT '',
|
|
338
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
339
|
+
created_at TEXT NOT NULL
|
|
340
|
+
);
|
|
341
|
+
`,
|
|
342
|
+
];
|
|
343
|
+
/** A run keeps at most this many tool-call rows; later calls are not recorded. */
|
|
344
|
+
export const MAX_RUN_TOOL_CALLS = 500;
|
|
345
|
+
/**
|
|
346
|
+
* A failed turn keeps at most this much of what the model wrote. The tail is
|
|
347
|
+
* kept, because the plan block is the last thing it writes.
|
|
348
|
+
*/
|
|
349
|
+
export const MAX_PLANNER_OUTPUT_CHARS = 100_000;
|
|
350
|
+
function toSkill(row) {
|
|
351
|
+
return {
|
|
352
|
+
name: String(row.name),
|
|
353
|
+
text: String(row.body ?? ""),
|
|
354
|
+
source: String(row.source ?? ""),
|
|
355
|
+
enabled: Number(row.enabled) === 1,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
function toProfile(row) {
|
|
359
|
+
return {
|
|
360
|
+
name: String(row.name),
|
|
361
|
+
model: String(row.model ?? ""),
|
|
362
|
+
harness: String(row.harness ?? ""),
|
|
363
|
+
thinking: parseThinkingLevel(String(row.thinking)) ?? "low",
|
|
364
|
+
touchesRepo: Number(row.touches_repo) === 1,
|
|
365
|
+
extraPrompt: String(row.extra_prompt ?? ""),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function toTicket(row) {
|
|
369
|
+
return {
|
|
370
|
+
id: String(row.id),
|
|
371
|
+
title: String(row.title),
|
|
372
|
+
goal: String(row.goal),
|
|
373
|
+
out_of_scope: String(row.out_of_scope),
|
|
374
|
+
acceptance: String(row.acceptance),
|
|
375
|
+
likely_files: JSON.parse(String(row.likely_files)),
|
|
376
|
+
context: parseContext(row.context),
|
|
377
|
+
plan: typeof row.plan === "string" && row.plan.trim() ? row.plan : null,
|
|
378
|
+
attachments: parseAttachments(row.attachments),
|
|
379
|
+
verify: parseVerify(row.verify),
|
|
380
|
+
state: String(row.state),
|
|
381
|
+
profile: row.profile === null ? null : String(row.profile),
|
|
382
|
+
thinking: parseThinkingLevel(row.thinking === null ? null : String(row.thinking)) ?? null,
|
|
383
|
+
model: typeof row.model === "string" && row.model.trim() ? row.model : null,
|
|
384
|
+
planner_harness: typeof row.planner_harness === "string" && row.planner_harness.trim()
|
|
385
|
+
? row.planner_harness
|
|
386
|
+
: null,
|
|
387
|
+
developer_harness: typeof row.developer_harness === "string" && row.developer_harness.trim()
|
|
388
|
+
? row.developer_harness
|
|
389
|
+
: null,
|
|
390
|
+
skills: parseSkills(row.skills),
|
|
391
|
+
blocker_kind: (row.blocker_kind ?? null),
|
|
392
|
+
blocker_reason: row.blocker_reason === null ? null : String(row.blocker_reason),
|
|
393
|
+
blocker_unblock: row.blocker_unblock === null ? null : String(row.blocker_unblock),
|
|
394
|
+
blocker_action: row.blocker_action === "edit_agents" ? "edit_agents" : null,
|
|
395
|
+
quick: Number(row.quick) === 1,
|
|
396
|
+
prepare_error: row.prepare_error === null ? null : String(row.prepare_error),
|
|
397
|
+
pr_url: row.pr_url === null || row.pr_url === undefined ? null : String(row.pr_url),
|
|
398
|
+
branch: row.branch === null || row.branch === undefined ? null : String(row.branch),
|
|
399
|
+
archived_at: row.archived_at === null || row.archived_at === undefined ? null : String(row.archived_at),
|
|
400
|
+
repo: row.repo === null || row.repo === undefined ? null : String(row.repo),
|
|
401
|
+
handoff: typeof row.handed_off_at === "string" && typeof row.handoff_harness === "string"
|
|
402
|
+
? {
|
|
403
|
+
harness: row.handoff_harness,
|
|
404
|
+
session: typeof row.handoff_session === "string" ? row.handoff_session : null,
|
|
405
|
+
at: row.handed_off_at,
|
|
406
|
+
}
|
|
407
|
+
: null,
|
|
408
|
+
created_at: String(row.created_at),
|
|
409
|
+
updated_at: String(row.updated_at),
|
|
410
|
+
confirmed_at: row.confirmed_at === null ? null : String(row.confirmed_at),
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
function hashHandoffToken(token) {
|
|
414
|
+
return createHash("sha256").update(token).digest("hex");
|
|
415
|
+
}
|
|
416
|
+
/** A malformed column reads as "no skills chosen", never as a crash. */
|
|
417
|
+
function parseSkills(value) {
|
|
418
|
+
if (typeof value !== "string")
|
|
419
|
+
return [];
|
|
420
|
+
try {
|
|
421
|
+
return skillIds(JSON.parse(value));
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
return [];
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/** A malformed or hostile column reads as "no screenshots", never as a crash. */
|
|
428
|
+
function parseAttachments(value) {
|
|
429
|
+
if (typeof value !== "string")
|
|
430
|
+
return [];
|
|
431
|
+
try {
|
|
432
|
+
return attachmentPaths(JSON.parse(value)) ?? [];
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
return [];
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
/** A malformed or hostile column reads as "no facts", never as a crash. */
|
|
439
|
+
function parseContext(value) {
|
|
440
|
+
if (typeof value !== "string")
|
|
441
|
+
return [];
|
|
442
|
+
try {
|
|
443
|
+
const parsed = JSON.parse(value);
|
|
444
|
+
return Array.isArray(parsed)
|
|
445
|
+
? parsed
|
|
446
|
+
.filter((line) => typeof line === "string")
|
|
447
|
+
.map((line) => line.trim())
|
|
448
|
+
.filter(Boolean)
|
|
449
|
+
: [];
|
|
450
|
+
}
|
|
451
|
+
catch {
|
|
452
|
+
return [];
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
function toComment(row) {
|
|
456
|
+
const actions = parseCommentActions(row.actions);
|
|
457
|
+
return {
|
|
458
|
+
id: String(row.id),
|
|
459
|
+
ticket_id: String(row.ticket_id),
|
|
460
|
+
type: String(row.type),
|
|
461
|
+
text: String(row.text),
|
|
462
|
+
author: String(row.author),
|
|
463
|
+
blocker_kind: row.blocker_kind === "needs_human" || row.blocker_kind === "decision"
|
|
464
|
+
? row.blocker_kind
|
|
465
|
+
: null,
|
|
466
|
+
created_at: String(row.created_at),
|
|
467
|
+
reply_to: typeof row.reply_to === "string" ? row.reply_to : null,
|
|
468
|
+
run_id: typeof row.run_id === "string" ? row.run_id : null,
|
|
469
|
+
...(actions ? { actions } : {}),
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
function toAgentRun(row) {
|
|
473
|
+
return {
|
|
474
|
+
id: String(row.id),
|
|
475
|
+
ticket_id: String(row.ticket_id),
|
|
476
|
+
state: String(row.state),
|
|
477
|
+
started_at: String(row.started_at),
|
|
478
|
+
ended_at: row.ended_at === null ? null : String(row.ended_at),
|
|
479
|
+
exit_code: row.exit_code === null ? null : Number(row.exit_code),
|
|
480
|
+
git_status: row.git_status === null ? null : String(row.git_status),
|
|
481
|
+
git_diff: row.git_diff === null ? null : String(row.git_diff),
|
|
482
|
+
error: row.error === null ? null : String(row.error),
|
|
483
|
+
input_tokens: row.input_tokens === null || row.input_tokens === undefined ? null : Number(row.input_tokens),
|
|
484
|
+
output_tokens: row.output_tokens === null || row.output_tokens === undefined
|
|
485
|
+
? null
|
|
486
|
+
: Number(row.output_tokens),
|
|
487
|
+
cost: row.cost === null || row.cost === undefined ? null : Number(row.cost),
|
|
488
|
+
attempt: Number(row.attempt) || 1,
|
|
489
|
+
workflow_stage: parseWorkflowStage(row.workflow_stage),
|
|
490
|
+
workflow: parseWorkflow(row.workflow),
|
|
491
|
+
session_id: row.session_id === null || row.session_id === undefined ? null : String(row.session_id),
|
|
492
|
+
resume_count: Number(row.resume_count) || 0,
|
|
493
|
+
profile: row.profile === null || row.profile === undefined ? null : String(row.profile),
|
|
494
|
+
harness: row.harness === null || row.harness === undefined ? null : String(row.harness),
|
|
495
|
+
model: row.model === null || row.model === undefined ? null : String(row.model),
|
|
496
|
+
job_source: row.job_source === "comment" || row.job_source === "conflict" || row.job_source === "check"
|
|
497
|
+
? row.job_source
|
|
498
|
+
: "ticket",
|
|
499
|
+
job_prompt: row.job_prompt === null || row.job_prompt === undefined ? null : String(row.job_prompt),
|
|
500
|
+
job_system_prompt: row.job_system_prompt === null || row.job_system_prompt === undefined
|
|
501
|
+
? null
|
|
502
|
+
: String(row.job_system_prompt),
|
|
503
|
+
result_report: parseResult(row.result_report),
|
|
504
|
+
command_evidence: parseCommandEvidence(row.command_evidence),
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function parseResult(value) {
|
|
508
|
+
try {
|
|
509
|
+
const parsed = normaliseRunResult(JSON.parse(String(value)));
|
|
510
|
+
return parsed.ok ? parsed.report : null;
|
|
511
|
+
}
|
|
512
|
+
catch {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function parseCommandEvidence(value) {
|
|
517
|
+
try {
|
|
518
|
+
const rows = JSON.parse(String(value));
|
|
519
|
+
if (!Array.isArray(rows))
|
|
520
|
+
return [];
|
|
521
|
+
return rows
|
|
522
|
+
.filter((row) => row &&
|
|
523
|
+
typeof row.id === "string" &&
|
|
524
|
+
typeof row.command === "string" &&
|
|
525
|
+
["passed", "failed"].includes(row.outcome) &&
|
|
526
|
+
(typeof row.revision === "string" || row.revision === null))
|
|
527
|
+
.slice(-64);
|
|
528
|
+
}
|
|
529
|
+
catch {
|
|
530
|
+
return [];
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
function parseWorkflowStage(value) {
|
|
534
|
+
return typeof value === "string" && isWorkflowStage(value) ? value : null;
|
|
535
|
+
}
|
|
536
|
+
/** A malformed row reads as "no snapshot" rather than taking the board down. */
|
|
537
|
+
function parseWorkflow(value) {
|
|
538
|
+
if (typeof value !== "string" || !value.trim())
|
|
539
|
+
return null;
|
|
540
|
+
try {
|
|
541
|
+
const parsed = normaliseWorkflow(JSON.parse(value));
|
|
542
|
+
return parsed.ok ? parsed.workflow : null;
|
|
543
|
+
}
|
|
544
|
+
catch {
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function parseChecks(value) {
|
|
549
|
+
if (typeof value !== "string")
|
|
550
|
+
return [];
|
|
551
|
+
try {
|
|
552
|
+
const parsed = normaliseWorkflow({
|
|
553
|
+
checks: JSON.parse(value),
|
|
554
|
+
notes: "",
|
|
555
|
+
askFirst: [],
|
|
556
|
+
});
|
|
557
|
+
return parsed.ok ? parsed.workflow.checks : [];
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
return [];
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
function parseAskFirst(value) {
|
|
564
|
+
if (typeof value !== "string")
|
|
565
|
+
return [];
|
|
566
|
+
try {
|
|
567
|
+
const parsed = normaliseWorkflow({
|
|
568
|
+
checks: [],
|
|
569
|
+
notes: "",
|
|
570
|
+
askFirst: JSON.parse(value),
|
|
571
|
+
});
|
|
572
|
+
return parsed.ok ? parsed.workflow.askFirst : [];
|
|
573
|
+
}
|
|
574
|
+
catch {
|
|
575
|
+
return [];
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
export class ZelioDb {
|
|
579
|
+
db;
|
|
580
|
+
listeners = new Set();
|
|
581
|
+
constructor(path) {
|
|
582
|
+
if (path !== ":memory:")
|
|
583
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
584
|
+
this.db = new DatabaseSync(path);
|
|
585
|
+
this.db.exec("PRAGMA foreign_keys = ON");
|
|
586
|
+
if (path !== ":memory:")
|
|
587
|
+
this.db.exec("PRAGMA journal_mode = WAL");
|
|
588
|
+
for (const migration of MIGRATIONS)
|
|
589
|
+
this.db.exec(migration);
|
|
590
|
+
// Databases created before these columns existed still have to open. The
|
|
591
|
+
// guard makes the ALTER idempotent: SQLite has no ADD COLUMN IF NOT EXISTS.
|
|
592
|
+
this.ensureColumn("tickets", "attachments", "TEXT NOT NULL DEFAULT '[]'");
|
|
593
|
+
this.ensureColumn("tickets", "context", "TEXT NOT NULL DEFAULT '[]'");
|
|
594
|
+
this.ensureColumn("tickets", "plan", "TEXT");
|
|
595
|
+
this.ensureColumn("tickets", "quick", "INTEGER NOT NULL DEFAULT 0");
|
|
596
|
+
this.ensureColumn("tickets", "thinking", "TEXT");
|
|
597
|
+
this.ensureColumn("tickets", "model", "TEXT");
|
|
598
|
+
this.ensureColumn("tickets", "blocker_action", "TEXT");
|
|
599
|
+
this.ensureColumn("tickets", "planner_harness", "TEXT");
|
|
600
|
+
this.ensureColumn("tickets", "developer_harness", "TEXT");
|
|
601
|
+
this.ensureColumn("tickets", "skills", "TEXT NOT NULL DEFAULT '[]'");
|
|
602
|
+
this.ensureColumn("tickets", "prepare_error", "TEXT");
|
|
603
|
+
this.ensureColumn("tickets", "pr_url", "TEXT");
|
|
604
|
+
this.ensureColumn("tickets", "branch", "TEXT");
|
|
605
|
+
this.ensureColumn("tickets", "archived_at", "TEXT");
|
|
606
|
+
this.ensureColumn("tickets", "verify", "TEXT NOT NULL DEFAULT '[]'");
|
|
607
|
+
this.ensureColumn("tickets", "repo", "TEXT");
|
|
608
|
+
this.ensureColumn("tickets", "handoff_harness", "TEXT");
|
|
609
|
+
this.ensureColumn("tickets", "handoff_session", "TEXT");
|
|
610
|
+
this.ensureColumn("tickets", "handed_off_at", "TEXT");
|
|
611
|
+
this.ensureColumn("tickets", "handoff_token", "TEXT");
|
|
612
|
+
this.ensureColumn("conversations", "summary", "TEXT");
|
|
613
|
+
this.ensureColumn("conversations", "summary_from", "TEXT");
|
|
614
|
+
this.ensureColumn("conversations", "kind", "TEXT NOT NULL DEFAULT 'panel'");
|
|
615
|
+
this.ensureColumn("conversations", "planner_harness", "TEXT");
|
|
616
|
+
this.ensureColumn("conversations", "planner_model", "TEXT");
|
|
617
|
+
this.ensureColumn("orchestrator_messages", "kind", "TEXT NOT NULL DEFAULT 'message'");
|
|
618
|
+
this.ensureColumn("comments", "blocker_kind", "TEXT");
|
|
619
|
+
this.ensureColumn("comments", "reply_to", "TEXT");
|
|
620
|
+
this.ensureColumn("comments", "run_id", "TEXT");
|
|
621
|
+
this.ensureColumn("comments", "actions", "TEXT");
|
|
622
|
+
this.ensureColumn("agent_runs", "attempt", "INTEGER NOT NULL DEFAULT 1");
|
|
623
|
+
this.ensureColumn("agent_runs", "input_tokens", "INTEGER");
|
|
624
|
+
this.ensureColumn("agent_runs", "output_tokens", "INTEGER");
|
|
625
|
+
this.ensureColumn("agent_runs", "cost", "REAL");
|
|
626
|
+
this.ensureColumn("agent_runs", "session_id", "TEXT");
|
|
627
|
+
this.ensureColumn("agent_runs", "resume_count", "INTEGER NOT NULL DEFAULT 0");
|
|
628
|
+
this.ensureColumn("agent_runs", "profile", "TEXT");
|
|
629
|
+
this.ensureColumn("agent_runs", "harness", "TEXT");
|
|
630
|
+
this.ensureColumn("agent_runs", "model", "TEXT");
|
|
631
|
+
this.ensureColumn("agent_runs", "job_source", "TEXT NOT NULL DEFAULT 'ticket'");
|
|
632
|
+
this.ensureColumn("agent_runs", "job_prompt", "TEXT");
|
|
633
|
+
this.ensureColumn("agent_runs", "job_system_prompt", "TEXT");
|
|
634
|
+
this.ensureColumn("agent_runs", "result_report", "TEXT");
|
|
635
|
+
this.ensureColumn("agent_runs", "command_evidence", "TEXT");
|
|
636
|
+
this.ensureColumn("agent_runs", "workflow_stage", "TEXT");
|
|
637
|
+
this.ensureColumn("agent_runs", "workflow", "TEXT");
|
|
638
|
+
this.ensureColumn("planner_turns", "tool_budget", "INTEGER NOT NULL DEFAULT 0");
|
|
639
|
+
this.ensureColumn("planner_turns", "capped", "TEXT");
|
|
640
|
+
this.ensureColumn("planner_turns", "output", "TEXT");
|
|
641
|
+
this.seedProfiles();
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Seed once, then leave the rows alone: a restart must not undo an edit, and
|
|
645
|
+
* `INSERT OR IGNORE` keeps this idempotent. `resetProfiles()` is the explicit
|
|
646
|
+
* way back to these values.
|
|
647
|
+
*/
|
|
648
|
+
seedProfiles() {
|
|
649
|
+
const insert = this.db.prepare(`INSERT OR IGNORE INTO agent_profiles
|
|
650
|
+
(name, model, harness, thinking, touches_repo, extra_prompt, position)
|
|
651
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);
|
|
652
|
+
Object.values(PROFILES).forEach((profile, position) => {
|
|
653
|
+
insert.run(profile.name, profile.model, profile.harness, profile.thinking, profile.touchesRepo ? 1 : 0, profile.extraPrompt, position);
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
ensureColumn(table, column, definition) {
|
|
657
|
+
const columns = this.db.prepare(`PRAGMA table_info(${table})`).all();
|
|
658
|
+
if (columns.some((item) => item.name === column))
|
|
659
|
+
return;
|
|
660
|
+
this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
|
|
661
|
+
}
|
|
662
|
+
close() {
|
|
663
|
+
this.db.close();
|
|
664
|
+
}
|
|
665
|
+
/** The board subscribes to this; the server fans it out as a content-free tick. */
|
|
666
|
+
onChange(listener) {
|
|
667
|
+
this.listeners.add(listener);
|
|
668
|
+
return () => this.listeners.delete(listener);
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* The persisted revision. A board that has never changed is 0. Any listener
|
|
672
|
+
* that sees a higher number can refetch the snapshot; equal means 304.
|
|
673
|
+
*/
|
|
674
|
+
revision() {
|
|
675
|
+
const row = this.db.prepare("SELECT value FROM meta WHERE key = 'board_rev'").get();
|
|
676
|
+
return row ? Number(row.value) || 0 : 0;
|
|
677
|
+
}
|
|
678
|
+
/** Bumped on every board write, before listeners run. */
|
|
679
|
+
nextRevision() {
|
|
680
|
+
this.db
|
|
681
|
+
.prepare(`INSERT INTO meta (key, value) VALUES ('board_rev', '1')
|
|
682
|
+
ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`)
|
|
683
|
+
.run();
|
|
684
|
+
return this.revision();
|
|
685
|
+
}
|
|
686
|
+
emit(event) {
|
|
687
|
+
this.nextRevision();
|
|
688
|
+
for (const listener of this.listeners)
|
|
689
|
+
listener(event);
|
|
690
|
+
}
|
|
691
|
+
getIdempotency(key) {
|
|
692
|
+
const row = this.db.prepare("SELECT * FROM idempotency_keys WHERE key = ?").get(key);
|
|
693
|
+
if (!row)
|
|
694
|
+
return null;
|
|
695
|
+
let headers = {};
|
|
696
|
+
try {
|
|
697
|
+
const parsed = JSON.parse(String(row.headers ?? "{}"));
|
|
698
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
699
|
+
headers = Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
catch {
|
|
703
|
+
headers = {};
|
|
704
|
+
}
|
|
705
|
+
return {
|
|
706
|
+
key: String(row.key),
|
|
707
|
+
method: String(row.method),
|
|
708
|
+
path: String(row.path),
|
|
709
|
+
status: Number(row.status),
|
|
710
|
+
headers,
|
|
711
|
+
body: String(row.body ?? ""),
|
|
712
|
+
created_at: String(row.created_at),
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
saveIdempotency(record) {
|
|
716
|
+
this.db
|
|
717
|
+
.prepare(`INSERT INTO idempotency_keys (key, method, path, status, headers, body, created_at)
|
|
718
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
719
|
+
ON CONFLICT(key) DO NOTHING`)
|
|
720
|
+
.run(record.key, record.method, record.path, record.status, JSON.stringify(record.headers), record.body, record.created_at);
|
|
721
|
+
}
|
|
722
|
+
pruneIdempotency(before) {
|
|
723
|
+
this.db.prepare("DELETE FROM idempotency_keys WHERE created_at < ?").run(before);
|
|
724
|
+
}
|
|
725
|
+
/** Comment counts for board cards, including tickets whose timeline is unopened. */
|
|
726
|
+
ticketCommentCounts() {
|
|
727
|
+
const rows = this.db
|
|
728
|
+
.prepare("SELECT ticket_id, count(*) AS count FROM comments GROUP BY ticket_id")
|
|
729
|
+
.all();
|
|
730
|
+
return Object.fromEntries(rows.map((row) => [row.ticket_id, row.count]));
|
|
731
|
+
}
|
|
732
|
+
listTickets() {
|
|
733
|
+
const rows = this.db
|
|
734
|
+
.prepare("SELECT * FROM tickets WHERE archived_at IS NULL ORDER BY created_at ASC, id ASC")
|
|
735
|
+
.all();
|
|
736
|
+
return rows.map(toTicket);
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* The cards Complete took off the board. They keep every field they had, so
|
|
740
|
+
* ⌘K can still reach one and the drawer can read it as a record.
|
|
741
|
+
*/
|
|
742
|
+
listArchivedTickets() {
|
|
743
|
+
const rows = this.db
|
|
744
|
+
.prepare("SELECT * FROM tickets WHERE archived_at IS NOT NULL ORDER BY archived_at DESC, id ASC")
|
|
745
|
+
.all();
|
|
746
|
+
return rows.map(toTicket);
|
|
747
|
+
}
|
|
748
|
+
getTicket(id) {
|
|
749
|
+
const row = this.db.prepare("SELECT * FROM tickets WHERE id = ?").get(id);
|
|
750
|
+
return row ? toTicket(row) : null;
|
|
751
|
+
}
|
|
752
|
+
/** In seed order, so the Agents page is stable across loads. */
|
|
753
|
+
listProfiles() {
|
|
754
|
+
const rows = this.db
|
|
755
|
+
.prepare("SELECT * FROM agent_profiles ORDER BY position ASC, name ASC")
|
|
756
|
+
.all();
|
|
757
|
+
return rows.map(toProfile);
|
|
758
|
+
}
|
|
759
|
+
getProfile(name) {
|
|
760
|
+
const row = this.db.prepare("SELECT * FROM agent_profiles WHERE name = ?").get(name);
|
|
761
|
+
return row ? toProfile(row) : null;
|
|
762
|
+
}
|
|
763
|
+
/** Edits the half a person owns; the permissions stay as seeded. */
|
|
764
|
+
updateProfile(name, patch) {
|
|
765
|
+
const current = this.getProfile(name);
|
|
766
|
+
if (!current)
|
|
767
|
+
return null;
|
|
768
|
+
const next = { ...current, ...patch };
|
|
769
|
+
this.db
|
|
770
|
+
.prepare(`UPDATE agent_profiles SET model = ?, harness = ?, thinking = ?, extra_prompt = ?
|
|
771
|
+
WHERE name = ?`)
|
|
772
|
+
.run(next.model, next.harness, next.thinking, next.extraPrompt, name);
|
|
773
|
+
return this.getProfile(name);
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* A machine setup is the new choice of harness, so every profile goes back
|
|
777
|
+
* to following it. Both columns clear together: a harness left pinned would
|
|
778
|
+
* keep sending runs to the old runtime with a model that may not exist there.
|
|
779
|
+
* Thinking and extra prompts are not runtime choices and stay.
|
|
780
|
+
*/
|
|
781
|
+
clearProfileRuntimeOverrides() {
|
|
782
|
+
this.db.prepare("UPDATE agent_profiles SET model = '', harness = ''").run();
|
|
783
|
+
}
|
|
784
|
+
/** The Agents page's "Reset to seed": every row back to the four defaults. */
|
|
785
|
+
resetProfiles() {
|
|
786
|
+
this.db.exec("DELETE FROM agent_profiles");
|
|
787
|
+
this.seedProfiles();
|
|
788
|
+
return this.listProfiles();
|
|
789
|
+
}
|
|
790
|
+
/** Oldest first, so a skill keeps its place in the list once saved. */
|
|
791
|
+
listSkills() {
|
|
792
|
+
const rows = this.db
|
|
793
|
+
.prepare("SELECT * FROM skills ORDER BY created_at ASC, name ASC")
|
|
794
|
+
.all();
|
|
795
|
+
return rows.map(toSkill);
|
|
796
|
+
}
|
|
797
|
+
getSkill(name) {
|
|
798
|
+
const row = this.db.prepare("SELECT * FROM skills WHERE name = ?").get(name);
|
|
799
|
+
return row ? toSkill(row) : null;
|
|
800
|
+
}
|
|
801
|
+
addSkill(input) {
|
|
802
|
+
this.db
|
|
803
|
+
.prepare("INSERT INTO skills (name, body, source, enabled, created_at) VALUES (?, ?, ?, ?, ?)")
|
|
804
|
+
.run(input.name, input.text, input.source ?? "", input.enabled === false ? 0 : 1, new Date().toISOString());
|
|
805
|
+
return this.getSkill(input.name);
|
|
806
|
+
}
|
|
807
|
+
/** Edits the text or the enabled switch; the name is the key and stays. */
|
|
808
|
+
updateSkill(name, patch) {
|
|
809
|
+
const current = this.getSkill(name);
|
|
810
|
+
if (!current)
|
|
811
|
+
return null;
|
|
812
|
+
const next = { ...current, ...patch };
|
|
813
|
+
this.db
|
|
814
|
+
.prepare("UPDATE skills SET body = ?, enabled = ? WHERE name = ?")
|
|
815
|
+
.run(next.text, next.enabled ? 1 : 0, name);
|
|
816
|
+
return this.getSkill(name);
|
|
817
|
+
}
|
|
818
|
+
createTicket(input) {
|
|
819
|
+
const now = new Date().toISOString();
|
|
820
|
+
const state = input.state ?? "proposed";
|
|
821
|
+
const thinking = parseThinkingLevel(input.thinking ?? null) ?? null;
|
|
822
|
+
const model = input.model?.trim() || null;
|
|
823
|
+
const plannerHarness = input.planner_harness?.trim() || null;
|
|
824
|
+
const developerHarness = input.developer_harness?.trim() || null;
|
|
825
|
+
const skills = skillIds(input.skills);
|
|
826
|
+
const ticket = {
|
|
827
|
+
id: `T-${randomUUID().slice(0, 8)}`,
|
|
828
|
+
title: input.title,
|
|
829
|
+
goal: input.goal ?? "",
|
|
830
|
+
out_of_scope: input.out_of_scope ?? "",
|
|
831
|
+
acceptance: input.acceptance ?? "",
|
|
832
|
+
likely_files: input.likely_files ?? [],
|
|
833
|
+
context: input.context ?? [],
|
|
834
|
+
plan: input.plan?.trim() || null,
|
|
835
|
+
attachments: input.attachments ?? [],
|
|
836
|
+
verify: normaliseVerify(input.verify),
|
|
837
|
+
state,
|
|
838
|
+
profile: input.profile ?? null,
|
|
839
|
+
thinking,
|
|
840
|
+
model,
|
|
841
|
+
planner_harness: plannerHarness,
|
|
842
|
+
developer_harness: developerHarness,
|
|
843
|
+
skills,
|
|
844
|
+
blocker_kind: null,
|
|
845
|
+
blocker_reason: null,
|
|
846
|
+
blocker_unblock: null,
|
|
847
|
+
quick: input.quick === true,
|
|
848
|
+
prepare_error: null,
|
|
849
|
+
pr_url: null,
|
|
850
|
+
branch: null,
|
|
851
|
+
archived_at: null,
|
|
852
|
+
repo: input.repo?.trim() || null,
|
|
853
|
+
created_at: now,
|
|
854
|
+
updated_at: now,
|
|
855
|
+
confirmed_at: state === "todo" ? now : null,
|
|
856
|
+
};
|
|
857
|
+
this.db
|
|
858
|
+
.prepare(`INSERT INTO tickets (id, title, goal, out_of_scope, acceptance, likely_files, context, plan, attachments,
|
|
859
|
+
verify, state, profile, thinking, model, planner_harness, developer_harness, skills, blocker_kind, blocker_reason, blocker_unblock,
|
|
860
|
+
quick, prepare_error, repo, created_at, updated_at, confirmed_at)
|
|
861
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
862
|
+
.run(ticket.id, ticket.title, ticket.goal, ticket.out_of_scope, ticket.acceptance, JSON.stringify(ticket.likely_files), JSON.stringify(ticket.context), ticket.plan?.trim() || null, JSON.stringify(ticket.attachments), JSON.stringify(ticket.verify), ticket.state, ticket.profile, thinking, model, plannerHarness, developerHarness, JSON.stringify(skills), null, null, null, ticket.quick ? 1 : 0, null, ticket.repo ?? null, ticket.created_at, ticket.updated_at, ticket.confirmed_at);
|
|
863
|
+
this.emit({ type: "ticket_created", ticket });
|
|
864
|
+
return ticket;
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* Confirm a proposed card. The spec gate is enforced here so no path — API,
|
|
868
|
+
* CLI, or agent — can put an unchecked ticket on the board.
|
|
869
|
+
*/
|
|
870
|
+
confirmTicket(id, options = {}) {
|
|
871
|
+
const ticket = this.getTicket(id);
|
|
872
|
+
if (!ticket)
|
|
873
|
+
throw new TransitionError("proposed", "todo", `no ticket ${id}`);
|
|
874
|
+
if (!canTransition(ticket.state, "todo")) {
|
|
875
|
+
throw new TransitionError(ticket.state, "todo", describeRefusal(ticket.state, "todo"));
|
|
876
|
+
}
|
|
877
|
+
const spec = checkSpec(ticket);
|
|
878
|
+
if (!spec.ok && !options.allowIncomplete) {
|
|
879
|
+
throw new TransitionError(ticket.state, "todo", `spec is incomplete: ${spec.missing.join(", ")}`);
|
|
880
|
+
}
|
|
881
|
+
return this.setState(id, "todo", { confirmed_at: new Date().toISOString() });
|
|
882
|
+
}
|
|
883
|
+
/** Marks a ticket as quick, so a parked spec is picked up by the allocator. */
|
|
884
|
+
markQuick(id) {
|
|
885
|
+
const ticket = this.getTicket(id);
|
|
886
|
+
if (!ticket || ticket.quick)
|
|
887
|
+
return ticket;
|
|
888
|
+
const now = new Date().toISOString();
|
|
889
|
+
this.db.prepare("UPDATE tickets SET quick = 1, updated_at = ? WHERE id = ?").run(now, id);
|
|
890
|
+
const next = { ...ticket, quick: true, updated_at: now };
|
|
891
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
892
|
+
return next;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Fills spec fields without moving the card. The prepare pass uses it while
|
|
896
|
+
* the ticket is parked in Todo; existing text is never overwritten by a blank.
|
|
897
|
+
*/
|
|
898
|
+
updateSpec(id, patch, clearPrepareError = true) {
|
|
899
|
+
const ticket = this.getTicket(id);
|
|
900
|
+
if (!ticket)
|
|
901
|
+
return null;
|
|
902
|
+
const now = new Date().toISOString();
|
|
903
|
+
const next = {
|
|
904
|
+
...ticket,
|
|
905
|
+
goal: patch.goal?.trim() || ticket.goal,
|
|
906
|
+
out_of_scope: patch.out_of_scope?.trim() || ticket.out_of_scope,
|
|
907
|
+
acceptance: patch.acceptance?.trim() || ticket.acceptance,
|
|
908
|
+
likely_files: patch.likely_files?.length ? patch.likely_files : ticket.likely_files,
|
|
909
|
+
verify: patch.verify !== undefined ? normaliseVerify(patch.verify) : ticket.verify,
|
|
910
|
+
context: patch.context?.length ? [...patch.context] : (ticket.context ?? []),
|
|
911
|
+
plan: patch.plan?.trim() || ticket.plan || null,
|
|
912
|
+
prepare_error: clearPrepareError ? null : ticket.prepare_error,
|
|
913
|
+
updated_at: now,
|
|
914
|
+
};
|
|
915
|
+
this.db
|
|
916
|
+
.prepare(`UPDATE tickets SET goal = ?, out_of_scope = ?, acceptance = ?, likely_files = ?, verify = ?, context = ?, plan = ?,
|
|
917
|
+
prepare_error = ?, updated_at = ? WHERE id = ?`)
|
|
918
|
+
.run(next.goal, next.out_of_scope, next.acceptance, JSON.stringify(next.likely_files), JSON.stringify(next.verify), JSON.stringify(next.context), next.plan ?? null, next.prepare_error ?? null, next.updated_at, id);
|
|
919
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
920
|
+
return next;
|
|
921
|
+
}
|
|
922
|
+
/** The prepare pass failed; keep the reason on the card for the next pass and the person. */
|
|
923
|
+
setPrepareError(id, error) {
|
|
924
|
+
const ticket = this.getTicket(id);
|
|
925
|
+
if (!ticket)
|
|
926
|
+
return null;
|
|
927
|
+
const now = new Date().toISOString();
|
|
928
|
+
const next = { ...ticket, prepare_error: error, updated_at: now };
|
|
929
|
+
this.db
|
|
930
|
+
.prepare("UPDATE tickets SET prepare_error = ?, updated_at = ? WHERE id = ?")
|
|
931
|
+
.run(error, now, id);
|
|
932
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
933
|
+
return next;
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* A PR is a fact about the ticket, not a line in its chat. Storing it lets the
|
|
937
|
+
* drawer, the reviewer prompt and the merge watcher read one URL instead of
|
|
938
|
+
* each of them parsing comments.
|
|
939
|
+
*/
|
|
940
|
+
setPullRequest(id, url) {
|
|
941
|
+
const ticket = this.getTicket(id);
|
|
942
|
+
if (!ticket || (ticket.pr_url ?? null) === url)
|
|
943
|
+
return ticket;
|
|
944
|
+
const now = new Date().toISOString();
|
|
945
|
+
const next = { ...ticket, pr_url: url, updated_at: now };
|
|
946
|
+
this.db.prepare("UPDATE tickets SET pr_url = ?, updated_at = ? WHERE id = ?").run(url, now, id);
|
|
947
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
948
|
+
return next;
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* The branch is a fact about the checkout, so it is written once, when the
|
|
952
|
+
* checkout is made. A later start reads the branch the checkout is on and
|
|
953
|
+
* leaves the recorded one alone: renaming it would lose the review surface.
|
|
954
|
+
*/
|
|
955
|
+
setBranch(id, branch) {
|
|
956
|
+
const ticket = this.getTicket(id);
|
|
957
|
+
const name = branch.trim();
|
|
958
|
+
if (!ticket || !name || ticket.branch)
|
|
959
|
+
return ticket;
|
|
960
|
+
const now = new Date().toISOString();
|
|
961
|
+
const next = { ...ticket, branch: name, updated_at: now };
|
|
962
|
+
this.db
|
|
963
|
+
.prepare("UPDATE tickets SET branch = ?, updated_at = ? WHERE id = ?")
|
|
964
|
+
.run(name, now, id);
|
|
965
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
966
|
+
return next;
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Moves the ticket to `handed_off` and records who has it, in one statement:
|
|
970
|
+
* a token that outlived its state, or a state with no token, would be a card
|
|
971
|
+
* nobody can write to or one an old agent still can.
|
|
972
|
+
*/
|
|
973
|
+
handOff(id, input) {
|
|
974
|
+
const ticket = this.getTicket(id);
|
|
975
|
+
if (!ticket)
|
|
976
|
+
throw new TransitionError("todo", "handed_off", `no ticket ${id}`);
|
|
977
|
+
if (!canTransition(ticket.state, "handed_off")) {
|
|
978
|
+
throw new TransitionError(ticket.state, "handed_off", describeRefusal(ticket.state, "handed_off"));
|
|
979
|
+
}
|
|
980
|
+
const now = new Date().toISOString();
|
|
981
|
+
this.db
|
|
982
|
+
.prepare(`UPDATE tickets SET state = 'handed_off', blocker_kind = NULL, blocker_reason = NULL,
|
|
983
|
+
blocker_unblock = NULL, blocker_action = NULL, handoff_harness = ?, handoff_session = ?, handed_off_at = ?,
|
|
984
|
+
handoff_token = ?, updated_at = ? WHERE id = ?`)
|
|
985
|
+
.run(input.harness, input.session, now, hashHandoffToken(input.token), now, id);
|
|
986
|
+
const next = this.getTicket(id);
|
|
987
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
988
|
+
return next;
|
|
989
|
+
}
|
|
990
|
+
/** The handed-off agent's token, valid only while the card is still handed off. */
|
|
991
|
+
verifyHandoffToken(id, token) {
|
|
992
|
+
if (!token)
|
|
993
|
+
return false;
|
|
994
|
+
const row = this.db.prepare("SELECT state, handoff_token FROM tickets WHERE id = ?").get(id);
|
|
995
|
+
if (!row || row.state !== "handed_off" || typeof row.handoff_token !== "string")
|
|
996
|
+
return false;
|
|
997
|
+
const expected = Buffer.from(row.handoff_token);
|
|
998
|
+
const actual = Buffer.from(hashHandoffToken(token));
|
|
999
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
1000
|
+
}
|
|
1001
|
+
transition(id, to, extra = {}) {
|
|
1002
|
+
const ticket = this.getTicket(id);
|
|
1003
|
+
if (!ticket)
|
|
1004
|
+
throw new TransitionError("todo", to, `no ticket ${id}`);
|
|
1005
|
+
return this.setState(id, to, extra);
|
|
1006
|
+
}
|
|
1007
|
+
setState(id, to, extra) {
|
|
1008
|
+
const ticket = this.getTicket(id);
|
|
1009
|
+
if (!ticket)
|
|
1010
|
+
throw new TransitionError("proposed", to, `no ticket ${id}`);
|
|
1011
|
+
if (!canTransition(ticket.state, to)) {
|
|
1012
|
+
throw new TransitionError(ticket.state, to, describeRefusal(ticket.state, to));
|
|
1013
|
+
}
|
|
1014
|
+
const now = new Date().toISOString();
|
|
1015
|
+
const next = {
|
|
1016
|
+
...ticket,
|
|
1017
|
+
...extra,
|
|
1018
|
+
state: to,
|
|
1019
|
+
updated_at: now,
|
|
1020
|
+
// An action belongs to the blocker that named it; any other move drops it.
|
|
1021
|
+
blocker_action: to === "blocked" ? (extra.blocker_action ?? null) : null,
|
|
1022
|
+
};
|
|
1023
|
+
this.db
|
|
1024
|
+
.prepare(`UPDATE tickets SET state = ?, profile = ?, model = ?, blocker_kind = ?, blocker_reason = ?,
|
|
1025
|
+
blocker_unblock = ?, blocker_action = ?, updated_at = ?, confirmed_at = ? WHERE id = ?`)
|
|
1026
|
+
.run(next.state, next.profile, next.model ?? null, next.blocker_kind, next.blocker_reason, next.blocker_unblock, next.blocker_action ?? null, next.updated_at, next.confirmed_at, id);
|
|
1027
|
+
// Leaving `handed_off` ends that agent's access; the record of who had it stays.
|
|
1028
|
+
if (ticket.state === "handed_off" && to !== "handed_off") {
|
|
1029
|
+
this.db.prepare("UPDATE tickets SET handoff_token = NULL WHERE id = ?").run(id);
|
|
1030
|
+
}
|
|
1031
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
1032
|
+
return next;
|
|
1033
|
+
}
|
|
1034
|
+
/** Attached repositories, oldest first. */
|
|
1035
|
+
listRepos() {
|
|
1036
|
+
const rows = this.db
|
|
1037
|
+
.prepare("SELECT name, root, added_at FROM project_repos ORDER BY added_at ASC, name ASC")
|
|
1038
|
+
.all();
|
|
1039
|
+
return rows.map((row) => ({
|
|
1040
|
+
name: String(row.name),
|
|
1041
|
+
root: String(row.root),
|
|
1042
|
+
added_at: String(row.added_at),
|
|
1043
|
+
}));
|
|
1044
|
+
}
|
|
1045
|
+
addRepo(input) {
|
|
1046
|
+
const repo = {
|
|
1047
|
+
name: input.name,
|
|
1048
|
+
root: input.root,
|
|
1049
|
+
added_at: new Date().toISOString(),
|
|
1050
|
+
};
|
|
1051
|
+
this.db
|
|
1052
|
+
.prepare("INSERT INTO project_repos (name, root, added_at) VALUES (?, ?, ?)")
|
|
1053
|
+
.run(repo.name, repo.root, repo.added_at);
|
|
1054
|
+
this.emit({ type: "repo_changed", name: repo.name });
|
|
1055
|
+
return repo;
|
|
1056
|
+
}
|
|
1057
|
+
/** Detaches a repository row. Its tickets are the caller's to archive or refuse first. */
|
|
1058
|
+
removeRepo(name) {
|
|
1059
|
+
const result = this.db.prepare("DELETE FROM project_repos WHERE name = ?").run(name);
|
|
1060
|
+
if (Number(result.changes) === 0)
|
|
1061
|
+
return false;
|
|
1062
|
+
this.emit({ type: "repo_changed", name });
|
|
1063
|
+
return true;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Takes every card of one added repository off the board, the same way
|
|
1067
|
+
* archiveDone() does: rows, comments and runs stay.
|
|
1068
|
+
*/
|
|
1069
|
+
archiveRepoTickets(name) {
|
|
1070
|
+
const rows = this.db
|
|
1071
|
+
.prepare("SELECT * FROM tickets WHERE repo = ? AND archived_at IS NULL")
|
|
1072
|
+
.all(name);
|
|
1073
|
+
if (rows.length === 0)
|
|
1074
|
+
return [];
|
|
1075
|
+
const now = new Date().toISOString();
|
|
1076
|
+
this.db
|
|
1077
|
+
.prepare("UPDATE tickets SET archived_at = ?, updated_at = ? WHERE repo = ? AND archived_at IS NULL")
|
|
1078
|
+
.run(now, now, name);
|
|
1079
|
+
const archived = rows.map((row) => {
|
|
1080
|
+
const ticket = toTicket(row);
|
|
1081
|
+
ticket.archived_at = now;
|
|
1082
|
+
ticket.updated_at = now;
|
|
1083
|
+
return ticket;
|
|
1084
|
+
});
|
|
1085
|
+
for (const ticket of archived)
|
|
1086
|
+
this.emit({ type: "ticket_updated", ticket });
|
|
1087
|
+
return archived;
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Takes every completed card off the board without deleting anything: the
|
|
1091
|
+
* rows, their comments and their runs stay, and only listTickets() stops
|
|
1092
|
+
* returning them. Done is the only state this touches.
|
|
1093
|
+
*/
|
|
1094
|
+
archiveDone() {
|
|
1095
|
+
const rows = this.db
|
|
1096
|
+
.prepare("SELECT * FROM tickets WHERE state = 'done' AND archived_at IS NULL")
|
|
1097
|
+
.all();
|
|
1098
|
+
if (rows.length === 0)
|
|
1099
|
+
return [];
|
|
1100
|
+
const now = new Date().toISOString();
|
|
1101
|
+
this.db
|
|
1102
|
+
.prepare("UPDATE tickets SET archived_at = ?, updated_at = ? WHERE state = 'done' AND archived_at IS NULL")
|
|
1103
|
+
.run(now, now);
|
|
1104
|
+
const archived = rows.map((row) => {
|
|
1105
|
+
const ticket = toTicket(row);
|
|
1106
|
+
ticket.archived_at = now;
|
|
1107
|
+
ticket.updated_at = now;
|
|
1108
|
+
return ticket;
|
|
1109
|
+
});
|
|
1110
|
+
for (const ticket of archived)
|
|
1111
|
+
this.emit({ type: "ticket_updated", ticket });
|
|
1112
|
+
return archived;
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Removes a ticket and everything hanging off it. Almost nothing earns this:
|
|
1116
|
+
* the board is the record, so a card that simply stopped being interesting is
|
|
1117
|
+
* `cancelled`, and one whose work landed is `done`. The one case is a pull
|
|
1118
|
+
* request closed without a merge — the card was waiting on a diff that will
|
|
1119
|
+
* never exist, so review has nothing left to say about it.
|
|
1120
|
+
*
|
|
1121
|
+
* The row, its comments and its runs go in one transaction; a surviving
|
|
1122
|
+
* comment would be a row pointing at a ticket nobody can open. The worktree is
|
|
1123
|
+
* deliberately not this layer's business, and the branch is not either.
|
|
1124
|
+
*/
|
|
1125
|
+
deleteTicket(id) {
|
|
1126
|
+
const ticket = this.getTicket(id);
|
|
1127
|
+
if (!ticket)
|
|
1128
|
+
return null;
|
|
1129
|
+
this.db.exec("BEGIN");
|
|
1130
|
+
try {
|
|
1131
|
+
// Explicit, like reset(): this must not depend on ON DELETE CASCADE being
|
|
1132
|
+
// enabled on whichever connection happens to run it.
|
|
1133
|
+
this.db.prepare("DELETE FROM comments WHERE ticket_id = ?").run(id);
|
|
1134
|
+
this.db
|
|
1135
|
+
.prepare("DELETE FROM run_tool_calls WHERE run_id IN (SELECT id FROM agent_runs WHERE ticket_id = ?)")
|
|
1136
|
+
.run(id);
|
|
1137
|
+
this.db.prepare("DELETE FROM agent_runs WHERE ticket_id = ?").run(id);
|
|
1138
|
+
this.db.prepare("DELETE FROM tickets WHERE id = ?").run(id);
|
|
1139
|
+
this.db.exec("COMMIT");
|
|
1140
|
+
}
|
|
1141
|
+
catch (cause) {
|
|
1142
|
+
this.db.exec("ROLLBACK");
|
|
1143
|
+
throw cause;
|
|
1144
|
+
}
|
|
1145
|
+
this.emit({ type: "ticket_deleted", ticket });
|
|
1146
|
+
return ticket;
|
|
1147
|
+
}
|
|
1148
|
+
addComment(input) {
|
|
1149
|
+
const comment = {
|
|
1150
|
+
id: randomUUID(),
|
|
1151
|
+
ticket_id: input.ticket_id,
|
|
1152
|
+
type: input.type,
|
|
1153
|
+
text: input.text,
|
|
1154
|
+
author: input.author ?? "orchestrator",
|
|
1155
|
+
blocker_kind: input.type === "blocker" ? (input.blocker_kind ?? "decision") : null,
|
|
1156
|
+
created_at: new Date().toISOString(),
|
|
1157
|
+
reply_to: input.reply_to ?? null,
|
|
1158
|
+
run_id: input.run_id ?? null,
|
|
1159
|
+
...(input.actions ? { actions: input.actions } : {}),
|
|
1160
|
+
};
|
|
1161
|
+
this.db
|
|
1162
|
+
.prepare(`INSERT INTO comments (id, ticket_id, type, text, author, blocker_kind, created_at, reply_to, run_id, actions)
|
|
1163
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1164
|
+
.run(comment.id, comment.ticket_id, comment.type, comment.text, comment.author, comment.blocker_kind, comment.created_at, comment.reply_to ?? null, comment.run_id ?? null, input.actions ? JSON.stringify(input.actions) : null);
|
|
1165
|
+
this.emit({ type: "comment_added", comment });
|
|
1166
|
+
return comment;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Records where a filed issue lives on the comment that offered it. The
|
|
1170
|
+
* stored actions are merged, not replaced; a comment with no issue draft has
|
|
1171
|
+
* nothing to attach a link to, so it returns null like a missing comment.
|
|
1172
|
+
*/
|
|
1173
|
+
setCommentIssueUrl(commentId, url) {
|
|
1174
|
+
const row = this.db.prepare("SELECT * FROM comments WHERE id = ?").get(commentId);
|
|
1175
|
+
if (!row)
|
|
1176
|
+
return null;
|
|
1177
|
+
const current = parseCommentActions(row.actions);
|
|
1178
|
+
if (!current?.issue)
|
|
1179
|
+
return null;
|
|
1180
|
+
const actions = { ...current, issue: { ...current.issue, url } };
|
|
1181
|
+
this.db
|
|
1182
|
+
.prepare("UPDATE comments SET actions = ? WHERE id = ?")
|
|
1183
|
+
.run(JSON.stringify(actions), commentId);
|
|
1184
|
+
return toComment({ ...row, actions: JSON.stringify(actions) });
|
|
1185
|
+
}
|
|
1186
|
+
listComments(ticketId) {
|
|
1187
|
+
const rows = this.db
|
|
1188
|
+
.prepare("SELECT * FROM comments WHERE ticket_id = ? ORDER BY created_at ASC, rowid ASC")
|
|
1189
|
+
.all(ticketId);
|
|
1190
|
+
return rows.map(toComment);
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* The conversation the panel shows. Created on first read so the client never
|
|
1194
|
+
* has to deal with "no conversation yet" as a special case.
|
|
1195
|
+
*
|
|
1196
|
+
* `kind = 'panel'` is not a detail: a new-task wizard session is a conversation
|
|
1197
|
+
* too, and it must never become the chat the person is having with the
|
|
1198
|
+
* orchestrator — including by being the most recently touched row.
|
|
1199
|
+
*/
|
|
1200
|
+
activeConversation() {
|
|
1201
|
+
// rowid breaks a millisecond tie in favour of the row inserted last. A new
|
|
1202
|
+
// conversation can be minted in the same millisecond as the last message
|
|
1203
|
+
// of the old one, and `id DESC` would then pick the wrong chat.
|
|
1204
|
+
const row = this.db
|
|
1205
|
+
.prepare("SELECT id FROM conversations WHERE kind = 'panel' ORDER BY updated_at DESC, rowid DESC LIMIT 1")
|
|
1206
|
+
.get();
|
|
1207
|
+
if (!row)
|
|
1208
|
+
return this.newConversation();
|
|
1209
|
+
return this.readConversation(row.id);
|
|
1210
|
+
}
|
|
1211
|
+
getConversation(id) {
|
|
1212
|
+
const row = this.db.prepare("SELECT id FROM conversations WHERE id = ?").get(id);
|
|
1213
|
+
return row ? this.readConversation(row.id) : null;
|
|
1214
|
+
}
|
|
1215
|
+
newConversation(handoff, kind = "panel") {
|
|
1216
|
+
const now = new Date().toISOString();
|
|
1217
|
+
const id = randomUUID();
|
|
1218
|
+
this.db
|
|
1219
|
+
.prepare(`INSERT INTO conversations (id, plan, summary, summary_from, kind, created_at, updated_at)
|
|
1220
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`)
|
|
1221
|
+
.run(id, null, handoff?.summary ?? null, handoff?.from ?? null, kind, now, now);
|
|
1222
|
+
return this.readConversation(id);
|
|
1223
|
+
}
|
|
1224
|
+
/** One wizard session. Never active, never shown in the panel. */
|
|
1225
|
+
newTaskConversation() {
|
|
1226
|
+
return this.newConversation(undefined, "task");
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* A session the client never received — the turn it was created for failed
|
|
1230
|
+
* before returning. Nothing ever displayed this row, so nothing can refer to
|
|
1231
|
+
* it; that is what makes deleting it safe where discarding a draft is not.
|
|
1232
|
+
*/
|
|
1233
|
+
deleteConversation(id) {
|
|
1234
|
+
this.db.exec("BEGIN");
|
|
1235
|
+
try {
|
|
1236
|
+
this.db.prepare("DELETE FROM orchestrator_messages WHERE conversation_id = ?").run(id);
|
|
1237
|
+
this.db.prepare("DELETE FROM conversations WHERE id = ?").run(id);
|
|
1238
|
+
this.db.exec("COMMIT");
|
|
1239
|
+
}
|
|
1240
|
+
catch (cause) {
|
|
1241
|
+
this.db.exec("ROLLBACK");
|
|
1242
|
+
throw cause;
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
appendMessage(role, content, kind = "message", conversationId) {
|
|
1246
|
+
const id = conversationId ?? this.activeConversation().id;
|
|
1247
|
+
const now = new Date().toISOString();
|
|
1248
|
+
this.db
|
|
1249
|
+
.prepare(`INSERT INTO orchestrator_messages (id, conversation_id, role, content, kind, created_at)
|
|
1250
|
+
VALUES (?, ?, ?, ?, ?, ?)`)
|
|
1251
|
+
.run(randomUUID(), id, role, content, kind, now);
|
|
1252
|
+
this.touch(id, now);
|
|
1253
|
+
return this.readConversation(id);
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* The draft plan is part of the record: reloading the panel mid-review has to
|
|
1257
|
+
* show the same cards, and a plan nobody confirmed is not a decision.
|
|
1258
|
+
*/
|
|
1259
|
+
setPlan(plan, conversationId) {
|
|
1260
|
+
const id = conversationId ?? this.activeConversation().id;
|
|
1261
|
+
const now = new Date().toISOString();
|
|
1262
|
+
this.db
|
|
1263
|
+
.prepare("UPDATE conversations SET plan = ?, updated_at = ? WHERE id = ?")
|
|
1264
|
+
.run(plan ? JSON.stringify(plan) : null, now, id);
|
|
1265
|
+
return this.readConversation(id);
|
|
1266
|
+
}
|
|
1267
|
+
setConversationPlannerChoice(conversationId, harness, model) {
|
|
1268
|
+
this.db
|
|
1269
|
+
.prepare("UPDATE conversations SET planner_harness = ?, planner_model = ? WHERE id = ?")
|
|
1270
|
+
.run(harness, model, conversationId);
|
|
1271
|
+
return this.readConversation(conversationId);
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* The summary belongs to the conversation it compresses. It deliberately
|
|
1275
|
+
* does not touch updated_at: writing it must not make the old chat active
|
|
1276
|
+
* again just as a new one is being minted.
|
|
1277
|
+
*/
|
|
1278
|
+
setSummary(conversationId, summary, summaryFrom = null) {
|
|
1279
|
+
this.db
|
|
1280
|
+
.prepare("UPDATE conversations SET summary = ?, summary_from = ? WHERE id = ?")
|
|
1281
|
+
.run(summary, summaryFrom, conversationId);
|
|
1282
|
+
}
|
|
1283
|
+
touch(id, at) {
|
|
1284
|
+
this.db.prepare("UPDATE conversations SET updated_at = ? WHERE id = ?").run(at, id);
|
|
1285
|
+
}
|
|
1286
|
+
readConversation(id) {
|
|
1287
|
+
const row = this.db.prepare("SELECT * FROM conversations WHERE id = ?").get(id);
|
|
1288
|
+
const messages = this.db
|
|
1289
|
+
.prepare("SELECT role, content, kind FROM orchestrator_messages WHERE conversation_id = ? ORDER BY created_at ASC, rowid ASC")
|
|
1290
|
+
.all(id);
|
|
1291
|
+
return {
|
|
1292
|
+
id,
|
|
1293
|
+
messages: messages.map((message) => ({
|
|
1294
|
+
role: message.role === "user" ? "user" : "assistant",
|
|
1295
|
+
content: message.content,
|
|
1296
|
+
kind: message.kind === "note" ? "note" : "message",
|
|
1297
|
+
})),
|
|
1298
|
+
plan: this.readPlan(row.plan),
|
|
1299
|
+
kind: row.kind === "task" ? "task" : "panel",
|
|
1300
|
+
summary: row.summary === null || row.summary === undefined ? null : String(row.summary),
|
|
1301
|
+
summaryFrom: row.summary_from === null || row.summary_from === undefined
|
|
1302
|
+
? null
|
|
1303
|
+
: String(row.summary_from),
|
|
1304
|
+
plannerHarness: typeof row.planner_harness === "string" && row.planner_harness.trim()
|
|
1305
|
+
? row.planner_harness
|
|
1306
|
+
: null,
|
|
1307
|
+
plannerModel: typeof row.planner_model === "string" && row.planner_model.trim()
|
|
1308
|
+
? row.planner_model
|
|
1309
|
+
: null,
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* A draft was stored before cards had ids, and a plan is not a schema you can
|
|
1314
|
+
* migrate lazily at write time: every read has to be usable. A card without
|
|
1315
|
+
* an id gets `""`, which the next turn replaces with a real one.
|
|
1316
|
+
*/
|
|
1317
|
+
readPlan(raw) {
|
|
1318
|
+
if (raw === null || raw === undefined)
|
|
1319
|
+
return null;
|
|
1320
|
+
const plan = JSON.parse(String(raw));
|
|
1321
|
+
return {
|
|
1322
|
+
...plan,
|
|
1323
|
+
cards: (plan.cards ?? []).map((card) => Object.assign({}, card, { id: String(card.id ?? "") })),
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* A row per process. `session` carries the conversation forward: a resuming
|
|
1328
|
+
* run is given the id it already had, a fresh one gets its own id so there is
|
|
1329
|
+
* always something for the next restart to open.
|
|
1330
|
+
*/
|
|
1331
|
+
startAgentRun(ticketId, attempt = 1, snapshot = null, session = {}) {
|
|
1332
|
+
const workflow = snapshot && hasWorkflow(snapshot.workflow) ? snapshot.workflow : null;
|
|
1333
|
+
const run = {
|
|
1334
|
+
id: randomUUID(),
|
|
1335
|
+
ticket_id: ticketId,
|
|
1336
|
+
attempt,
|
|
1337
|
+
state: "running",
|
|
1338
|
+
started_at: new Date().toISOString(),
|
|
1339
|
+
ended_at: null,
|
|
1340
|
+
exit_code: null,
|
|
1341
|
+
git_status: null,
|
|
1342
|
+
git_diff: null,
|
|
1343
|
+
error: null,
|
|
1344
|
+
input_tokens: null,
|
|
1345
|
+
output_tokens: null,
|
|
1346
|
+
cost: null,
|
|
1347
|
+
workflow_stage: workflow ? (snapshot?.stage ?? null) : null,
|
|
1348
|
+
workflow,
|
|
1349
|
+
session_id: session.id ?? null,
|
|
1350
|
+
resume_count: session.resumeCount ?? 0,
|
|
1351
|
+
profile: session.profile ?? null,
|
|
1352
|
+
harness: session.harness ?? null,
|
|
1353
|
+
model: session.model ?? null,
|
|
1354
|
+
job_source: session.source ?? "ticket",
|
|
1355
|
+
job_prompt: session.prompt ?? null,
|
|
1356
|
+
job_system_prompt: session.systemPrompt ?? null,
|
|
1357
|
+
};
|
|
1358
|
+
// A fresh run is its own session: the id is written before the process
|
|
1359
|
+
// starts, so a crash one second later is still resumable.
|
|
1360
|
+
if (!run.session_id && session.seedId !== false)
|
|
1361
|
+
run.session_id = run.id;
|
|
1362
|
+
this.db
|
|
1363
|
+
.prepare(`INSERT INTO agent_runs (id, ticket_id, attempt, state, started_at, ended_at, exit_code,
|
|
1364
|
+
git_status, git_diff, error, input_tokens, output_tokens, cost, workflow_stage, workflow,
|
|
1365
|
+
session_id, resume_count, profile, harness, model, job_source, job_prompt, job_system_prompt)
|
|
1366
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1367
|
+
.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);
|
|
1368
|
+
return run;
|
|
1369
|
+
}
|
|
1370
|
+
finishAgentRun(id, input) {
|
|
1371
|
+
this.db
|
|
1372
|
+
.prepare(`UPDATE agent_runs SET state = ?, ended_at = ?, exit_code = ?, git_status = ?,
|
|
1373
|
+
git_diff = ?, error = ?, input_tokens = ?, output_tokens = ?, cost = ? WHERE id = ?`)
|
|
1374
|
+
.run(input.state, new Date().toISOString(), input.exit_code, input.git_status, input.git_diff, input.error, input.input_tokens ?? null, input.output_tokens ?? null, input.cost ?? null, id);
|
|
1375
|
+
return this.getAgentRun(id);
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* A live total, written while the run is still going. It only touches a run
|
|
1379
|
+
* that is still `running`: a finish must be the last word on its own row.
|
|
1380
|
+
*/
|
|
1381
|
+
updateAgentRunTokens(id, tokens, cost = null) {
|
|
1382
|
+
this.db
|
|
1383
|
+
.prepare("UPDATE agent_runs SET input_tokens = ?, output_tokens = ?, cost = ? WHERE id = ? AND state = 'running'")
|
|
1384
|
+
.run(tokens.input, tokens.output, cost, id);
|
|
1385
|
+
}
|
|
1386
|
+
/** Keep the latest measured duration of one check command; a later run replaces it. */
|
|
1387
|
+
recordCommandDuration(repo, command, durationMs) {
|
|
1388
|
+
this.db
|
|
1389
|
+
.prepare(`INSERT INTO command_durations (repo, command, duration_ms, measured_at)
|
|
1390
|
+
VALUES (?, ?, ?, ?)
|
|
1391
|
+
ON CONFLICT(repo, command) DO UPDATE SET
|
|
1392
|
+
duration_ms = excluded.duration_ms, measured_at = excluded.measured_at`)
|
|
1393
|
+
.run(repo ?? "", command, Math.max(0, Math.round(durationMs)), new Date().toISOString());
|
|
1394
|
+
}
|
|
1395
|
+
/** The last measured duration of each command that has one, in milliseconds. */
|
|
1396
|
+
commandDurations(repo, commands) {
|
|
1397
|
+
const found = new Map();
|
|
1398
|
+
const read = this.db.prepare("SELECT duration_ms FROM command_durations WHERE repo = ? AND command = ?");
|
|
1399
|
+
for (const command of new Set(commands)) {
|
|
1400
|
+
const row = read.get(repo ?? "", command);
|
|
1401
|
+
if (typeof row?.duration_ms === "number")
|
|
1402
|
+
found.set(command, row.duration_ms);
|
|
1403
|
+
}
|
|
1404
|
+
return found;
|
|
1405
|
+
}
|
|
1406
|
+
recordCommandEvidence(id, evidence) {
|
|
1407
|
+
this.db
|
|
1408
|
+
.prepare("UPDATE agent_runs SET command_evidence = ? WHERE id = ? AND state = 'running'")
|
|
1409
|
+
.run(JSON.stringify(evidence.slice(-64)), id);
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* Keep one completed tool call of a run. Once the run holds its cap the call
|
|
1413
|
+
* is dropped, not paged: the first calls are the evidence, and a runaway loop
|
|
1414
|
+
* must not grow the table without bound. Output is kept only for a failure.
|
|
1415
|
+
*/
|
|
1416
|
+
recordToolCall(input) {
|
|
1417
|
+
const counted = this.db
|
|
1418
|
+
.prepare("SELECT count(*) AS n, COALESCE(MAX(seq), 0) AS top FROM run_tool_calls WHERE run_id = ?")
|
|
1419
|
+
.get(input.runId);
|
|
1420
|
+
if (counted.n >= MAX_RUN_TOOL_CALLS)
|
|
1421
|
+
return false;
|
|
1422
|
+
const output = input.state === "failed" && input.output?.trim()
|
|
1423
|
+
? input.output.trim().slice(-MAX_ACTION_OUTPUT)
|
|
1424
|
+
: null;
|
|
1425
|
+
this.db
|
|
1426
|
+
.prepare(`INSERT INTO run_tool_calls (run_id, seq, tool, detail, path, state, blocked,
|
|
1427
|
+
started_at, ended_at, output)
|
|
1428
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1429
|
+
.run(input.runId, Number(counted.top) + 1, input.tool, input.detail, input.path, input.state, input.blocked ? 1 : 0, input.startedAt, input.endedAt, output);
|
|
1430
|
+
return true;
|
|
1431
|
+
}
|
|
1432
|
+
/** Every recorded call of a run, in the order it ran. */
|
|
1433
|
+
listToolCalls(runId) {
|
|
1434
|
+
const rows = this.db
|
|
1435
|
+
.prepare("SELECT * FROM run_tool_calls WHERE run_id = ? ORDER BY seq ASC")
|
|
1436
|
+
.all(runId);
|
|
1437
|
+
return rows.map((row) => ({
|
|
1438
|
+
seq: Number(row.seq),
|
|
1439
|
+
tool: String(row.tool),
|
|
1440
|
+
detail: String(row.detail ?? ""),
|
|
1441
|
+
path: row.path == null ? null : String(row.path),
|
|
1442
|
+
state: row.state === "failed" ? "failed" : "done",
|
|
1443
|
+
blocked: Number(row.blocked) === 1,
|
|
1444
|
+
startedAt: Number(row.started_at),
|
|
1445
|
+
endedAt: Number(row.ended_at),
|
|
1446
|
+
output: row.output == null ? null : String(row.output),
|
|
1447
|
+
}));
|
|
1448
|
+
}
|
|
1449
|
+
/** Persist the declaration, human report, and ticket move as one transaction. */
|
|
1450
|
+
recordAgentResult(runId, report, text) {
|
|
1451
|
+
const run = this.getAgentRun(runId);
|
|
1452
|
+
const ticket = run ? this.getTicket(run.ticket_id) : null;
|
|
1453
|
+
const to = report.outcome === "ready_for_review" ? "review" : "blocked";
|
|
1454
|
+
if (!run || run.state !== "running" || run.result_report || ticket?.state !== "in_progress") {
|
|
1455
|
+
throw new Error("the active run cannot accept this result");
|
|
1456
|
+
}
|
|
1457
|
+
const now = new Date().toISOString();
|
|
1458
|
+
const next = {
|
|
1459
|
+
...ticket,
|
|
1460
|
+
state: to,
|
|
1461
|
+
updated_at: now,
|
|
1462
|
+
blocker_kind: to === "blocked" ? "decision" : null,
|
|
1463
|
+
blocker_reason: to === "blocked" ? (report.reason ?? null) : null,
|
|
1464
|
+
blocker_unblock: to === "blocked" ? (report.unblock ?? null) : null,
|
|
1465
|
+
blocker_action: null,
|
|
1466
|
+
};
|
|
1467
|
+
const comment = {
|
|
1468
|
+
id: randomUUID(),
|
|
1469
|
+
ticket_id: ticket.id,
|
|
1470
|
+
type: to === "review" ? "done" : "blocker",
|
|
1471
|
+
text,
|
|
1472
|
+
author: run.profile ?? "developer",
|
|
1473
|
+
created_at: now,
|
|
1474
|
+
blocker_kind: to === "blocked" ? "decision" : null,
|
|
1475
|
+
run_id: runId,
|
|
1476
|
+
reply_to: null,
|
|
1477
|
+
};
|
|
1478
|
+
this.db.exec("BEGIN");
|
|
1479
|
+
try {
|
|
1480
|
+
this.db
|
|
1481
|
+
.prepare("UPDATE agent_runs SET result_report = ? WHERE id = ?")
|
|
1482
|
+
.run(JSON.stringify(report), runId);
|
|
1483
|
+
this.db
|
|
1484
|
+
.prepare(`INSERT INTO comments (id, ticket_id, type, text, author, blocker_kind, created_at, run_id)
|
|
1485
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1486
|
+
.run(comment.id, ticket.id, comment.type, text, comment.author, comment.blocker_kind, now, runId);
|
|
1487
|
+
this.db
|
|
1488
|
+
.prepare(`UPDATE tickets SET state = ?, blocker_kind = ?, blocker_reason = ?, blocker_unblock = ?, blocker_action = NULL, updated_at = ? WHERE id = ?`)
|
|
1489
|
+
.run(next.state, next.blocker_kind, next.blocker_reason, next.blocker_unblock, now, ticket.id);
|
|
1490
|
+
this.db.exec("COMMIT");
|
|
1491
|
+
}
|
|
1492
|
+
catch (error) {
|
|
1493
|
+
this.db.exec("ROLLBACK");
|
|
1494
|
+
throw error;
|
|
1495
|
+
}
|
|
1496
|
+
this.emit({ type: "comment_added", comment });
|
|
1497
|
+
this.emit({ type: "ticket_updated", ticket: next });
|
|
1498
|
+
return next;
|
|
1499
|
+
}
|
|
1500
|
+
/** A harness-created conversation id, written before the process can die. */
|
|
1501
|
+
setAgentRunSessionId(id, sessionId) {
|
|
1502
|
+
this.db
|
|
1503
|
+
.prepare("UPDATE agent_runs SET session_id = ? WHERE id = ? AND state = 'running'")
|
|
1504
|
+
.run(sessionId, id);
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* The run ended without moving its ticket. Only the state and the reason are
|
|
1508
|
+
* written: the captured status and diff stay, because the work is still there
|
|
1509
|
+
* and the person still has to read it.
|
|
1510
|
+
*/
|
|
1511
|
+
markRunStalled(id, error) {
|
|
1512
|
+
this.db
|
|
1513
|
+
.prepare(`UPDATE agent_runs SET state = 'stalled', error = COALESCE(error, ?),
|
|
1514
|
+
ended_at = COALESCE(ended_at, ?) WHERE id = ?`)
|
|
1515
|
+
.run(error, new Date().toISOString(), id);
|
|
1516
|
+
return this.getAgentRun(id);
|
|
1517
|
+
}
|
|
1518
|
+
getAgentRun(id) {
|
|
1519
|
+
const row = this.db.prepare("SELECT * FROM agent_runs WHERE id = ?").get(id);
|
|
1520
|
+
return row ? toAgentRun(row) : null;
|
|
1521
|
+
}
|
|
1522
|
+
latestAgentRun(ticketId) {
|
|
1523
|
+
const row = this.db
|
|
1524
|
+
.prepare("SELECT * FROM agent_runs WHERE ticket_id = ? ORDER BY started_at DESC, rowid DESC LIMIT 1")
|
|
1525
|
+
.get(ticketId);
|
|
1526
|
+
return row ? toAgentRun(row) : null;
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* The latest run of every ticket that has one, keyed by ticket id. The board
|
|
1530
|
+
* needs one row per card to say what that card last did and cost without
|
|
1531
|
+
* opening it; asking per ticket would be a request per card, and a card wants
|
|
1532
|
+
* the answer before anyone clicks it.
|
|
1533
|
+
*/
|
|
1534
|
+
latestAgentRuns() {
|
|
1535
|
+
const rows = this.db
|
|
1536
|
+
.prepare(`SELECT * FROM agent_runs AS run
|
|
1537
|
+
WHERE run.rowid = (
|
|
1538
|
+
SELECT rowid FROM agent_runs WHERE ticket_id = run.ticket_id
|
|
1539
|
+
ORDER BY started_at DESC, rowid DESC LIMIT 1
|
|
1540
|
+
)`)
|
|
1541
|
+
.all();
|
|
1542
|
+
const runs = {};
|
|
1543
|
+
for (const row of rows) {
|
|
1544
|
+
const run = toAgentRun(row);
|
|
1545
|
+
runs[run.ticket_id] = run;
|
|
1546
|
+
}
|
|
1547
|
+
return runs;
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* The latest run that actually left a diff. A reviewer run or a failed spawn
|
|
1551
|
+
* can be newer than the developer's run, but it has nothing to show; the
|
|
1552
|
+
* changes card still belongs to the run that changed the branch.
|
|
1553
|
+
*/
|
|
1554
|
+
latestAgentRunWithDiff(ticketId) {
|
|
1555
|
+
const row = this.db
|
|
1556
|
+
.prepare("SELECT * FROM agent_runs WHERE ticket_id = ? AND git_diff IS NOT NULL AND length(git_diff) > 0 ORDER BY started_at DESC, rowid DESC LIMIT 1")
|
|
1557
|
+
.get(ticketId);
|
|
1558
|
+
return row ? toAgentRun(row) : null;
|
|
1559
|
+
}
|
|
1560
|
+
/**
|
|
1561
|
+
* What each ticket's runs cost in total, keyed by ticket id. A ticket whose
|
|
1562
|
+
* runs reported no price is absent rather than zero, so the card can say
|
|
1563
|
+
* "Cost not reported" instead of "$0.00".
|
|
1564
|
+
*/
|
|
1565
|
+
ticketCostTotals() {
|
|
1566
|
+
const rows = this.db
|
|
1567
|
+
.prepare(`SELECT ticket_id, SUM(cost) AS cost FROM agent_runs
|
|
1568
|
+
WHERE cost IS NOT NULL GROUP BY ticket_id`)
|
|
1569
|
+
.all();
|
|
1570
|
+
const totals = {};
|
|
1571
|
+
for (const row of rows)
|
|
1572
|
+
totals[String(row.ticket_id)] = Number(row.cost);
|
|
1573
|
+
return totals;
|
|
1574
|
+
}
|
|
1575
|
+
/** One ticket's summed spend across every run it has, or null if none priced it. */
|
|
1576
|
+
ticketCost(ticketId) {
|
|
1577
|
+
const row = this.db
|
|
1578
|
+
.prepare("SELECT SUM(cost) AS cost FROM agent_runs WHERE ticket_id = ? AND cost IS NOT NULL")
|
|
1579
|
+
.get(ticketId);
|
|
1580
|
+
return row?.cost === null || row?.cost === undefined ? null : Number(row.cost);
|
|
1581
|
+
}
|
|
1582
|
+
/** The board-wide spend behind the Insights tile. Null when no run priced itself. */
|
|
1583
|
+
costTotal() {
|
|
1584
|
+
const row = this.db
|
|
1585
|
+
.prepare("SELECT SUM(cost) AS cost FROM agent_runs WHERE cost IS NOT NULL")
|
|
1586
|
+
.get();
|
|
1587
|
+
return row?.cost === null || row?.cost === undefined ? null : Number(row.cost);
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* The board-wide token total, kept for callers that still want it. Null never
|
|
1591
|
+
* becomes a guessed number: rows without usage are simply absent from the
|
|
1592
|
+
* sum, and a board with no runs at all totals zero.
|
|
1593
|
+
*/
|
|
1594
|
+
tokenTotals() {
|
|
1595
|
+
const row = this.db
|
|
1596
|
+
.prepare(`SELECT COALESCE(SUM(input_tokens), 0) AS input,
|
|
1597
|
+
COALESCE(SUM(output_tokens), 0) AS output
|
|
1598
|
+
FROM agent_runs`)
|
|
1599
|
+
.get();
|
|
1600
|
+
const input = Number(row.input);
|
|
1601
|
+
const output = Number(row.output);
|
|
1602
|
+
return { input, output, total: input + output };
|
|
1603
|
+
}
|
|
1604
|
+
getRepoIndex() {
|
|
1605
|
+
const row = this.db.prepare("SELECT json FROM repo_index WHERE id = 1").get();
|
|
1606
|
+
if (!row)
|
|
1607
|
+
return null;
|
|
1608
|
+
try {
|
|
1609
|
+
return JSON.parse(row.json);
|
|
1610
|
+
}
|
|
1611
|
+
catch {
|
|
1612
|
+
return null;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
listAreaNotes() {
|
|
1616
|
+
const rows = this.db
|
|
1617
|
+
.prepare("SELECT path, hash, head, note, written_at FROM area_notes ORDER BY path")
|
|
1618
|
+
.all();
|
|
1619
|
+
return rows.map((row) => ({
|
|
1620
|
+
path: String(row.path),
|
|
1621
|
+
hash: String(row.hash),
|
|
1622
|
+
head: row.head === null ? null : String(row.head),
|
|
1623
|
+
note: String(row.note),
|
|
1624
|
+
written_at: String(row.written_at),
|
|
1625
|
+
}));
|
|
1626
|
+
}
|
|
1627
|
+
saveAreaNote(note) {
|
|
1628
|
+
this.db
|
|
1629
|
+
.prepare(`INSERT INTO area_notes (path, hash, head, note, written_at) VALUES (?, ?, ?, ?, ?)
|
|
1630
|
+
ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, head = excluded.head,
|
|
1631
|
+
note = excluded.note, written_at = excluded.written_at`)
|
|
1632
|
+
.run(note.path, note.hash, note.head, note.note, note.written_at);
|
|
1633
|
+
}
|
|
1634
|
+
saveRepoIndex(index) {
|
|
1635
|
+
this.db
|
|
1636
|
+
.prepare(`INSERT INTO repo_index (id, head_sha, indexed_at, duration_ms, json) VALUES (1, ?, ?, ?, ?)
|
|
1637
|
+
ON CONFLICT(id) DO UPDATE SET head_sha = excluded.head_sha, indexed_at = excluded.indexed_at,
|
|
1638
|
+
duration_ms = excluded.duration_ms, json = excluded.json`)
|
|
1639
|
+
.run(index.head, index.indexed_at, index.duration_ms, JSON.stringify(index));
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* One row per planner turn. Append-only: a turn is a fact that already ended.
|
|
1643
|
+
* `output` is what the model wrote, kept only for a turn that failed on it;
|
|
1644
|
+
* it stays out of `listPlannerTurns`, so the metrics payload does not carry it.
|
|
1645
|
+
*/
|
|
1646
|
+
recordPlannerTurn(turn, output = null) {
|
|
1647
|
+
const row = { ...turn, id: randomUUID() };
|
|
1648
|
+
const kept = output === null || output.length <= MAX_PLANNER_OUTPUT_CHARS
|
|
1649
|
+
? output
|
|
1650
|
+
: output.slice(-MAX_PLANNER_OUTPUT_CHARS);
|
|
1651
|
+
this.db
|
|
1652
|
+
.prepare(`INSERT INTO planner_turns (id, conversation_id, kind, mode, ok, error, duration_ms,
|
|
1653
|
+
index_ms, first_event_ms, harness_ms, tool_calls, tool_errors, tool_budget, capped,
|
|
1654
|
+
prompt_chars, output_chars, questions, cards, started_at, output)
|
|
1655
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1656
|
+
.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);
|
|
1657
|
+
return row;
|
|
1658
|
+
}
|
|
1659
|
+
/** What the model wrote on a failed turn, or null when nothing was kept. */
|
|
1660
|
+
plannerTurnOutput(id) {
|
|
1661
|
+
const row = this.db.prepare("SELECT output FROM planner_turns WHERE id = ?").get(id);
|
|
1662
|
+
return typeof row?.output === "string" ? row.output : null;
|
|
1663
|
+
}
|
|
1664
|
+
/** Newest first. The reader only ever wants recent turns. */
|
|
1665
|
+
listPlannerTurns(limit = 50) {
|
|
1666
|
+
const rows = this.db
|
|
1667
|
+
.prepare("SELECT * FROM planner_turns ORDER BY started_at DESC, rowid DESC LIMIT ?")
|
|
1668
|
+
.all(limit);
|
|
1669
|
+
return rows.map((row) => ({
|
|
1670
|
+
id: String(row.id),
|
|
1671
|
+
conversation_id: String(row.conversation_id),
|
|
1672
|
+
kind: String(row.kind),
|
|
1673
|
+
mode: row.mode === null ? null : String(row.mode),
|
|
1674
|
+
ok: Number(row.ok) === 1,
|
|
1675
|
+
error: row.error === null ? null : String(row.error),
|
|
1676
|
+
duration_ms: Number(row.duration_ms),
|
|
1677
|
+
index_ms: Number(row.index_ms),
|
|
1678
|
+
first_event_ms: row.first_event_ms === null ? null : Number(row.first_event_ms),
|
|
1679
|
+
harness_ms: Number(row.harness_ms),
|
|
1680
|
+
tool_calls: Number(row.tool_calls),
|
|
1681
|
+
tool_errors: Number(row.tool_errors),
|
|
1682
|
+
tool_budget: Number(row.tool_budget ?? 0),
|
|
1683
|
+
capped: row.capped === null || row.capped === undefined ? null : String(row.capped),
|
|
1684
|
+
prompt_chars: Number(row.prompt_chars),
|
|
1685
|
+
output_chars: Number(row.output_chars),
|
|
1686
|
+
questions: Number(row.questions),
|
|
1687
|
+
cards: Number(row.cards),
|
|
1688
|
+
started_at: String(row.started_at),
|
|
1689
|
+
}));
|
|
1690
|
+
}
|
|
1691
|
+
/**
|
|
1692
|
+
* The board-wide knobs, with typed defaults. A malformed stored value falls
|
|
1693
|
+
* back instead of taking the board down; the API refuses malformed writes.
|
|
1694
|
+
*/
|
|
1695
|
+
getBoardSettings() {
|
|
1696
|
+
const maxAgents = this.metaValue("max_agents");
|
|
1697
|
+
const plannerThinking = this.metaValue("planner_thinking");
|
|
1698
|
+
const testsFirstEnabled = this.metaValue("tests_first_enabled");
|
|
1699
|
+
const plannerChoiceEnabled = this.metaValue("planner_choice_enabled");
|
|
1700
|
+
const plannerHarness = this.metaValue("planner_harness");
|
|
1701
|
+
const plannerModel = this.metaValue("planner_model");
|
|
1702
|
+
const hiddenModels = this.metaValue("hidden_models");
|
|
1703
|
+
return {
|
|
1704
|
+
maxAgents: asMaxAgents(maxAgents) ?? DEFAULT_MAX_AGENTS,
|
|
1705
|
+
plannerThinking: asPlannerThinking(plannerThinking) ?? DEFAULT_PLANNER_THINKING,
|
|
1706
|
+
testsFirstEnabled: testsFirstEnabled === "true"
|
|
1707
|
+
? true
|
|
1708
|
+
: testsFirstEnabled === "false"
|
|
1709
|
+
? false
|
|
1710
|
+
: DEFAULT_TESTS_FIRST_ENABLED,
|
|
1711
|
+
plannerChoiceEnabled: plannerChoiceEnabled === "true"
|
|
1712
|
+
? true
|
|
1713
|
+
: plannerChoiceEnabled === "false"
|
|
1714
|
+
? false
|
|
1715
|
+
: DEFAULT_PLANNER_CHOICE_ENABLED,
|
|
1716
|
+
...(plannerHarness ? { plannerHarness } : {}),
|
|
1717
|
+
...(plannerModel !== null ? { plannerModel } : {}),
|
|
1718
|
+
...(hiddenModels
|
|
1719
|
+
? { hiddenModels: JSON.parse(hiddenModels) }
|
|
1720
|
+
: {}),
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
setBoardSettings(patch) {
|
|
1724
|
+
if (patch.maxAgents !== undefined) {
|
|
1725
|
+
this.writeMeta("max_agents", String(patch.maxAgents));
|
|
1726
|
+
}
|
|
1727
|
+
if (patch.plannerThinking !== undefined) {
|
|
1728
|
+
this.writeMeta("planner_thinking", patch.plannerThinking);
|
|
1729
|
+
}
|
|
1730
|
+
if (patch.testsFirstEnabled !== undefined) {
|
|
1731
|
+
this.writeMeta("tests_first_enabled", String(patch.testsFirstEnabled));
|
|
1732
|
+
}
|
|
1733
|
+
if (patch.plannerChoiceEnabled !== undefined) {
|
|
1734
|
+
this.writeMeta("planner_choice_enabled", String(patch.plannerChoiceEnabled));
|
|
1735
|
+
}
|
|
1736
|
+
if (patch.plannerHarness !== undefined)
|
|
1737
|
+
this.writeMeta("planner_harness", patch.plannerHarness);
|
|
1738
|
+
if (patch.plannerModel !== undefined)
|
|
1739
|
+
this.writeMeta("planner_model", patch.plannerModel);
|
|
1740
|
+
if (patch.hiddenModels !== undefined)
|
|
1741
|
+
this.writeMeta("hidden_models", JSON.stringify(patch.hiddenModels));
|
|
1742
|
+
return this.getBoardSettings();
|
|
1743
|
+
}
|
|
1744
|
+
metaValue(key) {
|
|
1745
|
+
const row = this.db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
|
|
1746
|
+
return typeof row?.value === "string" ? row.value : null;
|
|
1747
|
+
}
|
|
1748
|
+
writeMeta(key, value) {
|
|
1749
|
+
this.db
|
|
1750
|
+
.prepare(`INSERT INTO meta (key, value) VALUES (?, ?)
|
|
1751
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`)
|
|
1752
|
+
.run(key, value);
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* The standing instructions for one stage. A missing row is the empty
|
|
1756
|
+
* workflow, which is what makes "never configured" a safe default.
|
|
1757
|
+
*/
|
|
1758
|
+
getStageWorkflow(stage) {
|
|
1759
|
+
const row = this.db.prepare("SELECT * FROM stage_workflows WHERE stage = ?").get(stage);
|
|
1760
|
+
if (!row)
|
|
1761
|
+
return emptyWorkflow();
|
|
1762
|
+
const checks = parseChecks(row.checks);
|
|
1763
|
+
return {
|
|
1764
|
+
checks,
|
|
1765
|
+
notes: row.notes === null ? "" : String(row.notes),
|
|
1766
|
+
askFirst: parseAskFirst(row.ask_first),
|
|
1767
|
+
};
|
|
1768
|
+
}
|
|
1769
|
+
/**
|
|
1770
|
+
* Saves a stage's instructions; an empty workflow deletes the row. Returns
|
|
1771
|
+
* what is stored, because the client shows that rather than what it sent.
|
|
1772
|
+
*/
|
|
1773
|
+
setStageWorkflow(stage, workflow) {
|
|
1774
|
+
if (!hasWorkflow(workflow)) {
|
|
1775
|
+
this.db.prepare("DELETE FROM stage_workflows WHERE stage = ?").run(stage);
|
|
1776
|
+
return emptyWorkflow();
|
|
1777
|
+
}
|
|
1778
|
+
this.db
|
|
1779
|
+
.prepare(`INSERT INTO stage_workflows
|
|
1780
|
+
(stage, checks, allow_ticket_checks, notes, ask_first, updated_at)
|
|
1781
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
1782
|
+
ON CONFLICT(stage) DO UPDATE SET checks = excluded.checks,
|
|
1783
|
+
notes = excluded.notes,
|
|
1784
|
+
ask_first = excluded.ask_first,
|
|
1785
|
+
updated_at = excluded.updated_at`)
|
|
1786
|
+
.run(stage, JSON.stringify(workflow.checks), 1, workflow.notes, JSON.stringify(workflow.askFirst), new Date().toISOString());
|
|
1787
|
+
return this.getStageWorkflow(stage);
|
|
1788
|
+
}
|
|
1789
|
+
/** Tickets in a state where something is (or is about to be) running. */
|
|
1790
|
+
runningTickets() {
|
|
1791
|
+
const rows = this.db
|
|
1792
|
+
.prepare("SELECT * FROM tickets WHERE state IN ('queued', 'in_progress') ORDER BY created_at ASC")
|
|
1793
|
+
.all();
|
|
1794
|
+
return rows.map(toTicket);
|
|
1795
|
+
}
|
|
1796
|
+
/**
|
|
1797
|
+
* Empties the board. Throws away the whole record of what happened, which is
|
|
1798
|
+
* why the CLI asks first and why it refuses while work is in flight: a
|
|
1799
|
+
* worktree on disk with no ticket pointing at it is worse than a bad ticket.
|
|
1800
|
+
*/
|
|
1801
|
+
stats() {
|
|
1802
|
+
return {
|
|
1803
|
+
tickets: this.db.prepare("SELECT count(*) AS n FROM tickets").get().n,
|
|
1804
|
+
comments: this.db.prepare("SELECT count(*) AS n FROM comments").get().n,
|
|
1805
|
+
messages: this.db.prepare("SELECT count(*) AS n FROM orchestrator_messages").get().n,
|
|
1806
|
+
conversations: this.db.prepare("SELECT count(*) AS n FROM conversations").get().n,
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1809
|
+
reset() {
|
|
1810
|
+
const counts = this.stats();
|
|
1811
|
+
this.db.exec("BEGIN");
|
|
1812
|
+
try {
|
|
1813
|
+
// Explicit, not trusting ON DELETE CASCADE: foreign_keys is per
|
|
1814
|
+
// connection and this must not depend on a pragma someone drops later.
|
|
1815
|
+
this.db.exec("DELETE FROM comments");
|
|
1816
|
+
this.db.exec("DELETE FROM run_tool_calls");
|
|
1817
|
+
this.db.exec("DELETE FROM agent_runs");
|
|
1818
|
+
this.db.exec("DELETE FROM tickets");
|
|
1819
|
+
// The conversation goes with the board: it explains why these tickets
|
|
1820
|
+
// exist, so keeping it after deleting them leaves a plan for nothing.
|
|
1821
|
+
this.db.exec("DELETE FROM orchestrator_messages");
|
|
1822
|
+
this.db.exec("DELETE FROM conversations");
|
|
1823
|
+
// Measurements of turns that no longer exist would outlive their subject.
|
|
1824
|
+
this.db.exec("DELETE FROM planner_turns");
|
|
1825
|
+
this.db.exec("COMMIT");
|
|
1826
|
+
}
|
|
1827
|
+
catch (cause) {
|
|
1828
|
+
this.db.exec("ROLLBACK");
|
|
1829
|
+
throw cause;
|
|
1830
|
+
}
|
|
1831
|
+
// No event: reset runs in its own process, so listeners in a running server
|
|
1832
|
+
// would never hear it. An open board clears on reload. The revision still
|
|
1833
|
+
// moves, so a cached snapshot from before the reset cannot answer 304.
|
|
1834
|
+
this.nextRevision();
|
|
1835
|
+
return counts;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
//# sourceMappingURL=db.js.map
|