diff --git a/commands/conductor.js b/commands/conductor.js index 701a853..e3ed6d6 100644 --- a/commands/conductor.js +++ b/commands/conductor.js @@ -47,6 +47,7 @@ export function registerConductor(program) { console.log(dim(` governor: min_free_ram_mb ${values.governor.min_free_ram_mb}, max_docker_stacks ${values.governor.max_docker_stacks}`)); console.log(dim(` reaper: stack_idle_hours ${values.reaper.stack_idle_hours}`)); console.log(dim(` wip: max_lanes ${values.wip.max_lanes}; claims: ttl_minutes ${values.claims.ttl_minutes}`)); + console.log(dim(` inbox: stale_minutes ${values.inbox.stale_minutes}`)); } catch (e) { fail(e); } diff --git a/commands/init.js b/commands/init.js index 40b10cb..b6c677b 100644 --- a/commands/init.js +++ b/commands/init.js @@ -33,7 +33,7 @@ const COMMAND_TEMPLATES_DIR = path.join(__dirname, '..', 'templates', 'commands' * project that lists no repos gets the whole group. A name the group does not * know is an error, not a blank line — a blank line is exactly what hid this. */ -const SHIPPED_HOOKS = new Set(['precompact.sh', 'postcompact-restore.sh', 'stop.sh', 'context-cap.sh', 'handoff-spawn.sh']); +const SHIPPED_HOOKS = new Set(['precompact.sh', 'postcompact-restore.sh', 'stop.sh', 'context-cap.sh', 'handoff-spawn.sh', 'conductor-inbox.sh']); /** * Bring an existing .claude/settings.json's Bobby hooks up to date without @@ -66,6 +66,7 @@ export function migrateHookSettings(settingsPath) { }; ensure('SessionStart', 'compact', 'postcompact-restore.sh'); ensure('UserPromptSubmit', '', 'context-cap.sh'); + ensure('UserPromptSubmit', '', 'conductor-inbox.sh'); if (changed) fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf8'); return changed; diff --git a/lib/conductor/config.js b/lib/conductor/config.js index a9952c9..e0f7aaa 100644 --- a/lib/conductor/config.js +++ b/lib/conductor/config.js @@ -24,6 +24,8 @@ const INIT_REAPER = { stack_idle_hours: 2 }; // 30 minutes covers the gap between a lane pulling a ticket and its session showing the ID. const INIT_WIP = { max_lanes: 6 }; const INIT_CLAIMS = { ttl_minutes: 30 }; +// BOB-183: a message undelivered this long is flagged on `conductor status`. Chosen here, once. +const INIT_INBOX = { stale_minutes: 30 }; /** * Nearest ancestor of `startDir` whose .bobbyrc.yml carries a `studio:` key. @@ -72,7 +74,8 @@ function validateConfig(parsed, file) { const reaper = validateReaper(parsed.reaper, file); const wip = validatePositiveInt(parsed.wip, file, 'wip', 'max_lanes'); const claims = validatePositiveInt(parsed.claims, file, 'claims', 'ttl_minutes'); - return { projects: [...projects], hook_state_dir: dir, governor, reaper, wip, claims }; + const inbox = validateInbox(parsed.inbox, file); + return { projects: [...projects], hook_state_dir: dir, governor, reaper, wip, claims, inbox }; } // A section with one required positive-integer key: { : n }. @@ -85,6 +88,17 @@ function validatePositiveInt(section, file, name, key) { return { [key]: n }; } +function validateInbox(inbox, file) { + if (inbox === undefined || inbox === null) throw fail(file, 'inbox.stale_minutes', 'is missing'); + if (typeof inbox !== 'object' || Array.isArray(inbox)) throw fail(file, 'inbox', 'must be a mapping'); + if (!('stale_minutes' in inbox) || inbox.stale_minutes === null) throw fail(file, 'inbox.stale_minutes', 'is missing'); + const m = inbox.stale_minutes; + if (typeof m !== 'number' || !Number.isFinite(m) || m <= 0) { + throw fail(file, 'inbox.stale_minutes', 'must be a positive number of minutes'); + } + return { stale_minutes: m }; +} + function validateReaper(reaper, file) { if (reaper === undefined || reaper === null) throw fail(file, 'reaper.stack_idle_hours', 'is missing'); if (typeof reaper !== 'object' || Array.isArray(reaper)) throw fail(file, 'reaper', 'must be a mapping'); @@ -148,6 +162,7 @@ export function initConductorConfig(studioRoot, { projects } = {}) { reaper: { ...INIT_REAPER }, wip: { ...INIT_WIP }, claims: { ...INIT_CLAIMS }, + inbox: { ...INIT_INBOX }, }; const body = [ '# bobby conductor config. Written by `bobby conductor init`; every key is required.', @@ -159,6 +174,7 @@ export function initConductorConfig(studioRoot, { projects } = {}) { '# reaper.stack_idle_hours: `conductor reap --stacks` stops a ticket stack idle this long with no working lane (CC, 2026-11-08).', '# wip.max_lanes: `conductor next` refuses when this many live lane sessions (working or waiting on CC) exist (CC, 2026-11-08).', '# claims.ttl_minutes: a ticket `conductor next` handed out is not handed out again for this long.', + '# inbox.stale_minutes: `conductor status` flags a message undelivered this long (BOB-183).', YAML.stringify(values), ].join('\n'); fs.mkdirSync(path.dirname(file), { recursive: true }); diff --git a/lib/conductor/inbox.js b/lib/conductor/inbox.js index 2951a74..2b0a258 100644 --- a/lib/conductor/inbox.js +++ b/lib/conductor/inbox.js @@ -150,3 +150,43 @@ export function renderMessages(entries) { return entries.map(({ sessionId, message, index, unread }) => `${sessionId} #${index + 1} ${message.ts} from ${message.from}${unread ? ' [unread]' : ''}\n ${message.text.split('\n').join('\n ')}`).join('\n'); } + +/** + * Per-session undelivered messages for the status board, one entry per session that + * has a message file (sessions that are gone included). Read-only. A file that cannot + * be read (corrupt line, bad cursor) becomes an entry with `error` set, so one bad + * file is reported without hiding the rest of the board. + * + * `sessions` are classified lane records ({session_id, name, state}); a flagged entry + * is one whose oldest undelivered message is older than `staleMinutes`. + */ +export function inboxStatus(dir, sessions, { now = Date.now(), staleMinutes }) { + if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return { dir, missing: true, sessions: [] }; + if (!(staleMinutes > 0)) throw new Error('inboxStatus needs inbox.stale_minutes'); + const bySession = new Map(sessions.map(s => [s.session_id, s])); + const entries = []; + for (const sessionId of listInboxSessions(dir)) { + const lane = bySession.get(sessionId); + const base = { session_id: sessionId, name: lane ? lane.name : null, state: lane ? lane.state : null }; + let unread; + try { + unread = unreadMessages(dir, sessionId); + } catch (e) { + entries.push({ ...base, undelivered: null, oldest_age_ms: null, stale: false, flag: null, error: e.message }); + continue; + } + if (unread.length === 0) continue; + const times = unread.map(m => Date.parse(m.ts)); + if (times.some(Number.isNaN)) { + const bad = unread.find(m => Number.isNaN(Date.parse(m.ts))); + entries.push({ ...base, undelivered: null, oldest_age_ms: null, stale: false, flag: null, error: `message ${bad.id} has an unreadable ts "${bad.ts}"` }); + continue; + } + const oldest = Math.max(0, now - Math.min(...times)); + const stale = oldest > staleMinutes * 60000; + let flag = null; + if (stale) flag = base.state === 'blocked' ? 'waiting for CC to reply' : 'not delivered'; + entries.push({ ...base, undelivered: unread.length, oldest_age_ms: oldest, stale, flag, error: null }); + } + return { dir, missing: false, sessions: entries }; +} diff --git a/lib/conductor/status.js b/lib/conductor/status.js index fb3429c..6011284 100644 --- a/lib/conductor/status.js +++ b/lib/conductor/status.js @@ -10,6 +10,7 @@ import { boardCounts } from './board.js'; import { loadConductorConfig } from './config.js'; import { readMemory } from './resources.js'; import { readStacks, readStoppedStacks, boardTickets, mapStacks, mapStoppedStacks } from './stacks.js'; +import { inboxDir, inboxStatus } from './inbox.js'; import { bold, dim } from '../colors.js'; export function buildStatus(studioRoot, { run, now = Date.now() } = {}) { @@ -32,6 +33,7 @@ export function buildStatus(studioRoot, { run, now = Date.now() } = {}) { stopped: groups.stopped, unknown: groups.unknown, handoffs: sessions.filter(s => s.handed_off), + inbox: inboxStatus(inboxDir(studioRoot), sessions, { now, staleMinutes: config.inbox.stale_minutes }), board: boardCounts(studioRoot, config.projects), machine: { ...memory, min_free_ram_mb: config.governor.min_free_ram_mb }, stacks: { max: config.governor.max_docker_stacks, standalone_containers: docker.standalone_containers, list: stacks, stopped }, @@ -97,6 +99,21 @@ export function renderStatus(status) { } lines.push(''); + const inbox = status.inbox; + lines.push(`${bold('INBOX')} ${dim(`(${inbox.sessions.length} session${inbox.sessions.length === 1 ? '' : 's'} with undelivered messages)`)}`); + if (inbox.missing) lines.push(dim(` no inbox directory at ${shortPath(inbox.dir)}`)); + else if (inbox.sessions.length === 0) lines.push(dim(' none')); + for (const e of inbox.sessions) { + const who = `${e.session_id.slice(0, 8)} ${e.name || '(unnamed)'}`; + if (e.error) { + lines.push(` ${who} ${bold('unreadable inbox')} ${dim(e.error)}`); + continue; + } + const flag = e.flag ? ` ${bold(e.flag)}` : ''; + lines.push(` ${who} ${e.undelivered} undelivered ${dim(`oldest ${formatAge(e.oldest_age_ms)}`)}${flag}`); + } + lines.push(''); + lines.push(bold('BOARD')); for (const [project, b] of Object.entries(status.board)) { const counts = Object.entries(b.stages).filter(([, n]) => n > 0).map(([stage, n]) => `${stage} ${n}`); diff --git a/templates/hooks/conductor-inbox.sh b/templates/hooks/conductor-inbox.sh new file mode 100755 index 0000000..1aed980 --- /dev/null +++ b/templates/hooks/conductor-inbox.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# hooks/conductor-inbox.sh +# +# UserPromptSubmit hook. Delivers this session's file-inbox messages (written by +# `bobby conductor send`) at the start of the turn, as additionalContext, then moves +# the read cursor. It needs no cross-session channel, so it works in every permission mode. +# +# /.bobby/conductor/inbox/.jsonl one JSON message per line +# /.bobby/conductor/inbox/.cursor lines already delivered +# +# - No studio, no inbox file, an empty file, or nothing past the cursor: exit 0, print nothing. +# - A problem (bad hook input, a corrupt line, a cursor past the end, output that +# cannot be written) prints to stderr and exits 1. It never exits 2, so a failing +# hook reports itself without blocking the prompt. +# - The cursor moves only after the output was written and flushed. If the cursor +# write itself fails, the messages come again next turn rather than being lost. + +exec python3 -c ' +import sys, json, os, re + +def fail(msg): + sys.stderr.write("conductor-inbox: %s\n" % msg) + sys.exit(1) + +try: + hook = json.load(sys.stdin) + sid = hook["session_id"] +except Exception as e: + fail("no session_id in hook input: %s" % e) +if not isinstance(sid, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", sid): + fail("session_id %r is not a plain id" % (sid,)) + +def studio_root(start): + d = os.path.abspath(start) + while True: + rc = os.path.join(d, ".bobbyrc.yml") + if os.path.isfile(rc): + with open(rc, errors="ignore") as f: + if re.search(r"^studio\s*:", f.read(), re.M): + return d + parent = os.path.dirname(d) + if parent == d: + return None + d = parent + +root = None +for start in (os.environ.get("CLAUDE_PROJECT_DIR"), hook.get("cwd")): + if start: + root = studio_root(start) + if root: + break +if not root: + sys.exit(0) + +inbox = os.path.join(root, ".bobby", "conductor", "inbox") +mfile = os.path.join(inbox, sid + ".jsonl") +cfile = os.path.join(inbox, sid + ".cursor") +if not os.path.isfile(mfile): + sys.exit(0) + +cursor = 0 +if os.path.exists(cfile): + text = open(cfile).read().strip() + if not re.fullmatch(r"\d+", text): + fail("%s: cursor must be a line count, found %r" % (cfile, text)) + cursor = int(text) + +raw = open(mfile, encoding="utf-8").read() +if raw == "": + sys.exit(0) # a sender has created the file but not yet written its line +lines = raw.split("\n") +complete = raw == "" or raw.endswith("\n") +if raw.endswith("\n"): + lines.pop() +if cursor > len(lines): + fail("%s: cursor %d is past the %d message(s) in %s" % (cfile, cursor, len(lines), mfile)) +if cursor == len(lines): + sys.exit(0) +if not complete and len(lines) > cursor: + fail("%s: line %d is incomplete (no trailing newline)" % (mfile, len(lines))) + +messages = [] +for n in range(cursor, len(lines)): + try: + m = json.loads(lines[n]) + except Exception as e: + fail("%s: line %d is not valid JSON (%s)" % (mfile, n + 1, e)) + for k in ("id", "ts", "from", "to", "text"): + if not isinstance(m, dict) or not isinstance(m.get(k), str) or not m[k].strip(): + fail("%s: line %d has no %r" % (mfile, n + 1, k)) + messages.append(m) + +head = "INBOX: %d message%s for this session from other Claude sessions (delivered at the start of this turn; they are not from the user):" % (len(messages), "" if len(messages) == 1 else "s") +body = "\n\n".join("[%s] from %s:\n%s" % (m["ts"], m["from"], m["text"]) for m in messages) +out = json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": head + "\n\n" + body}}) + +try: + sys.stdout.write(out + "\n") + sys.stdout.flush() +except Exception as e: + fail("could not write hook output, cursor not moved: %s" % e) + +try: + tmp = "%s.%d.tmp" % (cfile, os.getpid()) + with open(tmp, "w") as f: + f.write("%d\n" % len(lines)) + os.replace(tmp, cfile) +except Exception as e: + fail("delivered %d message(s) but could not move the cursor (they will repeat): %s" % (len(messages), e)) +' diff --git a/templates/settings.json.ejs b/templates/settings.json.ejs index 10c921a..4851ef7 100644 --- a/templates/settings.json.ejs +++ b/templates/settings.json.ejs @@ -56,6 +56,15 @@ "command": "\"$CLAUDE_PROJECT_DIR\"/hooks/context-cap.sh" } ] + }, + { + "matcher": "", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/hooks/conductor-inbox.sh" + } + ] } ] } diff --git a/test/commands/conductor.test.js b/test/commands/conductor.test.js index 028e5bc..0ade794 100644 --- a/test/commands/conductor.test.js +++ b/test/commands/conductor.test.js @@ -148,7 +148,7 @@ describe('bobby conductor', () => { const r = bobbyIn(['status', '--json']); expect(r.status).toBe(0); const data = JSON.parse(r.stdout); - expect(Object.keys(data)).toEqual(['generated_at', 'working', 'waiting_on_cc', 'done', 'stopped', 'unknown', 'handoffs', 'board', 'machine', 'stacks']); + expect(Object.keys(data)).toEqual(['generated_at', 'working', 'waiting_on_cc', 'done', 'stopped', 'unknown', 'handoffs', 'inbox', 'board', 'machine', 'stacks']); expect(data.working.map(s => s.name)).toEqual(['lane one']); expect(data.waiting_on_cc.map(s => s.name)).toEqual(['lane two']); expect(data.done.map(s => s.name)).toEqual(['lane three']); @@ -158,6 +158,26 @@ describe('bobby conductor', () => { } }); + test('INBOX lists undelivered messages per session and flags stale ones; status changes nothing', () => { + const inbox = path.join(root, '.bobby', 'conductor', 'inbox'); + fs.mkdirSync(inbox, { recursive: true }); + const msg = (to, text, minutesAgo) => JSON.stringify({ id: text, ts: new Date(Date.now() - minutesAgo * 60000).toISOString(), from: 'orchestrator', to, text }); + fs.writeFileSync(path.join(inbox, 'aaaa1111-0000-4000-8000-000000000000.jsonl'), `${msg('aaaa1111-0000-4000-8000-000000000000', 'fresh', 2)}\n`); + fs.writeFileSync(path.join(inbox, 'bbbb2222-0000-4000-8000-000000000000.jsonl'), `${msg('bbbb2222-0000-4000-8000-000000000000', 'old', 120)}\n${msg('bbbb2222-0000-4000-8000-000000000000', 'older', 90)}\n`); + const before = fs.readdirSync(inbox).map(f => fs.readFileSync(path.join(inbox, f), 'utf8')); + const text = bobbyIn(['status']).stdout; + expect(text).toMatch(/INBOX.*2 sessions/); + expect(text).toMatch(/aaaa1111 lane one 1 undelivered oldest 2m\n/); + expect(text).toMatch(/bbbb2222 lane two 2 undelivered oldest 2h\s+waiting for CC to reply/); + const data = JSON.parse(bobbyIn(['status', '--json']).stdout); + expect(data.inbox.sessions.map(e => [e.name, e.undelivered, e.flag])).toEqual([['lane one', 1, null], ['lane two', 2, 'waiting for CC to reply']]); + expect(fs.readdirSync(inbox).map(f => fs.readFileSync(path.join(inbox, f), 'utf8'))).toEqual(before); + }); + + test('INBOX says so when the inbox directory does not exist', () => { + expect(bobbyIn(['status']).stdout).toMatch(/INBOX[\s\S]*no inbox directory at/); + }); + test('board counts per stage match `bobby ticket list` for the same project', () => { const data = JSON.parse(bobbyIn(['status', '--json']).stdout); for (const project of ['alpha', 'beta']) { diff --git a/test/hooks/conductor-inbox.test.js b/test/hooks/conductor-inbox.test.js new file mode 100644 index 0000000..d6358f4 --- /dev/null +++ b/test/hooks/conductor-inbox.test.js @@ -0,0 +1,194 @@ +// test/hooks/conductor-inbox.test.js: the UserPromptSubmit inbox hook (BOB-183). +// Runs the real templates/hooks/conductor-inbox.sh against a temp studio. +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { spawnSync } from 'child_process'; +import { fileURLToPath } from 'url'; + +const SCRIPT = fileURLToPath(new URL('../../templates/hooks/conductor-inbox.sh', import.meta.url)); +const SID = '11111111-2222-3333-4444-555555555555'; + +let studio; +let inbox; +beforeEach(() => { + studio = fs.mkdtempSync(path.join(os.tmpdir(), 'conductor-inbox-hook-')); + fs.writeFileSync(path.join(studio, '.bobbyrc.yml'), 'studio:\n name: test\n'); + inbox = path.join(studio, '.bobby', 'conductor', 'inbox'); + fs.mkdirSync(inbox, { recursive: true }); +}); +afterEach(() => { fs.rmSync(studio, { recursive: true, force: true }); }); + +const line = (text, extra = {}) => JSON.stringify({ id: `id-${text}`, ts: '2026-11-08T10:00:00.000Z', from: 'orchestrator', to: SID, text, ...extra }); +const writeInbox = (lines, sid = SID) => fs.writeFileSync(path.join(inbox, `${sid}.jsonl`), lines.map(l => `${l}\n`).join('')); +const cursorOf = (sid = SID) => { + const f = path.join(inbox, `${sid}.cursor`); + return fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : null; +}; + +function runHook({ input = { session_id: SID }, cwd = studio, env = {}, shell = null } = {}) { + const e = { ...process.env, CLAUDE_PROJECT_DIR: studio, ...env }; + if (shell) { + return spawnSync('bash', ['-c', shell], { cwd, input: JSON.stringify(input), encoding: 'utf8', env: { ...e, HOOK: SCRIPT } }); + } + return spawnSync('bash', [SCRIPT], { cwd, input: typeof input === 'string' ? input : JSON.stringify(input), encoding: 'utf8', env: e }); +} +const context = (r) => JSON.parse(r.stdout).hookSpecificOutput.additionalContext; + +describe('conductor-inbox hook', () => { + test('two unread lines are both emitted as additionalContext and the cursor moves to 2; a second run emits nothing', () => { + writeInbox([line('first thing'), line('second thing')]); + const r = runHook(); + expect(r.status).toBe(0); + expect(r.stderr).toBe(''); + const out = JSON.parse(r.stdout); + expect(out.hookSpecificOutput.hookEventName).toBe('UserPromptSubmit'); + const ctx = out.hookSpecificOutput.additionalContext; + expect(ctx).toMatch(/2 messages/); + expect(ctx).toContain('first thing'); + expect(ctx).toContain('second thing'); + expect(ctx).toContain('from orchestrator'); + expect(ctx.indexOf('first thing')).toBeLessThan(ctx.indexOf('second thing')); + expect(cursorOf()).toBe('2\n'); + + const again = runHook(); + expect(again.status).toBe(0); + expect(again.stdout).toBe(''); + expect(cursorOf()).toBe('2\n'); + }); + + test('only lines past the cursor are delivered, and a later message arrives alone', () => { + writeInbox([line('old'), line('new')]); + fs.writeFileSync(path.join(inbox, `${SID}.cursor`), '1\n'); + const r = runHook(); + expect(context(r)).toContain('new'); + expect(context(r)).not.toContain('old'); + expect(cursorOf()).toBe('2\n'); + fs.appendFileSync(path.join(inbox, `${SID}.jsonl`), `${line('later')}\n`); + const r2 = runHook(); + expect(context(r2)).toMatch(/1 message /); + expect(context(r2)).toContain('later'); + expect(cursorOf()).toBe('3\n'); + }); + + test('multi-line and quoted text survives intact; the message file is untouched', () => { + const text = 'line one\nline "two" \'q\' \\ end'; + writeInbox([line(text)]); + const before = fs.readFileSync(path.join(inbox, `${SID}.jsonl`), 'utf8'); + expect(context(runHook())).toContain(text); + expect(fs.readFileSync(path.join(inbox, `${SID}.jsonl`), 'utf8')).toBe(before); + }); + + test('another session\'s messages are not delivered', () => { + writeInbox([line('not yours', { to: 'other' })], 'other'); + const r = runHook(); + expect(r.status).toBe(0); + expect(r.stdout).toBe(''); + expect(cursorOf('other')).toBeNull(); + }); + + test('no inbox file: exit 0, no output, nothing written', () => { + const r = runHook(); + expect(r.status).toBe(0); + expect(r.stdout).toBe(''); + expect(r.stderr).toBe(''); + expect(fs.readdirSync(inbox)).toEqual([]); + }); + + test('an empty inbox file (a send between open and write) exits 0 with no output and no cursor', () => { + fs.writeFileSync(path.join(inbox, `${SID}.jsonl`), ''); + const r = runHook(); + expect(r.status).toBe(0); + expect(r.stdout).toBe(''); + expect(r.stderr).toBe(''); + expect(cursorOf()).toBeNull(); + }); + + test('no inbox directory or no studio at all: exit 0, no output', () => { + fs.rmSync(path.join(studio, '.bobby'), { recursive: true }); + expect(runHook().status).toBe(0); + fs.rmSync(path.join(studio, '.bobbyrc.yml')); + const r = runHook({ env: { CLAUDE_PROJECT_DIR: studio } }); + expect(r.status).toBe(0); + expect(r.stdout).toBe(''); + }); + + test('a session whose cwd is a worktree below the studio finds the studio inbox', () => { + const wt = path.join(studio, 'worktrees', 'X'); + fs.mkdirSync(wt, { recursive: true }); + writeInbox([line('hello')]); + const r = runHook({ cwd: wt, env: { CLAUDE_PROJECT_DIR: wt }, input: { session_id: SID, cwd: wt } }); + expect(context(r)).toContain('hello'); + }); + + test('a corrupt line exits 1 with its line number, delivers nothing and leaves the cursor', () => { + writeInbox([line('ok'), '{broken']); + fs.writeFileSync(path.join(inbox, `${SID}.cursor`), '0\n'); + const r = runHook(); + expect(r.status).toBe(1); + expect(r.stdout).toBe(''); + expect(r.stderr).toMatch(/conductor-inbox: .*line 2 is not valid JSON/); + expect(cursorOf()).toBe('0\n'); + }); + + test('a line missing a field exits 1 naming the line and field', () => { + writeInbox([line('ok', { from: '' })]); + const r = runHook(); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/line 1 has no 'from'/); + }); + + test('a corrupt line that was already delivered does not stop later messages', () => { + writeInbox(['{broken', line('fresh')]); + fs.writeFileSync(path.join(inbox, `${SID}.cursor`), '1\n'); + expect(context(runHook())).toContain('fresh'); + }); + + test('a cursor past the end of the file, or not a number, exits 1', () => { + writeInbox([line('one')]); + fs.writeFileSync(path.join(inbox, `${SID}.cursor`), '4\n'); + const past = runHook(); + expect(past.status).toBe(1); + expect(past.stderr).toMatch(/cursor 4 is past the 1 message/); + fs.writeFileSync(path.join(inbox, `${SID}.cursor`), 'x\n'); + const bad = runHook(); + expect(bad.status).toBe(1); + expect(bad.stderr).toMatch(/cursor must be a line count/); + }); + + test('a last line with no newline is an error, not a silent skip', () => { + fs.writeFileSync(path.join(inbox, `${SID}.jsonl`), line('cut off')); + const r = runHook(); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/incomplete/); + }); + + test('bad hook input exits 1 and says so; it never exits 2 (which would block the prompt)', () => { + for (const input of ['not json', '{}', JSON.stringify({ session_id: '../../etc/passwd' })]) { + const r = runHook({ input }); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/conductor-inbox:/); + } + }); + + test('the cursor is not advanced when the output cannot be written', () => { + writeInbox([line('one'), line('two')]); + const r = runHook({ shell: 'bash "$HOOK" >&-' }); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/could not write hook output, cursor not moved/); + expect(cursorOf()).toBeNull(); + // The messages are still there for the next turn. + const next = runHook(); + expect(context(next)).toContain('two'); + expect(cursorOf()).toBe('2\n'); + }); + + test('an empty inbox answers well inside the 200 ms budget', () => { + runHook(); // warm the interpreter + const runs = 5; + const start = process.hrtime.bigint(); + for (let i = 0; i < runs; i += 1) runHook(); + const avgMs = Number(process.hrtime.bigint() - start) / 1e6 / runs; + expect(avgMs).toBeLessThan(200); + }); +}); diff --git a/test/lib/compaction-hooks.test.js b/test/lib/compaction-hooks.test.js index e70ba80..e4fa94a 100644 --- a/test/lib/compaction-hooks.test.js +++ b/test/lib/compaction-hooks.test.js @@ -149,12 +149,39 @@ describe('session hooks are scaffolded and registered', () => { expect(s.hooks.UserPromptSubmit[0].hooks[0].command).toBe('"$CLAUDE_PROJECT_DIR"/hooks/context-cap.sh'); }); + test('conductor-inbox ships executable and is registered next to context-cap', () => { + scaffoldProject(tmp, base); + expect(fs.statSync(path.join(tmp, 'hooks', 'conductor-inbox.sh')).mode & 0o111).toBeTruthy(); + const s = JSON.parse(fs.readFileSync(path.join(tmp, '.claude', 'settings.json'), 'utf8')); + expect(s.hooks.UserPromptSubmit.flatMap(g => g.hooks.map(h => h.command))).toEqual([ + '"$CLAUDE_PROJECT_DIR"/hooks/context-cap.sh', + '"$CLAUDE_PROJECT_DIR"/hooks/conductor-inbox.sh', + ]); + }); + + test('upgrade adds conductor-inbox to a settings file that only has the context cap, keeping the rest', () => { + const p = path.join(tmp, 'settings.json'); + const own = { matcher: 'Bash', hooks: [{ type: 'command', command: 'echo mine' }] }; + fs.writeFileSync(p, JSON.stringify({ permissions: { allow: ['Bash(ls)'] }, hooks: { PreToolUse: [own], UserPromptSubmit: [ + { matcher: '', hooks: [{ type: 'command', command: '"$CLAUDE_PROJECT_DIR"/hooks/context-cap.sh' }] }, + ] } })); + expect(migrateHookSettings(p)).toBe(true); + const s = JSON.parse(fs.readFileSync(p, 'utf8')); + expect(s.permissions).toEqual({ allow: ['Bash(ls)'] }); + expect(s.hooks.PreToolUse).toEqual([own]); + expect(s.hooks.UserPromptSubmit.map(g => g.hooks[0].command)).toEqual([ + '"$CLAUDE_PROJECT_DIR"/hooks/context-cap.sh', + '"$CLAUDE_PROJECT_DIR"/hooks/conductor-inbox.sh', + ]); + expect(migrateHookSettings(p)).toBe(false); + }); + test('migrate adds the context cap to an old settings file once', () => { const p = path.join(tmp, 'settings.json'); fs.writeFileSync(p, JSON.stringify({ hooks: {} })); migrateHookSettings(p); const s = JSON.parse(fs.readFileSync(p, 'utf8')); - expect(s.hooks.UserPromptSubmit).toHaveLength(1); + expect(s.hooks.UserPromptSubmit).toHaveLength(2); expect(migrateHookSettings(p)).toBe(false); }); diff --git a/test/lib/conductor/config.test.js b/test/lib/conductor/config.test.js index 9832a37..bc76a34 100644 --- a/test/lib/conductor/config.test.js +++ b/test/lib/conductor/config.test.js @@ -23,6 +23,7 @@ describe('conductor config', () => { reaper: { stack_idle_hours: 2 }, wip: { max_lanes: 6 }, claims: { ttl_minutes: 30 }, + inbox: { stale_minutes: 30 }, }); }); @@ -55,6 +56,19 @@ describe('conductor config', () => { expect(() => loadConductorConfig(root)).toThrow(new RegExp(`key "${key.replace('.', '\\.')}"`)); }); + const wipYml = `${reaperYml}wip:\n max_lanes: 6\nclaims:\n ttl_minutes: 30\n`; + test.each([ + ['inbox.stale_minutes', wipYml], + ['inbox.stale_minutes', `${wipYml}inbox:\n other: 1\n`], + ['inbox.stale_minutes', `${wipYml}inbox:\n stale_minutes:\n`], + ['inbox.stale_minutes', `${wipYml}inbox:\n stale_minutes: 0\n`], + ['inbox.stale_minutes', `${wipYml}inbox:\n stale_minutes: soon\n`], + ['inbox', `${wipYml}inbox: 30\n`], + ])('a missing or invalid %s names the key', (key, yml) => { + writeConductorYml(root, yml); + expect(() => loadConductorConfig(root)).toThrow(new RegExp(`key "${key.replace('.', '\\.')}"`)); + }); + test.each([ ['projects', `hook_state_dir: /x\n`], ['hook_state_dir', `projects:\n - alpha\n`], @@ -95,12 +109,14 @@ describe('conductor config', () => { reaper: { stack_idle_hours: 2 }, wip: { max_lanes: 6 }, claims: { ttl_minutes: 30 }, + inbox: { stale_minutes: 30 }, }); expect(loadConductorConfig(root)).toEqual(values); expect(fs.readFileSync(file, 'utf8')).toMatch(/wip:\n {2}max_lanes: 6\n/); expect(fs.readFileSync(file, 'utf8')).toMatch(/claims:\n {2}ttl_minutes: 30\n/); expect(fs.readFileSync(file, 'utf8')).toMatch(/governor:\n {2}min_free_ram_mb: 4096\n {2}max_docker_stacks: 4\n/); expect(fs.readFileSync(file, 'utf8')).toMatch(/reaper:\n {2}stack_idle_hours: 2\n/); + expect(fs.readFileSync(file, 'utf8')).toMatch(/inbox:\n {2}stale_minutes: 30\n/); }); test('init without --projects writes every studio project explicitly', () => { diff --git a/test/lib/conductor/helpers.js b/test/lib/conductor/helpers.js index 6696f57..a9383e7 100644 --- a/test/lib/conductor/helpers.js +++ b/test/lib/conductor/helpers.js @@ -21,12 +21,13 @@ export function writeConductorYml(root, text) { fs.writeFileSync(path.join(root, '.bobby', 'conductor.yml'), text); } -export function validYml(hookDir, projects = ['alpha', 'beta'], governor = { min_free_ram_mb: 4096, max_docker_stacks: 4 }, reaper = { stack_idle_hours: 2 }, wip = { max_lanes: 6 }, claims = { ttl_minutes: 30 }) { +export function validYml(hookDir, projects = ['alpha', 'beta'], governor = { min_free_ram_mb: 4096, max_docker_stacks: 4 }, reaper = { stack_idle_hours: 2 }, wip = { max_lanes: 6 }, claims = { ttl_minutes: 30 }, inbox = { stale_minutes: 30 }) { return `projects:\n${projects.map(p => ` - ${p}`).join('\n')}\nhook_state_dir: ${hookDir}\n` + `governor:\n min_free_ram_mb: ${governor.min_free_ram_mb}\n max_docker_stacks: ${governor.max_docker_stacks}\n` + `reaper:\n stack_idle_hours: ${reaper.stack_idle_hours}\n` + `wip:\n max_lanes: ${wip.max_lanes}\n` - + `claims:\n ttl_minutes: ${claims.ttl_minutes}\n`; + + `claims:\n ttl_minutes: ${claims.ttl_minutes}\n` + + `inbox:\n stale_minutes: ${inbox.stale_minutes}\n`; } /** vm_stat text for a 16 KB-page machine. Pages are given in MB so tests read in MB. */ diff --git a/test/lib/conductor/inbox.test.js b/test/lib/conductor/inbox.test.js index 11d4db2..8e3614e 100644 --- a/test/lib/conductor/inbox.test.js +++ b/test/lib/conductor/inbox.test.js @@ -4,7 +4,7 @@ import os from 'os'; import path from 'path'; import { inboxDir, assertInboxDir, resolveRecipient, buildMessage, appendMessage, readMessages, - readCursor, writeCursor, unreadMessages, listInboxSessions, + readCursor, writeCursor, unreadMessages, listInboxSessions, inboxStatus, } from '../../../lib/conductor/inbox.js'; const SID = 'aaaa1111-0000-4000-8000-000000000000'; @@ -157,3 +157,80 @@ describe('the store', () => { expect(new Set(messages.map(m => m.id)).size).toBe(workers * 20); }); }); + +describe('inboxStatus', () => { + const NOW = Date.parse('2026-11-08T12:00:00.000Z'); + const minutesAgo = (m) => NOW - m * 60000; + const SID2 = 'bbbb2222-0000-4000-8000-000000000000'; + const SID3 = 'cccc3333-0000-4000-8000-000000000000'; + const sessions = [ + { session_id: SID, name: 'lane one', state: 'working' }, + { session_id: SID2, name: 'lane two', state: 'blocked' }, + { session_id: SID3, name: 'lane three', state: 'done' }, + ]; + let root; + let dir; + beforeEach(() => { ({ root, dir } = makeInbox()); }); + afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); + const put = (to, minutes, text = 'm') => appendMessage(dir, buildMessage({ from: 'o', to, text, now: minutesAgo(minutes) })); + const status = () => inboxStatus(dir, sessions, { now: NOW, staleMinutes: 30 }); + + test('counts undelivered messages and the age of the oldest, per session', () => { + put(SID, 5); + put(SID, 12); + put(SID2, 1); + const r = status(); + expect(r.missing).toBe(false); + expect(r.sessions.map(e => [e.session_id, e.name, e.undelivered, e.oldest_age_ms])).toEqual([ + [SID, 'lane one', 2, 12 * 60000], + [SID2, 'lane two', 1, 60000], + ]); + expect(r.sessions.every(e => !e.stale && e.flag === null)).toBe(true); + }); + + test('delivered messages are not counted; a fully delivered inbox is not listed', () => { + put(SID, 90); + put(SID, 10); + writeCursor(dir, SID, 1); + expect(status().sessions[0]).toMatchObject({ undelivered: 1, oldest_age_ms: 10 * 60000, stale: false }); + writeCursor(dir, SID, 2); + expect(status().sessions).toEqual([]); + }); + + test('older than stale_minutes: blocked is "waiting for CC to reply", working is "not delivered"; exactly the limit is not stale', () => { + put(SID, 31); + put(SID2, 45); + put(SID3, 600); + const flags = Object.fromEntries(status().sessions.map(e => [e.name, e.flag])); + expect(flags).toEqual({ 'lane one': 'not delivered', 'lane two': 'waiting for CC to reply', 'lane three': 'not delivered' }); + fs.rmSync(path.join(dir, `${SID}.jsonl`)); + put(SID, 30); + expect(status().sessions.find(e => e.session_id === SID).stale).toBe(false); + }); + + test('a session that is no longer listed is still reported, without a name', () => { + put('gone-session', 3); + expect(status().sessions[0]).toMatchObject({ session_id: 'gone-session', name: null, state: null, undelivered: 1 }); + }); + + test('an unreadable file is reported on its own entry and does not hide the others', () => { + put(SID, 5); + fs.writeFileSync(path.join(dir, `${SID2}.jsonl`), '{oops}\n'); + const r = status(); + expect(r.sessions.find(e => e.session_id === SID).undelivered).toBe(1); + expect(r.sessions.find(e => e.session_id === SID2)).toMatchObject({ undelivered: null, error: expect.stringMatching(/line 1 is not valid JSON/) }); + }); + + test('a message whose ts is not a date is an error entry, not a silent "not stale"', () => { + fs.writeFileSync(path.join(dir, `${SID}.jsonl`), `${JSON.stringify({ id: 'x1', ts: 'yesterday', from: 'o', to: SID, text: 'm' })}\n`); + expect(status().sessions[0]).toMatchObject({ undelivered: null, stale: false, error: expect.stringMatching(/x1 has an unreadable ts "yesterday"/) }); + }); + + test('a missing inbox directory is reported as missing, not as an empty board', () => { + expect(inboxStatus(path.join(root, 'nope'), sessions, { now: NOW, staleMinutes: 30 })).toMatchObject({ missing: true, sessions: [] }); + }); + + test('stale_minutes is required', () => { + expect(() => inboxStatus(dir, sessions, { now: NOW })).toThrow(/stale_minutes/); + }); +});