proofdeck 0.0.0-stage → 0.1.0

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 (134) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +23 -0
  3. package/README.md +97 -2
  4. package/README.zh-CN.md +89 -0
  5. package/bin/proofdeck.js +126 -0
  6. package/board/LICENSE +201 -0
  7. package/board/README.md +473 -0
  8. package/board/README.zh-CN.md +424 -0
  9. package/board/dist/_chk.db-shm +0 -0
  10. package/board/dist/_chk.db-wal +0 -0
  11. package/board/dist/adapters.d.ts +40 -0
  12. package/board/dist/adapters.d.ts.map +1 -0
  13. package/board/dist/adapters.js +124 -0
  14. package/board/dist/adapters.js.map +1 -0
  15. package/board/dist/board.d.ts +628 -0
  16. package/board/dist/board.d.ts.map +1 -0
  17. package/board/dist/board.js +2767 -0
  18. package/board/dist/board.js.map +1 -0
  19. package/board/dist/cli.d.ts +3 -0
  20. package/board/dist/cli.d.ts.map +1 -0
  21. package/board/dist/cli.js +1663 -0
  22. package/board/dist/cli.js.map +1 -0
  23. package/board/dist/config.d.ts +57 -0
  24. package/board/dist/config.d.ts.map +1 -0
  25. package/board/dist/config.js +99 -0
  26. package/board/dist/config.js.map +1 -0
  27. package/board/dist/db.d.ts +9 -0
  28. package/board/dist/db.d.ts.map +1 -0
  29. package/board/dist/db.js +506 -0
  30. package/board/dist/db.js.map +1 -0
  31. package/board/dist/git.d.ts +35 -0
  32. package/board/dist/git.d.ts.map +1 -0
  33. package/board/dist/git.js +147 -0
  34. package/board/dist/git.js.map +1 -0
  35. package/board/dist/index.d.ts +18 -0
  36. package/board/dist/index.d.ts.map +1 -0
  37. package/board/dist/index.js +13 -0
  38. package/board/dist/index.js.map +1 -0
  39. package/board/dist/mcp-config.d.ts +26 -0
  40. package/board/dist/mcp-config.d.ts.map +1 -0
  41. package/board/dist/mcp-config.js +88 -0
  42. package/board/dist/mcp-config.js.map +1 -0
  43. package/board/dist/mcp.d.ts +3 -0
  44. package/board/dist/mcp.d.ts.map +1 -0
  45. package/board/dist/mcp.js +949 -0
  46. package/board/dist/mcp.js.map +1 -0
  47. package/board/dist/quickstart.d.ts +75 -0
  48. package/board/dist/quickstart.d.ts.map +1 -0
  49. package/board/dist/quickstart.js +156 -0
  50. package/board/dist/quickstart.js.map +1 -0
  51. package/board/dist/serve.d.ts +10 -0
  52. package/board/dist/serve.d.ts.map +1 -0
  53. package/board/dist/serve.js +445 -0
  54. package/board/dist/serve.js.map +1 -0
  55. package/board/dist/signing.d.ts +18 -0
  56. package/board/dist/signing.d.ts.map +1 -0
  57. package/board/dist/signing.js +26 -0
  58. package/board/dist/signing.js.map +1 -0
  59. package/board/dist/sync.d.ts +49 -0
  60. package/board/dist/sync.d.ts.map +1 -0
  61. package/board/dist/sync.js +158 -0
  62. package/board/dist/sync.js.map +1 -0
  63. package/board/dist/types.d.ts +359 -0
  64. package/board/dist/types.d.ts.map +1 -0
  65. package/board/dist/types.js +20 -0
  66. package/board/dist/types.js.map +1 -0
  67. package/board/docs/adr/0001-shared-worktree-collision.md +102 -0
  68. package/board/docs/adr/0001-shared-worktree-collision.zh-CN.md +90 -0
  69. package/board/docs/attribution.md +123 -0
  70. package/board/docs/attribution.zh-CN.md +104 -0
  71. package/board/docs/development-workflow.md +81 -0
  72. package/board/docs/development-workflow.zh-CN.md +75 -0
  73. package/board/docs/diagrams/banner.png +0 -0
  74. package/board/docs/diagrams/banner.svg +1 -0
  75. package/board/docs/diagrams/before-after.png +0 -0
  76. package/board/docs/diagrams/before-after.svg +1 -0
  77. package/board/docs/diagrams/governance-chain.png +0 -0
  78. package/board/docs/diagrams/governance-chain.svg +1 -0
  79. package/board/docs/diagrams/value-flow.png +0 -0
  80. package/board/docs/diagrams/value-flow.svg +1 -0
  81. package/board/docs/entry-point.md +81 -0
  82. package/board/docs/entry-point.zh-CN.md +65 -0
  83. package/board/docs/kanban.png +0 -0
  84. package/board/docs/octoryn-mark.png +0 -0
  85. package/board/docs/registry-metadata.md +34 -0
  86. package/board/docs/registry-metadata.zh-CN.md +30 -0
  87. package/board/package.json +87 -0
  88. package/config.example.json +71 -0
  89. package/daemon.js +1112 -0
  90. package/docs/assets/demo.gif +0 -0
  91. package/docs/demo-run.mjs +61 -0
  92. package/docs/render-demo.py +94 -0
  93. package/e2e/verify-acceptance.mjs +150 -0
  94. package/e2e/verify-antifraud.mjs +128 -0
  95. package/e2e/verify-caps.mjs +46 -0
  96. package/e2e/verify-checkpoint.mjs +208 -0
  97. package/e2e/verify-firstclass.mjs +110 -0
  98. package/e2e/verify-judge.mjs +52 -0
  99. package/e2e/verify-lease.mjs +95 -0
  100. package/e2e/verify-replay.mjs +92 -0
  101. package/e2e/verify-resilience.mjs +323 -0
  102. package/e2e/verify-review.mjs +86 -0
  103. package/e2e/verify-scheduling.mjs +110 -0
  104. package/e2e/verify-schema-evolution.mjs +107 -0
  105. package/e2e/verify-sla-digest.mjs +105 -0
  106. package/guard.js +97 -0
  107. package/lib/adapters/codex.js +206 -0
  108. package/lib/billing-convert.js +57 -0
  109. package/lib/board.js +46 -0
  110. package/lib/caps.js +35 -0
  111. package/lib/checkpoint.js +130 -0
  112. package/lib/gating.js +218 -0
  113. package/lib/guard-core.mjs +108 -0
  114. package/lib/http.js +161 -0
  115. package/lib/judge.js +89 -0
  116. package/lib/lease.js +93 -0
  117. package/lib/notify.js +56 -0
  118. package/lib/platform.js +120 -0
  119. package/lib/replay.js +68 -0
  120. package/lib/review.js +40 -0
  121. package/lib/runner.js +152 -0
  122. package/lib/schedule.js +59 -0
  123. package/lib/sla.js +42 -0
  124. package/lib/spans.js +36 -0
  125. package/lib/starve.js +43 -0
  126. package/lib/store.js +109 -0
  127. package/lib/supply.js +101 -0
  128. package/lib/usage.js +103 -0
  129. package/lib/verify.js +223 -0
  130. package/lib/watchdog-core.mjs +68 -0
  131. package/lib/watchdog-worker.mjs +75 -0
  132. package/package.json +55 -4
  133. package/scripts/run-daemon.sh +18 -0
  134. package/scripts/run-e2e.mjs +39 -0
