modboard 0.5.1 → 0.6.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.
@@ -1,9 +1,12 @@
1
1
  import { atom, read, update } from 'claude-code'
2
2
  import type { EngineInterface, Register } from 'claude-code'
3
3
 
4
- import type { Agent, Task } from '../types'
4
+ import type { Agent, Task, TaskFile } from '../types'
5
5
  import { BLOCKS, type BandForm, type Block, type Ctx } from './blocks'
6
6
  import { commandBlock, firstLine, parseCommandBlocks } from './blocks/command'
7
+ import { groupOpen, type GroupName } from './blocks/tasks'
8
+ import { tone } from './blocks/meter'
9
+ import { nextTier, openItems } from './blocks/taskfile'
7
10
 
8
11
  // The mod is an adapter: every board read and write goes through bin/board.mjs,
9
12
  // the same CLI Codex or a human runs, so it works whatever storage block holds
@@ -15,6 +18,8 @@ const PANE = 'modboard'
15
18
  const HEARTBEAT_MS = 60_000
16
19
  const PRESENCE_MS = 60_000
17
20
  const POLL_MS = 3_000
21
+ // Pane blocks that draw a bar; together they make one section.
22
+ const BARS = new Set(['compact', 'usage', 'context'])
18
23
  const COMMAND_MS = 30_000
19
24
  const NAME_TRIES = 9
20
25
 
@@ -25,6 +30,16 @@ const usage = atom({ plugin: 'modboard', key: 'usage' } as const, { limits: [] }
25
30
  const model = atom({ plugin: 'modboard', key: 'model' } as const, '')
26
31
  const effort = atom({ plugin: 'modboard', key: 'effort' } as const, '')
27
32
  const custom = atom({ plugin: 'modboard', key: 'custom' } as const, {} as Record<string, string>)
33
+ const taskfile = atom({ plugin: 'modboard', key: 'taskfile' } as const, { file: null, items: [] } as TaskFile)
34
+ const taskfileOpen = atom({ plugin: 'modboard', key: 'taskfileOpen' } as const, false)
35
+ // Whether the pane is open now: set when it is placed, cleared when it closes,
36
+ // by modBOARD on the band or by its own ✕.
37
+ const paneOpen = atom({ plugin: 'modboard', key: 'paneOpen' } as const, false)
38
+ const taskfileTier = atom({ plugin: 'modboard', key: 'taskfileTier' } as const, '')
39
+ const groupsOpen = atom({ plugin: 'modboard', key: 'groupsOpen' } as const, {} as Record<string, boolean>)
40
+ // Why the last read of the board failed, or '' when it worked: the pane would
41
+ // otherwise go on showing old tasks as if they were current.
42
+ const boardError = atom({ plugin: 'modboard', key: 'boardError' } as const, '')
28
43
 
29
44
  let session = ''
30
45
  let lastBeat = 0
@@ -38,14 +53,19 @@ async function board($: EngineInterface, args: string[]) {
38
53
  return cli($, [...args, '--as', await read($, me)])
39
54
  }
40
55
 
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.
56
+ // The board names the session by what it runs and when it joined ("claude 1",
57
+ // "claude 2"), unless BOARD_AGENT asks for a name: then that one, or the next
58
+ // free one after it.
59
+ async function joined($: EngineInterface) {
60
+ const out = await cli($, ['join', 'claude', '--session', session, '--json'])
61
+ try {
62
+ if (out.ok) return (JSON.parse(out.text) as { name: string }).name
63
+ } catch {}
64
+ return `claude:${session.slice(0, 8)}`
65
+ }
66
+
43
67
  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
- }
68
+ if (!wanted) return joined($)
49
69
  for (let i = 1; i <= NAME_TRIES; i++) {
50
70
  const name = i === 1 ? wanted : `${wanted}-${i}`
51
71
  const taken = await cli($, ['register', name, '--session', session])
@@ -55,18 +75,55 @@ async function takeName($: EngineInterface, wanted: string | undefined) {
55
75
  }
56
76
  if (taken.code !== 7) break
57
77
  }
