Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions commands/conductor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
3 changes: 2 additions & 1 deletion commands/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
import fs from 'fs';
import path from 'path';
import inquirer from 'inquirer';
import { writeConfig, writeConfigCommented, readConfig, configExists } from '../lib/config.js';

Check warning on line 5 in commands/init.js

View workflow job for this annotation

GitHub Actions / test (22)

'writeConfig' is defined but never used. Allowed unused vars must match /^_/u

Check warning on line 5 in commands/init.js

View workflow job for this annotation

GitHub Actions / test (20)

'writeConfig' is defined but never used. Allowed unused vars must match /^_/u

Check warning on line 5 in commands/init.js

View workflow job for this annotation

GitHub Actions / test (18)

'writeConfig' is defined but never used. Allowed unused vars must match /^_/u
import { renderTemplate, renderSkillTemplates, pruneStaleShipped, isUserOwned } from '../lib/template.js';
import { withAgentModel, withAgentEffort, resolveModelForFile, resolveEffortForFile } from '../lib/models.js';
import { createRequire } from 'module';
import { success, warn, error, bold, dim } from '../lib/colors.js';
import { getTarget, TARGETS } from '../lib/targets/index.js';

Check warning on line 10 in commands/init.js

View workflow job for this annotation

GitHub Actions / test (22)

'TARGETS' is defined but never used. Allowed unused vars must match /^_/u

Check warning on line 10 in commands/init.js

View workflow job for this annotation

GitHub Actions / test (20)

'TARGETS' is defined but never used. Allowed unused vars must match /^_/u

Check warning on line 10 in commands/init.js

View workflow job for this annotation

GitHub Actions / test (18)

'TARGETS' is defined but never used. Allowed unused vars must match /^_/u
import { detectServices, aggregateAreas, aggregateHealthChecks } from '../lib/services.js';
import { deriveDefaultWorkflow } from '../lib/workflow.js';
import { runLocalProfileWizard, saveLocalProfile } from './local-init.js';
Expand All @@ -33,7 +33,7 @@
* 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
Expand Down Expand Up @@ -66,6 +66,7 @@
};
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;
Expand Down
18 changes: 17 additions & 1 deletion lib/conductor/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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: { <key>: n }.
Expand All @@ -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');
Expand Down Expand Up @@ -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.',
Expand All @@ -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 });
Expand Down
40 changes: 40 additions & 0 deletions lib/conductor/inbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
17 changes: 17 additions & 0 deletions lib/conductor/status.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() } = {}) {
Expand All @@ -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 },
Expand Down Expand Up @@ -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}`);
Expand Down
110 changes: 110 additions & 0 deletions templates/hooks/conductor-inbox.sh
Original file line number Diff line number Diff line change
@@ -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.
#
# <studio>/.bobby/conductor/inbox/<session_id>.jsonl one JSON message per line
# <studio>/.bobby/conductor/inbox/<session_id>.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))
'
9 changes: 9 additions & 0 deletions templates/settings.json.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@
"command": "\"$CLAUDE_PROJECT_DIR\"/hooks/context-cap.sh"
}
]
},
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/hooks/conductor-inbox.sh"
}
]
}
]
}
Expand Down
22 changes: 21 additions & 1 deletion test/commands/conductor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand All @@ -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']) {
Expand Down
Loading
Loading