modboard 0.0.0-stage → 0.5.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.
@@ -0,0 +1,356 @@
1
+ import { atom, read, update } from 'claude-code'
2
+ import type { EngineInterface, Register } from 'claude-code'
3
+
4
+ import type { Agent, Task } from '../types'
5
+ import { BLOCKS, type BandForm, type Block, type Ctx } from './blocks'
6
+ import { commandBlock, firstLine, parseCommandBlocks } from './blocks/command'
7
+
8
+ // The mod is an adapter: every board read and write goes through bin/board.mjs,
9
+ // the same CLI Codex or a human runs, so it works whatever storage block holds
10
+ // the board. The mod adds what only Claude's host can: the session's identity,
11
+ // heartbeats, usage readings, and a display built from blocks (./blocks): a
12
+ // one-line band above the prompt, and the /board pane.
13
+
14
+ const PANE = 'modboard'
15
+ const HEARTBEAT_MS = 60_000
16
+ const PRESENCE_MS = 60_000
17
+ const POLL_MS = 3_000
18
+ const COMMAND_MS = 30_000
19
+ const NAME_TRIES = 9
20
+
21
+ const tasks = atom({ plugin: 'modboard', key: 'tasks' } as const, [])
22
+ const agents = atom({ plugin: 'modboard', key: 'agents' } as const, [])
23
+ const me = atom({ plugin: 'modboard', key: 'me' } as const, '')
24
+ const usage = atom({ plugin: 'modboard', key: 'usage' } as const, { limits: [] })
25
+ const model = atom({ plugin: 'modboard', key: 'model' } as const, '')
26
+ const effort = atom({ plugin: 'modboard', key: 'effort' } as const, '')
27
+ const custom = atom({ plugin: 'modboard', key: 'custom' } as const, {} as Record<string, string>)
28
+
29
+ let session = ''
30
+ let lastBeat = 0
31
+
32
+ async function cli($: EngineInterface, args: string[]) {
33
+ const run = await $.process.run(['node', `${$.plugin.root}/bin/board.mjs`, ...args])
34
+ return { ok: run.exitCode === 0, code: run.exitCode, text: (run.exitCode === 0 ? run.stdout : run.stderr || run.stdout).trim() }
35
+ }
36
+
37
+ async function board($: EngineInterface, args: string[]) {
38
+ return cli($, [...args, '--as', await read($, me)])
39
+ }
40
+
41
+ // Take the name asked for in BOARD_AGENT, or the next free one after it; with
42
+ // none asked for, a name from the session id, which no other session has.
43
+ async function takeName($: EngineInterface, wanted: string | undefined) {
44
+ if (!wanted) {
45
+ const name = `claude:${session.slice(0, 8)}`
46
+ await cli($, ['register', name, '--session', session])
47
+ return name
48
+ }
49
+ for (let i = 1; i <= NAME_TRIES; i++) {
50
+ const name = i === 1 ? wanted : `${wanted}-${i}`
51
+ const taken = await cli($, ['register', name, '--session', session])
52
+ if (taken.ok) {
53
+ if (i > 1) $.ui.toast(`board: "${wanted}" is in use by another live session, so this one is "${name}"`)
54
+ return name
55
+ }
56
+ if (taken.code !== 7) break
57
+ }
58
+ const name = `claude:${session.slice(0, 8)}`
59
+ $.ui.toast(`board: could not take the name "${wanted}", so this session is "${name}"`)
60
+ await cli($, ['register', name, '--session', session])
61
+ return name
62
+ }
63
+
64
+ async function refresh($: EngineInterface) {
65
+ const out = await cli($, ['view', '--json'])
66
+ if (!out.ok) return
67
+ const view = JSON.parse(out.text) as { tasks: Task[]; agents: Agent[] }
68
+ await update($, tasks, () => view.tasks)
69
+ await update($, agents, () => view.agents)
70
+ }
71
+
72
+ const TOOLS = [
73
+ {
74
+ name: 'board_list',
75
+ description:
76
+ 'List open tasks on the shared board several agents work from at once (○ todo, ◐ claimed, with owner). ' +
77
+ 'Protocol: claim a task before working on it, note progress, release with a handoff if you stop, never touch a task another agent holds.',
78
+ args: () => ['list'],
79
+ },
80
+ {
81
+ name: 'board_show',
82
+ description: 'Show one task with its acceptance criteria, notes and handoffs. Read this before resuming a task someone else released.',
83
+ schema: { id: { type: 'string' } },
84
+ required: ['id'],
85
+ args: (i: any) => ['show', i.id],
86
+ },
87
+ {
88
+ name: 'board_add',
89
+ description: 'Add a task to the shared board. Give it acceptance criteria: how to tell it is done.',
90
+ schema: { title: { type: 'string' }, description: { type: 'string' }, accept: { type: 'string' } },
91
+ required: ['title'],
92
+ args: (i: any) => [
93
+ 'add',
94
+ i.title,
95
+ ...(i.description ? ['--desc', i.description] : []),
96
+ ...(i.accept ? ['--accept', i.accept] : []),
97
+ ],
98
+ },
99
+ {
100
+ name: 'board_claim',
101
+ description:
102
+ 'Claim a task before working on it. Fails if another agent holds it — then pick another task. Your lease renews automatically while you work.',
103
+ schema: { id: { type: 'string' } },
104
+ required: ['id'],
105
+ args: (i: any) => ['claim', i.id],
106
+ },
107
+ {
108
+ name: 'board_note',
109
+ description: 'Record progress on a task you hold (what is done, what is next, decisions).',
110
+ schema: { id: { type: 'string' }, text: { type: 'string' } },
111
+ required: ['id', 'text'],
112
+ args: (i: any) => ['note', i.id, i.text],
113
+ },
114
+ {
115
+ name: 'board_release',
116
+ description:
117
+ 'Give up a task you hold without finishing it. Always write a handoff: what is done, what is left, where to look — the next agent starts from it.',
118
+ schema: { id: { type: 'string' }, handoff: { type: 'string' } },
119
+ required: ['id', 'handoff'],
120
+ args: (i: any) => ['release', i.id, '--handoff', i.handoff],
121
+ },
122
+ {
123
+ name: 'board_done',
124
+ description:
125
+ 'Mark a task you hold as done. Only after you have checked it against its acceptance criteria (board_show lists them). ' +
126
+ 'The note says how you verified it: what you ran or checked and what you saw.',
127
+ schema: { id: { type: 'string' }, note: { type: 'string' } },
128
+ required: ['id', 'note'],
129
+ args: (i: any) => ['done', i.id, '--note', i.note ?? ''],
130
+ },
131
+ ]
132
+
133
+ const SYMBOL = { todo: '○', claimed: '◐', done: '●' } as const
134
+
135
+ const pick = (all: Block[], setting: unknown, fallback: string) =>
136
+ String(setting ?? fallback)
137
+ .split(',')
138
+ .map(name => all.find(b => b.name === name.trim()))
139
+ .filter(b => b !== undefined)
140
+
141
+ // Each command block's first line of output; a failing command shows nothing.
142
+ async function runCommands($: EngineInterface, commands: Record<string, string>) {
143
+ const out: Record<string, string> = {}
144
+ for (const [name, command] of Object.entries(commands)) {
145
+ const run = await $.process.run(['sh', '-c', command]).catch(() => undefined)
146
+ if (run && run.exitCode === 0) out[name] = firstLine(run.stdout)
147
+ }
148
+ await update($, custom, () => out)
149
+ }
150
+
151
+ const GAP = 3
152
+ // Claude Code draws its own collapse control ([-]) at the line's right end.
153
+ const CONTROL = 4
154
+
155
+ // The band never wraps. The `band` setting's order is the order of importance,
156
+ // so the first block (the board's summary, by default) holds its full form
157
+ // longest: first the others narrow, last first; then the others go, last
158
+ // first; only then does the first block narrow.
159
+ function fit(offered: BandForm[][], columns: number): BandForm[] {
160
+ const chosen = offered.map(() => 0)
161
+ let kept = offered.length
162
+ const width = () => offered.slice(0, kept).reduce((sum, forms, i) => sum + forms[chosen[i]!]!.width, 0) + GAP * Math.max(0, kept - 1)
163
+ for (let i = kept - 1; i >= 1 && width() > columns; i--) while (chosen[i]! < offered[i]!.length - 1 && width() > columns) chosen[i]!++
164
+ while (kept > 1 && width() > columns) kept--
165
+ while (kept === 1 && chosen[0]! < offered[0]!.length - 1 && width() > columns) chosen[0]!++
166
+ if (width() > columns) kept = 0
167
+ return offered.slice(0, kept).map((forms, i) => forms[chosen[i]!]!)
168
+ }
169
+
170
+ const list = (setting: unknown, fallback: string) =>
171
+ String(setting ?? fallback)
172
+ .split(',')
173
+ .map(item => item.trim())
174
+ .filter(Boolean)
175
+
176
+ // The entry after `current` in `cycle`, wrapping from the last to the first;
177
+ // the first when `current` matches none. An exact match wins, so "xhigh" is
178
+ // never taken for "high"; otherwise the longest name inside it, so a model
179
+ // named in full ("claude-opus-5-5") matches its short name ("opus").
180
+ function after(cycle: string[], current: string) {
181
+ const now = current.toLowerCase()
182
+ let at = cycle.findIndex(item => item.toLowerCase() === now)
183
+ if (at < 0) {
184
+ const inside = cycle.filter(item => now.includes(item.toLowerCase())).sort((a, b) => b.length - a.length)[0]
185
+ at = inside === undefined ? -1 : cycle.indexOf(inside)
186
+ }
187
+ return cycle[(at + 1) % cycle.length]!
188
+ }
189
+
190
+ // Switch the way the person would, through Claude Code's own commands, so
191
+ // everything else in the session sees the change.
192
+ function actions($: EngineInterface, cycles: { models: string[]; efforts: string[] }): Ctx['act'] {
193
+ return {
194
+ nextModel: async () => {
195
+ const to = after(cycles.models, await read($, model))
196
+ await $.command.run({ command: 'model', args: to }).catch(() => $.ui.toast(`board: could not switch the model to ${to}`))
197
+ const now = await $.session.model()
198
+ await update($, model, () => now || to)
199
+ },
200
+ nextEffort: async () => {
201
+ const to = after(cycles.efforts, await read($, effort))
202
+ await $.command.run({ command: 'effort', args: to }).catch(() => $.ui.toast(`board: could not set effort to ${to}`))
203
+ await update($, effort, () => to)
204
+ },
205
+ }
206
+ }
207
+
208
+ async function context($: EngineInterface, width: number, ui: Ctx['ui'], act: Ctx['act']): Promise<Ctx> {
209
+ return {
210
+ ui,
211
+ width,
212
+ now: await $.clock.now(),
213
+ who: await read($, me),
214
+ tasks: await read($, tasks),
215
+ agents: await read($, agents),
216
+ usage: await read($, usage),
217
+ model: await read($, model),
218
+ effort: await read($, effort),
219
+ custom: await read($, custom),
220
+ act,
221
+ }
222
+ }
223
+
224
+ export const register: Register = (on, options) => {
225
+ const { commands, problems } = parseCommandBlocks(options.blocks, BLOCKS.map(b => b.name))
226
+ const all = [...BLOCKS, ...Object.keys(commands).map(commandBlock)]
227
+ const band = pick(all, options.band, 'summary,usage,model,effort').filter(b => b.band)
228
+ const pane = pick(all, options.pane, 'tasks,usage').filter(b => b.pane)
229
+ const cycles = { models: list(options.models, 'opus,sonnet,haiku'), efforts: list(options.efforts, 'low,medium,high,xhigh,max') }
230
+
231
+ on('session.start', async ($, e, next) => {
232
+ // Clears a status line an earlier version of this mod left behind.
233
+ $.ui.status(undefined)
234
+ const startModel = await $.session.model()
235
+ // Before the first request, the level the session will start on: the env
236
+ // override, else the model's own effortLevel (modelSettings), else the
237
+ // general one (what /effort saves). The first request's effort
238
+ // (turn.step below) then replaces it with the truth.
239
+ const level = (v: unknown) => (typeof v === 'string' && !['auto', 'unset', ''].includes(v) ? v : undefined)
240
+ const settings: any = await $.settings.read().catch(() => ({}))
241
+ const perModel = Object.entries(settings?.modelSettings ?? {}).find(([key]) => key === startModel || startModel.includes(key))?.[1] as any
242
+ const startEffort =
243
+ level(await $.env.get('CLAUDE_CODE_EFFORT_LEVEL')) ?? level(perModel?.effortLevel) ?? level(settings?.effortLevel) ?? ''
244
+ await update($, model, () => startModel)
245
+ await update($, effort, () => startEffort)
246
+ session = await $.session.id()
247
+ const name = await takeName($, await $.env.get('BOARD_AGENT'))
248
+ await update($, me, () => name)
249
+
250
+ for (const t of TOOLS)
251
+ await $.tool.register({
252
+ name: t.name,
253
+ description: t.description,
254
+ inputSchema: { type: 'object', properties: t.schema ?? {}, required: t.required ?? [] },
255
+ isDeferred: false,
256
+ })
257
+ await $.command.register({ name: 'board', description: 'Open the modboard pane' })
258
+
259
+ await refresh($)
260
+ $.clock.every(POLL_MS, () => refresh($).catch(() => {}))
261
+ for (const problem of problems) $.ui.toast(`board: ${problem}`)
262
+ if (Object.keys(commands).length) {
263
+ await runCommands($, commands)
264
+ $.clock.every(COMMAND_MS, () => runCommands($, commands).catch(() => {}))
265
+ }
266
+ // Presence: keeps this session's name while it is open, so no other
267
+ // session can take it; leases stay tied to work (see tool.call below).
268
+ $.clock.every(PRESENCE_MS, () => cli($, ['register', name, '--session', session]).catch(() => {}))
269
+
270
+ return next(e)
271
+ })
272
+
273
+ for (const t of TOOLS)
274
+ on('tool.call', { tool: `mcp__modboard__${t.name}` }, async ($, e) => {
275
+ const out = await board($, t.args(e))
276
+ await refresh($)
277
+ return { result: out.ok ? out.text : `error: ${out.text}` }
278
+ }).catch(() => ({ result: 'error: the board CLI could not run (is node on PATH?)' }))
279
+
280
+ // Leases need a heartbeat; an LLM won't send one, so tool activity does.
281
+ on('tool.call', async ($, e, next) => {
282
+ const ran = await next(e)
283
+ const now = await $.clock.now()
284
+ if (now - lastBeat > HEARTBEAT_MS) {
285
+ lastBeat = now
286
+ const who = await read($, me)
287
+ // A failed heartbeat must never fail the tool call it rode in on.
288
+ if ((await read($, tasks)).some(t => t.claim?.owner === who)) await board($, ['heartbeat']).catch(() => {})
289
+ }
290
+ return ran
291
+ })
292
+
293
+ // Each main-session request names the model and effort it runs with: the
294
+ // truth when the person switched with /model or /effort themselves.
295
+ on('turn.step', async function* ($, e, next) {
296
+ if (e.agentId === undefined) {
297
+ try {
298
+ await update($, model, () => e.model)
299
+ if (e.effort !== undefined) await update($, effort, () => String(e.effort))
300
+ } catch {}
301
+ }
302
+ return yield* next(e)
303
+ })
304
+
305
+ on('session.measure', async ($, e, next) => {
306
+ await update($, usage, () => ({
307
+ limits: e.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt })),
308
+ context: e.context.percent,
309
+ costUsd: e.cost?.usd,
310
+ }))
311
+ return next(e)
312
+ })
313
+
314
+ // A session that ends (exit, /clear, resume, logout) releases what it holds
315
+ // and gives up its name, so neither sits orphaned until a lease runs out.
316
+ on('session.end', async ($, e, next) => {
317
+ await board($, ['release-all', '--session', session]).catch(() => {})
318
+ return next(e)
319
+ }).catch(($, e, next) => next(e))
320
+
321
+ on('command.run', { command: 'board' }, async $ => {
322
+ await refresh($)
323
+ const opened = await $.ui.open({ id: PANE, title: 'modboard' })
324
+ if (opened.isPlaced) return { text: 'Board pane opened.' }
325
+ const list = (await read($, tasks)).filter(t => t.status !== 'done')
326
+ return { text: list.map(t => `${SYMBOL[t.status]} ${t.id} ${t.title}${t.claim ? ` ${t.claim.owner}` : ''}`).join('\n') || '(no open tasks)' }
327
+ })
328
+
329
+ // The band: one line above the prompt, quiet when no block has anything to say.
330
+ on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
331
+ if (e.props.hasSurvey || !band.length) return next(e)
332
+ const { Box, Text, Button } = $.ui.resolve(e)
333
+ const c = await context($, e.props.bodyColumns, { Box, Text, Button }, actions($, cycles))
334
+ const offered = band.map(b => b.band!(c)).filter((forms): forms is BandForm[] => forms !== null && forms.length > 0)
335
+ const parts = fit(offered, e.props.bodyColumns - CONTROL)
336
+ if (!parts.length) return next(e)
337
+ return (
338
+ <Box gap={GAP} flexWrap="nowrap">
339
+ {parts.map(part => (
340
+ <Box flexShrink={0}>{part.tree}</Box>
341
+ ))}
342
+ </Box>
343
+ )
344
+ })
345
+
346
+ on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
347
+ const { Box, Text, Button } = $.ui.resolve(e)
348
+ const c = await context($, e.props.bodyColumns ?? 40, { Box, Text, Button }, actions($, cycles))
349
+ const parts = pane.map(b => b.pane!(c)).filter(part => part !== null)
350
+ return (
351
+ <Box flexDirection="column" gap={1} paddingX={1}>
352
+ {parts}
353
+ </Box>
354
+ )
355
+ })
356
+ }
@@ -0,0 +1,61 @@
1
+ // The rules every storage block must keep, as a test suite a block's author
2
+ // runs against their own block (node --test). The engine depends on these and
3
+ // nothing else: one winner per contested claim, distinct ids under concurrent
4
+ // adds, stale writes refused, and names held by one live session at a time.
5
+
6
+ import { describe, test } from 'node:test'
7
+ import assert from 'node:assert/strict'
8
+
9
+ import { createEngine } from './engine.mjs'
10
+
11
+ const refused = async (promise, code) => assert.equal(await promise.then(() => 0, err => err.code), code)
12
+
13
+ export function storeContract(name, make) {
14
+ describe(`the ${name} block`, () => {
15
+ test('one of many concurrent claims wins; the rest are refused and recorded', async () => {
16
+ const store = make()
17
+ const board = createEngine(store)
18
+ await board.add('human', { title: 'contested' })
19
+ const outcomes = await Promise.all(
20
+ Array.from({ length: 10 }, (_, i) => board.claim('T-001', `a${i}`).then(() => 'won', err => err.code)),
21
+ )
22
+ assert.equal(outcomes.filter(o => o === 'won').length, 1)
23
+ assert.equal(outcomes.filter(o => o === 6).length, 9)
24
+ const events = await store.events(0)
25
+ assert.equal(events.filter(e => e.type === 'claim-rejected').length, 9)
26
+ })
27
+
28
+ test('concurrent adds get distinct ids', async () => {
29
+ const board = createEngine(make())
30
+ const added = await Promise.all(Array.from({ length: 8 }, (_, i) => board.add('human', { title: `t${i}` })))
31
+ assert.equal(new Set(added.map(t => t.id)).size, 8)
32
+ })
33
+
34
+ test('a write from an agent that no longer owns the task is refused', async () => {
35
+ const board = createEngine(make(), { leaseMs: 50 })
36
+ await board.add('human', { title: 'x' })
37
+ await board.claim('T-001', 'alice')
38
+ await new Promise(resolve => setTimeout(resolve, 80))
39
+ await board.claim('T-001', 'bob')
40
+ await refused(board.note('T-001', 'alice', 'stale write'), 5)
41
+ assert.equal((await board.show('T-001')).claim.owner, 'bob')
42
+ })
43
+
44
+ test('a name is refused while another live session holds it, and freed when it ends', async () => {
45
+ const board = createEngine(make())
46
+ await board.register('frontend', 'session-a')
47
+ await board.register('frontend', 'session-a')
48
+ await refused(board.register('frontend', 'session-b'), 7)
49
+ await board.releaseAll('frontend', { session: 'session-a' })
50
+ await board.register('frontend', 'session-b')
51
+ assert.deepEqual((await board.agents()).map(a => a.name), ['frontend'])
52
+ })
53
+
54
+ test('a name whose session went silent can be taken over', async () => {
55
+ const board = createEngine(make(), { presenceMs: 50 })
56
+ await board.register('frontend', 'session-a')
57
+ await new Promise(resolve => setTimeout(resolve, 80))
58
+ await board.register('frontend', 'session-b')
59
+ })
60
+ })
61
+ }
package/lib/engine.mjs ADDED
@@ -0,0 +1,217 @@
1
+ // The board's rules, written once. Storage is a Store (see lib/store-file.mjs
2
+ // for the contract): the engine reads a snapshot, decides, and commits its
3
+ // writes conditionally, each guarded by the version it read. A commit that
4
+ // finds a version moved fails as a whole and the engine decides again from a
5
+ // fresh snapshot. That is the one property every backend must give: local
6
+ // files under a lock, or a database in one transaction.
7
+
8
+ export class BoardError extends Error {
9
+ constructor(code, message) {
10
+ super(message)
11
+ this.code = code
12
+ }
13
+ }
14
+
15
+ const ATTEMPTS = 50
16
+
17
+ export function createEngine(store, { leaseMs = 15 * 60 * 1000, presenceMs = 3 * 60 * 1000 } = {}) {
18
+ async function transact(decide) {
19
+ for (let i = 0; i < ATTEMPTS; i++) {
20
+ const snap = await store.snapshot()
21
+ const tx = newTx(snap, await store.now())
22
+ settle(snap, tx, presenceMs)
23
+ const result = decide(tx)
24
+ if (tx.writes.length || tx.events.length) {
25
+ const committed = await store.commit({ writes: tx.writes, events: tx.events })
26
+ if (!committed.ok) {
27
+ await new Promise(resolve => setTimeout(resolve, 5 + Math.random() * 20))
28
+ continue
29
+ }
30
+ }
31
+ if (tx.refusal) throw tx.refusal
32
+ return result
33
+ }
34
+ throw new BoardError(3, 'the board is busy; try again')
35
+ }
36
+
37
+ const lease = tx => new Date(tx.now + leaseMs).toISOString()
38
+ const stamp = tx => new Date(tx.now).toISOString()
39
+
40
+ // Working on the board is a sign of life too, for an agent that registered.
41
+ function seen(tx, actor) {
42
+ const agent = tx.agent(actor)
43
+ if (agent) tx.put('agent', actor, { ...agent, lastSeen: tx.now })
44
+ }
45
+
46
+ function owned(tx, id, actor) {
47
+ const t = tx.task(id)
48
+ if (t.status !== 'claimed' || t.claim.owner !== actor)
49
+ throw new BoardError(5, `${t.id} is not claimed by ${actor}${t.claim ? ` (owner: ${t.claim.owner})` : ''}`)
50
+ return t
51
+ }
52
+
53
+ return {
54
+ list: ({ all = false } = {}) =>
55
+ transact(tx => tx.tasks().filter(t => all || t.status !== 'done')),
56
+
57
+ show: id => transact(tx => tx.task(id)),
58
+
59
+ add: (actor, { title, description = '', accept = '' }) =>
60
+ transact(tx => {
61
+ const id = `T-${String(tx.nextNumber()).padStart(3, '0')}`
62
+ const task = { id, title, description, accept, status: 'todo', claim: null, notes: [], createdBy: actor }
63
+ tx.put('task', id, task)
64
+ tx.event(actor, 'add', id)
65
+ return task
66
+ }),
67
+
68
+ claim: (id, actor) =>
69
+ transact(tx => {
70
+ const t = tx.task(id)
71
+ if (t.status === 'done') throw new BoardError(5, `${t.id} is done`)
72
+ if (t.status === 'claimed' && t.claim.owner !== actor) {
73
+ // A lost race is evidence too: keep it in the ledger, not only in a transcript.
74
+ tx.event(actor, 'claim-rejected', t.id, { holder: t.claim.owner })
75
+ tx.refusal = new BoardError(6, `${t.id} is already claimed by ${t.claim.owner} until ${new Date(t.claim.expiresAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`)
76
+ return null
77
+ }
78
+ const claimed = { ...t, status: 'claimed', claim: { owner: actor, since: t.claim?.since ?? stamp(tx), expiresAt: lease(tx) } }
79
+ tx.put('task', t.id, claimed)
80
+ tx.event(actor, 'claim', t.id)
81
+ seen(tx, actor)
82
+ return claimed
83
+ }),
84
+
85
+ // Renew every lease this actor holds, and its presence.
86
+ heartbeat: actor =>
87
+ transact(tx => {
88
+ const mine = tx.tasks().filter(t => t.claim?.owner === actor)
89
+ for (const t of mine) tx.put('task', t.id, { ...t, claim: { ...t.claim, expiresAt: lease(tx) } })
90
+ const agent = tx.agent(actor)
91
+ if (agent) tx.put('agent', actor, { ...agent, lastSeen: tx.now })
92
+ return { renewed: mine.map(t => t.id) }
93
+ }),
94
+
95
+ note: (id, actor, text) =>
96
+ transact(tx => {
97
+ const t = owned(tx, id, actor)
98
+ tx.put('task', t.id, { ...t, notes: [...t.notes, { at: stamp(tx), by: actor, text }], claim: { ...t.claim, expiresAt: lease(tx) } })
99
+ tx.event(actor, 'note', t.id)
100
+ seen(tx, actor)
101
+ return tx.task(t.id)
102
+ }),
103
+
104
+ release: (id, actor, handoff) =>
105
+ transact(tx => {
106
+ const t = owned(tx, id, actor)
107
+ const notes = handoff ? [...t.notes, { at: stamp(tx), by: actor, text: `HANDOFF: ${handoff}` }] : t.notes
108
+ tx.put('task', t.id, { ...t, status: 'todo', claim: null, notes })
109
+ tx.event(actor, 'release', t.id)
110
+ return tx.task(t.id)
111
+ }),
112
+
113
+ // Done means verified: the note says how, against the task's acceptance if it has one.
114
+ done: (id, actor, note) =>
115
+ transact(tx => {
116
+ const t = owned(tx, id, actor)
117
+ if (!note?.trim())
118
+ throw new BoardError(2, `done needs --note saying how you verified ${t.id}` + (t.accept ? ` against: ${t.accept}` : ''))
119
+ tx.put('task', t.id, { ...t, status: 'done', claim: null, notes: [...t.notes, { at: stamp(tx), by: actor, text: `VERIFIED: ${note}` }] })
120
+ tx.event(actor, 'done', t.id)
121
+ return tx.task(t.id)
122
+ }),
123
+
124
+ // Free everything this actor holds and give up its name, e.g. when its session ends.
125
+ releaseAll: (actor, { handoff, session } = {}) =>
126
+ transact(tx => {
127
+ const text = `HANDOFF: ${handoff ?? `${actor} ended without releasing; read the notes above`}`
128
+ const mine = tx.tasks().filter(t => t.claim?.owner === actor)
129
+ for (const t of mine) {
130
+ tx.put('task', t.id, { ...t, status: 'todo', claim: null, notes: [...t.notes, { at: stamp(tx), by: actor, text }] })
131
+ tx.event(actor, 'release', t.id)
132
+ }
133
+ const agent = tx.agent(actor)
134
+ if (agent && (!session || agent.session === session)) tx.put('agent', actor, null)
135
+ return { released: mine.map(t => t.id) }
136
+ }),
137
+
138
+ // Take or keep a name. Refused while another live session holds it, since two
139
+ // sessions under one name would share every claim.
140
+ register: (name, session) =>
141
+ transact(tx => {
142
+ const agent = tx.agent(name)
143
+ if (agent && agent.session !== session && tx.now - agent.lastSeen < presenceMs)
144
+ throw new BoardError(7, `the name ${name} is in use by another live session`)
145
+ tx.put('agent', name, { session, lastSeen: tx.now })
146
+ if (agent?.session !== session) tx.event(name, 'register', undefined, { session })
147
+ return { name }
148
+ }),
149
+
150
+ agents: () =>
151
+ transact(tx => Object.entries(tx.agentsLive(presenceMs)).map(([name, a]) => ({ name, lastSeen: new Date(a.lastSeen).toISOString() }))),
152
+
153
+ events: since => store.events(since),
154
+ doctor: () => store.verify(),
155
+ }
156
+ }
157
+
158
+ // Expiry is a real transition, written like any other, so every reader sees it.
159
+ // A claim ends when its lease runs out, or sooner when its owner registered a
160
+ // session and that session has gone silent (killed outright, so it never said
161
+ // goodbye): no presence ping for presenceMs. An owner that never registered
162
+ // (a plain CLI agent) keeps the lease alone.
163
+ function settle(snap, tx, presenceMs) {
164
+ for (const t of Object.values(snap.tasks)) {
165
+ if (t.status !== 'claimed') continue
166
+ const agent = snap.agents[t.claim.owner]
167
+ const silent = agent !== undefined && tx.now - agent.lastSeen >= presenceMs
168
+ if (!silent && Date.parse(t.claim.expiresAt) >= tx.now) continue
169
+ const why = silent ? `${t.claim.owner} stopped responding (its session went silent)` : `lease of ${t.claim.owner} expired`
170
+ const note = { at: new Date(tx.now).toISOString(), by: 'board', text: why }
171
+ tx.put('task', t.id, { ...t, status: 'todo', claim: null, notes: [...t.notes, note] })
172
+ tx.event('board', 'expire', t.id, silent ? { reason: 'silent' } : {})
173
+ }
174
+ }
175
+
176
+ function newTx(snap, now) {
177
+ const pending = new Map()
178
+ const current = (kind, key) => {
179
+ const write = pending.get(`${kind}:${key}`)
180
+ if (write) return write.value ?? undefined
181
+ return (kind === 'task' ? snap.tasks : snap.agents)[key]
182
+ }
183
+ return {
184
+ now,
185
+ events: [],
186
+ refusal: null,
187
+ get writes() {
188
+ return [...pending.values()]
189
+ },
190
+ // Each write carries the version this decision read, not a later one.
191
+ put(kind, key, value) {
192
+ const base = (kind === 'task' ? snap.tasks : snap.agents)[key]
193
+ pending.set(`${kind}:${key}`, { kind, key, value, expect: base?.version ?? 0 })
194
+ },
195
+ event(actor, type, task, extra = {}) {
196
+ this.events.push({ actor, type, task, ...extra })
197
+ },
198
+ task(id) {
199
+ const t = current('task', String(id).toUpperCase())
200
+ if (!t) throw new BoardError(4, `no task ${id}`)
201
+ return t
202
+ },
203
+ tasks() {
204
+ return Object.keys({ ...snap.tasks, ...Object.fromEntries([...pending.values()].filter(w => w.kind === 'task').map(w => [w.key, 1])) })
205
+ .map(id => current('task', id))
206
+ .filter(Boolean)
207
+ .sort((a, b) => a.id.localeCompare(b.id))
208
+ },
209
+ agent: name => current('agent', name),
210
+ agentsLive(presenceMs) {
211
+ return Object.fromEntries(Object.entries(snap.agents).filter(([, a]) => now - a.lastSeen < presenceMs))
212
+ },
213
+ nextNumber() {
214
+ return Math.max(0, ...Object.keys(snap.tasks).map(id => Number(id.replace(/\D/g, '')) || 0)) + 1
215
+ },
216
+ }
217
+ }