58
- const name = `claude:${session.slice(0, 8)}`
78
+ const name = await joined($)
59
79
  $.ui.toast(`board: could not take the name "${wanted}", so this session is "${name}"`)
60
- await cli($, ['register', name, '--session', session])
61
80
  return name
62
81
  }
63
82
 
83
+ // The context window's fill before the session's first reply, when Claude Code
84
+ // has not measured it yet: its own local estimate, as /context makes, with no
85
+ // API call. Each reply's measurement (session.measure) replaces it.
86
+ async function estimateContext($: EngineInterface) {
87
+ if ((await read($, usage)).context !== undefined) return
88
+ try {
89
+ const now = await $.session.usage({ breakdown: 'summary' })
90
+ const percent = now.context.percent ?? now.context.breakdown?.percentage
91
+ if (percent !== undefined) await update($, usage, u => ({ ...u, context: percent }))
92
+ } catch {}
93
+ }
94
+
95
+ // Whether any shown block reads task.md; when none does, it is never read.
96
+ let readsTaskfile = false
97
+
98
+ // What went wrong, in one line: the board's own message, or the error line of
99
+ // a crash ("EACCES: permission denied, open '…/board.json'"), not its stack.
100
+ function reason(text: string) {
101
+ const lines = text.split('\n').map(l => l.trim())
102
+ const line = lines.find(l => /^board:/.test(l)) ?? lines.find(l => /^\w*Error\b/.test(l)) ?? lines.find(Boolean) ?? ''
103
+ return line.replace(/^board:\s*/, '').replace(/^\w*Error:\s*/, '')
104
+ }
105
+
64
106
  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)
107
+ let problem = ''
108
+ try {
109
+ const out = await cli($, ['view', '--json'])
110
+ if (out.ok) {
111
+ const view = JSON.parse(out.text) as { tasks: Task[]; agents: Agent[] }
112
+ await update($, tasks, () => view.tasks)
113
+ await update($, agents, () => view.agents)
114
+ } else problem = reason(out.text) || `the board CLI exited with ${out.code}`
115
+ } catch {
116
+ problem = 'the board CLI could not run (is node on PATH?)'
117
+ }
118
+ if ((await read($, boardError)) !== problem) await update($, boardError, () => problem)
119
+ if (readsTaskfile) {
120
+ const file = await cli($, ['taskfile', '--json'])
121
+ let parsed: TaskFile | undefined
122
+ try {
123
+ parsed = file.ok ? (JSON.parse(file.text) as TaskFile) : undefined
124
+ } catch {}
125
+ if (parsed) await update($, taskfile, () => parsed!)
126
+ }
70
127
  }
71
128
 
