codex-supervisor-mcp 0.13.4 → 0.13.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.en.md +101 -297
  2. package/README.md +99 -310
  3. package/package.json +24 -63
  4. package/src/{acceptance.js → app/acceptance.js} +54 -68
  5. package/src/app/cancel.js +60 -0
  6. package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
  7. package/src/app/compose.js +7 -0
  8. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  9. package/src/app/dispatch.js +396 -0
  10. package/src/app/followup.js +98 -0
  11. package/src/app/land-chain.js +124 -0
  12. package/src/app/landing.js +357 -0
  13. package/src/app/ownership.js +57 -0
  14. package/src/app/rebase.js +216 -0
  15. package/src/app/resume.js +164 -0
  16. package/src/app/run-state.js +26 -0
  17. package/src/app/settled.js +28 -0
  18. package/src/{side-chat.js → app/side-chat.js} +79 -266
  19. package/src/app/sse.js +20 -0
  20. package/src/app/start-run.js +77 -0
  21. package/src/app/verify-push.js +119 -0
  22. package/src/app/worktree-setup.js +176 -0
  23. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  24. package/src/domain/acceptance-spec.js +30 -0
  25. package/src/domain/command-outcome.js +6 -0
  26. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  27. package/src/domain/side-turn-view.js +73 -0
  28. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  29. package/src/infra/git.js +30 -0
  30. package/src/infra/process.js +59 -0
  31. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  32. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  33. package/src/infra/store/db.js +265 -0
  34. package/src/infra/store/events.js +146 -0
  35. package/src/infra/store/facts.js +338 -0
  36. package/src/infra/store/reconcile.js +172 -0
  37. package/src/infra/store/records.js +160 -0
  38. package/src/infra/store/runner-readers.js +16 -0
  39. package/src/infra/store/schema.js +306 -0
  40. package/src/infra/store/sessions.js +138 -0
  41. package/src/infra/store/tasks.js +307 -0
  42. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  43. package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
  44. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  45. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  46. package/src/{worktree.js → infra/worktree.js} +57 -42
  47. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  48. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  49. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  50. package/src/{setup.js → interface/bin/setup.js} +9 -8
  51. package/src/{stage.js → interface/bin/stage.js} +1 -1
  52. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  53. package/src/interface/mcp/meta.js +7 -0
  54. package/src/interface/mcp/result.js +34 -0
  55. package/src/interface/mcp/schemas.js +24 -0
  56. package/src/interface/mcp/server.js +94 -0
  57. package/src/interface/mcp/tools/delivery.js +197 -0
  58. package/src/interface/mcp/tools/dispatch.js +267 -0
  59. package/src/interface/mcp/tools/facts.js +239 -0
  60. package/src/interface/mcp/tools/overview.js +202 -0
  61. package/src/interface/mcp/tools/poll.js +62 -0
  62. package/src/interface/mcp/tools/results.js +270 -0
  63. package/src/interface/mcp/tools/review.js +135 -0
  64. package/src/interface/mcp/tools/wait.js +145 -0
  65. package/src/interface/mcp/update-state.js +34 -0
  66. package/src/interface/mcp/views/overview.js +183 -0
  67. package/src/interface/mcp/views/task.js +223 -0
  68. package/src/interface/web/app.js +226 -0
  69. package/src/interface/web/views.js +224 -0
  70. package/src/mcp-server.js +3 -2223
  71. package/src/run-host/entry.js +23 -0
  72. package/src/run-host/finalize.js +236 -0
  73. package/src/run-host/launch.js +63 -0
  74. package/src/run-host/live-run.js +73 -0
  75. package/src/run-host/outcome-facts.js +61 -0
  76. package/src/run-host/streams.js +76 -0
  77. package/src/run-host/track.js +128 -0
  78. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  79. package/src/runners/codex/chat-chunks.js +97 -0
  80. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  81. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  82. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  83. package/src/codex-runner.js +0 -1586
  84. package/src/landing.js +0 -507
  85. package/src/task-store.js +0 -1800
  86. package/src/web-app.js +0 -425
  87. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  88. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  89. /package/src/{prompt.js → domain/prompt.js} +0 -0
  90. /package/src/{status.js → domain/status.js} +0 -0
  91. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  92. /package/src/{truncate.js → domain/truncate.js} +0 -0
  93. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  94. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  95. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  96. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  97. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  98. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  99. /package/src/{external-output.js → infra/external-output.js} +0 -0
  100. /package/src/{handoff.js → infra/handoff.js} +0 -0
  101. /package/src/{paths.js → infra/paths.js} +0 -0
  102. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  103. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,16 @@