@@ -0,0 +1,2767 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from "node:fs";
3
+ import { hostname } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { openDb } from "./db.js";
6
+ import { loadConfig, } from "./config.js";
7
+ import * as git from "./git.js";
8
+ import { generateSessionKeypair, signHash, verifyHash } from "./signing.js";
9
+ const GENESIS_HASH = "0".repeat(64);
10
+ /** Valid project lifecycle values (step 2). Enforced by `setProjectStatus`. */
11
+ const PROJECT_STATUSES = ["active", "paused", "archived"];
12
+ // evidence-ledger (2026-10-10): the controlled vocabulary for `evidence.kind`.
13
+ // A whitelist, not free text, so the sedimentation register cannot fragment into
14
+ // spelling variants the way `tasks.project` once did.
15
+ const EVIDENCE_KINDS = ["memory", "skill", "hook", "lesson", "playbook"];
16
+ /**
17
+ * Agent-identity aliases (2026-10-10). The same assistant is registered on the
18
+ * board under two identities: `xiaoyu` (this session's persona) and `workbuddy`
19
+ * (the WorkBuddy MCP-client identity that other agents such as lingyu message).
20
+ * With no merge, a message sent to `workbuddy` is invisible in `xiaoyu`'s inbox,
21
+ * so the assistant "never received" things it was told about. `recipientSet`
22
+ * expands an agent to the full set of identities that share ONE inbox, so
23
+ * reading or acking either identity covers both. Agents absent from the map keep
24
+ * their original single-identity behaviour — fully backward compatible.
25
+ */
26
+ const AGENT_ALIASES = {
27
+ xiaoyu: ["xiaoyu", "workbuddy"],
28
+ workbuddy: ["xiaoyu", "workbuddy"],
29
+ };
30
+ function recipientSet(agent) {
31
+ return AGENT_ALIASES[agent] ?? [agent];
32
+ }
33
+ function now() {
34
+ return new Date().toISOString();
35
+ }
36
+ function id() {
37
+ return randomUUID();
38
+ }
39
+ /** Schema tag for the portable attribution bundle. Bump on breaking changes. */
40
+ export const BUNDLE_VERSION = "octopus-blackboard/attribution-bundle@1";
41
+ /**
42
+ * The blackboard. A thin, synchronous wrapper over a SQLite database. Every
43
+ * mutation also appends one tamper-evident entry to the timeline within the
44
+ * same transaction, so the board and its audit log can never diverge.
45
+ *
46
+ * The board is deliberately passive: it records and reports. It never triggers
47
+ * an agent, schedules work, or decides anything on an agent's behalf.
48
+ */
49
+ export class Board {
50
+ config;
51
+ db;
52
+ /** Active session id for the acting agent; stamped onto every write. */
53
+ activeSession;
54
+ constructor(config) {
55
+ this.config = config;
56
+ this.db = openDb(config.dbPath);
57
+ // LOCAL PUSH PATCH (best-effort doorbell): after the OUTERMOST committed
58
+ // transaction, overwrite <boardDir>/notify.json with a hint so resident
59
+ // watchers wake on an OS file event instead of polling. The timeline hash
60
+ // chain stays the source of truth; hint loss or staleness is recoverable.
61
+ this._pending = [];
62
+ this._doorbell = process.env.OCTOBOARD_NOTIFY?.trim() ||
63
+ join(config.boardDir, "notify.json");
64
+ this._wrapTransactions();
65
+ // An explicit env/flag session wins; otherwise resolve the agent's active
66
+ // session from the DB (set transactionally by session start/stop).
67
+ this.activeSession =
68
+ config.sessionId ?? this.currentSessionFromDb(config.agent);
69
+ }
70
+ /** Guard every transaction flavor so the doorbell fires only after a real
71
+ * commit (never on rollback) and only from the outermost one (savepoint
72
+ * children still run inside the transaction). */
73
+ _wrapTransactions() {
74
+ const db = this.db;
75
+ const rawTx = db.transaction.bind(db);
76
+ db.transaction = (fn) => {
77
+ const t = rawTx(fn);
78
+ const board = this;
79
+ const guard = (m) => (...a) => {
80
+ try {
81
+ return m.apply(t, a);
82
+ }
83
+ catch (e) {
84
+ board._pending = []; // rolled back — stay silent
85
+ throw e;
86
+ }
87
+ finally {
88
+ if (!db.inTransaction)
89
+ board._notify();
90
+ }
91
+ };
92
+ const wrapped = (...a) => guard(t)(...a);
93
+ wrapped.deferred = guard(t.deferred);
94
+ wrapped.immediate = guard(t.immediate);
95
+ wrapped.exclusive = guard(t.exclusive);
96
+ return wrapped;
97
+ };
98
+ }
99
+ /** Overwrite the doorbell hint atomically. Never throws: a failed fan-out
100
+ * must not affect the write that already committed. */
101
+ _notify() {
102
+ try {
103
+ const q = this._pending;
104
+ this._pending = [];
105
+ if (!q.length)
106
+ return;
107
+ const last = q[q.length - 1];
108
+ mkdirSync(dirname(this._doorbell), { recursive: true });
109
+ const tmp = `${this._doorbell}.${process.pid}.tmp`;
110
+ writeFileSync(tmp, JSON.stringify({
111
+ head: last.seq,
112
+ n: q.length,
113
+ at: last.at,
114
+ kind: last.kind,
115
+ actor: last.actor,
116
+ }));
117
+ renameSync(tmp, this._doorbell);
118
+ }
119
+ catch {
120
+ /* hint is advisory; drop it on failure */
121
+ }
122
+ }
123
+ currentSessionFromDb(agent) {
124
+ const row = this.db
125
+ .prepare("SELECT session_id FROM current_sessions WHERE agent = ?")
126
+ .get(agent);
127
+ return row?.session_id ?? null;
128
+ }
129
+ /** The active session id for this board's agent (null if none). */
130
+ activeSessionId() {
131
+ return this.activeSession;
132
+ }
133
+ static open(overrides = {}) {
134
+ const config = loadConfig(overrides);
135
+ // Per-handle session overrides are required when one process writes on
136
+ // behalf of concurrent tasks. They win over the process-wide env default.
137
+ if (Object.prototype.hasOwnProperty.call(overrides, "sessionId")) {
138
+ config.sessionId = overrides.sessionId ?? null;
139
+ }
140
+ return new Board(config);
141
+ }
142
+ close() {
143
+ this.db.close();
144
+ }
145
+ // --- timeline (hash chain) -------------------------------------------------
146
+ headHash() {
147
+ const row = this.db
148
+ .prepare("SELECT seq, hash FROM timeline ORDER BY seq DESC LIMIT 1")
149
+ .get();
150
+ return row
151
+ ? { seq: row.seq, hash: row.hash }
152
+ : { seq: 0, hash: GENESIS_HASH };
153
+ }
154
+ /**
155
+ * The tamper-evident core of a timeline entry.
156
+ *
157
+ * ⚠️ `project` / `task_key` (step 2) are deliberately EXCLUDED. Adding them
158
+ * would change the array length and therefore break the recomputed hash of
159
+ * every pre-existing row — i.e. it would make `verifyChain()` report the whole
160
+ * history as altered. Consequence to be aware of: those two columns are
161
+ * *attached attributes*, not hash-protected. Falsifying them does not break
162
+ * `verifyChain()`. They are safe for ownership/aggregation, not for proof.
163
+ * (The same is true of the `project` columns on the other six trace tables,
164
+ * which live in separate tables and were never inside the chain either.)
165
+ */
166
+ static computeHash(e) {
167
+ const canonical = JSON.stringify([
168
+ e.seq,
169
+ e.at,
170
+ e.actor,
171
+ e.sessionId,
172
+ e.kind,
173
+ e.refTable,
174
+ e.refId,
175
+ e.summary,
176
+ e.payload ?? null,
177
+ e.prevHash,
178
+ ]);
179
+ return createHash("sha256").update(canonical).digest("hex");
180
+ }
181
+ /** Append one entry to the timeline. Must run inside a transaction.
182
+ * `opts.project` / `opts.taskKey` (step 2) record four-layer ownership.
183
+ * NOTE: they are deliberately NOT part of `computeHash` — see the comment on
184
+ * `computeHash` for why, and the caveat that follows from it. */
185
+ append(actor, kind, summary, refTable, refId, payload, opts = {}) {
186
+ const head = this.headHash();
187
+ const seq = head.seq + 1;
188
+ const at = now();
189
+ const event = {
190
+ id: id(),
191
+ seq,
192
+ at,
193
+ actor,
194
+ sessionId: this.activeSession,
195
+ kind,
196
+ refTable,
197
+ refId,
198
+ summary,
199
+ payload: payload ?? null,
200
+ prevHash: head.hash,
201
+ hash: "",
202
+ };
203
+ event.hash = Board.computeHash(event);
204
+ this.db
205
+ .prepare(`INSERT INTO timeline (id, seq, at, actor, session_id, kind, ref_table, ref_id, summary, payload, prev_hash, hash, project, task_key)
206
+ VALUES (@id, @seq, @at, @actor, @sessionId, @kind, @refTable, @refId, @summary, @payload, @prevHash, @hash, @project, @taskKey)`)
207
+ .run({
208
+ ...event,
209
+ payload: event.payload === null ? null : JSON.stringify(event.payload),
210
+ project: opts.project ?? null,
211
+ taskKey: opts.taskKey ?? null,
212
+ });
213
+ // Anchor the head (seq + hash) so tail truncation is detectable: deleting
214
+ // the newest rows leaves an internally-consistent chain, but no longer
215
+ // matches the recorded head. Same transaction as the insert.
216
+ this.db
217
+ .prepare("INSERT INTO meta (key, value) VALUES ('head_seq', @seq), ('head_hash', @hash) ON CONFLICT(key) DO UPDATE SET value = excluded.value")
218
+ .run({ seq: String(event.seq), hash: event.hash });
219
+ // LOCAL PUSH PATCH: queue the hint; flushed post-commit by the
220
+ // transaction guard. Must never break a write.
221
+ try {
222
+ (this._pending ??= []).push({ seq: event.seq, at: event.at, kind, actor });
223
+ }
224
+ catch { }
225
+ return event;
226
+ }
227
+ /** The current timeline head (seq + hash). Record this OUTSIDE the DB — in a
228
+ * commit, a log, a second machine — to anchor against tail truncation. */
229
+ head() {
230
+ return this.headHash();
231
+ }
232
+ /**
233
+ * Check the chain against an anchor recorded earlier (e.g. committed to git).
234
+ * `ok` = the anchored row still exists with that hash and history through it
235
+ * is intact; `truncated` = rows at/below the anchor were deleted; `altered` =
236
+ * history at/below the anchor was edited. This is what closes the "attacker
237
+ * drops the trigger and truncates" gap — an external anchor makes truncation
238
+ * provable.
239
+ */
240
+ verifyAnchor(seq, hash) {
241
+ const chain = this.verifyChain();
242
+ const headSeq = this.headHash().seq;
243
+ if (headSeq < seq) {
244
+ return { status: "truncated", headSeq };
245
+ }
246
+ const row = this.db
247
+ .prepare("SELECT hash FROM timeline WHERE seq = ?")
248
+ .get(seq);
249
+ if (!row) {
250
+ return { status: "truncated", headSeq };
251
+ }
252
+ if (row.hash !== hash) {
253
+ return { status: "altered", headSeq };
254
+ }
255
+ if (!chain.ok && chain.brokenAtSeq !== null && chain.brokenAtSeq <= seq) {
256
+ return { status: "altered", headSeq };
257
+ }
258
+ return { status: "ok", headSeq };
259
+ }
260
+ headAnchor() {
261
+ const rows = this.db
262
+ .prepare("SELECT key, value FROM meta WHERE key IN ('head_seq','head_hash')")
263
+ .all();
264
+ const map = new Map(rows.map((r) => [r.key, r.value]));
265
+ const seq = map.get("head_seq");
266
+ const hash = map.get("head_hash");
267
+ return seq !== undefined && hash !== undefined
268
+ ? { seq: Number(seq), hash }
269
+ : null;
270
+ }
271
+ /** Re-walk the chain and confirm every hash links to its predecessor. */
272
+ verifyChain() {
273
+ const rows = this.db
274
+ .prepare("SELECT * FROM timeline ORDER BY seq ASC")
275
+ .all();
276
+ const anchor = this.headAnchor();
277
+ const anchored = anchor !== null;
278
+ let prevHash = GENESIS_HASH;
279
+ let prevSeq = 0;
280
+ for (const row of rows) {
281
+ // Contiguity: seq must increment by exactly 1 (catches a missing middle
282
+ // row even before the hash check).
283
+ if (row.seq !== prevSeq + 1) {
284
+ return {
285
+ ok: false,
286
+ length: rows.length,
287
+ brokenAtSeq: row.seq,
288
+ anchored,
289
+ };
290
+ }
291
+ const recomputed = Board.computeHash({
292
+ seq: row.seq,
293
+ at: row.at,
294
+ actor: row.actor,
295
+ sessionId: row.session_id,
296
+ kind: row.kind,
297
+ refTable: row.ref_table,
298
+ refId: row.ref_id,
299
+ summary: row.summary,
300
+ payload: row.payload === null ? null : JSON.parse(row.payload),
301
+ prevHash,
302
+ });
303
+ if (row.prev_hash !== prevHash || row.hash !== recomputed) {
304
+ return {
305
+ ok: false,
306
+ length: rows.length,
307
+ brokenAtSeq: row.seq,
308
+ anchored,
309
+ };
310
+ }
311
+ prevHash = row.hash;
312
+ prevSeq = row.seq;
313
+ }
314
+ // Tail-truncation check against the recorded head anchor. When no anchor is
315
+ // present on a non-empty timeline (legacy board, OR a deleted anchor), tail
316
+ // truncation cannot be detected from the DB alone — reported via `anchored`
317
+ // so callers don't present it as a clean pass.
318
+ if (anchor) {
319
+ const lastSeq = rows.length > 0 ? rows[rows.length - 1].seq : 0;
320
+ const lastHash = rows.length > 0 ? rows[rows.length - 1].hash : GENESIS_HASH;
321
+ if (lastSeq !== anchor.seq || lastHash !== anchor.hash) {
322
+ return {
323
+ ok: false,
324
+ length: rows.length,
325
+ brokenAtSeq: anchor.seq,
326
+ anchored,
327
+ };
328
+ }
329
+ }
330
+ return { ok: true, length: rows.length, brokenAtSeq: null, anchored };
331
+ }
332
+ timeline(limit = 50) {
333
+ const rows = this.db
334
+ .prepare("SELECT * FROM timeline ORDER BY seq DESC LIMIT ?")
335
+ .all(limit);
336
+ return this.applyRedactions(rows.map(rowToTimeline).reverse());
337
+ }
338
+ /** The current head sequence number (0 if the board is empty). */
339
+ headSeq() {
340
+ return this.headHash().seq;
341
+ }
342
+ /** Timeline events after `afterSeq`, oldest first — the polling primitive
343
+ * behind `watch`/`subscribe`. Passive: callers poll; the board never pushes. */
344
+ since(afterSeq) {
345
+ return this.applyRedactions(this.db
346
+ .prepare("SELECT * FROM timeline WHERE seq > ? ORDER BY seq ASC")
347
+ .all(afterSeq).map(rowToTimeline));
348
+ }
349
+ /**
350
+ * Filter events down to those an agent should be notified about: messages to
351
+ * it (or broadcast), handoffs to it, and claim conflicts on keys it holds. An
352
+ * agent's own actions are excluded. This is what makes `watch --for <agent>`
353
+ * a useful inbox rather than a firehose.
354
+ */
355
+ notable(events, agent) {
356
+ return events.filter((e) => {
357
+ if (e.actor === agent) {
358
+ return false;
359
+ }
360
+ const payload = (e.payload ?? {});
361
+ switch (e.kind) {
362
+ case "message":
363
+ return payload.to === agent || payload.to === null;
364
+ case "claim":
365
+ return payload.conflict === agent;
366
+ case "handoff": {
367
+ if (!e.refId) {
368
+ return false;
369
+ }
370
+ const row = this.db
371
+ .prepare("SELECT to_agent FROM handoffs WHERE id = ?")
372
+ .get(e.refId);
373
+ return row?.to_agent === agent;
374
+ }
375
+ default:
376
+ return false;
377
+ }
378
+ });
379
+ }
380
+ // --- agents ----------------------------------------------------------------
381
+ /**
382
+ * Register the agent if new and stamp `last_seen`. Idempotent by name. When
383
+ * registering the acting agent, its full provider-independent identity
384
+ * (provider/model/cli/version) is merged in; non-null fields never overwrite
385
+ * with null, so a later bare touch cannot erase identity.
386
+ */
387
+ ensureAgent(name, identity) {
388
+ const id0 = identity ??
389
+ (name === this.config.agent ? this.config.identity : undefined);
390
+ const existing = this.db
391
+ .prepare("SELECT * FROM agents WHERE name = ?")
392
+ .get(name);
393
+ const at = now();
394
+ if (existing) {
395
+ this.db
396
+ .prepare(`UPDATE agents SET last_seen = ?,
397
+ kind = COALESCE(?, kind), provider = COALESCE(?, provider),
398
+ model = COALESCE(?, model), cli = COALESCE(?, cli), version = COALESCE(?, version)
399
+ WHERE id = ?`)
400
+ .run(at, id0?.kind ?? null, id0?.provider ?? null, id0?.model ?? null, id0?.cli ?? null, id0?.version ?? null, existing.id);
401
+ return rowToAgent(this.db.prepare("SELECT * FROM agents WHERE id = ?").get(existing.id));
402
+ }
403
+ const agent = {
404
+ id: id(),
405
+ name,
406
+ kind: id0?.kind ?? null,
407
+ provider: id0?.provider ?? null,
408
+ model: id0?.model ?? null,
409
+ cli: id0?.cli ?? null,
410
+ version: id0?.version ?? null,
411
+ createdAt: at,
412
+ lastSeen: at,
413
+ };
414
+ this.db
415
+ .prepare("INSERT INTO agents (id, name, kind, provider, model, cli, version, created_at, last_seen) VALUES (@id, @name, @kind, @provider, @model, @cli, @version, @createdAt, @lastSeen)")
416
+ .run(agent);
417
+ return agent;
418
+ }
419
+ getAgent(name) {
420
+ const row = this.db
421
+ .prepare("SELECT * FROM agents WHERE name = ?")
422
+ .get(name);
423
+ return row ? rowToAgent(row) : undefined;
424
+ }
425
+ // --- sessions --------------------------------------------------------------
426
+ /**
427
+ * Open a new session for the acting agent and make it current (persisted in
428
+ * the DB, so later CLI invocations attribute to it). Captures the machine and
429
+ * repository context the session runs in.
430
+ */
431
+ startSession(label = null, options = {}) {
432
+ const { project = null, taskKey = null, detached = false } = options ?? {};
433
+ const sessionId = id();
434
+ // Generate the session keypair up front; the private key stays local (in
435
+ // the board's keys/ dir), only the public key is recorded on the session.
436
+ const keypair = generateSessionKeypair();
437
+ this.saveSessionKey(sessionId, keypair.privateKeyPem);
438
+ const tx = this.db.transaction(() => {
439
+ this.ensureAgent(this.config.agent);
440
+ const at = now();
441
+ const session = {
442
+ id: sessionId,
443
+ agentName: this.config.agent,
444
+ label,
445
+ machine: hostname(),
446
+ workingDirectory: process.cwd(),
447
+ gitBranch: git.currentBranch() ?? null,
448
+ repository: git.remoteUrl() ?? git.repoRoot() ?? null,
449
+ publicKey: keypair.publicKeyPem,
450
+ lastHeartbeat: at,
451
+ startedAt: at,
452
+ finishedAt: null,
453
+ project,
454
+ taskKey,
455
+ };
456
+ this.db
457
+ .prepare(`INSERT INTO sessions (id, agent_name, label, machine, working_directory, git_branch, repository, public_key, last_heartbeat, started_at, finished_at, project, task_key)
458
+ VALUES (@id, @agentName, @label, @machine, @workingDirectory, @gitBranch, @repository, @publicKey, @lastHeartbeat, @startedAt, @finishedAt, @project, @taskKey)`)
459
+ .run(session);
460
+ // Stamp subsequent events (including this one) with the new session.
461
+ // Detached sessions deliberately avoid the per-agent current_sessions pointer:
462
+ // the bridge can run several tasks concurrently without cross-attribution.
463
+ this.activeSession = session.id;
464
+ if (!detached) {
465
+ this.db
466
+ .prepare("INSERT OR REPLACE INTO current_sessions (agent, session_id) VALUES (?, ?)")
467
+ .run(this.config.agent, session.id);
468
+ }
469
+ const sessionPayload = { machine: session.machine, gitBranch: session.gitBranch };
470
+ if (project != null || taskKey != null || detached) {
471
+ Object.assign(sessionPayload, { project, taskKey, detached: !!detached });
472
+ }
473
+ this.append(this.config.agent, "session-start", `session started${label ? ` (${label})` : ""}`, "sessions", session.id, sessionPayload);
474
+ return session;
475
+ });
476
+ return tx.immediate();
477
+ }
478
+ // --- session signing (v0) --------------------------------------------------
479
+ keyPath(sessionId) {
480
+ return join(this.config.boardDir, "keys", `${sessionId}.key`);
481
+ }
482
+ saveSessionKey(sessionId, privateKeyPem) {
483
+ const path = this.keyPath(sessionId);
484
+ // 0700 dir + 0600 file: private keys are not listable/readable by other
485
+ // local users.
486
+ mkdirSync(join(this.config.boardDir, "keys"), {
487
+ recursive: true,
488
+ mode: 0o700,
489
+ });
490
+ writeFileSync(path, privateKeyPem, { mode: 0o600 });
491
+ }
492
+ loadSessionKey(sessionId) {
493
+ const path = this.keyPath(sessionId);
494
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
495
+ }
496
+ /**
497
+ * Sign the current timeline head hash with a session's private key. The
498
+ * signature attests "this session vouches for board state through seq N".
499
+ * Recorded in the `signatures` table (not the chain, so the head stays put).
500
+ */
501
+ signHead(sessionId) {
502
+ const sid = sessionId ?? this.activeSession;
503
+ if (!sid) {
504
+ return undefined;
505
+ }
506
+ const priv = this.loadSessionKey(sid);
507
+ const session = this.getSession(sid);
508
+ if (!priv || !session?.publicKey) {
509
+ return undefined;
510
+ }
511
+ const head = this.headHash();
512
+ if (head.seq === 0) {
513
+ return undefined;
514
+ }
515
+ const signature = signHash(priv, head.hash);
516
+ this.db
517
+ .prepare(`INSERT INTO signatures (id, session_id, head_seq, head_hash, signature, public_key, created_at)
518
+ VALUES (@id, @sessionId, @headSeq, @headHash, @signature, @publicKey, @createdAt)`)
519
+ .run({
520
+ id: id(),
521
+ sessionId: sid,
522
+ headSeq: head.seq,
523
+ headHash: head.hash,
524
+ signature,
525
+ publicKey: session.publicKey,
526
+ createdAt: now(),
527
+ });
528
+ return { headSeq: head.seq, headHash: head.hash };
529
+ }
530
+ /**
531
+ * Verify every recorded signature. `valid` = the signature checks out against
532
+ * its public key. `current` = the signed head hash still matches the timeline
533
+ * row at that seq (i.e. history below it was not altered/truncated since).
534
+ */
535
+ verifySignatures(chain) {
536
+ const rows = this.db
537
+ .prepare("SELECT * FROM signatures ORDER BY head_seq ASC")
538
+ .all();
539
+ if (rows.length === 0) {
540
+ return [];
541
+ }
542
+ // A signature only "covers" its head if the chain is actually intact up to
543
+ // that seq — otherwise a tamper below the signed head (that leaves the head
544
+ // row's stored hash untouched) would still read as trusted. Accept a
545
+ // precomputed chain to avoid re-verifying the whole timeline repeatedly.
546
+ const verified = chain ?? this.verifyChain();
547
+ return rows.map((r) => {
548
+ const valid = verifyHash(r.public_key, r.head_hash, r.signature);
549
+ const row = this.db
550
+ .prepare("SELECT hash FROM timeline WHERE seq = ?")
551
+ .get(r.head_seq);
552
+ const chainOkThroughHead = verified.ok ||
553
+ (verified.brokenAtSeq !== null && r.head_seq < verified.brokenAtSeq);
554
+ const session = this.getSession(r.session_id);
555
+ return {
556
+ sessionId: r.session_id,
557
+ agent: session?.agentName ?? null,
558
+ headSeq: r.head_seq,
559
+ valid,
560
+ current: row?.hash === r.head_hash && chainOkThroughHead,
561
+ at: r.created_at,
562
+ };
563
+ });
564
+ }
565
+ /** Highest seq that a valid, still-current signature vouches for (0 = none). */
566
+ signedThrough(chain) {
567
+ return this.verifySignatures(chain)
568
+ .filter((s) => s.valid && s.current)
569
+ .reduce((max, s) => Math.max(max, s.headSeq), 0);
570
+ }
571
+ /** Close a session (the active one by default) and clear the pointer. */
572
+ stopSession(sessionId) {
573
+ const target = sessionId ?? this.activeSession;
574
+ if (!target) {
575
+ return undefined;
576
+ }
577
+ const tx = this.db.transaction(() => {
578
+ const existing = this.getSession(target);
579
+ if (!existing) {
580
+ return undefined;
581
+ }
582
+ const at = now();
583
+ this.db
584
+ .prepare("UPDATE sessions SET finished_at = ? WHERE id = ?")
585
+ .run(at, target);
586
+ this.activeSession = target;
587
+ // Clear the pointer transactionally (only if it still points here, so a
588
+ // concurrent new session for the same agent is not clobbered).
589
+ this.db
590
+ .prepare("DELETE FROM current_sessions WHERE agent = ? AND session_id = ?")
591
+ .run(existing.agentName ?? this.config.agent, target);
592
+ this.append(existing.agentName ?? this.config.agent, "session-stop", "session stopped", "sessions", target, null);
593
+ return this.getSession(target);
594
+ });
595
+ const session = tx.immediate();
596
+ if (session) {
597
+ // Sign the head (now including the session-stop event) so the session's
598
+ // final state is vouched for. Best-effort: never fails a stop.
599
+ try {
600
+ this.signHead(target);
601
+ }
602
+ catch {
603
+ /* signing is advisory in v0 */
604
+ }
605
+ }
606
+ return session;
607
+ }
608
+ getSession(sessionId) {
609
+ const row = this.db
610
+ .prepare("SELECT * FROM sessions WHERE id = ?")
611
+ .get(sessionId);
612
+ return row ? rowToSession(row) : undefined;
613
+ }
614
+ listSessions(limit = 30) {
615
+ return this.db
616
+ .prepare("SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?")
617
+ .all(limit).map(rowToSession);
618
+ }
619
+ /** All timeline events belonging to a session, oldest first. */
620
+ sessionTimeline(sessionId) {
621
+ return this.applyRedactions(this.db
622
+ .prepare("SELECT * FROM timeline WHERE session_id = ? ORDER BY seq ASC")
623
+ .all(sessionId).map(rowToTimeline));
624
+ }
625
+ listAgents() {
626
+ return this.db
627
+ .prepare("SELECT * FROM agents ORDER BY last_seen DESC")
628
+ .all().map(rowToAgent);
629
+ }
630
+ // --- writes (each is one transaction: entity + timeline entry) -------------
631
+ /** A free-form status note broadcast to the board.
632
+ * `opts.project` / `opts.taskKey` (step 2) scope the note to a project/task. */
633
+ note(actor, text, opts = {}) {
634
+ const tx = this.db.transaction(() => {
635
+ this.ensureAgent(actor);
636
+ return this.append(actor, "note", text, null, null, null, {
637
+ project: opts.project ?? null,
638
+ taskKey: opts.taskKey ?? null,
639
+ });
640
+ });
641
+ return tx.immediate();
642
+ }
643
+ /**
644
+ * Claim a task by key, creating it if absent. If another agent already holds
645
+ * an unreleased claim, the claim still records but `conflict` names the
646
+ * holder — the board surfaces the collision rather than blocking it.
647
+ */
648
+ claim(actor, key, title = null) {
649
+ const tx = this.db.transaction(() => {
650
+ this.ensureAgent(actor);
651
+ const at = now();
652
+ const existing = this.db
653
+ .prepare("SELECT * FROM tasks WHERE key = ?")
654
+ .get(key);
655
+ let conflict = null;
656
+ let task;
657
+ if (!existing) {
658
+ this.db
659
+ .prepare(`INSERT INTO tasks (id, key, number, title, status, created_by, claimed_by, claimed_at, created_at, updated_at)
660
+ VALUES (?, ?, ?, ?, 'claimed', ?, ?, ?, ?, ?)`)
661
+ .run(id(), key, this.nextTaskNumber(), title, actor, actor, at, at, at);
662
+ task = rowToTask(this.db.prepare("SELECT * FROM tasks WHERE key = ?").get(key));
663
+ }
664
+ else {
665
+ if (existing.claimed_by &&
666
+ existing.claimed_by !== actor &&
667
+ !existing.released_at) {
668
+ conflict = existing.claimed_by;
669
+ }
670
+ this.db
671
+ .prepare("UPDATE tasks SET status = 'claimed', claimed_by = ?, claimed_at = ?, released_at = NULL, title = COALESCE(?, title), updated_at = ? WHERE key = ?")
672
+ .run(actor, at, title, at, key);
673
+ task = rowToTask(this.db.prepare("SELECT * FROM tasks WHERE key = ?").get(key));
674
+ }
675
+ const summary = conflict
676
+ ? `claimed "${key}" (CONFLICT: also held by ${conflict})`
677
+ : `claimed "${key}"`;
678
+ this.append(actor, "claim", summary, "tasks", task.id, { key, conflict }, { project: task.project ?? null, taskKey: task.key });
679
+ return { task, conflict };
680
+ });
681
+ return tx.immediate();
682
+ }
683
+ /** Release a claim the actor holds. */
684
+ release(actor, key) {
685
+ const tx = this.db.transaction(() => {
686
+ this.ensureAgent(actor);
687
+ const at = now();
688
+ const existing = this.db
689
+ .prepare("SELECT * FROM tasks WHERE key = ?")
690
+ .get(key);
691
+ if (!existing) {
692
+ return undefined;
693
+ }
694
+ this.db
695
+ .prepare("UPDATE tasks SET status = 'open', released_at = ?, claimed_by = NULL, updated_at = ? WHERE key = ?")
696
+ .run(at, at, key);
697
+ const task = rowToTask(this.db.prepare("SELECT * FROM tasks WHERE key = ?").get(key));
698
+ this.append(actor, "release", `released "${key}"`, "tasks", task.id, {
699
+ key,
700
+ }, { project: task.project ?? null, taskKey: task.key });
701
+ return task;
702
+ });
703
+ return tx.immediate();
704
+ }
705
+ /** Mark a task done. */
706
+ complete(actor, key) {
707
+ const tx = this.db.transaction(() => {
708
+ this.ensureAgent(actor);
709
+ const at = now();
710
+ const existing = this.db
711
+ .prepare("SELECT * FROM tasks WHERE key = ?")
712
+ .get(key);
713
+ if (!existing) {
714
+ return undefined;
715
+ }
716
+ // Same hole as setTaskStatus: only setProgress(100) implied done, never the
717
+ // reverse, so `done` cards kept a stale progress and readers that trusted
718
+ // that field reported them as unfinished forever.
719
+ const stamp = (existing.progress ?? 0) < 100;
720
+ this.db
721
+ .prepare("UPDATE tasks SET status = 'done', progress = ?, updated_at = ? WHERE key = ?")
722
+ .run(stamp ? 100 : existing.progress, at, key);
723
+ const task = rowToTask(this.db.prepare("SELECT * FROM tasks WHERE key = ?").get(key));
724
+ this.append(actor, "complete", `completed "${key}"${stamp ? " (progress → 100)" : ""}`, "tasks", task.id, {
725
+ key,
726
+ ...(stamp ? { progress: 100 } : {}),
727
+ }, { project: task.project ?? null, taskKey: task.key });
728
+ return task;
729
+ });
730
+ return tx.immediate();
731
+ }
732
+ listTasks(status, filters = {}) {
733
+ const clauses = [];
734
+ const params = [];
735
+ if (status) {
736
+ clauses.push("status = ?");
737
+ params.push(status);
738
+ }
739
+ if (filters.project) {
740
+ clauses.push("project = ?");
741
+ params.push(filters.project);
742
+ }
743
+ if (filters.stream) {
744
+ clauses.push("stream = ?");
745
+ params.push(filters.stream);
746
+ }
747
+ const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
748
+ const rows = this.db
749
+ .prepare(`SELECT * FROM tasks${where} ORDER BY updated_at DESC`)
750
+ .all(...params);
751
+ return rows.map(rowToTask);
752
+ }
753
+ // --- projects (four-layer: board -> project -> task -> trace) --------------
754
+ /** Does a project with this key exist on the board? */
755
+ projectExists(key) {
756
+ if (!key) {
757
+ return false;
758
+ }
759
+ return !!this.db.prepare("SELECT 1 FROM projects WHERE key = ?").get(key);
760
+ }
761
+ getProject(key) {
762
+ const row = this.db.prepare("SELECT * FROM projects WHERE key = ?").get(key);
763
+ return row ? rowToProject(row) : undefined;
764
+ }
765
+ /**
766
+ * Create or update a project. `created_by` is stamped on first insert and never
767
+ * rewritten; later calls only fill in fields that were actually provided.
768
+ *
769
+ * `opts.streams` (array, or comma-separated / JSON string) declares the
770
+ * project's controlled stream vocabulary. Once declared, `defineTask` rejects
771
+ * any stream outside it (see defineTask). Omitting it leaves the vocabulary
772
+ * untouched; note COALESCE semantics mean it can never be cleared back to NULL
773
+ * through this API.
774
+ *
775
+ * NOTE: the board does NOT auto-create projects as a side effect of anything
776
+ * else (constitution §7 / project hard-constraint #3: agents must not silently
777
+ * create projects). This is the only path that writes to `projects`, and it is
778
+ * always an explicit, attributed action.
779
+ */
780
+ createProject(actor, key, opts = {}) {
781
+ const tx = this.db.transaction(() => {
782
+ this.ensureAgent(actor);
783
+ const at = now();
784
+ const existing = this.getProject(key);
785
+ if (!existing) {
786
+ this.db
787
+ .prepare(`INSERT INTO projects (id, key, name, description, status, streams, created_by, created_at, updated_at)
788
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
789
+ .run(id(), key, opts.name ?? key, opts.description ?? null, opts.status ?? "active", streamsToStorage(opts.streams), actor, at, at);
790
+ }
791
+ else {
792
+ this.db
793
+ .prepare(`UPDATE projects SET name = COALESCE(?, name), description = COALESCE(?, description),
794
+ status = COALESCE(?, status), streams = COALESCE(?, streams), updated_at = ? WHERE key = ?`)
795
+ .run(opts.name ?? null, opts.description ?? null, opts.status ?? null, streamsToStorage(opts.streams), at, key);
796
+ }
797
+ const project = this.getProject(key);
798
+ this.append(actor, "project", `${existing ? "updated" : "created"} project "${key}"`, "projects", project.id, {
799
+ key,
800
+ status: project.status,
801
+ }, { project: project.key });
802
+ return project;
803
+ });
804
+ return tx.immediate();
805
+ }
806
+ /** Set a project's lifecycle status. Returns undefined for an unknown key. */
807
+ setProjectStatus(actor, key, status) {
808
+ if (!PROJECT_STATUSES.includes(status)) {
809
+ throw new Error(`status must be one of ${PROJECT_STATUSES.join(" | ")}`);
810
+ }
811
+ const tx = this.db.transaction(() => {
812
+ this.ensureAgent(actor);
813
+ const project = this.getProject(key);
814
+ if (!project) {
815
+ return undefined;
816
+ }
817
+ this.db
818
+ .prepare("UPDATE projects SET status = ?, updated_at = ? WHERE key = ?")
819
+ .run(status, now(), key);
820
+ this.append(actor, "project", `project "${key}" → ${status}`, "projects", project.id, {
821
+ key,
822
+ status,
823
+ }, { project: key });
824
+ return this.getProject(key);
825
+ });
826
+ return tx.immediate();
827
+ }
828
+ /**
829
+ * Is `agent` a member of `project`? Derived, not stored: a member is anyone who
830
+ * has a project-scoped timeline write, is an assignee of a task under the
831
+ * project, or has a session bound to it. Judged from what already exists, so a
832
+ * caller cannot self-authorise by writing first (see `evidence`).
833
+ *
834
+ * CAVEAT: `timeline.project` / `task_key` are NOT part of `computeHash`, so this
835
+ * is a "collaboration trust" signal, not a tamper-proof one.
836
+ */
837
+ isProjectMember(agent, project) {
838
+ if (!project) {
839
+ return false;
840
+ }
841
+ return this.projectMembers(project).includes(agent);
842
+ }
843
+ /** The derived member set of a project (union of three sources). */
844
+ projectMembers(project) {
845
+ if (!project) {
846
+ return [];
847
+ }
848
+ const rows = this.db
849
+ .prepare(`SELECT actor AS a FROM timeline WHERE project = ?
850
+ UNION SELECT ta.agent AS a FROM task_assignees ta
851
+ JOIN tasks t ON t.key = ta.task_key WHERE t.project = ?
852
+ UNION SELECT agent_name AS a FROM sessions WHERE project = ?`)
853
+ .all(project, project, project);
854
+ return rows.map((r) => r.a).filter(Boolean);
855
+ }
856
+ /** The sedimentation register: evidence filtered by project / task / kind. */
857
+ listEvidence(filters = {}) {
858
+ const clauses = [];
859
+ const params = [];
860
+ if (filters.project !== undefined) {
861
+ clauses.push("project = ?");
862
+ params.push(filters.project);
863
+ }
864
+ if (filters.taskKey !== undefined) {
865
+ clauses.push("task_key = ?");
866
+ params.push(filters.taskKey);
867
+ }
868
+ if (filters.kind !== undefined) {
869
+ clauses.push("kind = ?");
870
+ params.push(filters.kind);
871
+ }
872
+ const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
873
+ const rows = this.db
874
+ .prepare(`SELECT * FROM evidence${where} ORDER BY created_at DESC`)
875
+ .all(...params);
876
+ return rows.map(rowToEvidence);
877
+ }
878
+ /** All projects, each with its live task count (and per-status breakdown). */
879
+ listProjects() {
880
+ const rows = this.db
881
+ .prepare("SELECT * FROM projects ORDER BY key")
882
+ .all();
883
+ const counts = this.db
884
+ .prepare(`SELECT project, status, COUNT(*) AS n FROM tasks
885
+ WHERE project IS NOT NULL GROUP BY project, status`)
886
+ .all();
887
+ const byKey = new Map();
888
+ for (const c of counts) {
889
+ const entry = byKey.get(c.project) ?? { total: 0, byStatus: {} };
890
+ entry.total += c.n;
891
+ entry.byStatus[c.status] = c.n;
892
+ byKey.set(c.project, entry);
893
+ }
894
+ return rows.map((r) => {
895
+ const p = rowToProject(r);
896
+ const agg = byKey.get(p.key) ?? { total: 0, byStatus: {} };
897
+ return { ...p, taskCount: agg.total, tasksByStatus: agg.byStatus };
898
+ });
899
+ }
900
+ /**
901
+ * Three-level aggregation for one project: project -> tasks -> trace.
902
+ *
903
+ * Trace counts are read from the six trace tables that carry a `project`
904
+ * column, plus timeline notes. Nothing here is inferred by key-prefix
905
+ * guessing: a record counts toward a project only if it says so.
906
+ */
907
+ projectReport(key) {
908
+ const project = this.getProject(key);
909
+ if (!project) {
910
+ return undefined;
911
+ }
912
+ return this.readSnapshot(() => {
913
+ const one = (sql, ...params) => this.db.prepare(sql).get(...params)?.n ?? 0;
914
+ const tasks = this.listTasks(undefined, { project: key });
915
+ const byStatus = {};
916
+ for (const t of tasks) {
917
+ byStatus[t.status] = (byStatus[t.status] ?? 0) + 1;
918
+ }
919
+ const traceTable = (table) => one(`SELECT COUNT(*) AS n FROM ${table} WHERE project = ?`, key);
920
+ // Per-task trace counts (the third level of the drilldown). The three
921
+ // non-timeline tables are linked by task_key alone, so they stay grouped
922
+ // (3 queries). The TIMELINE count uses BOTH exact links a row may carry
923
+ // -- task_key OR ref_id = the task's UUID -- because the bridge stamps
924
+ // ref_id but not task_key, so counting task_key alone undercounts most
925
+ // cards. Either way it is an exact match, never key-prefix guessing.
926
+ const byTaskKey = (table) => {
927
+ const rows = this.db
928
+ .prepare(`SELECT task_key AS k, COUNT(*) AS n FROM ${table} WHERE project = ? AND task_key IS NOT NULL GROUP BY task_key`)
929
+ .all(key);
930
+ return new Map(rows.map((r) => [r.k, r.n]));
931
+ };
932
+ const riskByTask = byTaskKey("risks");
933
+ const evByTask = byTaskKey("evidence");
934
+ const sessByTask = byTaskKey("sessions");
935
+ const tlByTask = new Map(tasks.map((t) => [
936
+ t.key,
937
+ one("SELECT COUNT(*) AS n FROM timeline WHERE (ref_table = 'tasks' AND ref_id = ?) OR task_key = ?", t.id, t.key),
938
+ ]));
939
+ const cards = tasks.map((t) => {
940
+ const card = this.taskCard(t.key);
941
+ if (!card)
942
+ return undefined;
943
+ return {
944
+ ...card,
945
+ trace: {
946
+ timeline: tlByTask.get(t.key) ?? 0,
947
+ risks: riskByTask.get(t.key) ?? 0,
948
+ evidence: evByTask.get(t.key) ?? 0,
949
+ sessions: sessByTask.get(t.key) ?? 0,
950
+ },
951
+ };
952
+ }).filter((c) => c !== undefined);
953
+ return {
954
+ project,
955
+ tasks: { total: tasks.length, byStatus, cards },
956
+ trace: {
957
+ messages: traceTable("messages"),
958
+ decisions: traceTable("decisions"),
959
+ risks: traceTable("risks"),
960
+ handoffs: traceTable("handoffs"),
961
+ evidence: traceTable("evidence"),
962
+ filesChanged: traceTable("files_changed"),
963
+ notes: one("SELECT COUNT(*) AS n FROM timeline WHERE project = ? AND kind = 'note'", key),
964
+ },
965
+ timeline: {
966
+ total: one("SELECT COUNT(*) AS n FROM timeline WHERE project = ?", key),
967
+ firstSeq: one("SELECT MIN(seq) AS n FROM timeline WHERE project = ?", key) || null,
968
+ lastSeq: one("SELECT MAX(seq) AS n FROM timeline WHERE project = ?", key) || null,
969
+ },
970
+ };
971
+ });
972
+ }
973
+ /**
974
+ * The trace entries attributable to ONE task, newest first -- the fourth level
975
+ * of the drilldown (task -> trace).
976
+ *
977
+ * A timeline row belongs to the task when it names it EXACTLY, by either of
978
+ * the two links the board actually uses:
979
+ * - task_key = the task's key (notes / evidence scoped with --task), or
980
+ * - ref_table = 'tasks' AND ref_id = the task's UUID (the claim / progress /
981
+ * complete events written by the bridge, plus defineTask itself).
982
+ * Both are exact matches -- nothing is inferred by key-prefix guessing.
983
+ */
984
+ taskTrace(ref, limit = 50) {
985
+ const t = this.resolveTask(String(ref));
986
+ if (!t) {
987
+ return undefined;
988
+ }
989
+ const where = "(ref_table = 'tasks' AND ref_id = ?) OR task_key = ?";
990
+ const total = this.db
991
+ .prepare(`SELECT COUNT(*) AS n FROM timeline WHERE ${where}`)
992
+ .get(t.id, t.key).n;
993
+ const rows = this.db
994
+ .prepare(`SELECT * FROM timeline WHERE ${where} ORDER BY seq DESC LIMIT ?`)
995
+ .all(t.id, t.key, limit);
996
+ return {
997
+ taskKey: t.key,
998
+ taskNumber: t.number,
999
+ total,
1000
+ entries: this.applyRedactions(rows.map(rowToTimeline)),
1001
+ };
1002
+ }
1003
+ // --- tasks (kanban) --------------------------------------------------------
1004
+ nextTaskNumber() {
1005
+ const row = this.db
1006
+ .prepare("SELECT COALESCE(MAX(number), 0) + 1 AS n FROM tasks")
1007
+ .get();
1008
+ return row.n;
1009
+ }
1010
+ getTask(key) {
1011
+ const row = this.db.prepare("SELECT * FROM tasks WHERE key = ?").get(key);
1012
+ return row ? rowToTask(row) : undefined;
1013
+ }
1014
+ /** Resolve a task by key OR by its human number (`"145"` / `"#145"`). */
1015
+ resolveTask(ref) {
1016
+ const m = /^#?(\d+)$/.exec(ref.trim());
1017
+ if (m) {
1018
+ const row = this.db
1019
+ .prepare("SELECT * FROM tasks WHERE number = ?")
1020
+ .get(Number(m[1]));
1021
+ if (row)
1022
+ return rowToTask(row);
1023
+ }
1024
+ return this.getTask(ref);
1025
+ }
1026
+ /**
1027
+ * Create or update a task's kanban fields (title, description, project,
1028
+ * impact/blast-radius, risk level). Creates the task (with a fresh number) if
1029
+ * the key is new; otherwise updates only the provided fields.
1030
+ *
1031
+ * Stream is CONTROLLED: if the target project has declared a non-empty
1032
+ * vocabulary (`projects.streams`), a supplied stream outside it is REJECTED
1033
+ * (fail-closed). Projects with no declared vocabulary accept any stream, so
1034
+ * legacy boards are unaffected.
1035
+ */
1036
+ defineTask(actor, key, opts = {}) {
1037
+ const tx = this.db.transaction(() => {
1038
+ this.ensureAgent(actor);
1039
+ const at = now();
1040
+ const existing = this.getTask(key);
1041
+ // --- project-existence guard (fail-closed, step8) ---------------------
1042
+ // `tasks.project` MUST reference an existing `projects.key` — it is the
1043
+ // one field whose value is validated (design §1.5 chose the `projects`
1044
+ // table exactly for "校验引用 + 不会继续漂移"). Two real orphans slipped
1045
+ // through this method before any check: #116 `agent-evals` (typo of the
1046
+ // GitHub repo name) and #162 `zz-nonexistent-proj-20261018` (a negative-
1047
+ // test probe whose own description recorded "接受且只 warn 不拒"). A
1048
+ // non-null project that does not exist is now rejected on BOTH the
1049
+ // create and re-point paths; NULL/omitted stays accepted (a fresh task
1050
+ // without a project still asks the human first — hard-constraint #3).
1051
+ const suppliedProject = opts.project == null ? null : String(opts.project).trim();
1052
+ if (suppliedProject && !this.projectExists(suppliedProject)) {
1053
+ const known = this.listProjects().map((p) => p.key).sort();
1054
+ throw new Error(`defineTask: project "${suppliedProject}" does not exist. Known projects: [${known.join(", ")}]. Create it first with \`project add ${suppliedProject}\`.`);
1055
+ }
1056
+ // --- stream controlled-vocabulary guard (fail-closed) ----------------
1057
+ // Only fires when a stream is being SUPPLIED and the target project has
1058
+ // DECLARED a non-empty vocabulary. Unknown projects and vocabulary-less
1059
+ // projects accept anything, so this stays purely additive.
1060
+ const suppliedStream = opts.stream == null ? null : String(opts.stream).trim();
1061
+ if (suppliedStream) {
1062
+ const projKey = opts.project ?? existing?.project ?? null;
1063
+ const allowed = projKey ? this.getProject(projKey)?.streams ?? [] : [];
1064
+ if (allowed.length > 0 && !allowed.includes(suppliedStream)) {
1065
+ throw new Error(`defineTask: stream "${suppliedStream}" is not in project "${projKey}"'s vocabulary [${allowed.join(", ")}]. Declare it first with \`project add ${projKey} --streams "..."\`.`);
1066
+ }
1067
+ }
1068
+ if (!existing) {
1069
+ this.db
1070
+ .prepare(`INSERT INTO tasks (id, key, number, title, description, status, project, stream, impact, risk_level, acceptance, created_by, created_at, updated_at)
1071
+ VALUES (?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?, ?, ?, ?)`)
1072
+ .run(id(), key, this.nextTaskNumber(), opts.title ?? null, opts.description ?? null, opts.project ?? null, opts.stream ?? null, opts.impact ?? null, opts.riskLevel ?? null, acceptanceToStorage(opts.acceptance), actor, at, at);
1073
+ }
1074
+ else {
1075
+ this.db
1076
+ .prepare(`UPDATE tasks SET title = COALESCE(?, title), description = COALESCE(?, description),
1077
+ project = COALESCE(?, project), stream = COALESCE(?, stream), impact = COALESCE(?, impact),
1078
+ risk_level = COALESCE(?, risk_level), acceptance = COALESCE(?, acceptance), updated_at = ? WHERE key = ?`)
1079
+ .run(opts.title ?? null, opts.description ?? null, opts.project ?? null, opts.stream ?? null, opts.impact ?? null, opts.riskLevel ?? null, acceptanceToStorage(opts.acceptance), at, key);
1080
+ }
1081
+ const task = this.getTask(key);
1082
+ this.append(actor, "task", `defined task #${task.number} "${key}"`, "tasks", task.id, {
1083
+ key,
1084
+ ...(task.acceptance ? { acceptance: task.acceptance } : {}),
1085
+ }, { project: task.project ?? null, taskKey: task.key });
1086
+ return task;
1087
+ });
1088
+ return tx.immediate();
1089
+ }
1090
+ /**
1091
+ * Assign a task to an agent and notify them — records the assignee AND drops a
1092
+ * message in that agent's inbox ("please look at task #145 …"). This is the
1093
+ * passive form of "notify Claude to look at 145": the board records the ask;
1094
+ * the agent reads its inbox and decides to act. The board never launches it.
1095
+ */
1096
+ assign(actor, key, toAgent) {
1097
+ const tx = this.db.transaction(() => {
1098
+ this.ensureAgent(actor);
1099
+ this.ensureAgent(toAgent);
1100
+ const task = this.getTask(key);
1101
+ if (!task) {
1102
+ return undefined;
1103
+ }
1104
+ const at = now();
1105
+ this.db
1106
+ .prepare("INSERT OR IGNORE INTO task_assignees (task_key, agent, assigned_by, assigned_at) VALUES (?, ?, ?, ?)")
1107
+ .run(key, toAgent, actor, at);
1108
+ // The notification: a message in the assignee's inbox.
1109
+ const label = `task #${task.number}${task.title ? ` "${task.title}"` : ` (${key})`}`;
1110
+ const where = task.project ? ` · project ${task.project}` : "";
1111
+ const risk = task.riskLevel ? ` · risk ${task.riskLevel}` : "";
1112
+ this.message(actor, toAgent, `please look at ${label}${where}${risk}`);
1113
+ this.append(actor, "assign", `assigned ${label} → ${toAgent}`, "tasks", task.id, {
1114
+ key,
1115
+ to: toAgent,
1116
+ });
1117
+ return this.getTask(key);
1118
+ });
1119
+ return tx.immediate();
1120
+ }
1121
+ /** Report progress (0–100). Moves status to in-progress, or done at 100. */
1122
+ setProgress(actor, key, progress) {
1123
+ const tx = this.db.transaction(() => {
1124
+ this.ensureAgent(actor);
1125
+ const task = this.getTask(key);
1126
+ if (!task) {
1127
+ return undefined;
1128
+ }
1129
+ const p = Math.max(0, Math.min(100, Math.round(progress)));
1130
+ const status = p >= 100
1131
+ ? "done"
1132
+ : p > 0 && (task.status === "open" || task.status === "claimed")
1133
+ ? "in-progress"
1134
+ : task.status;
1135
+ this.db
1136
+ .prepare("UPDATE tasks SET progress = ?, status = ?, updated_at = ? WHERE key = ?")
1137
+ .run(p, status, now(), key);
1138
+ this.append(actor, "progress", `task #${task.number} "${key}" → ${p}%`, "tasks", task.id, { key, progress: p }, { project: task.project ?? null, taskKey: task.key });
1139
+ return this.getTask(key);
1140
+ });
1141
+ return tx.immediate();
1142
+ }
1143
+ /** Set a task's status directly (e.g. blocked). */
1144
+ setTaskStatus(actor, key, status) {
1145
+ const tx = this.db.transaction(() => {
1146
+ this.ensureAgent(actor);
1147
+ const task = this.getTask(key);
1148
+ if (!task) {
1149
+ return undefined;
1150
+ }
1151
+ // setProgress(100) already implies "done"; the reverse was never true, so a
1152
+ // card could read `status: done` with `progress: 5` and every reader had to
1153
+ // guess which field to trust (dsh, 2026-09-26 on task #33). Only `done`
1154
+ // stamps — cancelled/failed keep whatever progress they died at.
1155
+ const stamp = status === "done" && (task.progress ?? 0) < 100;
1156
+ if (stamp) {
1157
+ this.db
1158
+ .prepare("UPDATE tasks SET status = ?, progress = 100, updated_at = ? WHERE key = ?")
1159
+ .run(status, now(), key);
1160
+ }
1161
+ else {
1162
+ this.db
1163
+ .prepare("UPDATE tasks SET status = ?, updated_at = ? WHERE key = ?")
1164
+ .run(status, now(), key);
1165
+ }
1166
+ const extra = stamp ? " (progress → 100)" : "";
1167
+ this.append(actor, "task-status", `task #${task.number} "${key}" → ${status}${extra}`, "tasks", task.id, { key, status, ...(stamp ? { progress: 100 } : {}) }, { project: task.project ?? null, taskKey: task.key });
1168
+ return this.getTask(key);
1169
+ });
1170
+ return tx.immediate();
1171
+ }
1172
+ assigneesFor(key) {
1173
+ return this.db
1174
+ .prepare("SELECT agent FROM task_assignees WHERE task_key = ? ORDER BY assigned_at ASC")
1175
+ .all(key).map((r) => r.agent);
1176
+ }
1177
+ risksForTask(key) {
1178
+ return this.db
1179
+ .prepare("SELECT * FROM risks WHERE task_key = ? ORDER BY created_at DESC")
1180
+ .all(key).map(rowToRisk);
1181
+ }
1182
+ /**
1183
+ * How many agents are actively working the task right now: assignees (or the
1184
+ * claimer) that have an active (heartbeating) session.
1185
+ */
1186
+ activeAgentsOnTask(key) {
1187
+ const active = new Set(this.activeSessions().map((s) => s.agentName));
1188
+ const involved = new Set(this.assigneesFor(key));
1189
+ const claimer = this.getTask(key)?.claimedBy;
1190
+ if (claimer)
1191
+ involved.add(claimer);
1192
+ return [...involved].filter((a) => active.has(a)).length;
1193
+ }
1194
+ /** Full kanban card for one task. */
1195
+ taskCard(key) {
1196
+ const task = this.getTask(key);
1197
+ if (!task) {
1198
+ return undefined;
1199
+ }
1200
+ return {
1201
+ task,
1202
+ assignees: this.assigneesFor(key),
1203
+ activeAgents: this.activeAgentsOnTask(key),
1204
+ impactFiles: [...new Set(this.filesForTask(key).map((f) => f.path))],
1205
+ risks: this.risksForTask(key),
1206
+ };
1207
+ }
1208
+ /** Every task as a kanban card, newest-updated first. */
1209
+ listTaskCards(filters = {}) {
1210
+ return this.readSnapshot(() => this.listTasks(undefined, filters)
1211
+ .map((t) => this.taskCard(t.key))
1212
+ .filter((c) => c !== undefined));
1213
+ }
1214
+ /**
1215
+ * Record a verification outcome for a task as a first-class timeline event
1216
+ * (kind "verify"). This is the public write path for the verification layer:
1217
+ * callers (CLI, MCP, the task bridge) record pass/fail plus check evidence,
1218
+ * and the entry lands in the tamper-evident chain like every other write.
1219
+ * `verdict` is fail-closed: anything but "pass"/"fail" throws, so a buggy
1220
+ * caller can never poison the audit trail with an unparseable outcome.
1221
+ */
1222
+ verify(actor, key, verdict, opts = {}) {
1223
+ const v = String(verdict ?? "").toLowerCase();
1224
+ if (v !== "pass" && v !== "fail") {
1225
+ throw new Error(`verify: verdict must be "pass" or "fail" (got ${JSON.stringify(verdict)})`);
1226
+ }
1227
+ const tx = this.db.transaction(() => {
1228
+ this.ensureAgent(actor);
1229
+ const task = this.getTask(key);
1230
+ if (!task) {
1231
+ return undefined;
1232
+ }
1233
+ const level = typeof opts.level === "string" && opts.level.trim() ? opts.level.trim() : "V1";
1234
+ const payload = {
1235
+ key,
1236
+ verdict: v,
1237
+ level,
1238
+ ...(opts.checks !== undefined ? { checks: opts.checks } : {}),
1239
+ ...(opts.evidence !== undefined ? { evidence: opts.evidence } : {}),
1240
+ };
1241
+ const summary = typeof opts.summary === "string" && opts.summary.trim()
1242
+ ? opts.summary.trim()
1243
+ : `verify ${v.toUpperCase()} ${key} (${level})`;
1244
+ return this.append(actor, "verify", summary, "tasks", task.id, payload);
1245
+ });
1246
+ return tx.immediate();
1247
+ }
1248
+ /** Verification events recorded for a task, newest first. */
1249
+ verificationsFor(key) {
1250
+ const task = this.getTask(key);
1251
+ if (!task) {
1252
+ return [];
1253
+ }
1254
+ return this.db
1255
+ .prepare("SELECT * FROM timeline WHERE kind = 'verify' AND ref_id = ? ORDER BY seq DESC")
1256
+ .all(task.id)
1257
+ .map((r) => {
1258
+ let payload = null;
1259
+ try {
1260
+ payload = r.payload ? JSON.parse(r.payload) : null;
1261
+ }
1262
+ catch { /* malformed payload reads back without fields */ }
1263
+ return { seq: r.seq, at: r.at, actor: r.actor, summary: r.summary, ...(payload ?? {}) };
1264
+ });
1265
+ }
1266
+ /** Leave a message for another agent, or broadcast (to = null). */
1267
+ message(actor, to, body, opts = {}) {
1268
+ const tx = this.db.transaction(() => {
1269
+ this.ensureAgent(actor);
1270
+ if (to) {
1271
+ this.ensureAgent(to);
1272
+ }
1273
+ const at = now();
1274
+ const msg = {
1275
+ id: id(),
1276
+ fromAgent: actor,
1277
+ toAgent: to,
1278
+ body,
1279
+ createdAt: at,
1280
+ readAt: null,
1281
+ };
1282
+ this.db
1283
+ .prepare("INSERT INTO messages (id, from_agent, to_agent, body, created_at, read_at, project) VALUES (@id, @fromAgent, @toAgent, @body, @createdAt, @readAt, @project)")
1284
+ .run({ ...msg, project: opts.project ?? null });
1285
+ // Metadata-only summary: the message BODY lives only in messages.body
1286
+ // (which redact() blanks), never in the hashed, append-only timeline — so
1287
+ // redacting a message truly erases its content from all storage. The
1288
+ // timeline still records who messaged whom, and when.
1289
+ const dest = to ? `→ ${to}` : "(broadcast)";
1290
+ this.append(actor, "message", `message ${dest}`, "messages", msg.id, {
1291
+ to,
1292
+ }, { project: opts.project ?? null, taskKey: opts.taskKey ?? null });
1293
+ return msg;
1294
+ });
1295
+ return tx.immediate();
1296
+ }
1297
+ /** Messages addressed to `agent` (or broadcast) that it has not acked yet. */
1298
+ inbox(agent, includeRead = false) {
1299
+ // The filter is the per-agent message_reads ledger, NOT messages.read_at:
1300
+ // read_at is a single global column, so acking one broadcast would hide it
1301
+ // from every other agent on the board. Switching the predicate from
1302
+ // `read_at IS NULL` to the ledger cannot hide anything that used to show,
1303
+ // because read_at was NULL on every row in production (0/26 read).
1304
+ // UNION ALL of two disjoint branches (direct vs broadcast) so each can use
1305
+ // idx_messages_to; a single `to_agent = ? OR to_agent IS NULL` predicate
1306
+ // would force a full table scan.
1307
+ // 2026-10-10: a recipient is now the alias set (recipientSet), so xiaoyu and
1308
+ // workbuddy share one inbox. A direct message is unread only if NONE of the
1309
+ // recipient identities has acked it; the ledger-agent set is the same set.
1310
+ const recips = recipientSet(agent);
1311
+ const ph = recips.map(() => "?").join(", ");
1312
+ const unread = includeRead
1313
+ ? ""
1314
+ : ` AND NOT EXISTS (SELECT 1 FROM message_reads mr
1315
+ WHERE mr.message_id = messages.id AND mr.agent IN (${ph}))`;
1316
+ const sql = `SELECT * FROM messages WHERE to_agent IN (${ph})${unread}
1317
+ UNION ALL SELECT * FROM messages WHERE to_agent IS NULL${unread}
1318
+ ORDER BY created_at DESC`;
1319
+ // Direct branch binds [recips (to_agent)] + [recips (ledger)]; broadcast
1320
+ // branch binds [recips (ledger)]. When includeRead, no ledger predicate.
1321
+ const params = includeRead ? [...recips] : [...recips, ...recips, ...recips];
1322
+ return this.db.prepare(sql).all(...params).map(rowToMessage);
1323
+ }
1324
+ /**
1325
+ * Ack a message on behalf of `agent`. Without an agent it falls back to the
1326
+ * legacy global stamp only — callers that represent a reader should always
1327
+ * pass one, or the ack is invisible to everyone else's inbox.
1328
+ */
1329
+ markRead(messageId, agent = null) {
1330
+ const at = now();
1331
+ let acked = false;
1332
+ const recips = agent ? recipientSet(agent) : [];
1333
+ const tx = this.db.transaction(() => {
1334
+ // Guard: without it an unknown id silently "succeeds" and leaves an
1335
+ // orphan ledger row keyed on a message that never existed.
1336
+ if (!this.db.prepare("SELECT 1 FROM messages WHERE id = ?").get(messageId)) {
1337
+ return;
1338
+ }
1339
+ acked = true;
1340
+ // 2026-10-10: ack every identity in the recipient set, so reading as
1341
+ // xiaoyu also clears workbuddy's copy (and vice-versa). This keeps the
1342
+ // sender's pendingAcks (which checks mr.agent = m.to_agent) correct and
1343
+ // prevents double-processing by another reader of the same merged inbox.
1344
+ for (const a of recips) {
1345
+ this.ensureAgent(a);
1346
+ this.db
1347
+ .prepare(`INSERT OR IGNORE INTO message_reads (message_id, agent, read_at)
1348
+ VALUES (?, ?, ?)`)
1349
+ .run(messageId, a, at);
1350
+ }
1351
+ // Legacy flag: first reader wins, so pre-ledger consumers (status,
1352
+ // allUnread, the dashboard) still see "has anyone opened this".
1353
+ this.db
1354
+ .prepare("UPDATE messages SET read_at = ? WHERE id = ? AND read_at IS NULL")
1355
+ .run(at, messageId);
1356
+ });
1357
+ tx.immediate();
1358
+ return acked;
1359
+ }
1360
+ /** Ack everything currently sitting in `agent`'s unread inbox. Returns the ids. */
1361
+ markInboxRead(agent) {
1362
+ const ids = this.inbox(agent).map((m) => m.id);
1363
+ for (const mid of ids)
1364
+ this.markRead(mid, agent);
1365
+ return ids;
1366
+ }
1367
+ /** Who has acked a message, oldest ack first. */
1368
+ readers(messageId) {
1369
+ return this.db
1370
+ .prepare(`SELECT agent, read_at FROM message_reads WHERE message_id = ?
1371
+ ORDER BY read_at ASC`)
1372
+ .all(messageId);
1373
+ }
1374
+ /**
1375
+ * Messages `agent` dispatched that nobody has opened yet — the sender's half
1376
+ * of the ack loop. Without this, "did they see it?" is unanswerable and every
1377
+ * dispatch is a guess. Broadcasts are excluded: they have no intended reader.
1378
+ */
1379
+ pendingAcks(agent) {
1380
+ return this.db
1381
+ .prepare(`SELECT m.id, m.to_agent AS toAgent, m.created_at AS createdAt,
1382
+ (SELECT COUNT(*) FROM message_reads mr WHERE mr.message_id = m.id) AS acks
1383
+ FROM messages m
1384
+ WHERE m.from_agent = ? AND m.to_agent IS NOT NULL
1385
+ AND NOT EXISTS (SELECT 1 FROM message_reads mr
1386
+ WHERE mr.message_id = m.id AND mr.agent = m.to_agent)
1387
+ ORDER BY m.created_at DESC`)
1388
+ .all(agent);
1389
+ }
1390
+ decision(actor, title, opts = {}) {
1391
+ const tx = this.db.transaction(() => {
1392
+ this.ensureAgent(actor);
1393
+ const dec = {
1394
+ id: id(),
1395
+ agentId: actor,
1396
+ sessionId: this.activeSession,
1397
+ title,
1398
+ rationale: opts.rationale ?? null,
1399
+ evidence: opts.evidence ?? null,
1400
+ relatedCommits: opts.relatedCommits ?? [],
1401
+ relatedTasks: opts.relatedTasks ?? [],
1402
+ createdAt: now(),
1403
+ };
1404
+ this.db
1405
+ .prepare(`INSERT INTO decisions (id, agent_id, session_id, title, rationale, evidence, related_commits, related_tasks, created_at, project)
1406
+ VALUES (@id, @agentId, @sessionId, @title, @rationale, @evidence, @relatedCommits, @relatedTasks, @createdAt, @project)`)
1407
+ .run({
1408
+ ...dec,
1409
+ relatedCommits: JSON.stringify(dec.relatedCommits),
1410
+ relatedTasks: JSON.stringify(dec.relatedTasks),
1411
+ project: opts.project ?? null,
1412
+ });
1413
+ // The free-text rationale lives only in decisions.rationale (redactable);
1414
+ // the timeline keeps the (short) title + related commits, not the rationale.
1415
+ this.append(actor, "decision", `decided: ${title}`, "decisions", dec.id, {
1416
+ relatedCommits: dec.relatedCommits,
1417
+ }, { project: opts.project ?? null, taskKey: opts.taskKey ?? null });
1418
+ return dec;
1419
+ });
1420
+ return tx.immediate();
1421
+ }
1422
+ decisionsForCommit(commitSha) {
1423
+ // A stored related-commit `c` matches when it is a prefix of the query sha
1424
+ // (or vice-versa), but only if it is at least a git short-sha (7 chars) —
1425
+ // this rejects false positives from empty strings (which prefix-match every
1426
+ // commit) and 1–2 char typos. Non-string elements are coerced defensively.
1427
+ const matches = (c, sha) => {
1428
+ const s = String(c);
1429
+ if (s.length < 7) {
1430
+ return s.length === sha.length && s === sha; // only an exact full match
1431
+ }
1432
+ return s.startsWith(sha) || sha.startsWith(s);
1433
+ };
1434
+ return this.db
1435
+ .prepare("SELECT * FROM decisions ORDER BY created_at DESC")
1436
+ .all()
1437
+ .map(rowToDecision)
1438
+ .filter((d) => d.relatedCommits.some((c) => matches(c, commitSha)));
1439
+ }
1440
+ evidence(actor, ref, note = null, target = null, project = null, opts = {}) {
1441
+ // Content-address the evidence when it is a readable local file, so the
1442
+ // referenced content is integrity-protected: a later swap/edit of the file
1443
+ // is detectable via verifyEvidence(). URLs / non-files store sha256 = null.
1444
+ //
1445
+ // Beyond the original shape this doubles as the project "sedimentation
1446
+ // register": `opts.taskKey` scopes the entry to a task, `opts.kind` tags it
1447
+ // (see EVIDENCE_KINDS). Old 5-arg callers keep byte-identical behaviour.
1448
+ const taskKey = opts.taskKey ?? null;
1449
+ const kind = opts.kind ?? null;
1450
+ if (kind !== null && !EVIDENCE_KINDS.includes(kind)) {
1451
+ throw new Error(`kind must be one of ${EVIDENCE_KINDS.join(" | ")}`);
1452
+ }
1453
+ const sha256 = Board.hashFileIfLocal(ref);
1454
+ const tx = this.db.transaction(() => {
1455
+ this.ensureAgent(actor);
1456
+ // Write gate: a project-scoped register entry requires membership, unless
1457
+ // the entry carries a taskKey (being assigned a task is itself admission).
1458
+ // Membership is judged BEFORE this write lands, so a caller cannot
1459
+ // self-authorise by writing a project note first.
1460
+ if (project && !taskKey && !this.isProjectMember(actor, project)) {
1461
+ this.append(actor, "note", `evidence not registered: ${actor} is not a member of "${project}"`, null, null, null, { project });
1462
+ return { skipped: "not-a-member", project, ref };
1463
+ }
1464
+ const ev = {
1465
+ id: id(),
1466
+ agentId: actor,
1467
+ ref,
1468
+ note,
1469
+ target,
1470
+ sha256,
1471
+ createdAt: now(),
1472
+ };
1473
+ this.db
1474
+ .prepare("INSERT INTO evidence (id, agent_id, ref, note, target, sha256, created_at, project, task_key, kind) VALUES (@id, @agentId, @ref, @note, @target, @sha256, @createdAt, @project, @taskKey, @kind)")
1475
+ .run({ ...ev, project, taskKey, kind });
1476
+ this.append(actor, "evidence", `evidence: ${ref}${sha256 ? ` (sha256 ${sha256.slice(0, 12)})` : ""}`, "evidence", ev.id, { target, sha256, ...(kind ? { kind } : {}) }, { project, taskKey });
1477
+ return ev;
1478
+ });
1479
+ return tx.immediate();
1480
+ }
1481
+ /** SHA-256 of a local file's content, or null if `ref` is not a readable file. */
1482
+ static hashFileIfLocal(ref) {
1483
+ try {
1484
+ if (!existsSync(ref) || !statSync(ref).isFile()) {
1485
+ return null;
1486
+ }
1487
+ return createHash("sha256").update(readFileSync(ref)).digest("hex");
1488
+ }
1489
+ catch {
1490
+ return null;
1491
+ }
1492
+ }
1493
+ /**
1494
+ * Re-check every content-hashed evidence file against its attach-time hash.
1495
+ * `ok` = unchanged, `changed` = content differs (tampered/edited), `missing`
1496
+ * = the file is gone, `unhashed` = a URL / non-file (never hashed).
1497
+ */
1498
+ verifyEvidence() {
1499
+ const rows = this.db
1500
+ .prepare("SELECT id, ref, sha256 FROM evidence ORDER BY created_at ASC")
1501
+ .all();
1502
+ return rows.map(({ id, ref, sha256 }) => {
1503
+ let status;
1504
+ if (sha256 === null) {
1505
+ status = "unhashed";
1506
+ }
1507
+ else if (!existsSync(ref) || !statSync(ref).isFile()) {
1508
+ status = "missing";
1509
+ }
1510
+ else {
1511
+ const now256 = createHash("sha256")
1512
+ .update(readFileSync(ref))
1513
+ .digest("hex");
1514
+ status = now256 === sha256 ? "ok" : "changed";
1515
+ }
1516
+ return { id, ref, status };
1517
+ });
1518
+ }
1519
+ fileChanged(actor, path, change, taskKey = null, project = null) {
1520
+ const tx = this.db.transaction(() => {
1521
+ this.ensureAgent(actor);
1522
+ const fc = {
1523
+ id: id(),
1524
+ agentId: actor,
1525
+ sessionId: this.activeSession,
1526
+ path,
1527
+ change,
1528
+ taskKey,
1529
+ createdAt: now(),
1530
+ };
1531
+ this.db
1532
+ .prepare("INSERT INTO files_changed (id, agent_id, session_id, path, change, task_key, created_at, project) VALUES (@id, @agentId, @sessionId, @path, @change, @taskKey, @createdAt, @project)")
1533
+ .run({ ...fc, project });
1534
+ this.append(actor, "file", `${change}: ${path}`, "files_changed", fc.id, {
1535
+ taskKey,
1536
+ }, { project, taskKey });
1537
+ return fc;
1538
+ });
1539
+ return tx.immediate();
1540
+ }
1541
+ /** Files another agent reports touching for a task — conflict awareness. */
1542
+ filesForTask(taskKey) {
1543
+ return this.db
1544
+ .prepare("SELECT * FROM files_changed WHERE task_key = ? ORDER BY created_at DESC")
1545
+ .all(taskKey).map(rowToFileChange);
1546
+ }
1547
+ risk(actor, title, severity = "medium", taskKey = null, project = null) {
1548
+ const tx = this.db.transaction(() => {
1549
+ this.ensureAgent(actor);
1550
+ const r = {
1551
+ id: id(),
1552
+ agentId: actor,
1553
+ title,
1554
+ severity,
1555
+ status: "open",
1556
+ taskKey,
1557
+ createdAt: now(),
1558
+ resolvedAt: null,
1559
+ resolvedBy: null,
1560
+ };
1561
+ this.db
1562
+ .prepare("INSERT INTO risks (id, agent_id, title, severity, status, task_key, created_at, project) VALUES (@id, @agentId, @title, @severity, @status, @taskKey, @createdAt, @project)")
1563
+ .run({ ...r, project });
1564
+ const on = taskKey ? ` (task ${taskKey})` : "";
1565
+ this.append(actor, "risk", `risk [${severity}]: ${title}${on}`, "risks", r.id, null, {
1566
+ project,
1567
+ taskKey,
1568
+ });
1569
+ return r;
1570
+ });
1571
+ return tx.immediate();
1572
+ }
1573
+ listRisks(status = "open") {
1574
+ const rows = status
1575
+ ? this.db
1576
+ .prepare("SELECT * FROM risks WHERE status = ? ORDER BY created_at DESC")
1577
+ .all(status)
1578
+ : this.db
1579
+ .prepare("SELECT * FROM risks ORDER BY created_at DESC")
1580
+ .all();
1581
+ return rows.map(rowToRisk);
1582
+ }
1583
+ /**
1584
+ * Look one risk up by full id, unique id prefix (uuids are hex, prefixes are
1585
+ * how agents quote them on the board), or the exact title. Returns undefined
1586
+ * when nothing matches; throws on an ambiguous prefix so a typo cannot close
1587
+ * the wrong card.
1588
+ */
1589
+ getRisk(ref) {
1590
+ const key = String(ref ?? "").trim();
1591
+ if (!key) {
1592
+ return undefined;
1593
+ }
1594
+ const exact = this.db.prepare("SELECT * FROM risks WHERE id = ?").get(key);
1595
+ if (exact) {
1596
+ return rowToRisk(exact);
1597
+ }
1598
+ const byTitle = this.db
1599
+ .prepare("SELECT * FROM risks WHERE title = ? ORDER BY created_at DESC LIMIT 2")
1600
+ .all(key);
1601
+ if (byTitle.length > 1) {
1602
+ throw new Error(`ambiguous risk title "${key}" — ${byTitle.length} cards share it, quote the id`);
1603
+ }
1604
+ if (byTitle.length === 1) {
1605
+ return rowToRisk(byTitle[0]);
1606
+ }
1607
+ // Prefix lookup only for things that can actually be an id prefix: a title
1608
+ // containing % or _ would otherwise be read as LIKE wildcards and could
1609
+ // settle the wrong card.
1610
+ if (!/^[0-9a-f][0-9a-f-]{3,}$/i.test(key)) {
1611
+ return undefined;
1612
+ }
1613
+ const byPrefix = this.db
1614
+ .prepare("SELECT * FROM risks WHERE id LIKE ? ORDER BY created_at DESC")
1615
+ .all(`${key}%`);
1616
+ if (byPrefix.length > 1) {
1617
+ throw new Error(`ambiguous risk id prefix "${key}" — matches ${byPrefix.length} risks, quote more characters`);
1618
+ }
1619
+ return byPrefix.length === 1 ? rowToRisk(byPrefix[0]) : undefined;
1620
+ }
1621
+ /**
1622
+ * Close the loop on a risk card: move it out of `open` (or back into it).
1623
+ * `status` is the upstream RiskStatus vocabulary — "open" | "mitigated" |
1624
+ * "closed". Settling stamps resolved_at/resolved_by; reopening clears them.
1625
+ * The `note` (how/why it was settled) goes into the append-only timeline.
1626
+ */
1627
+ resolveRisk(actor, ref, status = "closed", note = null) {
1628
+ const allowed = ["open", "mitigated", "closed"];
1629
+ if (!allowed.includes(status)) {
1630
+ throw new Error(`invalid risk status "${status}" — use: ${allowed.join(" | ")}`);
1631
+ }
1632
+ const tx = this.db.transaction(() => {
1633
+ this.ensureAgent(actor);
1634
+ const existing = this.getRisk(ref);
1635
+ if (!existing) {
1636
+ return undefined;
1637
+ }
1638
+ const at = now();
1639
+ const settled = status !== "open";
1640
+ this.db
1641
+ .prepare("UPDATE risks SET status = ?, resolved_at = ?, resolved_by = ? WHERE id = ?")
1642
+ .run(status, settled ? at : null, settled ? actor : null, existing.id);
1643
+ const why = note ? ` — ${note}` : "";
1644
+ this.append(actor, "risk-resolve", `risk "${existing.title}" → ${status}${why}`, "risks", existing.id, {
1645
+ id: existing.id,
1646
+ status,
1647
+ note: note ?? null,
1648
+ previousStatus: existing.status,
1649
+ });
1650
+ return this.getRisk(existing.id);
1651
+ });
1652
+ return tx.immediate();
1653
+ }
1654
+ handoff(actor, to, summary, opts = {}) {
1655
+ const tx = this.db.transaction(() => {
1656
+ this.ensureAgent(actor);
1657
+ this.ensureAgent(to);
1658
+ const h = {
1659
+ id: id(),
1660
+ fromAgent: actor,
1661
+ toAgent: to,
1662
+ fromSession: this.activeSession,
1663
+ toSession: null,
1664
+ summary,
1665
+ context: opts.context ?? null,
1666
+ relatedFiles: opts.relatedFiles ?? [],
1667
+ openQuestions: opts.openQuestions ?? [],
1668
+ taskKey: opts.taskKey ?? null,
1669
+ createdAt: now(),
1670
+ acceptedAt: null,
1671
+ };
1672
+ this.db
1673
+ .prepare(`INSERT INTO handoffs (id, from_agent, to_agent, from_session, to_session, summary, context, related_files, open_questions, task_key, created_at, accepted_at, project)
1674
+ VALUES (@id, @fromAgent, @toAgent, @fromSession, @toSession, @summary, @context, @relatedFiles, @openQuestions, @taskKey, @createdAt, @acceptedAt, @project)`)
1675
+ .run({
1676
+ ...h,
1677
+ relatedFiles: JSON.stringify(h.relatedFiles),
1678
+ openQuestions: JSON.stringify(h.openQuestions),
1679
+ project: opts.project ?? null,
1680
+ });
1681
+ this.append(actor, "handoff", `handoff → ${to}: ${summary}`, "handoffs", h.id, {
1682
+ taskKey: h.taskKey,
1683
+ openQuestions: h.openQuestions,
1684
+ }, { project: opts.project ?? null, taskKey: h.taskKey });
1685
+ return h;
1686
+ });
1687
+ return tx.immediate();
1688
+ }
1689
+ // --- attribution -----------------------------------------------------------
1690
+ /** Resolve the AI identity (agent + provider/model/cli) for a session. */
1691
+ identityForSession(sessionId) {
1692
+ if (sessionId) {
1693
+ const s = this.getSession(sessionId);
1694
+ if (s) {
1695
+ const a = this.getAgent(s.agentName);
1696
+ return {
1697
+ actor: s.agentName,
1698
+ provider: a?.provider ?? null,
1699
+ model: a?.model ?? null,
1700
+ cli: a?.cli ?? null,
1701
+ sessionId,
1702
+ };
1703
+ }
1704
+ }
1705
+ return {
1706
+ actor: this.config.agent,
1707
+ provider: this.config.identity.provider,
1708
+ model: this.config.identity.model,
1709
+ cli: this.config.identity.cli,
1710
+ sessionId: this.activeSession,
1711
+ };
1712
+ }
1713
+ /** Record a single attribution — who actually produced a change. */
1714
+ attribute(commit, opts = {}) {
1715
+ const sha = git.resolveRev(commit) ?? commit;
1716
+ const actorType = opts.actorType ?? "ai";
1717
+ const ident = actorType === "ai"
1718
+ ? this.identityForSession(opts.sessionId ?? this.activeSession)
1719
+ : {
1720
+ actor: this.config.agent,
1721
+ provider: null,
1722
+ model: null,
1723
+ cli: null,
1724
+ sessionId: opts.sessionId ?? null,
1725
+ };
1726
+ const attr = {
1727
+ id: id(),
1728
+ commit: sha,
1729
+ file: opts.file ?? null,
1730
+ hunk: opts.hunk ?? null,
1731
+ actorType,
1732
+ actor: opts.actor ?? ident.actor,
1733
+ provider: opts.provider ?? ident.provider,
1734
+ model: opts.model ?? ident.model,
1735
+ cli: opts.cli ?? ident.cli,
1736
+ sessionId: opts.sessionId ?? ident.sessionId,
1737
+ createdAt: now(),
1738
+ };
1739
+ const tx = this.db.transaction(() => {
1740
+ this.insertAttribution(attr);
1741
+ const where = attr.file ? ` ${attr.file}` : "";
1742
+ this.append(attr.actor, "attribution", `${attr.actorType} produced ${sha.slice(0, 8)}${where}`, "attributions", attr.id, {
1743
+ commit: sha,
1744
+ file: attr.file,
1745
+ });
1746
+ });
1747
+ tx.immediate();
1748
+ return attr;
1749
+ }
1750
+ insertAttribution(attr) {
1751
+ this.db
1752
+ .prepare(`INSERT INTO attributions (id, commit_sha, file, hunk, actor_type, actor, provider, model, cli, session_id, created_at)
1753
+ VALUES (@id, @commit, @file, @hunk, @actorType, @actor, @provider, @model, @cli, @sessionId, @createdAt)`)
1754
+ .run(attr);
1755
+ }
1756
+ /**
1757
+ * Associate a Git commit with the work that produced it. Resolves the rev to
1758
+ * a full sha, reads the files it touched from Git, and records one AI
1759
+ * attribution per file for the given (or active) session. Optionally writes
1760
+ * an additive `git notes` entry — Git history is never rewritten.
1761
+ */
1762
+ link(rev, opts = {}) {
1763
+ const sha = git.resolveRev(rev);
1764
+ if (!sha) {
1765
+ return undefined;
1766
+ }
1767
+ // Never attribute the board's own storage.
1768
+ const files = git
1769
+ .filesInCommit(sha)
1770
+ .filter((f) => !f.startsWith(".octoboard/"));
1771
+ const actorType = opts.actorType ?? "ai";
1772
+ const ident = actorType === "ai"
1773
+ ? this.identityForSession(opts.sessionId ?? this.activeSession)
1774
+ : {
1775
+ actor: opts.actor ?? this.config.agent,
1776
+ provider: null,
1777
+ model: null,
1778
+ cli: null,
1779
+ sessionId: opts.sessionId ?? null,
1780
+ };
1781
+ const targets = files.length > 0 ? files : [null];
1782
+ const tx = this.db.transaction(() => {
1783
+ for (const file of targets) {
1784
+ this.insertAttribution({
1785
+ id: id(),
1786
+ commit: sha,
1787
+ file,
1788
+ hunk: null,
1789
+ actorType,
1790
+ actor: opts.actor ?? ident.actor,
1791
+ provider: ident.provider,
1792
+ model: ident.model,
1793
+ cli: ident.cli,
1794
+ sessionId: ident.sessionId,
1795
+ createdAt: now(),
1796
+ });
1797
+ }
1798
+ // A link event spans N attribution rows, so it references the commit
1799
+ // itself (ref_table "commit"), not any single attribution row id.
1800
+ this.append(opts.actor ?? ident.actor, "link", `linked ${sha.slice(0, 8)} → ${actorType} ${opts.actor ?? ident.actor} (${targets.length} file${targets.length === 1 ? "" : "s"})`, "commit", sha, { sha, files });
1801
+ });
1802
+ tx.immediate();
1803
+ if (opts.writeNote) {
1804
+ const label = `${ident.cli ?? ident.actor}${ident.model ? ` (${ident.model})` : ""}`;
1805
+ git.writeNote(sha, `blackboard: produced by ${label}, session ${ident.sessionId ?? "n/a"}`);
1806
+ }
1807
+ return { sha, files, count: targets.length };
1808
+ }
1809
+ attributionsForCommit(commitSha) {
1810
+ return this.db
1811
+ .prepare("SELECT * FROM attributions WHERE commit_sha = ? ORDER BY created_at ASC")
1812
+ .all(commitSha).map(rowToAttribution);
1813
+ }
1814
+ attributionsForFile(file) {
1815
+ return this.db
1816
+ .prepare("SELECT * FROM attributions WHERE file = ? ORDER BY created_at DESC")
1817
+ .all(file).map(rowToAttribution);
1818
+ }
1819
+ /**
1820
+ * Attributions on a commit that concern a specific file — the rows whose
1821
+ * `file` matches (or is null, i.e. whole-commit). Falls back to all of the
1822
+ * commit's attributions if none name the file. Used by `blame`, so tracing a
1823
+ * line doesn't surface attributions for the commit's other files.
1824
+ */
1825
+ attributionsForCommitFile(commitSha, file) {
1826
+ const all = this.attributionsForCommit(commitSha);
1827
+ const scoped = all.filter((a) => a.file === file || a.file === null);
1828
+ return scoped.length > 0 ? scoped : all;
1829
+ }
1830
+ // --- reviews ---------------------------------------------------------------
1831
+ /** Record who reviewed a commit and the outcome. */
1832
+ review(commit, opts = {}) {
1833
+ const sha = git.resolveRev(commit) ?? commit;
1834
+ const rev = {
1835
+ id: id(),
1836
+ commit: sha,
1837
+ reviewerType: opts.reviewerType ?? "ai",
1838
+ reviewer: opts.reviewer ?? this.config.agent,
1839
+ sessionId: opts.sessionId ?? this.activeSession,
1840
+ outcome: opts.outcome ?? "approved",
1841
+ note: opts.note ?? null,
1842
+ createdAt: now(),
1843
+ };
1844
+ const tx = this.db.transaction(() => {
1845
+ this.db
1846
+ .prepare(`INSERT INTO reviews (id, commit_sha, reviewer_type, reviewer, session_id, outcome, note, created_at)
1847
+ VALUES (@id, @commit, @reviewerType, @reviewer, @sessionId, @outcome, @note, @createdAt)`)
1848
+ .run(rev);
1849
+ this.append(rev.reviewer, "review", `${rev.reviewerType} review of ${sha.slice(0, 8)}: ${rev.outcome}`, "reviews", rev.id, { commit: sha, outcome: rev.outcome });
1850
+ });
1851
+ tx.immediate();
1852
+ return rev;
1853
+ }
1854
+ reviewsForCommit(commitSha) {
1855
+ return this.db
1856
+ .prepare("SELECT * FROM reviews WHERE commit_sha = ? ORDER BY created_at ASC")
1857
+ .all(commitSha).map(rowToReview);
1858
+ }
1859
+ /** Handoffs left FOR an agent — "what was passed to me", newest first. */
1860
+ handoffsFor(toAgent) {
1861
+ return this.db
1862
+ .prepare("SELECT * FROM handoffs WHERE to_agent = ? ORDER BY created_at DESC")
1863
+ .all(toAgent).map(rowToHandoff);
1864
+ }
1865
+ // --- queries ---------------------------------------------------------------
1866
+ /**
1867
+ * Who touched a file: Git authors, distinct (session, agent) pairs that
1868
+ * recorded a change, and commit attributions. The `agent` is the actor name
1869
+ * recorded on the change; one entry per distinct (session, agent), collapsing
1870
+ * repeated edits within a session to a single row (its latest timestamp).
1871
+ */
1872
+ whoTouched(file) {
1873
+ const rows = this.db
1874
+ .prepare(`SELECT session_id, agent_id, MAX(created_at) AS at FROM files_changed
1875
+ WHERE path = ?
1876
+ GROUP BY session_id, agent_id ORDER BY at DESC`)
1877
+ .all(file);
1878
+ return {
1879
+ gitAuthors: git.fileAuthors(file),
1880
+ attributions: this.attributionsForFile(file),
1881
+ sessions: rows.map((r) => ({
1882
+ sessionId: r.session_id,
1883
+ agent: r.agent_id,
1884
+ at: r.at,
1885
+ })),
1886
+ };
1887
+ }
1888
+ /**
1889
+ * Commits attributed to an actor, CLI, provider, or model (matched broadly
1890
+ * across those columns). Returns the actual matching attribution rows, so the
1891
+ * reported `actor`/`cli` always reflect a row that matched the query — never
1892
+ * an unrelated attribution on the same commit.
1893
+ */
1894
+ commitsByActor(query) {
1895
+ const rows = this.db
1896
+ .prepare(`SELECT DISTINCT commit_sha, actor, cli, created_at FROM attributions
1897
+ WHERE actor = ? OR cli = ? OR provider = ? OR model = ?
1898
+ ORDER BY created_at DESC`)
1899
+ .all(query, query, query, query);
1900
+ // Collapse to one row per (commit, actor, cli); keep the earliest time.
1901
+ const seen = new Map();
1902
+ for (const r of rows) {
1903
+ const key = `${r.commit_sha}\u0000${r.actor}\u0000${r.cli ?? ""}`;
1904
+ const existing = seen.get(key);
1905
+ if (!existing || r.created_at < existing.at) {
1906
+ seen.set(key, {
1907
+ commit: r.commit_sha,
1908
+ actor: r.actor,
1909
+ cli: r.cli,
1910
+ at: r.created_at,
1911
+ });
1912
+ }
1913
+ }
1914
+ return [...seen.values()].sort((x, y) => (x.at < y.at ? 1 : -1));
1915
+ }
1916
+ /**
1917
+ * AI-attributed commits with no APPROVED human review — the accountability
1918
+ * gap. A commit reviewed but rejected/changes-requested is still unreviewed
1919
+ * for this purpose (sign-off was withheld), so it appears here.
1920
+ */
1921
+ unreviewedCommits() {
1922
+ const rows = this.db
1923
+ .prepare(`SELECT a.commit_sha, a.actor, MIN(a.created_at) AS at FROM attributions a
1924
+ WHERE a.actor_type = 'ai'
1925
+ AND NOT EXISTS (
1926
+ SELECT 1 FROM reviews r
1927
+ WHERE r.commit_sha = a.commit_sha AND r.reviewer_type = 'human' AND r.outcome = 'approved'
1928
+ )
1929
+ GROUP BY a.commit_sha ORDER BY at DESC`)
1930
+ .all();
1931
+ return rows.map((r) => ({
1932
+ commit: r.commit_sha,
1933
+ actor: r.actor,
1934
+ at: r.at,
1935
+ }));
1936
+ }
1937
+ /**
1938
+ * Files touched by BOTH agents — joint-modification / collision surface.
1939
+ * Paths are normalized (leading `./` stripped) so a CLI-relative form and
1940
+ * git's repo-root form for the same file reconcile. Case and deeper path
1941
+ * differences are not reconciled.
1942
+ */
1943
+ jointFiles(agentA, agentB) {
1944
+ const norm = (p) => p.replace(/^\.\//, "");
1945
+ const filesOf = (agent) => {
1946
+ const fc = this.db
1947
+ .prepare("SELECT DISTINCT path FROM files_changed WHERE agent_id = ?")
1948
+ .all(agent);
1949
+ const at = this.db
1950
+ .prepare("SELECT DISTINCT file FROM attributions WHERE actor = ? AND file IS NOT NULL")
1951
+ .all(agent);
1952
+ return new Set([
1953
+ ...fc.map((r) => norm(r.path)),
1954
+ ...at.map((r) => norm(r.file)),
1955
+ ]);
1956
+ };
1957
+ const a = filesOf(agentA);
1958
+ const b = filesOf(agentB);
1959
+ return [...a].filter((f) => b.has(f)).sort();
1960
+ }
1961
+ // --- governance (CI gate) --------------------------------------------------
1962
+ distinctAttributedCommits() {
1963
+ return this.db
1964
+ .prepare("SELECT DISTINCT commit_sha FROM attributions")
1965
+ .all().map((r) => r.commit_sha);
1966
+ }
1967
+ hasAttribution(sha) {
1968
+ return (this.db
1969
+ .prepare("SELECT 1 FROM attributions WHERE commit_sha = ? LIMIT 1")
1970
+ .get(sha) !== undefined);
1971
+ }
1972
+ // NB: the "approved human review" and "AI attribution" checks are now
1973
+ // expressed set-based inside report()/unreviewedCommits()/check() rather than
1974
+ // per-commit helpers, to avoid N+1 query loops.
1975
+ /**
1976
+ * Evaluate governance policy over a set of commits — the read-only basis for
1977
+ * a CI gate. The board only reports pass/fail and the specific violations; it
1978
+ * never blocks anything itself (the CI system decides what to do with a
1979
+ * non-zero result). This keeps the blackboard passive while still enabling
1980
+ * "no unreviewed AI work reaches main".
1981
+ */
1982
+ check(opts) {
1983
+ const violations = [];
1984
+ let chain = null;
1985
+ if (opts.verifyChain) {
1986
+ chain = this.verifyChain();
1987
+ if (!chain.ok) {
1988
+ violations.push({
1989
+ kind: "chain-broken",
1990
+ commit: null,
1991
+ detail: `timeline hash chain broken at seq ${chain.brokenAtSeq}`,
1992
+ });
1993
+ }
1994
+ }
1995
+ // Attribution is required only for an explicit commit scope (otherwise the
1996
+ // "all attributed commits" scope trivially satisfies it).
1997
+ if (opts.requireAttribution && opts.commits) {
1998
+ for (const c of opts.commits) {
1999
+ if (!this.hasAttribution(c)) {
2000
+ violations.push({
2001
+ kind: "unattributed",
2002
+ commit: c,
2003
+ detail: "no attribution recorded for this commit",
2004
+ });
2005
+ }
2006
+ }
2007
+ }
2008
+ const scope = opts.commits ?? this.distinctAttributedCommits();
2009
+ if (opts.requireHumanReview) {
2010
+ // Set-based (was an N+1 of hasAiAttribution+hasHumanReview per commit):
2011
+ // unreviewedCommits() is the board-wide set of AI commits lacking an
2012
+ // approved human review; intersect it with the scope.
2013
+ const unreviewed = new Set(this.unreviewedCommits().map((c) => c.commit));
2014
+ for (const c of scope) {
2015
+ if (unreviewed.has(c)) {
2016
+ violations.push({
2017
+ kind: "unreviewed",
2018
+ commit: c,
2019
+ detail: "AI-produced commit has no approved human review",
2020
+ });
2021
+ }
2022
+ }
2023
+ }
2024
+ return {
2025
+ ok: violations.length === 0,
2026
+ violations,
2027
+ chain,
2028
+ checked: scope.length,
2029
+ };
2030
+ }
2031
+ // --- portability (export / import / trailers) ------------------------------
2032
+ allAttributions() {
2033
+ return this.db.prepare("SELECT * FROM attributions").all().map(rowToAttribution);
2034
+ }
2035
+ allReviews() {
2036
+ return this.db.prepare("SELECT * FROM reviews").all().map(rowToReview);
2037
+ }
2038
+ /**
2039
+ * Bundle attribution for a set of commits into a portable, version-stamped
2040
+ * object. This is how local-first attribution survives `git push`: export on
2041
+ * the machine that did the work, import into a team board (or CI) on the
2042
+ * other side. Git carries the code; the bundle carries the accountability.
2043
+ */
2044
+ exportBundle(commits) {
2045
+ const scope = new Set(commits ?? this.distinctAttributedCommits());
2046
+ const attributions = this.allAttributions().filter((a) => scope.has(a.commit));
2047
+ const reviews = this.allReviews().filter((r) => scope.has(r.commit));
2048
+ const sessionIds = new Set([...attributions, ...reviews]
2049
+ .map((x) => x.sessionId)
2050
+ .filter((s) => s !== null));
2051
+ const sessions = [...sessionIds]
2052
+ .map((sid) => this.getSession(sid))
2053
+ .filter((s) => s !== undefined);
2054
+ const decisions = this.db.prepare("SELECT * FROM decisions").all()
2055
+ .map(rowToDecision)
2056
+ .filter((d) => d.relatedCommits.some((c) => scope.has(c)));
2057
+ const bundle = {
2058
+ version: BUNDLE_VERSION,
2059
+ exportedAt: now(),
2060
+ attributions,
2061
+ reviews,
2062
+ sessions,
2063
+ decisions,
2064
+ signature: null,
2065
+ signedBy: null,
2066
+ signedSession: null,
2067
+ };
2068
+ // Sign the bundle with the active session's key so the importer can verify
2069
+ // it came from a holder of that key (origin authenticity), and that it was
2070
+ // not altered in transit (integrity).
2071
+ const sid = this.activeSession;
2072
+ const priv = sid ? this.loadSessionKey(sid) : undefined;
2073
+ const session = sid ? this.getSession(sid) : undefined;
2074
+ if (priv && session?.publicKey) {
2075
+ bundle.signature = signHash(priv, Board.bundleDigest(bundle));
2076
+ bundle.signedBy = session.publicKey;
2077
+ bundle.signedSession = sid;
2078
+ }
2079
+ return bundle;
2080
+ }
2081
+ /** Canonical SHA-256 over a bundle's records (excludes the signature fields). */
2082
+ static bundleDigest(bundle) {
2083
+ const sortById = (rows) => [...rows].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
2084
+ const canonical = JSON.stringify({
2085
+ version: bundle.version,
2086
+ attributions: sortById(bundle.attributions),
2087
+ reviews: sortById(bundle.reviews),
2088
+ sessions: sortById(bundle.sessions),
2089
+ decisions: sortById(bundle.decisions),
2090
+ });
2091
+ return createHash("sha256").update(canonical).digest("hex");
2092
+ }
2093
+ /** Verify a bundle's signature, if any: true/false, or null when unsigned. */
2094
+ static verifyBundle(bundle) {
2095
+ if (!bundle.signature || !bundle.signedBy) {
2096
+ return null;
2097
+ }
2098
+ return verifyHash(bundle.signedBy, Board.bundleDigest(bundle), bundle.signature);
2099
+ }
2100
+ /**
2101
+ * Merge a bundle into this board. Idempotent: rows already present (by id)
2102
+ * are left untouched, so re-importing is safe. One `import` event is appended
2103
+ * to the local timeline; the imported rows keep their original ids/times.
2104
+ */
2105
+ importBundle(bundle, opts = {}) {
2106
+ if (!bundle || bundle.version !== BUNDLE_VERSION) {
2107
+ throw new Error(`unsupported bundle version: ${bundle?.version ?? "(none)"}`);
2108
+ }
2109
+ // Authenticity/integrity: null = unsigned, true = valid, false = tampered.
2110
+ const verified = Board.verifyBundle(bundle);
2111
+ if (opts.requireSigned && verified !== true) {
2112
+ throw new Error(verified === false
2113
+ ? "bundle signature is INVALID (tampered or wrong key)"
2114
+ : "bundle is unsigned and --require-signed was set");
2115
+ }
2116
+ const counts = { attributions: 0, reviews: 0, sessions: 0, decisions: 0 };
2117
+ const tx = this.db.transaction(() => {
2118
+ const insSession = this.db.prepare(`INSERT OR IGNORE INTO sessions (id, agent_name, label, machine, working_directory, git_branch, repository, public_key, last_heartbeat, started_at, finished_at)
2119
+ VALUES (@id, @agentName, @label, @machine, @workingDirectory, @gitBranch, @repository, @publicKey, @lastHeartbeat, @startedAt, @finishedAt)`);
2120
+ for (const s of bundle.sessions ?? []) {
2121
+ // Normalize: an external bundle may predate newer session columns, so
2122
+ // fill any missing field with null before binding.
2123
+ counts.sessions += insSession.run({
2124
+ id: s.id,
2125
+ agentName: s.agentName,
2126
+ label: s.label ?? null,
2127
+ machine: s.machine ?? null,
2128
+ workingDirectory: s.workingDirectory ?? null,
2129
+ gitBranch: s.gitBranch ?? null,
2130
+ repository: s.repository ?? null,
2131
+ publicKey: s.publicKey ?? null,
2132
+ lastHeartbeat: s.lastHeartbeat ?? null,
2133
+ startedAt: s.startedAt,
2134
+ finishedAt: s.finishedAt ?? null,
2135
+ }).changes;
2136
+ }
2137
+ const insAttr = this.db.prepare(`INSERT OR IGNORE INTO attributions (id, commit_sha, file, hunk, actor_type, actor, provider, model, cli, session_id, created_at)
2138
+ VALUES (@id, @commit, @file, @hunk, @actorType, @actor, @provider, @model, @cli, @sessionId, @createdAt)`);
2139
+ for (const a of bundle.attributions ?? []) {
2140
+ counts.attributions += insAttr.run(a).changes;
2141
+ }
2142
+ const insReview = this.db.prepare(`INSERT OR IGNORE INTO reviews (id, commit_sha, reviewer_type, reviewer, session_id, outcome, note, created_at)
2143
+ VALUES (@id, @commit, @reviewerType, @reviewer, @sessionId, @outcome, @note, @createdAt)`);
2144
+ for (const r of bundle.reviews ?? []) {
2145
+ counts.reviews += insReview.run(r).changes;
2146
+ }
2147
+ const insDecision = this.db.prepare(`INSERT OR IGNORE INTO decisions (id, agent_id, session_id, title, rationale, evidence, related_commits, related_tasks, created_at)
2148
+ VALUES (@id, @agentId, @sessionId, @title, @rationale, @evidence, @relatedCommits, @relatedTasks, @createdAt)`);
2149
+ for (const d of bundle.decisions ?? []) {
2150
+ counts.decisions += insDecision.run({
2151
+ ...d,
2152
+ relatedCommits: JSON.stringify(d.relatedCommits ?? []),
2153
+ relatedTasks: JSON.stringify(d.relatedTasks ?? []),
2154
+ }).changes;
2155
+ }
2156
+ // Skip the audit event on a pure no-op re-import (all rows already
2157
+ // present) so re-syncing the same bundle doesn't accrete noise.
2158
+ if (counts.attributions +
2159
+ counts.reviews +
2160
+ counts.sessions +
2161
+ counts.decisions >
2162
+ 0) {
2163
+ const trust = verified === true
2164
+ ? " [signed ✓]"
2165
+ : verified === false
2166
+ ? " [signature INVALID]"
2167
+ : " [unsigned]";
2168
+ this.append(this.config.agent, "import", `imported bundle: ${counts.attributions} attribution(s), ${counts.reviews} review(s)${trust}`, null, null, { ...counts, verified });
2169
+ }
2170
+ });
2171
+ tx.immediate();
2172
+ return { ...counts, verified };
2173
+ }
2174
+ /**
2175
+ * Git trailer lines encoding a commit's attribution, for embedding in a
2176
+ * commit message so it travels with the commit itself (a lightweight
2177
+ * alternative to a bundle). Blackboard-namespaced — it does not hijack
2178
+ * `Co-Authored-By`.
2179
+ */
2180
+ trailersFor(rev) {
2181
+ const sha = git.resolveRev(rev) ?? rev;
2182
+ const attrs = this.attributionsForCommit(sha);
2183
+ const lines = [];
2184
+ const seen = new Set();
2185
+ for (const a of attrs) {
2186
+ const model = a.model ? ` ${a.model}` : "";
2187
+ const line = `Blackboard-Attribution: ${a.actorType} ${a.actor}${model}${a.cli ? ` via ${a.cli}` : ""}`;
2188
+ if (!seen.has(line)) {
2189
+ seen.add(line);
2190
+ lines.push(line);
2191
+ }
2192
+ }
2193
+ const sessionIds = [
2194
+ ...new Set(attrs.map((a) => a.sessionId).filter((s) => s !== null)),
2195
+ ];
2196
+ for (const sid of sessionIds) {
2197
+ lines.push(`Blackboard-Session: ${sid}`);
2198
+ }
2199
+ return lines;
2200
+ }
2201
+ /** Everything the board knows about a commit — the `explain` view. */
2202
+ explain(rev) {
2203
+ const sha = git.resolveRev(rev) ?? rev;
2204
+ const info = git.commitInfo(sha) ?? { sha };
2205
+ const attributions = this.attributionsForCommit(sha);
2206
+ if (attributions.length === 0 && !git.resolveRev(rev)) {
2207
+ return undefined;
2208
+ }
2209
+ return {
2210
+ commit: info,
2211
+ attributions,
2212
+ reviews: this.reviewsForCommit(sha),
2213
+ decisions: this.decisionsForCommit(sha),
2214
+ note: git.readNote(sha) ?? null,
2215
+ };
2216
+ }
2217
+ /** Which session introduced a line — Git blame → attribution. */
2218
+ blame(file, line) {
2219
+ const b = git.blameLine(file, line);
2220
+ if (!b) {
2221
+ return undefined;
2222
+ }
2223
+ return {
2224
+ sha: b.sha,
2225
+ gitAuthor: b.author,
2226
+ attributions: this.attributionsForCommitFile(b.sha, file),
2227
+ };
2228
+ }
2229
+ /**
2230
+ * Blame → narrative: from a single line, trace back to the session that
2231
+ * introduced it and surface that session's whole story — what else it did,
2232
+ * the decisions it made, and the handoffs it left. Turns `git blame` into
2233
+ * "why does this line exist".
2234
+ */
2235
+ blameNarrative(file, line) {
2236
+ const b = git.blameLine(file, line);
2237
+ if (!b) {
2238
+ return undefined;
2239
+ }
2240
+ const attributions = this.attributionsForCommitFile(b.sha, file);
2241
+ const sessionId = attributions
2242
+ .map((a) => a.sessionId)
2243
+ .find((s) => s !== null) ?? null;
2244
+ const session = sessionId ? (this.getSession(sessionId) ?? null) : null;
2245
+ const sessionTimeline = sessionId ? this.sessionTimeline(sessionId) : [];
2246
+ const decisions = sessionId
2247
+ ? this.db
2248
+ .prepare("SELECT * FROM decisions WHERE session_id = ? ORDER BY created_at ASC")
2249
+ .all(sessionId).map(rowToDecision)
2250
+ : [];
2251
+ const handoffs = sessionId
2252
+ ? this.db
2253
+ .prepare("SELECT * FROM handoffs WHERE from_session = ? ORDER BY created_at ASC")
2254
+ .all(sessionId).map(rowToHandoff)
2255
+ : [];
2256
+ return {
2257
+ sha: b.sha,
2258
+ gitAuthor: b.author,
2259
+ attributions,
2260
+ session,
2261
+ sessionTimeline,
2262
+ decisions,
2263
+ handoffs,
2264
+ };
2265
+ }
2266
+ // --- reporting -------------------------------------------------------------
2267
+ /** Aggregate metrics for a scorecard: coverage, AI/human ratio, per-agent. */
2268
+ /**
2269
+ * Accountability scorecard. With `projectKey`, returns the three-level
2270
+ * project -> task -> trace aggregation instead (a DIFFERENT shape — callers
2271
+ * that need both must call twice). Unknown key returns undefined.
2272
+ */
2273
+ report(projectKey = null) {
2274
+ if (projectKey) {
2275
+ return this.projectReport(projectKey);
2276
+ }
2277
+ return this.readSnapshot(() => this.reportSnapshot());
2278
+ }
2279
+ reportSnapshot() {
2280
+ const one = (sql, ...params) => {
2281
+ const row = this.db.prepare(sql).get(...params);
2282
+ return row?.n ?? 0;
2283
+ };
2284
+ const attrTotal = one("SELECT COUNT(*) AS n FROM attributions");
2285
+ const attrAi = one("SELECT COUNT(*) AS n FROM attributions WHERE actor_type = 'ai'");
2286
+ const attrHuman = one("SELECT COUNT(*) AS n FROM attributions WHERE actor_type = 'human'");
2287
+ const commitsTotal = one("SELECT COUNT(DISTINCT commit_sha) AS n FROM attributions");
2288
+ // Set-based (was an N+1 loop of hasHumanReview per AI commit): count AI
2289
+ // commits, and those with an approved human review, in two queries.
2290
+ const aiProduced = one("SELECT COUNT(DISTINCT commit_sha) AS n FROM attributions WHERE actor_type = 'ai'");
2291
+ const reviewed = one(`SELECT COUNT(*) AS n FROM (
2292
+ SELECT DISTINCT a.commit_sha FROM attributions a
2293
+ WHERE a.actor_type = 'ai'
2294
+ AND EXISTS (SELECT 1 FROM reviews r
2295
+ WHERE r.commit_sha = a.commit_sha
2296
+ AND r.reviewer_type = 'human' AND r.outcome = 'approved')
2297
+ )`);
2298
+ const unreviewed = aiProduced - reviewed;
2299
+ // N/A (null), not 100%, when there is no AI work to review.
2300
+ const reviewCoverage = aiProduced === 0 ? null : reviewed / aiProduced;
2301
+ const perAgentRows = this.db
2302
+ .prepare(`SELECT actor AS agent, actor_type AS actorType, COUNT(*) AS attributions,
2303
+ COUNT(DISTINCT commit_sha) AS commits, COUNT(DISTINCT file) AS files
2304
+ FROM attributions GROUP BY actor, actor_type ORDER BY attributions DESC`)
2305
+ .all();
2306
+ return {
2307
+ attributions: { total: attrTotal, ai: attrAi, human: attrHuman },
2308
+ commits: {
2309
+ total: commitsTotal,
2310
+ aiProduced,
2311
+ humanReviewed: reviewed,
2312
+ unreviewed,
2313
+ },
2314
+ reviewCoverage,
2315
+ aiHumanRatio: { ai: attrAi, human: attrHuman },
2316
+ perAgent: perAgentRows,
2317
+ sessions: {
2318
+ total: one("SELECT COUNT(*) AS n FROM sessions"),
2319
+ open: one("SELECT COUNT(*) AS n FROM sessions WHERE finished_at IS NULL"),
2320
+ },
2321
+ risks: {
2322
+ open: one("SELECT COUNT(*) AS n FROM risks WHERE status = 'open'"),
2323
+ mitigated: one("SELECT COUNT(*) AS n FROM risks WHERE status = 'mitigated'"),
2324
+ closed: one("SELECT COUNT(*) AS n FROM risks WHERE status = 'closed'"),
2325
+ },
2326
+ };
2327
+ }
2328
+ // --- liveness (heartbeat) --------------------------------------------------
2329
+ /** Stamp a session's liveness. Cheap; not recorded on the timeline. */
2330
+ heartbeat(sessionId) {
2331
+ const sid = sessionId ?? this.activeSession;
2332
+ if (!sid) {
2333
+ return undefined;
2334
+ }
2335
+ this.db
2336
+ .prepare("UPDATE sessions SET last_heartbeat = ? WHERE id = ?")
2337
+ .run(now(), sid);
2338
+ return this.getSession(sid);
2339
+ }
2340
+ /** Open sessions whose heartbeat is within `withinMs` — genuinely active. */
2341
+ activeSessions(withinMs = 120_000) {
2342
+ const cutoff = new Date(Date.now() - withinMs).toISOString();
2343
+ return this.db
2344
+ .prepare("SELECT * FROM sessions WHERE finished_at IS NULL AND last_heartbeat >= ? ORDER BY last_heartbeat DESC")
2345
+ .all(cutoff).map(rowToSession);
2346
+ }
2347
+ /**
2348
+ * Other active sessions that recorded a change to the same file — real-time
2349
+ * collision awareness (two live agents editing one file), a step beyond the
2350
+ * same-task conflict surfaced by `fileChanged`.
2351
+ */
2352
+ activeEditorsOfFile(file, excludeSession, withinMs = 120_000) {
2353
+ const active = new Set(this.activeSessions(withinMs).map((s) => s.id));
2354
+ const rows = this.db
2355
+ .prepare("SELECT DISTINCT session_id, agent_id FROM files_changed WHERE path = ? AND session_id IS NOT NULL")
2356
+ .all(file);
2357
+ return rows
2358
+ .filter((r) => active.has(r.session_id) && r.session_id !== excludeSession)
2359
+ .map((r) => ({ sessionId: r.session_id, agent: r.agent_id }));
2360
+ }
2361
+ // --- retention & redaction -------------------------------------------------
2362
+ /**
2363
+ * Delete potentially-sensitive, bulky rows (messages, evidence, file-change
2364
+ * records) created before a horizon. The append-only timeline is NEVER pruned
2365
+ * — it is the audit trail — so pruning is recorded as one `prune` event.
2366
+ */
2367
+ prune(beforeIso) {
2368
+ const tx = this.db.transaction(() => {
2369
+ const del = (table) => this.db
2370
+ .prepare(`DELETE FROM ${table} WHERE created_at < ?`)
2371
+ .run(beforeIso).changes;
2372
+ const counts = {
2373
+ messages: del("messages"),
2374
+ evidence: del("evidence"),
2375
+ filesChanged: del("files_changed"),
2376
+ };
2377
+ this.append(this.config.agent, "prune", `pruned rows before ${beforeIso}: ${counts.messages} message(s), ${counts.evidence} evidence, ${counts.filesChanged} file-change(s)`, null, null, counts);
2378
+ return counts;
2379
+ });
2380
+ return tx.immediate();
2381
+ }
2382
+ /**
2383
+ * Redact a timeline entry's content across ALL read paths. Two things happen:
2384
+ * (1) the timeline row's displayed summary/payload is overlaid with a
2385
+ * tombstone (`timeline`/`since`/`sessionTimeline`), and (2) the underlying
2386
+ * source row that the entry points at (a message body, evidence note, handoff
2387
+ * text, decision rationale, risk title) is blanked in its own table — because
2388
+ * those tables are read directly by `inbox`/`status`/the dashboard and would
2389
+ * otherwise leak the content the overlay only hid on the timeline.
2390
+ *
2391
+ * The timeline row's stored hash input is left intact so the chain still
2392
+ * verifies. NOTE: this hides content at the read layer — it is not
2393
+ * cryptographic erasure (the original summary remains in the timeline row to
2394
+ * keep the chain valid). Don't store secrets you must be able to destroy.
2395
+ */
2396
+ redact(seq, reason = null) {
2397
+ const row = this.db
2398
+ .prepare("SELECT ref_table, ref_id FROM timeline WHERE seq = ?")
2399
+ .get(seq);
2400
+ if (!row) {
2401
+ return false;
2402
+ }
2403
+ const tx = this.db.transaction(() => {
2404
+ this.db
2405
+ .prepare("INSERT OR REPLACE INTO redactions (seq, reason, actor, created_at) VALUES (?, ?, ?, ?)")
2406
+ .run(seq, reason, this.config.agent, now());
2407
+ // Blank the free-text columns of the source row, if any, so no direct
2408
+ // read path can surface the redacted content.
2409
+ const TOMB = "[redacted]";
2410
+ const blanks = {
2411
+ messages: "UPDATE messages SET body = ? WHERE id = ?",
2412
+ evidence: "UPDATE evidence SET ref = ?, note = ? WHERE id = ?",
2413
+ handoffs: "UPDATE handoffs SET summary = ?, context = ? WHERE id = ?",
2414
+ decisions: "UPDATE decisions SET rationale = ? WHERE id = ?",
2415
+ risks: "UPDATE risks SET title = ? WHERE id = ?",
2416
+ };
2417
+ if (row.ref_table && row.ref_id && blanks[row.ref_table]) {
2418
+ const sql = blanks[row.ref_table];
2419
+ const argCount = (sql.match(/\?/g) ?? []).length;
2420
+ const params = Array(argCount - 1).fill(TOMB);
2421
+ this.db.prepare(sql).run(...params, row.ref_id);
2422
+ }
2423
+ this.append(this.config.agent, "redaction", `redacted #${seq}${reason ? `: ${reason}` : ""}`, "timeline", String(seq), { seq });
2424
+ });
2425
+ tx.immediate();
2426
+ return true;
2427
+ }
2428
+ /** Seqs that have been redacted, with their reason. */
2429
+ redactionMap() {
2430
+ const rows = this.db
2431
+ .prepare("SELECT seq, reason FROM redactions")
2432
+ .all();
2433
+ return new Map(rows.map((r) => [r.seq, r.reason]));
2434
+ }
2435
+ /** Apply the redaction overlay to a set of events (content → tombstone). */
2436
+ applyRedactions(events) {
2437
+ const redacted = this.redactionMap();
2438
+ if (redacted.size === 0) {
2439
+ return events;
2440
+ }
2441
+ return events.map((e) => redacted.has(e.seq)
2442
+ ? {
2443
+ ...e,
2444
+ summary: `[redacted${redacted.get(e.seq) ? `: ${redacted.get(e.seq)}` : ""}]`,
2445
+ payload: null,
2446
+ }
2447
+ : e);
2448
+ }
2449
+ // --- ingestion -------------------------------------------------------------
2450
+ /**
2451
+ * Record a batch of normalized ingest events (from a transcript adapter)
2452
+ * under the acting agent and active session, then append one `ingest`
2453
+ * summary event. Each file/decision/note is attributed like any other write.
2454
+ */
2455
+ ingest(events) {
2456
+ const counts = { files: 0, decisions: 0, notes: 0 };
2457
+ // One transaction for the whole batch: a crash mid-transcript leaves the
2458
+ // board unchanged (all-or-nothing), rather than a half-applied prefix that
2459
+ // a re-run would double-record. The per-item writes nest as savepoints.
2460
+ const tx = this.db.transaction(() => {
2461
+ for (const e of events) {
2462
+ if (e.type === "file") {
2463
+ this.fileChanged(this.config.agent, e.path, e.change);
2464
+ counts.files += 1;
2465
+ }
2466
+ else if (e.type === "decision") {
2467
+ this.decision(this.config.agent, e.title, {
2468
+ rationale: e.rationale ?? null,
2469
+ });
2470
+ counts.decisions += 1;
2471
+ }
2472
+ else if (e.type === "note") {
2473
+ this.note(this.config.agent, e.text);
2474
+ counts.notes += 1;
2475
+ }
2476
+ }
2477
+ // Skip the summary event for an empty ingest — it would be pure noise in
2478
+ // the immutable timeline on a no-op transcript.
2479
+ if (counts.files + counts.decisions + counts.notes > 0) {
2480
+ this.append(this.config.agent, "ingest", `ingested ${counts.files} file(s), ${counts.decisions} decision(s), ${counts.notes} note(s)`, null, null, counts);
2481
+ }
2482
+ });
2483
+ tx.immediate();
2484
+ return counts;
2485
+ }
2486
+ // --- read ------------------------------------------------------------------
2487
+ status(forAgent) {
2488
+ // One read snapshot for the whole view: a concurrent writer committing
2489
+ // between these queries can't produce a status that mixes pre- and
2490
+ // post-write state.
2491
+ return this.readSnapshot(() => ({
2492
+ agents: this.listAgents(),
2493
+ openTasks: this.listTasks().filter((t) => t.status !== "done"),
2494
+ unreadMessages: forAgent ? this.inbox(forAgent) : this.allUnread(),
2495
+ openRisks: this.listRisks("open"),
2496
+ recentTimeline: this.timeline(10),
2497
+ }));
2498
+ }
2499
+ /**
2500
+ * Run a read-only function inside a single SQLite snapshot so every query it
2501
+ * makes sees a consistent point-in-time view of the board. Nested calls (a
2502
+ * snapshot within a snapshot) reuse the outer one.
2503
+ */
2504
+ readSnapshot(fn) {
2505
+ if (this.db.inTransaction) {
2506
+ return fn();
2507
+ }
2508
+ return this.db.transaction(fn)();
2509
+ }
2510
+ allUnread() {
2511
+ return this.db
2512
+ .prepare("SELECT * FROM messages WHERE read_at IS NULL ORDER BY created_at DESC")
2513
+ .all().map(rowToMessage);
2514
+ }
2515
+ }
2516
+ // --- row mappers -------------------------------------------------------------
2517
+ function rowToAgent(r) {
2518
+ return {
2519
+ id: r.id,
2520
+ name: r.name,
2521
+ kind: r.kind,
2522
+ provider: r.provider ?? null,
2523
+ model: r.model ?? null,
2524
+ cli: r.cli ?? null,
2525
+ version: r.version ?? null,
2526
+ createdAt: r.created_at,
2527
+ lastSeen: r.last_seen,
2528
+ };
2529
+ }
2530
+ function rowToSession(r) {
2531
+ return {
2532
+ id: r.id,
2533
+ agentName: r.agent_name,
2534
+ label: r.label,
2535
+ machine: r.machine ?? null,
2536
+ workingDirectory: r.working_directory ?? null,
2537
+ gitBranch: r.git_branch ?? null,
2538
+ repository: r.repository ?? null,
2539
+ publicKey: r.public_key ?? null,
2540
+ lastHeartbeat: r.last_heartbeat ?? null,
2541
+ startedAt: r.started_at,
2542
+ finishedAt: r.finished_at ?? null,
2543
+ project: r.project ?? null,
2544
+ taskKey: r.task_key ?? null,
2545
+ };
2546
+ }
2547
+ function parseJsonObject(value) {
2548
+ if (typeof value !== "string" || value.length === 0) {
2549
+ return null;
2550
+ }
2551
+ try {
2552
+ const parsed = JSON.parse(value);
2553
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2554
+ }
2555
+ catch {
2556
+ return null;
2557
+ }
2558
+ }
2559
+ function acceptanceToStorage(value) {
2560
+ if (value === undefined || value === null) {
2561
+ return null;
2562
+ }
2563
+ const obj = typeof value === "string" ? parseJsonObject(value) : value;
2564
+ return obj && typeof obj === "object" && !Array.isArray(obj) ? JSON.stringify(obj) : null;
2565
+ }
2566
+ /**
2567
+ * Normalize a project stream vocabulary to its stored form: a JSON string array
2568
+ * of unique, non-empty, trimmed strings. Accepts an array or a raw string
2569
+ * (either a JSON array, or a comma-separated list like "串讲,译文,精读").
2570
+ * Returns null when nothing usable was supplied -- which the store reads back as
2571
+ * "no vocabulary declared", meaning `defineTask` rejects nothing.
2572
+ */
2573
+ function streamsToStorage(value) {
2574
+ if (value === undefined || value === null)
2575
+ return null;
2576
+ let arr = value;
2577
+ if (typeof value === "string") {
2578
+ const raw = value.trim();
2579
+ if (!raw)
2580
+ return null;
2581
+ try {
2582
+ const parsed = JSON.parse(raw);
2583
+ arr = Array.isArray(parsed) ? parsed : raw.split(",");
2584
+ }
2585
+ catch {
2586
+ arr = raw.split(",");
2587
+ }
2588
+ }
2589
+ if (!Array.isArray(arr))
2590
+ return null;
2591
+ const cleaned = [...new Set(arr.map((e) => String(e).trim()).filter((s) => s.length > 0))];
2592
+ return cleaned.length ? JSON.stringify(cleaned) : null;
2593
+ }
2594
+ function parseJsonArray(value) {
2595
+ if (typeof value !== "string" || value.length === 0) {
2596
+ return [];
2597
+ }
2598
+ try {
2599
+ const parsed = JSON.parse(value);
2600
+ // Coerce every element to a string so the `string[]` type is honored even
2601
+ // if a caller stored non-strings (which would otherwise crash consumers
2602
+ // that call string methods on the elements).
2603
+ return Array.isArray(parsed) ? parsed.map((e) => String(e)) : [];
2604
+ }
2605
+ catch {
2606
+ return [];
2607
+ }
2608
+ }
2609
+ function rowToDecision(r) {
2610
+ return {
2611
+ id: r.id,
2612
+ agentId: r.agent_id,
2613
+ sessionId: r.session_id ?? null,
2614
+ title: r.title,
2615
+ rationale: r.rationale,
2616
+ evidence: r.evidence ?? null,
2617
+ relatedCommits: parseJsonArray(r.related_commits),
2618
+ relatedTasks: parseJsonArray(r.related_tasks),
2619
+ createdAt: r.created_at,
2620
+ };
2621
+ }
2622
+ function rowToAttribution(r) {
2623
+ return {
2624
+ id: r.id,
2625
+ commit: r.commit_sha,
2626
+ file: r.file,
2627
+ hunk: r.hunk,
2628
+ actorType: r.actor_type,
2629
+ actor: r.actor,
2630
+ provider: r.provider ?? null,
2631
+ model: r.model ?? null,
2632
+ cli: r.cli ?? null,
2633
+ sessionId: r.session_id ?? null,
2634
+ createdAt: r.created_at,
2635
+ };
2636
+ }
2637
+ function rowToReview(r) {
2638
+ return {
2639
+ id: r.id,
2640
+ commit: r.commit_sha,
2641
+ reviewerType: r.reviewer_type,
2642
+ reviewer: r.reviewer,
2643
+ sessionId: r.session_id ?? null,
2644
+ outcome: r.outcome,
2645
+ note: r.note ?? null,
2646
+ createdAt: r.created_at,
2647
+ };
2648
+ }
2649
+ function rowToHandoff(r) {
2650
+ return {
2651
+ id: r.id,
2652
+ fromAgent: r.from_agent,
2653
+ toAgent: r.to_agent,
2654
+ fromSession: r.from_session ?? null,
2655
+ toSession: r.to_session ?? null,
2656
+ summary: r.summary,
2657
+ context: r.context ?? null,
2658
+ relatedFiles: parseJsonArray(r.related_files),
2659
+ openQuestions: parseJsonArray(r.open_questions),
2660
+ taskKey: r.task_key ?? null,
2661
+ createdAt: r.created_at,
2662
+ acceptedAt: r.accepted_at ?? null,
2663
+ };
2664
+ }
2665
+ function rowToProject(r) {
2666
+ return {
2667
+ id: r.id,
2668
+ key: r.key,
2669
+ name: r.name,
2670
+ description: r.description ?? null,
2671
+ status: r.status,
2672
+ streams: parseJsonArray(r.streams),
2673
+ createdBy: r.created_by,
2674
+ createdAt: r.created_at,
2675
+ updatedAt: r.updated_at,
2676
+ };
2677
+ }
2678
+ function rowToTask(r) {
2679
+ return {
2680
+ id: r.id,
2681
+ key: r.key,
2682
+ number: r.number ?? null,
2683
+ title: r.title,
2684
+ description: r.description ?? null,
2685
+ status: r.status,
2686
+ project: r.project ?? null,
2687
+ stream: r.stream ?? null,
2688
+ impact: r.impact ?? null,
2689
+ riskLevel: r.risk_level ?? null,
2690
+ acceptance: parseJsonObject(r.acceptance),
2691
+ progress: r.progress ?? 0,
2692
+ createdBy: r.created_by,
2693
+ claimedBy: r.claimed_by,
2694
+ claimedAt: r.claimed_at,
2695
+ releasedAt: r.released_at,
2696
+ createdAt: r.created_at,
2697
+ updatedAt: r.updated_at,
2698
+ };
2699
+ }
2700
+ function rowToMessage(r) {
2701
+ return {
2702
+ id: r.id,
2703
+ fromAgent: r.from_agent,
2704
+ toAgent: r.to_agent,
2705
+ body: r.body,
2706
+ createdAt: r.created_at,
2707
+ readAt: r.read_at,
2708
+ };
2709
+ }
2710
+ function rowToRisk(r) {
2711
+ return {
2712
+ id: r.id,
2713
+ agentId: r.agent_id,
2714
+ title: r.title,
2715
+ severity: r.severity,
2716
+ status: r.status,
2717
+ taskKey: r.task_key ?? null,
2718
+ createdAt: r.created_at,
2719
+ resolvedAt: r.resolved_at ?? null,
2720
+ resolvedBy: r.resolved_by ?? null,
2721
+ };
2722
+ }
2723
+ function rowToEvidence(r) {
2724
+ return {
2725
+ id: r.id,
2726
+ agentId: r.agent_id,
2727
+ ref: r.ref,
2728
+ note: r.note ?? null,
2729
+ target: r.target ?? null,
2730
+ sha256: r.sha256 ?? null,
2731
+ project: r.project ?? null,
2732
+ taskKey: r.task_key ?? null,
2733
+ kind: r.kind ?? null,
2734
+ createdAt: r.created_at,
2735
+ };
2736
+ }
2737
+ function rowToFileChange(r) {
2738
+ return {
2739
+ id: r.id,
2740
+ agentId: r.agent_id,
2741
+ sessionId: r.session_id ?? null,
2742
+ path: r.path,
2743
+ change: r.change,
2744
+ taskKey: r.task_key,
2745
+ createdAt: r.created_at,
2746
+ };
2747
+ }
2748
+ function rowToTimeline(r) {
2749
+ return {
2750
+ id: r.id,
2751
+ seq: r.seq,
2752
+ at: r.at,
2753
+ actor: r.actor,
2754
+ sessionId: r.session_id ?? null,
2755
+ kind: r.kind,
2756
+ refTable: r.ref_table,
2757
+ refId: r.ref_id,
2758
+ summary: r.summary,
2759
+ payload: r.payload === null ? null : JSON.parse(r.payload),
2760
+ // step 2: four-layer ownership. Attached attributes, NOT inside computeHash.
2761
+ project: r.project ?? null,
2762
+ taskKey: r.task_key ?? null,
2763
+ prevHash: r.prev_hash,
2764
+ hash: r.hash,
2765
+ };
2766
+ }
2767
+ //# sourceMappingURL=board.js.map