72
129
  const TOOLS = [
@@ -114,7 +171,7 @@ const TOOLS = [
114
171
  {
115
172
  name: 'board_release',
116
173
  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.',
174
+ 'Give up a task you hold without finishing it. Always write a handoff: what is done, what is left, where to look, each part separated by a semicolon ("done X; left Y; see Z") — the next agent starts from it.',
118
175
  schema: { id: { type: 'string' }, handoff: { type: 'string' } },
119
176
  required: ['id', 'handoff'],
120
177
  args: (i: any) => ['release', i.id, '--handoff', i.handoff],
@@ -189,6 +246,18 @@ function after(cycle: string[], current: string) {
189
246
 
190
247
  // Switch the way the person would, through Claude Code's own commands, so
191
248
  // everything else in the session sees the change.
249
+ // Open the /board pane, fresh: the board and the task file read again first.
250
+ // Ask for room for the whole board; the surface may give less, and the pane's
251
+ // body scrolls with the wheel when it does.
252
+
253
+ async function openBoard($: EngineInterface) {
254
+ await refresh($)
255
+ await estimateContext($)
256
+ const opened = await $.ui.open({ id: PANE, title: 'modboard', rows: 30 })
257
+ if (opened.isPlaced) await update($, paneOpen, () => true)
258
+ return opened
259
+ }
260
+
192
261
  function actions($: EngineInterface, cycles: { models: string[]; efforts: string[] }): Ctx['act'] {
193
262
  return {
194
263
  nextModel: async () => {
@@ -202,6 +271,45 @@ function actions($: EngineInterface, cycles: { models: string[]; efforts: string
202
271
  await $.command.run({ command: 'effort', args: to }).catch(() => $.ui.toast(`board: could not set effort to ${to}`))
203
272
  await update($, effort, () => to)
204
273
  },
274
+ // modBOARD on the band: opens the pane, or closes it when it is already open.
275
+ openBoard: async () => {
276
+ if (!(await read($, paneOpen))) return void (await openBoard($))
277
+ await $.ui.close({ id: PANE }).catch(() => {})
278
+ await update($, paneOpen, () => false)
279
+ },
280
+ // A task's box on the band. With the pane closed, it opens the pane at
281
+ // the group that holds the task, unfolded, so the task and its note are
282
+ // in view. With the pane open, it folds or unfolds that group, and the
283
+ // pane stays open: modBOARD is what closes it.
284
+ showGroup: async (name: string) => {
285
+ if (!(await read($, paneOpen))) {
286
+ await update($, groupsOpen, chosen => ({ ...chosen, [name]: true }))
287
+ return void (await openBoard($))
288
+ }
289
+ await update($, groupsOpen, chosen => ({ ...chosen, [name]: !groupOpen(chosen, name as GroupName) }))
290
+ },
291
+ // The same call /compact makes. Claude Code refuses it while a turn runs.
292
+ compact: async () => {
293
+ $.ui.toast('board: compacting the conversation…')
294
+ await $.session.compact().catch(() => $.ui.toast("board: can't compact while Claude is working; press again when it's idle"))
295
+ },
296
+ toggleGroup: async (name: string) => {
297
+ await update($, groupsOpen, chosen => ({ ...chosen, [name]: !groupOpen(chosen, name as GroupName) }))
298
+ },
299
+ // A press reads the file again first, so what was just added is there.
300
+ toggleTaskfile: async () => {
301
+ await refresh($)
302
+ await update($, taskfileOpen, open => !open)
303
+ },
304
+ // Turn to the next priority the file has, wrapping through "all", and
305
+ // show it: like effort, one press, one step.
306
+ nextTier: async () => {
307
+ await refresh($)
308
+ const items = openItems((await read($, taskfile)).items)
309
+ const to = nextTier(items, await read($, taskfileTier))
310
+ await update($, taskfileTier, () => to)
311
+ await update($, taskfileOpen, () => true)
312
+ },
205
313
  }
206
314
  }
207
315
 
@@ -217,6 +325,10 @@ async function context($: EngineInterface, width: number, ui: Ctx['ui'], act: Ct
217
325
  model: await read($, model),
218
326
  effort: await read($, effort),
219
327
  custom: await read($, custom),
328
+ taskfile: await read($, taskfile),
329
+ taskfileOpen: await read($, taskfileOpen),
330
+ taskfileTier: await read($, taskfileTier),
331
+ groupsOpen: await read($, groupsOpen),
220
332
  act,
221
333
  }
222
334
  }
@@ -224,8 +336,9 @@ async function context($: EngineInterface, width: number, ui: Ctx['ui'], act: Ct
224
336
  export const register: Register = (on, options) => {
225
337
  const { commands, problems } = parseCommandBlocks(options.blocks, BLOCKS.map(b => b.name))
226
338
  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)
339
+ const band = pick(all, options.band, 'summary,model,effort,board').filter(b => b.band)
340
+ const pane = pick(all, options.pane, 'tasks,taskfile,compact,usage').filter(b => b.pane)
341
+ readsTaskfile = [...band, ...pane].some(b => b.name === 'taskfile')
229
342
  const cycles = { models: list(options.models, 'opus,sonnet,haiku'), efforts: list(options.efforts, 'low,medium,high,xhigh,max') }
230
343
 
231
344
  on('session.start', async ($, e, next) => {
@@ -255,6 +368,7 @@ export const register: Register = (on, options) => {
255
368
  isDeferred: false,
256
369
  })
257
370
  await $.command.register({ name: 'board', description: 'Open the modboard pane' })
371
+ await estimateContext($)
258
372
 
259
373
  await refresh($)
260
374
  $.clock.every(POLL_MS, () => refresh($).catch(() => {}))
@@ -319,26 +433,46 @@ export const register: Register = (on, options) => {
319
433
  }).catch(($, e, next) => next(e))
320
434
 
321
435
  on('command.run', { command: 'board' }, async $ => {
322
- await refresh($)
323
- const opened = await $.ui.open({ id: PANE, title: 'modboard' })
436
+ const opened = await openBoard($)
324
437
  if (opened.isPlaced) return { text: 'Board pane opened.' }
325
438
  const list = (await read($, tasks)).filter(t => t.status !== 'done')
326
439
  return { text: list.map(t => `${SYMBOL[t.status]} ${t.id} ${t.title}${t.claim ? ` ${t.claim.owner}` : ''}`).join('\n') || '(no open tasks)' }
327
440
  })
328
441
 
442
+ // The pane's own ✕ closes it too.
443
+ on('ui.close', async ($, e, next) => {
444
+ const result = await next(e)
445
+ if (e.id === PANE && (result as any)?.deny === undefined) await update($, paneOpen, () => false)
446
+ return result
447
+ })
448
+
329
449
  // The band: one line above the prompt, quiet when no block has anything to say.
330
450
  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
331
451
  if (e.props.hasSurvey || !band.length) return next(e)
332
452
  const { Box, Text, Button } = $.ui.resolve(e)
333
453
  const c = await context($, e.props.bodyColumns, { Box, Text, Button }, actions($, cycles))
334
454
  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)
455
+ // A part at the line's end is placed last but kept second only to the
456
+ // first block: on a short line, the parts between it and the first go first.
457
+ const ranked = offered.map((forms, at) => ({ forms, at })).sort((x, y) => (x.at === 0 ? -1 : y.at === 0 ? 1 : Number(!!y.forms[0]!.end) - Number(!!x.forms[0]!.end)))
458
+ const kept = fit(ranked.map(r => r.forms), e.props.bodyColumns - CONTROL)
459
+ const parts = kept.map((part, i) => ({ part, at: ranked[i]!.at })).sort((x, y) => x.at - y.at).map(r => r.part)
336
460
  if (!parts.length) return next(e)
461
+ // A part marked `end` takes the room left over and sits at its right edge.
462
+ // Claude Code keeps its [-] outside bodyColumns, so the line may run its
463
+ // full width: the end part then sits a space from the [-].
464
+ const ends = parts.some(part => part.end)
337
465
  return (
338
- <Box gap={GAP} flexWrap="nowrap">
339
- {parts.map(part => (
340
- <Box flexShrink={0}>{part.tree}</Box>
341
- ))}
466
+ <Box gap={GAP} flexWrap="nowrap" width={ends ? e.props.bodyColumns : undefined}>
467
+ {parts.map(part =>
468
+ part.end ? (
469
+ <Box flexGrow={1} flexShrink={0} justifyContent="flex-end">
470
+ {part.tree}
471
+ </Box>
472
+ ) : (
473
+ <Box flexShrink={0}>{part.tree}</Box>
474
+ ),
475
+ )}
342
476
  </Box>
343
477
  )
344
478
  })
@@ -346,10 +480,66 @@ export const register: Register = (on, options) => {
346
480
  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
347
481
  const { Box, Text, Button } = $.ui.resolve(e)
348
482
  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)
483
+ const parts = pane.map(b => ({ block: b, part: b.pane!(c) })).filter(p => p.part !== null)
484
+ // Sections, in order: each block on its own, except that bars side by
485
+ // side (context, the 5-hour limit) make one, under a Limits heading.
486
+ const sections: (typeof parts)[] = []
487
+ for (const p of parts) {
488
+ const last = sections.at(-1)
489
+ if (last && BARS.has(p.block.name) && BARS.has(last[0]!.block.name)) last.push(p)
490
+ else sections.push([p])
491
+ }
492
+ const limits = (bars: typeof parts) => {
493
+ const open = groupOpen(c.groupsOpen, 'limits')
494
+ // Folded, the heading keeps the figures, each in its bar's colour.
495
+ const seen = new Set<string>()
496
+ const brief = bars
497
+ .flatMap(b => b.block.brief?.(c) ?? [])
498
+ .filter(f => !seen.has(f.name) && seen.add(f.name))
499
+ return (
500
+ <Box flexDirection="column">
501
+ <Box>
502
+ <Button key="group-limits" plain onPress={() => c.act.toggleGroup('limits')}>
503
+ <Text bold>{`${open ? '▾' : '▸'} Limits`}</Text>
504
+ </Button>
505
+ {!open &&
506
+ brief.flatMap(f => [
507
+ <Text dimColor> · </Text>,
508
+ <Text color={tone(f.percent)} dimColor={!tone(f.percent)}>{`${f.name} ${Math.round(f.percent)}%`}</Text>,
509
+ ])}
510
+ </Box>
511
+ {open && (
512
+ <Box flexDirection="column" marginTop={1} paddingLeft={2}>
513
+ {bars.map((b, i) => (i ? <Box marginTop={1}>{b.part}</Box> : b.part))}
514
+ </Box>
515
+ )}
516
+ </Box>
517
+ )
518
+ }
519
+ const body = (section: typeof parts) => (BARS.has(section[0]!.block.name) ? limits(section) : section[0]!.part)
520
+ // A grey rule between sections.
521
+ const rule = '─'.repeat(Math.max(1, (e.props.bodyColumns ?? 40) - 2))
522
+ const problem = await read($, boardError)
350
523
  return (
351
- <Box flexDirection="column" gap={1} paddingX={1}>
352
- {parts}
524
+ <Box flexDirection="column" paddingX={1}>
525
+ {/* First, in red, when the board stopped answering: what is below is old. */}
526
+ {problem ? (
527
+ <Box marginBottom={1}>
528
+ <Text color="error" wrap="truncate">{`board not updating: ${problem}`}</Text>
529
+ </Box>
530
+ ) : null}
531
+ {sections.map((section, i) =>
532
+ i === 0 ? (
533
+ body(section)
534
+ ) : (
535
+ <Box flexDirection="column" marginTop={1}>
536
+ <Box marginBottom={1}>
537
+ <Text dimColor>{rule}</Text>
538
+ </Box>
539
+ {body(section)}
540
+ </Box>
541
+ ),
542
+ )}
353
543
  </Box>
354
544
  )
355
545
  })
package/lib/contract.mjs CHANGED
@@ -51,6 +51,18 @@ export function storeContract(name, make) {
51
51
  assert.deepEqual((await board.agents()).map(a => a.name), ['frontend'])
52
52
  })
