diff --git a/commands/conductor-queue.js b/commands/conductor-queue.js new file mode 100644 index 0000000..ec90b55 --- /dev/null +++ b/commands/conductor-queue.js @@ -0,0 +1,50 @@ +// commands/conductor-queue.js +// +// `bobby conductor next` and `bobby conductor queue` (BOB-180). Kept in its own file so +// commands/conductor.js only imports and calls registerQueueCommands. `queue` only reads. +// `next` reads the sessions and the board and writes one claim file (see lib/conductor/queue.js). + +import { findStudioRoot, loadConductorConfig } from '../lib/conductor/config.js'; +import { pickNext, queueView, renderNext, renderQueue } from '../lib/conductor/queue.js'; +import { assertM4Host } from '../lib/conductor/host.js'; +import { error } from '../lib/colors.js'; + +function fail(e) { + error(e.message); + process.exit(1); +} + +export function registerQueueCommands(conductor) { + conductor + .command('next') + .description('Pull the next ticket from the ranked queue (.bobby/conductor-queue.yml): WIP cap, governor, then finish-first. Records a claim. M4 only') + .option('--lane ', 'Name of the lane pulling, recorded on the claim') + .action((opts) => { + try { + assertM4Host(); + const studioRoot = findStudioRoot(); + const config = loadConductorConfig(studioRoot); + const result = pickNext({ studioRoot, config, lane: opts.lane ?? null }); + if (result.kind === 'refused') { + error(`next refused: ${result.reason}`); + process.exit(1); + } + console.log(renderNext(result)); + } catch (e) { + fail(e); + } + }); + + conductor + .command('queue') + .description('The ranked queue with each ticket\'s stage and whether a lane or a claim holds it (read-only)') + .action(() => { + try { + const studioRoot = findStudioRoot(); + const config = loadConductorConfig(studioRoot); + console.log(renderQueue(queueView({ studioRoot, config }))); + } catch (e) { + fail(e); + } + }); +} diff --git a/commands/conductor.js b/commands/conductor.js index 49092d6..701a853 100644 --- a/commands/conductor.js +++ b/commands/conductor.js @@ -19,6 +19,7 @@ import { inboxDir, assertInboxDir, resolveRecipient, buildMessage, appendMessage, listInboxSessions, readMessages, cursorWithin, renderMessages, } from '../lib/conductor/inbox.js'; +import { registerQueueCommands } from './conductor-queue.js'; import { success, error, dim } from '../lib/colors.js'; function fail(e) { @@ -45,6 +46,7 @@ export function registerConductor(program) { console.log(dim(` hook_state_dir: ${values.hook_state_dir}`)); 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}`)); } catch (e) { fail(e); } @@ -174,4 +176,6 @@ export function registerConductor(program) { fail(e); } }); + + registerQueueCommands(conductor); } diff --git a/lib/conductor/config.js b/lib/conductor/config.js index caa57ee..a9952c9 100644 --- a/lib/conductor/config.js +++ b/lib/conductor/config.js @@ -20,6 +20,10 @@ export const CONDUCTOR_FILE = 'conductor.yml'; const INIT_GOVERNOR = { min_free_ram_mb: 4096, max_docker_stacks: 4 }; // BOB-177: CC set 2 hours in the BOB-173 scope. const INIT_REAPER = { stack_idle_hours: 2 }; +// BOB-180: CC set 6 lanes (BOB-173 decision, 2026-11-08). The claim TTL was not named by CC; +// 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 }; /** * Nearest ancestor of `startDir` whose .bobbyrc.yml carries a `studio:` key. @@ -66,7 +70,19 @@ function validateConfig(parsed, file) { } const governor = validateGovernor(parsed.governor, file); const reaper = validateReaper(parsed.reaper, file); - return { projects: [...projects], hook_state_dir: dir, governor, reaper }; + 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 }; +} + +// A section with one required positive-integer key: { : n }. +function validatePositiveInt(section, file, name, key) { + if (section === undefined || section === null) throw fail(file, `${name}.${key}`, 'is missing'); + if (typeof section !== 'object' || Array.isArray(section)) throw fail(file, name, 'must be a mapping'); + if (!(key in section) || section[key] === null) throw fail(file, `${name}.${key}`, 'is missing'); + const n = section[key]; + if (!Number.isInteger(n) || n <= 0) throw fail(file, `${name}.${key}`, 'must be a positive integer'); + return { [key]: n }; } function validateReaper(reaper, file) { @@ -130,6 +146,8 @@ export function initConductorConfig(studioRoot, { projects } = {}) { hook_state_dir: path.join(os.homedir(), '.bobby', 'hook-state'), governor: { ...INIT_GOVERNOR }, reaper: { ...INIT_REAPER }, + wip: { ...INIT_WIP }, + claims: { ...INIT_CLAIMS }, }; const body = [ '# bobby conductor config. Written by `bobby conductor init`; every key is required.', @@ -139,6 +157,8 @@ export function initConductorConfig(studioRoot, { projects } = {}) { '# governor.min_free_ram_mb: `conductor check` refuses below this much free RAM (CC, 2026-11-08).', '# governor.max_docker_stacks: `conductor check stack` refuses at this many running stacks (CC, 2026-11-08).', '# 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.', YAML.stringify(values), ].join('\n'); fs.mkdirSync(path.dirname(file), { recursive: true }); diff --git a/lib/conductor/queue.js b/lib/conductor/queue.js new file mode 100644 index 0000000..cfc8f20 --- /dev/null +++ b/lib/conductor/queue.js @@ -0,0 +1,251 @@ +// lib/conductor/queue.js +// +// The ranked priority queue and `bobby conductor next` (BOB-180). +// +// The queue is one file CC edits by hand, /.bobby/conductor-queue.yml: a +// `queue:` list of ticket IDs across the conductor boards, top first. Nothing outside the +// list is ever picked, and nothing here starts a session (v1 is pull-only: a lane calls +// `conductor next` and runs what it is told). +// +// `next`, in order: +// 1. queue file missing, malformed or naming an unknown ticket = Error. An empty list +// = "queue empty". +// 2. WIP: live sessions that are working or waiting on CC (the session reader's +// `working` and `blocked` groups, process alive) must stay under wip.max_lanes. +// 3. Governor: the BOB-175 lane check (free RAM). +// 4. Candidates: queued tickets not done, not blocked, with no live lane naming them +// (the BOB-177 name/cwd match) and no unexpired claim. +// 5. Finish-first: the candidate furthest along the pipeline (STAGE_ORDER: shipping, +// testing, reviewing, ... planning, backlog); ties break by queue order. +// 6. The pick is recorded in /.bobby/conductor/claims.yml so two lanes never +// pull the same ticket. The file is rewritten whole, keeping every entry; a claim +// older than claims.ttl_minutes is ignored when read. + +import fs from 'fs'; +import path from 'path'; +import YAML from 'yaml'; +import { readAgents, classifySessions } from './sessions.js'; +import { boardTickets, laneStateFor } from './stacks.js'; +import { checkLane } from './governor.js'; +import { readMemory } from './resources.js'; +import { run as defaultRun } from './exec.js'; +import { STAGE_ORDER } from '../tickets.js'; + +export const QUEUE_FILE = 'conductor-queue.yml'; +const CLAIMS_DIR = 'conductor'; +const CLAIMS_FILE = 'claims.yml'; +const TICKET_ID_RE = /^[A-Za-z][A-Za-z0-9]*-\d+$/; +const MINUTE_MS = 60_000; + +// Stage -> `bobby run` agent. Stages with no agent of their own are run by `bobby run next`, +// which dispatches on the ticket's current stage. Every STAGE_ORDER stage is listed; an +// unlisted stage is an error, not a guess. +const STAGE_AGENT = { + backlog: 'plan', + planning: 'plan', + building: 'build', + security: 'security', + reviewing: 'review', + testing: 'test', + shipping: 'ship', + 'design-research': 'next', + 'design-analyze': 'next', + 'design-mockup': 'next', + 'design-spec': 'next', + 'define-brief': 'next', + 'define-personas': 'next', + 'define-journeys': 'next', + 'define-features': 'next', + 'define-blueprint': 'next', +}; + +export function queueFilePath(studioRoot) { + return path.join(studioRoot, '.bobby', QUEUE_FILE); +} + +export function claimsFilePath(studioRoot) { + return path.join(studioRoot, '.bobby', CLAIMS_DIR, CLAIMS_FILE); +} + +/** Ranked ticket IDs, top first. Missing file, bad shape or a duplicate = Error. [] is a valid queue. */ +export function loadQueue(studioRoot) { + const file = queueFilePath(studioRoot); + if (!fs.existsSync(file)) { + throw new Error(`${file} does not exist. Create it with a "queue:" list of ticket IDs (an empty list is fine); \`conductor next\` has no built-in list.`); + } + let parsed; + try { + parsed = YAML.parse(fs.readFileSync(file, 'utf8')); + } catch (e) { + throw new Error(`${file}: invalid YAML (${e.message})`); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || !('queue' in parsed)) { + throw new Error(`${file}: expected a mapping with a "queue" key (a list of ticket IDs)`); + } + const { queue } = parsed; + if (!Array.isArray(queue)) throw new Error(`${file}: key "queue" must be a list of ticket IDs`); + const seen = new Set(); + for (const id of queue) { + if (typeof id !== 'string' || !TICKET_ID_RE.test(id)) { + throw new Error(`${file}: "${String(id)}" is not a ticket ID like RF-1234`); + } + if (seen.has(id.toUpperCase())) throw new Error(`${file}: ticket ${id} is listed twice`); + seen.add(id.toUpperCase()); + } + return [...queue]; +} + +/** Claims by ticket ID: { : { claimed_at (ISO), lane (string|null) } }. A missing file = no claims yet. */ +export function readClaims(studioRoot) { + const file = claimsFilePath(studioRoot); + if (!fs.existsSync(file)) return {}; + let parsed; + try { + parsed = YAML.parse(fs.readFileSync(file, 'utf8')); + } catch (e) { + throw new Error(`${file}: invalid YAML (${e.message})`); + } + const claims = parsed && typeof parsed === 'object' ? parsed.claims : undefined; + if (!claims || typeof claims !== 'object' || Array.isArray(claims)) { + throw new Error(`${file}: expected a mapping with a "claims" mapping`); + } + for (const [id, c] of Object.entries(claims)) { + if (!c || typeof c.claimed_at !== 'string' || Number.isNaN(Date.parse(c.claimed_at))) { + throw new Error(`${file}: claim ${id} needs an ISO "claimed_at"`); + } + } + return claims; +} + +function isClaimed(claims, id, { ttlMinutes, now }) { + const c = claims[id]; + return Boolean(c) && now - Date.parse(c.claimed_at) < ttlMinutes * MINUTE_MS; +} + +/** Record `id` as claimed. The file is rewritten whole with every existing entry kept. */ +export function writeClaim(studioRoot, id, { lane, now }) { + const claims = { ...readClaims(studioRoot), [id]: { claimed_at: new Date(now).toISOString(), lane: lane ?? null } }; + const file = claimsFilePath(studioRoot); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, `# Written by \`bobby conductor next\`. A claim older than claims.ttl_minutes is ignored.\n${YAML.stringify({ claims })}`); +} + +/** The `bobby run` command for a ticket in `stage`, with the project it lives on. */ +export function runHint(project, id, stage) { + const agent = STAGE_AGENT[stage]; + if (!agent) throw new Error(`no \`bobby run\` agent is known for stage "${stage}"`); + return `BOBBY_PROJECT=${project} bobby run ${agent} ${id}`; +} + +/** Live sessions that count against wip.max_lanes: working or waiting on CC, process alive. */ +export function laneSessions(sessions) { + return sessions.filter(s => s.live && (s.state === 'working' || s.state === 'blocked')); +} + +/** + * Resolve each queued ID to its board ticket. An ID on no conductor board = Error. + * Returns [{ position (1-based), id, project, stage }]. + */ +export function resolveQueue(queue, tickets) { + return queue.map((raw, i) => { + const m = /^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(raw); + const found = tickets.get(`${m[1].toUpperCase()}-${Number(m[2])}`); + if (!found) throw new Error(`queue names ${raw}, which is not on any conductor board`); + return { position: i + 1, id: found.id, project: found.project, stage: found.stage, blocked: found.blocked }; + }); +} + +function rankOf(stage) { + if (!(stage in STAGE_ORDER)) throw new Error(`queued ticket stage "${stage}" has no finish-first rank`); + return STAGE_ORDER[stage]; +} + +function snapshot({ studioRoot, config, run, now }) { + const sessions = classifySessions(readAgents({ run }), { hookStateDir: config.hook_state_dir, now }); + const resolved = resolveQueue(loadQueue(studioRoot), boardTickets(studioRoot, config.projects)); + return { sessions, resolved }; +} + +/** + * `conductor next`. Returns one of + * { kind: 'empty' } + * { kind: 'refused', reason } + * { kind: 'none', skipped: [{ id, why }] } nothing in the queue is pullable + * { kind: 'picked', ticket: { id, project, stage, position }, hint, skipped } + * Throws on any unreadable input; a failing probe is never read as "nothing to do". + */ +export function pickNext({ studioRoot, config, run = defaultRun, now = Date.now(), lane = null, memory = null }) { + const { sessions, resolved } = snapshot({ studioRoot, config, run, now }); + if (resolved.length === 0) return { kind: 'empty' }; + + const active = laneSessions(sessions).length; + const cap = config.wip.max_lanes; + if (active >= cap) { + return { kind: 'refused', reason: `${active} live lane session(s) (working or waiting on CC) >= wip.max_lanes ${cap}` }; + } + const governor = checkLane(config, memory || readMemory({ run })); + if (!governor.ok) return { kind: 'refused', reason: governor.reason }; + + const claims = readClaims(studioRoot); + const lanes = laneSessions(sessions); + const skipped = []; + const candidates = []; + for (const t of resolved) { + if (t.stage === 'done') { skipped.push({ id: t.id, why: 'done' }); continue; } + if (t.stage === 'blocked' || t.blocked) { skipped.push({ id: t.id, why: 'blocked' }); continue; } + const held = laneStateFor(t.id, lanes); + if (held !== 'none') { skipped.push({ id: t.id, why: `a lane already holds it (${held})` }); continue; } + if (isClaimed(claims, t.id, { ttlMinutes: config.claims.ttl_minutes, now })) { + skipped.push({ id: t.id, why: `claimed by ${claims[t.id].lane || 'another lane'} within ${config.claims.ttl_minutes} min` }); + continue; + } + candidates.push({ ...t, rank: rankOf(t.stage) }); + } + if (candidates.length === 0) return { kind: 'none', skipped }; + + // Lowest STAGE_ORDER = furthest along; Array#sort is stable, so queue order breaks ties. + const pick = [...candidates].sort((a, b) => a.rank - b.rank)[0]; + writeClaim(studioRoot, pick.id, { lane, now }); + return { + kind: 'picked', + ticket: { id: pick.id, project: pick.project, stage: pick.stage, position: pick.position }, + hint: runHint(pick.project, pick.id, pick.stage), + skipped, + }; +} + +/** `conductor queue`: every ranked ticket with its stage and whether a lane or a claim holds it. */ +export function queueView({ studioRoot, config, run = defaultRun, now = Date.now() }) { + const { sessions, resolved } = snapshot({ studioRoot, config, run, now }); + const lanes = laneSessions(sessions); + const claims = readClaims(studioRoot); + return resolved.map(t => ({ + position: t.position, + id: t.id, + project: t.project, + stage: t.stage, + blocked: t.stage === 'blocked' || t.blocked, + lane: laneStateFor(t.id, lanes), + claimed: isClaimed(claims, t.id, { ttlMinutes: config.claims.ttl_minutes, now }), + })); +} + +export function renderQueue(rows) { + if (rows.length === 0) return 'queue empty'; + return rows.map(r => { + const notes = []; + if (r.blocked) notes.push('blocked'); + notes.push(r.lane === 'none' ? 'no lane' : `lane ${r.lane}`); + if (r.claimed) notes.push('claimed'); + return ` ${String(r.position).padStart(2)}. ${r.id} ${r.stage} (${notes.join(', ')})`; + }).join('\n'); +} + +export function renderNext(result) { + if (result.kind === 'empty') return 'queue empty'; + if (result.kind === 'none') { + return ['nothing to pull: no queued ticket is pullable', ...result.skipped.map(s => ` ${s.id} ${s.why}`)].join('\n'); + } + const t = result.ticket; + return [`${t.id} ${t.stage} (queue #${t.position}, project ${t.project})`, ` ${result.hint}`].join('\n'); +} diff --git a/lib/conductor/stacks.js b/lib/conductor/stacks.js index 30ccdf0..2b4ac16 100644 --- a/lib/conductor/stacks.js +++ b/lib/conductor/stacks.js @@ -126,14 +126,14 @@ export function mapStoppedStacks(stopped, { tickets }) { }); } -/** Map of ticket key (see ticketKeyFromProject) -> { id, project, stage } across the conductor boards. */ +/** Map of ticket key (see ticketKeyFromProject) -> { id, project, stage, blocked } across the conductor boards. */ export function boardTickets(studioRoot, projects) { const map = new Map(); for (const project of projects) { const config = configForProject(studioRoot, project); for (const t of listTickets(resolveTicketsDir(studioRoot, config))) { const key = ticketKey(t.id); - if (key) map.set(key, { id: t.id, project, stage: t.stage || 'backlog' }); + if (key) map.set(key, { id: t.id, project, stage: t.stage || 'backlog', blocked: Boolean(t.blocked) }); } } return map; diff --git a/test/commands/conductor-queue.test.js b/test/commands/conductor-queue.test.js new file mode 100644 index 0000000..526cf78 --- /dev/null +++ b/test/commands/conductor-queue.test.js @@ -0,0 +1,120 @@ +// End-to-end: `bobby conductor next|queue` in a temp studio, with fake claude, vm_stat and +// sysctl on PATH so no real session list or machine state is touched. +import { spawnSync } from 'child_process'; +import fs from 'fs'; +import path from 'path'; +import { listTickets } from '../../lib/tickets.js'; +import { makeStudio, writeConductorYml, validYml, seedTickets, vmStatText } from '../lib/conductor/helpers.js'; + +const bobby = path.resolve('bin/bobby.js'); + +describe('bobby conductor next / queue', () => { + let root; + let hookDir; + let fakeBin; + let agentsFile; + let vmFile; + let ids; + + const bg = (id, name, state) => ({ id, sessionId: `${id}-0000-4000-8000-000000000000`, name, cwd: '/studio', kind: 'background', startedAt: 1, state, pid: 5 }); + const setAgents = (list) => fs.writeFileSync(agentsFile, JSON.stringify(list)); + const setQueue = (list) => fs.writeFileSync(path.join(root, '.bobby', 'conductor-queue.yml'), list.length ? `queue:\n${list.map(i => ` - ${i}`).join('\n')}\n` : 'queue: []\n'); + const bobbyIn = (args, { cpu = 'Apple M4 Max' } = {}) => { + const env = { ...process.env, PATH: `${fakeBin}${path.delimiter}${process.env.PATH}`, FAKE_AGENTS_FILE: agentsFile, FAKE_VM_FILE: vmFile, FAKE_CPU: cpu, HOME: root }; + delete env.BOBBY_PROJECT; + return spawnSync('node', [bobby, 'conductor', ...args], { cwd: root, encoding: 'utf8', env }); + }; + + beforeEach(() => { + ({ root, hookDir } = makeStudio()); + fakeBin = path.join(root, 'fakebin'); + fs.mkdirSync(fakeBin); + agentsFile = path.join(root, 'agents.json'); + vmFile = path.join(root, 'vm.txt'); + setAgents([]); + fs.writeFileSync(vmFile, vmStatText({ freeMb: 9000, specMb: 0, purgeMb: 0, inactiveMb: 0, fileMb: 0 })); + fs.writeFileSync(path.join(fakeBin, 'claude'), '#!/bin/sh\n[ "$1 $2 $3" = "agents --json --all" ] || exit 2\ncat "$FAKE_AGENTS_FILE"\n', { mode: 0o755 }); + fs.writeFileSync(path.join(fakeBin, 'vm_stat'), '#!/bin/sh\ncat "$FAKE_VM_FILE"\n', { mode: 0o755 }); + fs.writeFileSync(path.join(fakeBin, 'sysctl'), '#!/bin/sh\ncase "$*" in\n "-n hw.memsize") echo 51539607552 ;;\n "-n machdep.cpu.brand_string") echo "$FAKE_CPU" ;;\n *) exit 2 ;;\nesac\n', { mode: 0o755 }); + writeConductorYml(root, validYml(hookDir)); + seedTickets(root, 'alpha', [{ title: 'ship me', stage: 'shipping' }, { title: 'plan me', stage: 'planning' }]); + ids = {}; + for (const t of listTickets(path.join(root, '.bobby', 'alpha', 'tickets'))) ids[t.title] = t.id; + }); + afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); + + test('an empty queue prints "queue empty" and exits 0', () => { + setQueue([]); + const r = bobbyIn(['next']); + expect(r.status).toBe(0); + expect(r.stdout.trim()).toBe('queue empty'); + expect(bobbyIn(['queue']).stdout.trim()).toBe('queue empty'); + }); + + test('a missing queue file exits non-zero naming the file', () => { + for (const cmd of ['next', 'queue']) { + const r = bobbyIn([cmd]); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/conductor-queue\.yml does not exist/); + } + }); + + test('a conductor.yml without wip.max_lanes is an error naming the key', () => { + setQueue([ids['ship me']]); + writeConductorYml(root, validYml(hookDir).replace(/wip:\n {2}max_lanes: 6\n/, '')); + const r = bobbyIn(['next']); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/key "wip\.max_lanes" is missing/); + }); + + test('next prints the finish-first ticket and its run command, then the next one', () => { + setQueue([ids['plan me'], ids['ship me']]); + const first = bobbyIn(['next', '--lane', 'lane A']); + expect(first.status).toBe(0); + expect(first.stdout).toContain(`${ids['ship me']} shipping (queue #2, project alpha)`); + expect(first.stdout).toContain(`BOBBY_PROJECT=alpha bobby run ship ${ids['ship me']}`); + const second = bobbyIn(['next']); + expect(second.stdout).toContain(`${ids['plan me']} planning`); + const claims = fs.readFileSync(path.join(root, '.bobby', 'conductor', 'claims.yml'), 'utf8'); + expect(claims).toContain('lane: lane A'); + }); + + test('next refuses with the count and the cap at six live lanes (exit 1)', () => { + setQueue([ids['ship me']]); + setAgents(Array.from({ length: 6 }, (_, i) => bg(`a${i}`, `lane ${i}`, 'working'))); + const r = bobbyIn(['next']); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/6 live lane session\(s\).*>= wip\.max_lanes 6/); + }); + + test('next refuses with the governor reason when RAM is short (exit 1)', () => { + setQueue([ids['ship me']]); + fs.writeFileSync(vmFile, vmStatText({ freeMb: 100, specMb: 0, purgeMb: 0, inactiveMb: 0, fileMb: 0 })); + const r = bobbyIn(['next']); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/free RAM 100 MB < min 4096 MB/); + }); + + test('next refuses on a host that is not the M4; queue still reads', () => { + setQueue([ids['ship me']]); + expect(bobbyIn(['next'], { cpu: 'Intel(R) Core(TM) i7' }).stderr).toMatch(/M4 only/); + expect(bobbyIn(['queue'], { cpu: 'Intel(R) Core(TM) i7' }).status).toBe(0); + expect(fs.existsSync(path.join(root, '.bobby', 'conductor', 'claims.yml'))).toBe(false); + }); + + test('queue prints each ticket with its stage and lane', () => { + setQueue([ids['ship me'], ids['plan me']]); + setAgents([bg('a1', `${ids['plan me']} planning`, 'blocked')]); + const r = bobbyIn(['queue']); + expect(r.status).toBe(0); + expect(r.stdout).toContain(`${ids['ship me']} shipping (no lane)`); + expect(r.stdout).toContain(`${ids['plan me']} planning (lane waiting_on_cc)`); + }); + + test('an unknown ticket ID in the queue exits non-zero', () => { + setQueue(['ZZ-9']); + const r = bobbyIn(['queue']); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/ZZ-9, which is not on any conductor board/); + }); +}); diff --git a/test/lib/conductor/config.test.js b/test/lib/conductor/config.test.js index 4d03b63..9832a37 100644 --- a/test/lib/conductor/config.test.js +++ b/test/lib/conductor/config.test.js @@ -21,6 +21,8 @@ describe('conductor config', () => { hook_state_dir: hookDir, governor: { min_free_ram_mb: 4096, max_docker_stacks: 4 }, reaper: { stack_idle_hours: 2 }, + wip: { max_lanes: 6 }, + claims: { ttl_minutes: 30 }, }); }); @@ -37,6 +39,22 @@ describe('conductor config', () => { expect(() => loadConductorConfig(root)).toThrow(new RegExp(`key "${key.replace('.', '\\.')}"`)); }); + const reaperYml = `${govYml}reaper:\n stack_idle_hours: 2\n`; + test.each([ + ['wip.max_lanes', reaperYml], + ['wip.max_lanes', `${reaperYml}wip:\n other: 1\n`], + ['wip.max_lanes', `${reaperYml}wip:\n max_lanes:\n`], + ['wip.max_lanes', `${reaperYml}wip:\n max_lanes: 0\n`], + ['wip.max_lanes', `${reaperYml}wip:\n max_lanes: 2.5\n`], + ['wip', `${reaperYml}wip: 6\n`], + ['claims.ttl_minutes', `${reaperYml}wip:\n max_lanes: 6\n`], + ['claims.ttl_minutes', `${reaperYml}wip:\n max_lanes: 6\nclaims:\n ttl_minutes: soon\n`], + ['claims', `${reaperYml}wip:\n max_lanes: 6\nclaims: 30\n`], + ])('a missing or invalid %s names the key (wip and claims)', (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`], @@ -75,8 +93,12 @@ describe('conductor config', () => { hook_state_dir: path.join(os.homedir(), '.bobby', 'hook-state'), governor: { min_free_ram_mb: 4096, max_docker_stacks: 4 }, reaper: { stack_idle_hours: 2 }, + wip: { max_lanes: 6 }, + claims: { ttl_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/); }); diff --git a/test/lib/conductor/helpers.js b/test/lib/conductor/helpers.js index 42c9deb..6696f57 100644 --- a/test/lib/conductor/helpers.js +++ b/test/lib/conductor/helpers.js @@ -21,10 +21,12 @@ 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 }) { +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 }) { 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`; + + `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`; } /** 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/queue.test.js b/test/lib/conductor/queue.test.js new file mode 100644 index 0000000..7766bde --- /dev/null +++ b/test/lib/conductor/queue.test.js @@ -0,0 +1,234 @@ +import fs from 'fs'; +import path from 'path'; +import { loadConductorConfig } from '../../../lib/conductor/config.js'; +import { loadQueue, readClaims, claimsFilePath, queueFilePath, pickNext, queueView, renderQueue, renderNext, runHint } from '../../../lib/conductor/queue.js'; +import { makeStudio, writeConductorYml, validYml, seedTickets, vmStatText } from './helpers.js'; +import { listTickets } from '../../../lib/tickets.js'; + +const NOW = Date.parse('2026-11-08T12:00:00Z'); +const MIN = 60_000; +const sid = (id) => `${id}-0000-4000-8000-000000000000`; +const bg = (id, name, state, extra = {}) => ({ id, sessionId: sid(id), name, cwd: '/studio', kind: 'background', startedAt: 1, state, pid: 99, ...extra }); + +function mockRun({ agents = [], freeMb = 9000, agentsFail = false } = {}) { + const calls = []; + const run = (cmd, args) => { + calls.push([cmd, ...args]); + if (cmd === 'claude' && args.join(' ') === 'agents --json --all') { + if (agentsFail) throw new Error('`claude agents --json --all` failed: down'); + return JSON.stringify(agents); + } + if (cmd === 'vm_stat') return vmStatText({ freeMb, specMb: 0, purgeMb: 0, inactiveMb: 0, fileMb: 0 }); + if (cmd === 'sysctl') return '51539607552'; + throw new Error(`unexpected exec ${cmd} ${args.join(' ')}`); + }; + return { run, calls }; +} + +describe('conductor queue and next', () => { + let root; + let hookDir; + let config; + let ids; + const idOf = (title) => ids[title]; + const writeQueue = (list) => fs.writeFileSync(queueFilePath(root), list.length ? `queue:\n${list.map(i => ` - ${i}`).join('\n')}\n` : 'queue: []\n'); + const next = (opts = {}) => { + const { agents, freeMb, agentsFail, ...rest } = opts; + const m = mockRun({ agents, freeMb, agentsFail }); + return { ...m, result: () => pickNext({ studioRoot: root, config, run: m.run, now: NOW, ...rest }) }; + }; + + beforeEach(() => { + ({ root, hookDir } = makeStudio()); + writeConductorYml(root, validYml(hookDir)); + config = loadConductorConfig(root); + seedTickets(root, 'alpha', [ + { title: 'planning one', stage: 'planning' }, + { title: 'building one', stage: 'building' }, + { title: 'shipping one', stage: 'shipping' }, + { title: 'done one', stage: 'done' }, + ]); + seedTickets(root, 'beta', [{ title: 'testing one', stage: 'testing' }, { title: 'building two', stage: 'building' }]); + ids = {}; + for (const p of ['alpha', 'beta']) { + for (const t of listTickets(path.join(root, '.bobby', p, 'tickets'))) ids[t.title] = t.id; + } + }); + afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); + + describe('the queue file', () => { + test('a missing file is an error naming the file, no built-in list', () => { + expect(() => loadQueue(root)).toThrow(/conductor-queue\.yml does not exist/); + }); + + test('an empty list is a valid queue', () => { + fs.writeFileSync(queueFilePath(root), '# ranked, top first\nqueue: []\n'); + expect(loadQueue(root)).toEqual([]); + }); + + test.each([ + ['no queue key', 'other: []\n'], + ['queue not a list', 'queue: AL-1\n'], + ['not an id', 'queue:\n - nonsense\n'], + ['a duplicate', 'queue:\n - AL-1\n - al-1\n'], + ['bad yaml', 'queue: [\n'], + ])('%s is an error', (_n, text) => { + fs.writeFileSync(queueFilePath(root), text); + expect(() => loadQueue(root)).toThrow(/conductor-queue\.yml/); + }); + }); + + describe('next', () => { + test('an empty queue prints "queue empty" and does not touch sessions or claims', () => { + writeQueue([]); + const n = next(); + const r = n.result(); + expect(r).toEqual({ kind: 'empty' }); + expect(renderNext(r)).toBe('queue empty'); + expect(fs.existsSync(claimsFilePath(root))).toBe(false); + }); + + test('a missing queue file is an error', () => { + expect(() => next().result()).toThrow(/does not exist/); + }); + + test('an ID on no board is an error, no fallback', () => { + writeQueue(['ZZ-9']); + expect(() => next().result()).toThrow(/ZZ-9, which is not on any conductor board/); + }); + + test('refuses with the count and the cap when live lanes reach wip.max_lanes', () => { + writeQueue([idOf('shipping one')]); + const agents = Array.from({ length: 6 }, (_, i) => bg(`a${i}`, `lane ${i}`, i % 2 ? 'blocked' : 'working')); + const r = next({ agents }).result(); + expect(r.kind).toBe('refused'); + expect(r.reason).toBe('6 live lane session(s) (working or waiting on CC) >= wip.max_lanes 6'); + expect(fs.existsSync(claimsFilePath(root))).toBe(false); + }); + + test('five live lanes are under the cap; done, stopped, interactive and unknown sessions do not count', () => { + writeQueue([idOf('shipping one')]); + const agents = [ + ...Array.from({ length: 5 }, (_, i) => bg(`a${i}`, `lane ${i}`, 'working')), + bg('d1', 'finished', 'done'), + bg('d2', 'gone', 'done', { pid: undefined }), + bg('b2', 'dead blocked', 'blocked', { pid: undefined }), + bg('u1', 'odd', 'failed'), + { sessionId: sid('i1'), name: 'bobby-code-studio-61', cwd: '/studio', kind: 'interactive', pid: 7 }, + ]; + expect(next({ agents }).result().kind).toBe('picked'); + }); + + test('refuses with the governor reason when free RAM is under the floor', () => { + writeQueue([idOf('shipping one')]); + const r = next({ freeMb: 100 }).result(); + expect(r.kind).toBe('refused'); + expect(r.reason).toMatch(/free RAM 100 MB < min 4096 MB/); + }); + + test('a failing session read is an error, not an empty answer', () => { + writeQueue([idOf('shipping one')]); + expect(() => next({ agentsFail: true }).result()).toThrow(/claude agents --json --all/); + }); + + test('finish-first: the shipping ticket wins even when it ranks last, across projects', () => { + writeQueue([idOf('planning one'), idOf('building one'), idOf('testing one'), idOf('shipping one')]); + const r = next().result(); + expect(r.kind).toBe('picked'); + expect(r.ticket).toEqual({ id: idOf('shipping one'), project: 'alpha', stage: 'shipping', position: 4 }); + expect(r.hint).toBe(`BOBBY_PROJECT=alpha bobby run ship ${idOf('shipping one')}`); + }); + + test('order is shipping > testing > reviewing > building > planning', () => { + writeQueue([idOf('planning one'), idOf('building one'), idOf('testing one')]); + const seen = []; + for (let i = 0; i < 3; i += 1) seen.push(next().result().ticket.stage); + expect(seen).toEqual(['testing', 'building', 'planning']); + }); + + test('ties break by queue order', () => { + writeQueue([idOf('building two'), idOf('building one')]); + expect(next().result().ticket.id).toBe(idOf('building two')); + }); + + test('two calls in a row return different tickets; a claim past the TTL is ignored', () => { + writeQueue([idOf('shipping one'), idOf('testing one')]); + const first = next({ lane: 'lane 1' }).result(); + const second = next({ lane: 'lane 2' }).result(); + expect(first.ticket.id).toBe(idOf('shipping one')); + expect(second.ticket.id).toBe(idOf('testing one')); + const third = next().result(); + expect(third.kind).toBe('none'); + expect(third.skipped.map(s => s.why)).toEqual([ + 'claimed by lane 1 within 30 min', + 'claimed by lane 2 within 30 min', + ]); + const later = pickNext({ studioRoot: root, config, run: mockRun().run, now: NOW + 31 * MIN }); + expect(later.ticket.id).toBe(idOf('shipping one')); + }); + + test('claims keep every entry when the file is rewritten', () => { + writeQueue([idOf('shipping one'), idOf('testing one')]); + next({ lane: 'a' }).result(); + next({ lane: 'b' }).result(); + expect(Object.keys(readClaims(root)).sort()).toEqual([idOf('shipping one'), idOf('testing one')].sort()); + expect(readClaims(root)[idOf('testing one')]).toEqual({ claimed_at: new Date(NOW).toISOString(), lane: 'b' }); + }); + + test('a ticket a live lane already holds is skipped; a done lane does not hold it', () => { + writeQueue([idOf('shipping one'), idOf('testing one')]); + const agents = [bg('a1', `lane for ${idOf('shipping one')}`, 'working'), bg('a2', `${idOf('testing one')} old`, 'done')]; + const r = next({ agents }).result(); + expect(r.ticket.id).toBe(idOf('testing one')); + expect(r.skipped).toEqual([{ id: idOf('shipping one'), why: 'a lane already holds it (working)' }]); + }); + + test('done and blocked tickets are never picked', () => { + seedTickets(root, 'alpha', [{ title: 'flagged', stage: 'shipping', blocked: true }]); + const flagged = listTickets(path.join(root, '.bobby', 'alpha', 'tickets')).find(t => t.title === 'flagged').id; + writeQueue([idOf('done one'), flagged, idOf('planning one')]); + const r = next().result(); + expect(r.ticket.id).toBe(idOf('planning one')); + expect(r.skipped).toEqual([{ id: idOf('done one'), why: 'done' }, { id: flagged, why: 'blocked' }]); + }); + + test('nothing pullable is reported with reasons, not an error', () => { + writeQueue([idOf('done one')]); + const r = next().result(); + expect(r.kind).toBe('none'); + expect(renderNext(r)).toMatch(/nothing to pull[\s\S]*done$/); + }); + + test('a queue is matched to the board case-insensitively and ignores zero padding', () => { + writeQueue([idOf('shipping one').toLowerCase()]); + expect(next().result().ticket.id).toBe(idOf('shipping one')); + }); + }); + + describe('queue', () => { + test('prints each ranked ticket with its stage and whether a lane holds it', () => { + writeQueue([idOf('shipping one'), idOf('planning one')]); + next({ lane: 'x' }).result(); // claims shipping one + const agents = [bg('a1', `${idOf('planning one')} planning lane`, 'blocked')]; + const rows = queueView({ studioRoot: root, config, run: mockRun({ agents }).run, now: NOW }); + expect(rows).toEqual([ + { position: 1, id: idOf('shipping one'), project: 'alpha', stage: 'shipping', blocked: false, lane: 'none', claimed: true }, + { position: 2, id: idOf('planning one'), project: 'alpha', stage: 'planning', blocked: false, lane: 'waiting_on_cc', claimed: false }, + ]); + expect(renderQueue(rows)).toBe([ + ` 1. ${idOf('shipping one')} shipping (no lane, claimed)`, + ` 2. ${idOf('planning one')} planning (lane waiting_on_cc)`, + ].join('\n')); + }); + + test('an empty queue prints "queue empty"', () => { + expect(renderQueue([])).toBe('queue empty'); + }); + }); + + test('stages without an agent of their own are run by `bobby run next`', () => { + expect(runHint('alpha', 'AL-1', 'design-research')).toBe('BOBBY_PROJECT=alpha bobby run next AL-1'); + expect(runHint('alpha', 'AL-1', 'backlog')).toBe('BOBBY_PROJECT=alpha bobby run plan AL-1'); + expect(() => runHint('alpha', 'AL-1', 'mystery')).toThrow(/no `bobby run` agent is known for stage "mystery"/); + }); +}); diff --git a/test/lib/conductor/read-only.test.js b/test/lib/conductor/read-only.test.js index 6c316ba..cbd2dd5 100644 --- a/test/lib/conductor/read-only.test.js +++ b/test/lib/conductor/read-only.test.js @@ -21,6 +21,7 @@ function sourceFiles() { return [ ...fs.readdirSync(libDir).map(f => path.join(libDir, f)), path.resolve('commands/conductor.js'), + path.resolve('commands/conductor-queue.js'), ].filter(f => f.endsWith('.js')); }