1
+ // The store hydrates a task with two facts only a runner can read: the CLI's
2
+ // native goal for a thread, and the agent message inside a stored event. The
3
+ // store may not import a runner, so the composition root registers the readers.
4
+ const missing = (name) => () => {
5
+ throw new Error(`store reader "${name}" is not registered; import app/compose.js before using the store`);
6
+ };
7
+
8
+ const readers = { nativeGoal: missing("nativeGoal"), agentMessage: missing("agentMessage") };
9
+
10
+ export function registerRunnerReaders({ nativeGoal, agentMessage }) {
11
+ readers.nativeGoal = nativeGoal;
12
+ readers.agentMessage = agentMessage;
13
+ }
14
+
15
+ export const readNativeGoal = (threadId) => readers.nativeGoal(threadId);
16
+ export const extractAgentMessage = (event) => readers.agentMessage(event);
@@ -0,0 +1,306 @@
1
+ // Columns added after v1. Kept in one place so the legacy rebuild and the
2
+ // fresh CREATE TABLE cannot drift apart.
3
+ export const POST_V1_COLUMNS = [
4
+ ["run_host_pid", "INTEGER"],
5
+ ["attention_reason", "TEXT"],
6
+ ["run_evidence", "TEXT"],
7
+ ["guard_policy", "TEXT"],
8
+ ["input_context", "TEXT"],
9
+ ["resumed_from", "TEXT"],
10
+ ["thread_id", "TEXT"],
11
+ ["owned_paths", "TEXT NOT NULL DEFAULT '[]'"],
12
+ ["depends_on", "TEXT NOT NULL DEFAULT '[]'"],
13
+ ["goal_objective", "TEXT"],
14
+ ["goal_token_budget", "INTEGER"],
15
+ ["goal_status", "TEXT"],
16
+ ["goal_tokens_used", "INTEGER"],
17
+ ["goal_time_used_seconds", "INTEGER"],
18
+ ["goal_updated_at", "TEXT"],
19
+ ["run_count", "INTEGER NOT NULL DEFAULT 0"],
20
+ ["cancel_requested_at", "TEXT"],
21
+ ["notices", "TEXT"],
22
+ ["session_id", "TEXT"],
23
+ ["base_commit", "TEXT"],
24
+ ["acceptance", "TEXT"],
25
+ ["acceptance_local", "TEXT"],
26
+ ["session_policy_revision", "INTEGER"],
27
+ ["acceptance_timeout_ms", "INTEGER"],
28
+ ["acceptance_results", "TEXT"],
29
+ ["landed_at", "TEXT"],
30
+ ["landed_head", "TEXT"],
31
+ ["landed_branch", "TEXT"],
32
+ ["push_verified_at", "TEXT"],
33
+ ["push_remote", "TEXT"],
34
+ ["push_branch", "TEXT"],
35
+ ["push_remote_head", "TEXT"]
36
+ ];
37
+
38
+ export const TASK_EXTRA_COLUMNS = [
39
+ ["workspace_kind", "TEXT NOT NULL DEFAULT 'legacy'"],
40
+ ["workspace_metadata", "TEXT"]
41
+ ];
42
+
43
+ export const TASKS_DDL = `
44
+ CREATE TABLE IF NOT EXISTS tasks (
45
+ id TEXT PRIMARY KEY,
46
+ title TEXT,
47
+ worker TEXT NOT NULL,
48
+ status TEXT NOT NULL,
49
+ phase TEXT,
50
+ cwd TEXT NOT NULL,
51
+ project_root TEXT NOT NULL,
52
+ workspace_kind TEXT NOT NULL DEFAULT 'legacy',
53
+ workspace_metadata TEXT,
54
+ sandbox TEXT NOT NULL,
55
+ model TEXT,
56
+ reasoning_effort TEXT NOT NULL DEFAULT 'high',
57
+ skip_git_repo_check INTEGER NOT NULL DEFAULT 1,
58
+ prompt TEXT NOT NULL,
59
+ changed_files TEXT NOT NULL DEFAULT '[]',
60
+ commands TEXT NOT NULL DEFAULT '[]',
61
+ created_at TEXT NOT NULL,
62
+ updated_at TEXT NOT NULL,
63
+ started_at TEXT,
64
+ completed_at TEXT,
65
+ pid INTEGER,
66
+ run_host_pid INTEGER,
67
+ attention_reason TEXT,
68
+ run_evidence TEXT,
69
+ guard_policy TEXT,
70
+ input_context TEXT,
71
+ exit_code INTEGER,
72
+ signal TEXT,
73
+ stderr_tail TEXT,
74
+ last_event_at TEXT,
75
+ last_event_type TEXT,
76
+ last_message TEXT,
77
+ current_action TEXT,
78
+ current_command TEXT,
79
+ error TEXT,
80
+ followup_of TEXT,
81
+ resumed_from TEXT,
82
+ session_id TEXT,
83
+ thread_id TEXT,
84
+ owned_paths TEXT NOT NULL DEFAULT '[]',
85
+ depends_on TEXT NOT NULL DEFAULT '[]',
86
+ goal_objective TEXT,
87
+ goal_token_budget INTEGER,
88
+ goal_status TEXT,
89
+ goal_tokens_used INTEGER,
90
+ goal_time_used_seconds INTEGER,
91
+ goal_updated_at TEXT,
92
+ run_count INTEGER NOT NULL DEFAULT 0,
93
+ cancel_requested_at TEXT,
94
+ notices TEXT,
95
+ worktree_path TEXT,
96
+ base_commit TEXT,
97
+ acceptance TEXT,
98
+ acceptance_local TEXT,
99
+ session_policy_revision INTEGER,
100
+ acceptance_timeout_ms INTEGER,
101
+ acceptance_results TEXT,
102
+ landed_at TEXT,
103
+ landed_head TEXT,
104
+ landed_branch TEXT,
105
+ push_verified_at TEXT,
106
+ push_remote TEXT,
107
+ push_branch TEXT,
108
+ push_remote_head TEXT,
109
+ run_log TEXT NOT NULL
110
+ );
111
+ `;
112
+
113
+ export const TASK_COLUMNS = [
114
+ "id", "title", "worker", "status", "phase", "cwd", "project_root", "workspace_kind", "workspace_metadata", "sandbox", "model",
115
+ "reasoning_effort", "skip_git_repo_check", "prompt", "changed_files", "commands",
116
+ "created_at", "updated_at", "started_at", "completed_at", "pid", "run_host_pid", "attention_reason", "run_evidence", "guard_policy", "input_context", "exit_code", "signal",
117
+ "stderr_tail", "last_event_at", "last_event_type", "last_message", "current_action",
118
+ "current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
119
+ "depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
120
+ "goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
121
+ "notices", "worktree_path", "base_commit", "acceptance", "acceptance_local", "session_policy_revision", "acceptance_timeout_ms", "acceptance_results", "landed_at", "landed_head", "landed_branch", "push_verified_at", "push_remote", "push_branch", "push_remote_head", "run_log"
122
+ ];
123
+
124
+ export const TASK_EVENTS_DDL = `
125
+ CREATE TABLE IF NOT EXISTS task_events (
126
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
127
+ task_id TEXT NOT NULL,
128
+ run_id TEXT,
129
+ seq INTEGER NOT NULL,
130
+ created_at TEXT NOT NULL,
131
+ actor TEXT NOT NULL DEFAULT 'legacy',
132
+ event_type TEXT NOT NULL,
133
+ payload TEXT NOT NULL,
134
+ payload_sha256 TEXT
135
+ );
136
+ `;
137
+
138
+ export const TASK_EVENTS_INDEX_DDL =
139
+ "CREATE INDEX IF NOT EXISTS idx_task_events_task_seq ON task_events(task_id, seq);";
140
+
141
+ export const TASKS_SESSION_INDEX_DDL =
142
+ "CREATE INDEX IF NOT EXISTS idx_tasks_session ON tasks(session_id);";
143
+
144
+ export const CONTROL_DDL = `
145
+ CREATE TABLE IF NOT EXISTS repos (
146
+ id TEXT PRIMARY KEY,
147
+ canonical_remote TEXT,
148
+ root TEXT NOT NULL UNIQUE,
149
+ default_branch TEXT,
150
+ created_at TEXT NOT NULL,
151
+ updated_at TEXT NOT NULL
152
+ );
153
+ CREATE TABLE IF NOT EXISTS work_items (
154
+ id TEXT PRIMARY KEY,
155
+ repo_id TEXT NOT NULL,
156
+ task_id TEXT NOT NULL UNIQUE,
157
+ parent_work_item_id TEXT,
158
+ objective TEXT,
159
+ owner TEXT,
160
+ delivery_state TEXT NOT NULL DEFAULT 'draft',
161
+ created_at TEXT NOT NULL,
162
+ updated_at TEXT NOT NULL
163
+ );
164
+ CREATE INDEX IF NOT EXISTS idx_work_items_repo ON work_items(repo_id, created_at);
165
+ CREATE TABLE IF NOT EXISTS runs (
166
+ id TEXT PRIMARY KEY,
167
+ task_id TEXT NOT NULL,
168
+ work_item_id TEXT NOT NULL,
169
+ attempt INTEGER NOT NULL,
170
+ codex_thread_id TEXT,
171
+ worktree_path TEXT,
172
+ branch TEXT,
173
+ base_sha TEXT,
174
+ run_status TEXT NOT NULL,
175
+ started_at TEXT NOT NULL,
176
+ finished_at TEXT,
177
+ UNIQUE(task_id, attempt)
178
+ );
179
+ CREATE INDEX IF NOT EXISTS idx_runs_work_item ON runs(work_item_id, attempt);
180
+ CREATE TABLE IF NOT EXISTS facts (
181
+ id TEXT PRIMARY KEY,
182
+ work_item_id TEXT NOT NULL,
183
+ scope_type TEXT NOT NULL,
184
+ scope_id TEXT NOT NULL,
185
+ key TEXT NOT NULL,
186
+ value_json TEXT NOT NULL,
187
+ state TEXT NOT NULL,
188
+ source_event_id INTEGER,
189
+ source_artifact_id TEXT,
190
+ valid_for_sha TEXT,
191
+ valid_for_content_hash TEXT,
192
+ valid_for_manifest_hash TEXT,
193
+ watched_paths TEXT NOT NULL DEFAULT '[]',
194
+ expires_at TEXT,
195
+ supersedes_id TEXT,
196
+ created_at TEXT NOT NULL,
197
+ verified_at TEXT,
198
+ verified_by TEXT
199
+ );
200
+ CREATE INDEX IF NOT EXISTS idx_facts_scope ON facts(scope_type, scope_id, state);
201
+ CREATE INDEX IF NOT EXISTS idx_facts_supersedes ON facts(supersedes_id, state);
202
+ CREATE TABLE IF NOT EXISTS artifacts (
203
+ id TEXT PRIMARY KEY,
204
+ run_id TEXT NOT NULL,
205
+ type TEXT NOT NULL,
206
+ uri TEXT NOT NULL,
207
+ sha256 TEXT,
208
+ security_class TEXT NOT NULL DEFAULT 'internal',
209
+ retention TEXT NOT NULL DEFAULT 'permanent',
210
+ created_at TEXT NOT NULL
211
+ );
212
+ CREATE INDEX IF NOT EXISTS idx_artifacts_run ON artifacts(run_id, created_at);
213
+ CREATE TABLE IF NOT EXISTS review_findings (
214
+ id TEXT PRIMARY KEY,
215
+ subject_task_id TEXT NOT NULL,
216
+ verifier_task_id TEXT NOT NULL UNIQUE,
217
+ subject_run_id TEXT,
218
+ subject_base_sha TEXT,
219
+ subject_fingerprint TEXT,
220
+ status TEXT NOT NULL,
221
+ verdict TEXT,
222
+ reason TEXT,
223
+ evidence_artifact_id TEXT,
224
+ finding_event_id INTEGER,
225
+ resolved_at TEXT,
226
+ resolved_by TEXT,
227
+ resolution TEXT,
228
+ created_at TEXT NOT NULL,
229
+ updated_at TEXT NOT NULL
230
+ );
231
+ CREATE INDEX IF NOT EXISTS idx_review_findings_subject ON review_findings(subject_task_id, created_at);
232
+ CREATE TABLE IF NOT EXISTS context_snapshots (
233
+ id TEXT PRIMARY KEY,
234
+ run_id TEXT NOT NULL,
235
+ recipient TEXT NOT NULL,
236
+ fact_versions TEXT NOT NULL DEFAULT '[]',
237
+ base_sha TEXT,
238
+ prompt_sha256 TEXT NOT NULL,
239
+ estimated_tokens INTEGER NOT NULL,
240
+ excluded_json TEXT NOT NULL DEFAULT '{}',
241
+ created_at TEXT NOT NULL
242
+ );
243
+ CREATE INDEX IF NOT EXISTS idx_context_snapshots_run ON context_snapshots(run_id, created_at);
244
+ CREATE TABLE IF NOT EXISTS cleanup_plans (
245
+ id TEXT PRIMARY KEY,
246
+ project_root TEXT,
247
+ generated_at TEXT NOT NULL,
248
+ expires_at TEXT NOT NULL,
249
+ policy TEXT NOT NULL,
250
+ summary_json TEXT NOT NULL
251
+ );
252
+ CREATE TABLE IF NOT EXISTS cleanup_plan_items (
253
+ id TEXT PRIMARY KEY,
254
+ plan_id TEXT NOT NULL,
255
+ task_id TEXT NOT NULL,
256
+ verdict TEXT NOT NULL,
257
+ reasons_json TEXT NOT NULL,
258
+ fingerprint TEXT,
259
+ reclaimable_bytes INTEGER NOT NULL DEFAULT 0,
260
+ eligible_after TEXT,
261
+ applied_at TEXT,
262
+ applied_by TEXT,
263
+ UNIQUE(plan_id, task_id)
264
+ );
265
+ CREATE INDEX IF NOT EXISTS idx_cleanup_plan_items_plan ON cleanup_plan_items(plan_id, verdict);
266
+ CREATE INDEX IF NOT EXISTS idx_cleanup_plan_items_task ON cleanup_plan_items(task_id, applied_at);
267
+ `;
268
+
269
+ // A session is a string on each task row; this table is what a session is
270
+ // *about*. A main thread sets it once per batch, so a reader sees "给 12
271
+ // 个接口补单测" instead of a bare id.
272
+ export const SESSIONS_DDL = `
273
+ CREATE TABLE IF NOT EXISTS sessions (
274
+ id TEXT PRIMARY KEY,
275
+ title TEXT,
276
+ note TEXT,
277
+ created_at TEXT NOT NULL,
278
+ updated_at TEXT NOT NULL
279
+ );
280
+ `;
281
+
282
+ // Side questions asked from the board. One side session per worker (the
283
+ // forked Codex thread), many turns under it. A turn keeps the stream chunks
284
+ // it produced, so a page that comes back can replay what it missed and the
285
+ // conversation survives a board restart.
286
+ export const SIDE_DDL = `
287
+ CREATE TABLE IF NOT EXISTS side_sessions (
288
+ task_id TEXT PRIMARY KEY,
289
+ fork_thread_id TEXT,
290
+ created_at TEXT NOT NULL,
291
+ ended_at TEXT,
292
+ worker_run_count INTEGER
293
+ );
294
+ CREATE TABLE IF NOT EXISTS side_turns (
295
+ id TEXT PRIMARY KEY,
296
+ task_id TEXT NOT NULL,
297
+ question TEXT NOT NULL,
298
+ status TEXT NOT NULL,
299
+ chunks TEXT NOT NULL DEFAULT '[]',
300
+ usage TEXT,
301
+ error TEXT,
302
+ started_at TEXT NOT NULL,
303
+ ended_at TEXT
304
+ );
305
+ CREATE INDEX IF NOT EXISTS idx_side_turns_task ON side_turns(task_id, started_at);
306
+ `;
@@ -0,0 +1,138 @@
1
+ import { normalizeAcceptance } from "../../domain/acceptance-spec.js";
2
+ import { decodeJson, ensureFilesystem, openDb, runWithRetry } from "./db.js";
3
+
4
+ export async function upsertSession({ id, title = null, note = null, objective, defaultAcceptance, approvalState, expectedRevision }) {
5
+ if (!id) throw new Error("session id is required");
6
+ await ensureFilesystem();
7
+ const now = new Date().toISOString();
8
+ // Only overwrite what the caller sent: a later dispatch that names the
9
+ // session without a title must not blank the title set earlier.
10
+ openDb()
11
+ .prepare(`
12
+ INSERT INTO sessions (id, title, note, created_at, updated_at) VALUES (@id, @title, @note, @now, @now)
13
+ ON CONFLICT(id) DO UPDATE SET
14
+ title = COALESCE(excluded.title, sessions.title),
15
+ note = COALESCE(excluded.note, sessions.note),
16
+ updated_at = excluded.updated_at
17
+ `)
18
+ .run({ id, title: title ?? null, note: note ?? null, now });
19
+ if (objective !== undefined || defaultAcceptance !== undefined || approvalState !== undefined || expectedRevision !== undefined) {
20
+ const acceptance = defaultAcceptance === undefined ? undefined : normalizeAcceptance(defaultAcceptance) ?? [];
21
+ if (objective !== undefined && (typeof objective !== "string" || !objective.trim())) throw new Error("session objective must be nonempty");
22
+ if (approvalState !== undefined && !["approved", "waiting_user"].includes(approvalState)) throw new Error("invalid session approval state");
23
+ runWithRetry(openDb(), () => {
24
+ const store = openDb();
25
+ store.exec("BEGIN IMMEDIATE");
26
+ try {
27
+ const before = store.prepare("SELECT * FROM sessions WHERE id=?").get(id);
28
+ if (expectedRevision !== undefined && expectedRevision !== before.policy_revision) {
29
+ const error = new Error(`session policy changed; current revision is ${before.policy_revision}`);
30
+ error.code = "session_policy_conflict";
31
+ throw error;
32
+ }
33
+ const policy = {
34
+ objective: objective ?? before.objective,
35
+ acceptance: acceptance === undefined ? before.default_acceptance : JSON.stringify(acceptance),
36
+ approval: approvalState ?? before.approval_state
37
+ };
38
+ const changed = policy.objective !== before.objective || policy.acceptance !== before.default_acceptance || policy.approval !== before.approval_state;
39
+ store.prepare("UPDATE sessions SET objective=?,default_acceptance=?,approval_state=?,policy_revision=?,updated_at=? WHERE id=?")
40
+ .run(policy.objective, policy.acceptance, policy.approval, before.policy_revision + (changed ? 1 : 0), now, id);
41
+ store.exec("COMMIT");
42
+ } catch (error) { store.exec("ROLLBACK"); throw error; }
43
+ });
44
+ }
45
+ return getSession(id);
46
+ }
47
+
48
+ export async function getSession(sessionId) {
49
+ await ensureFilesystem();
50
+ const row = openDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
51
+ return row ? { ...row, default_acceptance: decodeJson(row.default_acceptance, []) } : null;
52
+ }
53
+
54
+ export async function readSessions() {
55
+ await ensureFilesystem();
56
+ return openDb().prepare("SELECT * FROM sessions").all();
57
+ }
58
+
59
+ // ---- side sessions and turns
60
+
61
+ export async function getSideSession(taskId) {
62
+ await ensureFilesystem();
63
+ return openDb().prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
64
+ }
65
+
66
+ // `workerRunCount` is the worker's run_count when the fork is taken; a
67
+ // worker resumed after that has a thread the fork no longer reflects.
68
+ export async function openSideSession(taskId, workerRunCount = null) {
69
+ await ensureFilesystem();
70
+ const now = new Date().toISOString();
71
+ openDb()
72
+ .prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at, worker_run_count) VALUES (?, NULL, ?, NULL, ?)
73
+ ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL, worker_run_count = excluded.worker_run_count`)
74
+ .run(taskId, now, workerRunCount);
75
+ return getSideSession(taskId);
76
+ }
77
+
78
+ export async function setSideSessionFork(taskId, forkThreadId) {
79
+ await ensureFilesystem();
80
+ openDb().prepare("UPDATE side_sessions SET fork_thread_id = ? WHERE task_id = ? AND ended_at IS NULL").run(forkThreadId, taskId);
81
+ }
82
+
83
+ export async function closeSideSession(taskId) {
84
+ await ensureFilesystem();
85
+ const db = openDb();
86
+ const row = db.prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
87
+ const now = new Date().toISOString();
88
+ db.prepare("UPDATE side_sessions SET ended_at = ? WHERE task_id = ? AND ended_at IS NULL").run(now, taskId);
89
+ db.prepare("DELETE FROM side_turns WHERE task_id = ?").run(taskId);
90
+ return row;
91
+ }
92
+
93
+ export async function insertSideTurn(turn) {
94
+ await ensureFilesystem();
95
+ openDb()
96
+ .prepare(`INSERT INTO side_turns (id, task_id, question, status, chunks, usage, error, started_at, ended_at)
97
+ VALUES (@id, @task_id, @question, @status, @chunks, @usage, @error, @started_at, @ended_at)`)
98
+ .run({
99
+ id: turn.id,
100
+ task_id: turn.task_id,
101
+ question: turn.question,
102
+ status: turn.status,
103
+ chunks: JSON.stringify(turn.chunks ?? []),
104
+ usage: turn.usage ? JSON.stringify(turn.usage) : null,
105
+ error: turn.error ?? null,
106
+ started_at: turn.started_at,
107
+ ended_at: turn.ended_at ?? null
108
+ });
109
+ }
110
+
111
+ export async function updateSideTurn(id, fields) {
112
+ await ensureFilesystem();
113
+ const sets = [];
114
+ const params = { id };
115
+ for (const [key, value] of Object.entries(fields)) {
116
+ sets.push(`${key} = @${key}`);
117
+ params[key] = key === "chunks" || key === "usage" ? (value === null ? null : JSON.stringify(value)) : value;
118
+ }
119
+ if (sets.length === 0) return;
120
+ openDb().prepare(`UPDATE side_turns SET ${sets.join(", ")} WHERE id = @id`).run(params);
121
+ }
122
+
123
+ export async function readSideTurns(taskId) {
124
+ await ensureFilesystem();
125
+ return openDb()
126
+ .prepare("SELECT * FROM side_turns WHERE task_id = ? ORDER BY started_at ASC")
127
+ .all(taskId)
128
+ .map((row) => ({ ...row, chunks: decodeJson(row.chunks, []), usage: row.usage ? decodeJson(row.usage, null) : null }));
129
+ }
130
+
131
+ // A board that restarts cannot own a turn that was running when it died.
132
+ export async function interruptRunningSideTurns() {
133
+ await ensureFilesystem();
134
+ const now = new Date().toISOString();
135
+ return openDb()
136
+ .prepare("UPDATE side_turns SET status = 'interrupted', error = COALESCE(error, 'the board restarted while this turn was running'), ended_at = ? WHERE status = 'running'")
137
+ .run(now).changes;
138
+ }