53
53
 
54
+ test('join names a session by what it runs and when it joined, and gives a free number again', async () => {
55
+ const board = createEngine(make())
56
+ assert.equal((await board.join('claude', 'session-a')).name, 'claude 1')
57
+ assert.equal((await board.join('claude', 'session-b')).name, 'claude 2')
58
+ assert.equal((await board.join('codex', 'thread-a', { presence: false })).name, 'codex 1')
59
+ // A session that joined before keeps its name.
60
+ assert.equal((await board.join('claude', 'session-a')).name, 'claude 1')
61
+ await board.releaseAll('claude 1', { session: 'session-a' })
62
+ assert.equal((await board.join('claude', 'session-c')).name, 'claude 1')
63
+ assert.equal((await board.join('claude', 'session-d')).name, 'claude 3')
64
+ })
65
+
54
66
  test('a name whose session went silent can be taken over', async () => {
55
67
  const board = createEngine(make(), { presenceMs: 50 })
56
68
  await board.register('frontend', 'session-a')
package/lib/engine.mjs CHANGED
@@ -147,6 +147,26 @@ export function createEngine(store, { leaseMs = 15 * 60 * 1000, presenceMs = 3 *
147
147
  return { name }
148
148
  }),
149
149
 
150
+ // Name a session by what it runs and when it joined: "claude 1", then
151
+ // "claude 2". A session that joined before keeps its name; otherwise it
152
+ // gets the lowest number no session still holds. A held name belongs to a
153
+ // live session, or to one with a claim. A session with no presence ping
154
+ // (Codex, through the CLI) holds its name while it works the board, so
155
+ // only its leases end its claims, never silence.
156
+ join: (kind, session, { presence = true } = {}) =>
157
+ transact(tx => {
158
+ const all = tx.agentsAll()
159
+ const mine = Object.entries(all).find(([, a]) => a.session === session)?.[0]
160
+ const claimed = new Set(tx.tasks().filter(t => t.status === 'claimed').map(t => t.claim.owner))
161
+ const held = (name, a) => claimed.has(name) || tx.now - a.lastSeen < (a.presence === false ? leaseMs : presenceMs)
162
+ let name = mine
163
+ for (let n = 1; !name; n++) if (!all[`${kind} ${n}`] || !held(`${kind} ${n}`, all[`${kind} ${n}`])) name = `${kind} ${n}`
164
+ const agent = tx.agent(name)
165
+ tx.put('agent', name, { session, lastSeen: tx.now, ...(presence ? {} : { presence: false }) })
166
+ if (agent?.session !== session) tx.event(name, 'register', undefined, { session })
167
+ return { name }
168
+ }),
169
+
150
170
  agents: () =>
151
171
  transact(tx => Object.entries(tx.agentsLive(presenceMs)).map(([name, a]) => ({ name, lastSeen: new Date(a.lastSeen).toISOString() }))),
152
172
 
@@ -164,7 +184,7 @@ function settle(snap, tx, presenceMs) {
164
184
  for (const t of Object.values(snap.tasks)) {
165
185
  if (t.status !== 'claimed') continue
166
186
  const agent = snap.agents[t.claim.owner]
167
- const silent = agent !== undefined && tx.now - agent.lastSeen >= presenceMs
187
+ const silent = agent !== undefined && agent.presence !== false && tx.now - agent.lastSeen >= presenceMs
168
188
  if (!silent && Date.parse(t.claim.expiresAt) >= tx.now) continue
169
189
  const why = silent ? `${t.claim.owner} stopped responding (its session went silent)` : `lease of ${t.claim.owner} expired`
170
190
  const note = { at: new Date(tx.now).toISOString(), by: 'board', text: why }
@@ -207,6 +227,7 @@ function newTx(snap, now) {
207
227
  .sort((a, b) => a.id.localeCompare(b.id))
208
228
  },
209
229
  agent: name => current('agent', name),
230
+ agentsAll: () => ({ ...snap.agents, ...Object.fromEntries([...pending.values()].filter(w => w.kind === 'agent').map(w => [w.key, w.value]).filter(([, v]) => v)) }),
210
231
  agentsLive(presenceMs) {
211
232
  return Object.fromEntries(Object.entries(snap.agents).filter(([, a]) => now - a.lastSeen < presenceMs))
212
233
  },
@@ -0,0 +1,151 @@
1
+ // A project's own task file, read for display. It is not the board: nothing
2
+ // in it can be claimed, and the board never writes it. `board taskfile`
3
+ // prints it, and the mod's taskfile block shows it in the /board pane.
4
+ //
5
+ // What it reads:
6
+ // headings become sections. A heading that names a priority
7
+ // ("## P0 — foundation", "## Sync (P1)") gives it to every
8
+ // item under it, down to the next heading at its level.
9
+ // list items "- ", "* ", "+ ", "1. ", with "[ ]" / "[x]" for done. An
10
+ // item may lead with its own priority ("- [ ] P2 Benchmarks"),
11
+ // which wins over its heading's. Struck through
12
+ // ("~~old idea~~") counts as done.
13
+ // tables any table with a task column and a priority or status
14
+ // column, one item per row; a status of done, complete or ✅
15
+ // counts as checked off.
16
+ // Everything else (prose, code blocks, other tables) is left out. And when a
17
+ // file marks any item done or not (a checkbox, a status), its plain bullets
18
+ // are notes, not tasks, and are left out too.
19
+
20
+ import fs from 'node:fs'
21
+ import path from 'node:path'
22
+
23
+ export const NAMES = ['task.md', 'tasks.md', 'todo.md']
24
+ // Where a task file is looked for, in order, from the project's root.
25
+ export const PLACES = ['.', 'docs']
26
+
27
+ // The first of NAMES in the first of PLACES that has one, matched without
28
+ // regard to case, or null.
29
+ export function findTaskFile(root) {
30
+ for (const place of PLACES) {
31
+ const dir = path.join(root, place)
32
+ let entries
33
+ try {
34
+ entries = fs.readdirSync(dir)
35
+ } catch {
36
+ continue
37
+ }
38
+ for (const name of NAMES) {
39
+ const hit = entries.find(e => e.toLowerCase() === name)
40
+ // A broken link or an unreadable entry is no task file, not an error.
41
+ if (hit && fs.statSync(path.join(dir, hit), { throwIfNoEntry: false })?.isFile()) return path.join(dir, hit)
42
+ }
43
+ }
44
+ return null
45
+ }
46
+
47
+ const HEADING = /^(#{1,6})\s+(.+?)\s*#*\s*$/
48
+ const ITEM = /^(\s*)(?:[-*+]|\d+[.)])\s+(?:\[([ xX])\]\s+)?(.+?)\s*$/
49
+ const FENCE = /^\s*(```|~~~)/
50
+ const ROW = /^\s*\|(.*)\|\s*$/
51
+ const RULE = /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/
52
+ // A priority named in a heading: P0 to P9, standing alone.
53
+ const NAMED = /(?:^|[\s(\[—–-])P(\d)(?=$|[\s)\]:—–,-])/
54
+ // A priority leading an item: "P2 Benchmarks", "P1: Sync", "[P0] Fix".
55
+ const LEADING = /^\[?P(\d)\]?[:\s]\s*/
56
+ // Status marks and a trailing "complete" on a heading, which say nothing the
57
+ // items under it do not.
58
+ const MARKS = /[✅⬜⬛\u{1F7E0}-\u{1F7EB}\u{1F534}\u{1F535}❌✔️⬅➡]/gu
59
+ const DONE = /^(done|complete|completed|closed|shipped|x|\[x\])$|✅|✔/i
60
+
61
+ // Markdown's marks, taken off for display: **bold**, _em_, `code`,
62
+ // [links](url), ~~struck~~. The words stay.
63
+ const plain = text =>
64
+ text
65
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
66
+ .replace(/(\*\*|__|~~|`)/g, '')
67
+ .replace(MARKS, '')
68
+ .replace(/(^|\s)[*_]([^*_]+)[*_](?=\s|$|[.,;:])/g, '$1$2')
69
+ .trim()
70
+
71
+ const priorityIn = text => {
72
+ const m = NAMED.exec(text)
73
+ return m ? Number(m[1]) : null
74
+ }
75
+
76
+ const cells = line => ROW.exec(line)[1].split('|').map(c => c.trim())
77
+ const column = (header, pattern) => header.findIndex(h => pattern.test(h))
78
+
79
+ export function parseTaskFile(text) {
80
+ const lines = text.split(/\r?\n/)
81
+ const items = []
82
+ let section = ''
83
+ // Headings still in force: their level and the priority each gives.
84
+ let open = []
85
+ const inherited = () => open.findLast(h => h.priority !== null)?.priority ?? null
86
+ let fenced = false
87
+
88
+ for (let n = 0; n < lines.length; n++) {
89
+ const line = lines[n]
90
+ if (FENCE.test(line)) {
91
+ fenced = !fenced
92
+ continue
93
+ }
94
+ if (fenced) continue
95
+
96
+ const h = HEADING.exec(line)
97
+ if (h) {
98
+ const level = h[1].length
99
+ section = h[2].replace(MARKS, '').replace(/\s+complete\s*$/i, '').replace(/\s+/g, ' ').trim()
100
+ open = [...open.filter(o => o.level < level), { level, priority: priorityIn(h[2]) }]
101
+ continue
102
+ }
103
+
104
+ // A table: a header row, then a rule row.
105
+ if (ROW.test(line) && n + 1 < lines.length && RULE.test(lines[n + 1])) {
106
+ const header = cells(line)
107
+ const task = column(header, /^(task|title|item|todo|what)$/i)
108
+ const prio = column(header, /^(priority|prio|p)$/i)
109
+ const status = column(header, /^(status|state|done)$/i)
110
+ n++
111
+ if (task < 0 || (prio < 0 && status < 0)) {
112
+ while (n + 1 < lines.length && ROW.test(lines[n + 1])) n++
113
+ continue
114
+ }
115
+ while (n + 1 < lines.length && ROW.test(lines[n + 1])) {
116
+ const row = cells(lines[++n])
117
+ if (!row[task]) continue
118
+ const p = prio >= 0 ? /P?(\d)/i.exec(row[prio] ?? '') : null
119
+ items.push({
120
+ text: plain(row[task]),
121
+ done: status >= 0 ? DONE.test(row[status] ?? '') : null,
122
+ section,
123
+ depth: 0,
124
+ priority: p ? Number(p[1]) : inherited(),
125
+ })
126
+ }
127
+ continue
128
+ }
129
+
130
+ const m = ITEM.exec(line)
131
+ if (!m) continue
132
+ const lead = LEADING.exec(m[3])
133
+ const text = lead ? m[3].slice(lead[0].length) : m[3]
134
+ items.push({
135
+ text: plain(text),
136
+ done: text.startsWith('~~') ? true : m[2] === undefined ? null : m[2] !== ' ',
137
+ section,
138
+ depth: Math.floor(m[1].replace(/\t/g, ' ').length / 2),
139
+ priority: lead ? Number(lead[1]) : inherited(),
140
+ })
141
+ }
142
+ return items.some(i => i.done !== null) ? items.filter(i => i.done !== null) : items
143
+ }
144
+
145
+ // { file, items } for the task file under `root`, or { file: null, items: [] }.
146
+ // `file` is its path from the root: "TASKS.md", "docs/TASKS.md".
147
+ export function readTaskFile(root) {
148
+ const file = findTaskFile(root)
149
+ if (!file) return { file: null, items: [] }
150
+ return { file: path.relative(root, file), items: parseTaskFile(fs.readFileSync(file, 'utf8')) }
151
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "modboard",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "A task board several coding agents share, through one CLI",
5
5
  "type": "module",
6
6
  "bin": { "board": "bin/board.mjs" },
@@ -11,7 +11,7 @@
11
11
  "./examples/store-memory.mjs": "./examples/store-memory.mjs",
12
12
  "./package.json": "./package.json"
13
13
  },
14
- "files": ["bin/", "lib/", "examples/", "hooks/", "types/", ".claude-plugin/plugin.json", "tsconfig.json", "README.md", "CHANGELOG.md", "LICENSE"],
14
+ "files": ["bin/", "lib/", "examples/", "hooks/", "types/", ".claude-plugin/plugin.json", "tsconfig.json", "README.md", "CHANGELOG.md", "ROADMAP.md", "LICENSE"],
15
15
  "scripts": {
16
16
  "test": "node --test test/*.test.mjs",
17
17
  "test:mod": "claude plugin test .",
package/types/index.d.ts CHANGED
@@ -8,6 +8,13 @@ export type Task = {
8
8
  notes: { at: string; by: string; text: string }[]
9
9
  }
10
10
 
11
+ // A project's task file, read for display (lib/taskfile.mjs). `done` is null
12
+ // for a plain bullet with no checkbox; `priority` is 0 for P0, null for none.
13
+ export type TaskFile = {
14
+ file: string | null
15
+ items: { text: string; done: boolean | null; section: string; depth: number; priority: number | null }[]
16
+ }
17
+
11
18
  export type Agent = { name: string; lastSeen: string }
12
19
 
13
20
  export type Usage = {
@@ -18,6 +25,6 @@ export type Usage = {
18
25
 
19
26
  declare module 'claude-code' {
20
27
  interface PluginState {
21
- modboard: { tasks: Task[]; agents: Agent[]; me: string; usage: Usage; model: string; effort: string; custom: Record<string, string> }
28
+ modboard: { tasks: Task[]; agents: Agent[]; me: string; usage: Usage; model: string; effort: string; custom: Record<string, string>; taskfile: TaskFile; taskfileOpen: boolean; taskfileTier: string; paneOpen: boolean; groupsOpen: Record<string, boolean>; boardError: string }
22
29
  }
23
30
  }