From 1fcc3c3364a2a72922e414e22c8969f1922b9ce5 Mon Sep 17 00:00:00 2001 From: CC Evans Date: Sun, 8 Nov 2026 10:42:48 -0500 Subject: [PATCH 1/2] BOB-181: conductor ship lane per repo (claim/release lock, ready batch, status SHIP LANES) Co-Authored-By: Claude Sonnet 5.5 --- commands/conductor-ship.js | 51 +++++ commands/conductor.js | 2 + lib/conductor/ship-lane.js | 322 +++++++++++++++++++++++++++ lib/conductor/status.js | 13 ++ test/commands/conductor-ship.test.js | 95 ++++++++ test/commands/conductor.test.js | 2 +- test/lib/conductor/ship-lane.test.js | 213 ++++++++++++++++++ 7 files changed, 697 insertions(+), 1 deletion(-) create mode 100644 commands/conductor-ship.js create mode 100644 lib/conductor/ship-lane.js create mode 100644 test/commands/conductor-ship.test.js create mode 100644 test/lib/conductor/ship-lane.test.js diff --git a/commands/conductor-ship.js b/commands/conductor-ship.js new file mode 100644 index 0000000..bc5466a --- /dev/null +++ b/commands/conductor-ship.js @@ -0,0 +1,51 @@ +// commands/conductor-ship.js +// +// `bobby conductor ship claim|release ` (BOB-181). Takes or frees the per-repo ship +// lock and prints the ready batch; it never merges or deploys (see lib/conductor/ship-lane.js). + +import { findStudioRoot, loadConductorConfig } from '../lib/conductor/config.js'; +import { claimShipLane, releaseShipLane, renderClaim, renderRelease } from '../lib/conductor/ship-lane.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 registerShipCommands(conductor) { + const ship = conductor + .command('ship') + .description('One serial ship lane per repo: claim the lock and list the ready batch, release it. Ships nothing itself. M4 only'); + + ship + .command('claim ') + .description('Take the repo\'s ship lock and print the shipping-stage tickets for it, in queue order. Refused while another session holds it (a stale lock is an error naming the holder)') + .option('--session ', 'Claiming session (default: this session, from CLAUDE_CODE_SESSION_ID)') + .action((repo, opts) => { + try { + assertM4Host(); + const studioRoot = findStudioRoot(); + const config = loadConductorConfig(studioRoot); + console.log(renderClaim(claimShipLane({ studioRoot, config, repo, session: opts.session ?? null }))); + } catch (e) { + fail(e); + } + }); + + ship + .command('release ') + .description('Free the repo\'s ship lock. Only the holder may; --force overrides and prints what it overrode') + .option('--session ', 'Releasing session (default: this session, from CLAUDE_CODE_SESSION_ID)') + .option('--force', 'Release a lock held by another session') + .action((repo, opts) => { + try { + assertM4Host(); + const studioRoot = findStudioRoot(); + const config = loadConductorConfig(studioRoot); + console.log(renderRelease(releaseShipLane({ studioRoot, config, repo, session: opts.session ?? null, force: Boolean(opts.force) }))); + } catch (e) { + fail(e); + } + }); +} diff --git a/commands/conductor.js b/commands/conductor.js index e3ed6d6..359420a 100644 --- a/commands/conductor.js +++ b/commands/conductor.js @@ -20,6 +20,7 @@ import { listInboxSessions, readMessages, cursorWithin, renderMessages, } from '../lib/conductor/inbox.js'; import { registerQueueCommands } from './conductor-queue.js'; +import { registerShipCommands } from './conductor-ship.js'; import { success, error, dim } from '../lib/colors.js'; function fail(e) { @@ -179,4 +180,5 @@ export function registerConductor(program) { }); registerQueueCommands(conductor); + registerShipCommands(conductor); } diff --git a/lib/conductor/ship-lane.js b/lib/conductor/ship-lane.js new file mode 100644 index 0000000..0fc3deb --- /dev/null +++ b/lib/conductor/ship-lane.js @@ -0,0 +1,322 @@ +// lib/conductor/ship-lane.js +// +// One serial ship lane per repo (BOB-181). `bobby conductor ship claim ` takes an +// exclusive per-repo slot and lists the batch of tickets ready to ship; `ship release +// ` frees it. The conductor ships nothing and deploys nothing: it only holds the +// lock and prints the batch. The claiming session runs `bobby run ship ` itself. +// +// Why a lock per repo: a full listrobin_api suite takes minutes and two at once time out, +// so two sessions must never ship the same repo together. Different repos do not share a +// suite, so their lanes are independent. +// +// State: /.bobby/conductor/ship-.yml, rewritten whole and never deleted +// (a release writes a free lane: holder fields null). Keys: repo, holder_session_id, +// holder_name, since (ISO), released_at, released_by. +// +// Rules: +// - `repo` must appear in the `repos` of at least one ticket on a conductor board; +// anything else is an Error, never a guess. +// - A claim is refused (Error, so exit 1) while another session holds the lane. A holder +// that is working or waiting on CC (or a terminal session with a live process) is "live" +// and the Error says so. A holder that is done or gone from `claude agents` is a stale +// lock: the Error names it and says so, and the lane is NOT taken over. A person frees +// it with `ship release --force`, which prints what it overrode. +// - The holder claiming again gets the batch again; `since` is kept. +// - Release by anyone but the holder is refused unless `force`. +// - The batch is every ticket in stage `shipping`, not flagged blocked, whose `repos` +// include the repo: queued ones first in conductor-queue.yml order, then the rest in +// board order (the order of conductor.yml `projects`), by ticket number. +// +// The claim is a read-then-write of one small file. Two claims landing in the same few +// milliseconds could both succeed; lanes are started by hand minutes apart, the same +// trade-off as claims.yml (BOB-180). + +import fs from 'fs'; +import path from 'path'; +import YAML from 'yaml'; +import { readAgents, classifySessions } from './sessions.js'; +import { resolveRecipient } from './inbox.js'; +import { loadQueue, runHint } from './queue.js'; +import { run as defaultRun } from './exec.js'; +import { configForProject, resolveTicketsDir } from '../config.js'; +import { listTickets } from '../tickets.js'; + +const STATE_DIR = 'conductor'; +const REPO_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const TICKET_ID_RE = /^([A-Za-z][A-Za-z0-9]*)-(\d+)$/; + +export function shipLaneFile(studioRoot, repo) { + if (!REPO_RE.test(repo)) throw new Error(`"${repo}" is not a repo name`); + return path.join(studioRoot, '.bobby', STATE_DIR, `ship-${repo}.yml`); +} + +/** Every ticket on the conductor boards, in board order: { id, project, title, stage, blocked, repos }. */ +export function shipBoardTickets(studioRoot, projects) { + const out = []; + for (const project of projects) { + const config = configForProject(studioRoot, project); + for (const t of listTickets(resolveTicketsDir(studioRoot, config))) { + out.push({ + id: t.id, + project, + title: t.title || '', + stage: t.stage || 'backlog', + blocked: Boolean(t.blocked), + repos: Array.isArray(t.repos) ? t.repos : [], + }); + } + } + return out; +} + +export function knownRepos(tickets) { + return [...new Set(tickets.flatMap(t => t.repos))].sort(); +} + +function assertKnownRepo(repo, tickets) { + const repos = knownRepos(tickets); + if (!repos.includes(repo)) { + throw new Error(`Unknown repo "${repo}": no ticket on the conductor boards lists it in "repos". Known repos: ${repos.join(', ') || '(none)'}`); + } +} + +function ticketNumber(id) { + const m = TICKET_ID_RE.exec(id); + return m ? Number(m[2]) : 0; +} + +/** Ready batch for `repo`: [{ id, project, title, position (queue place or null), hint }] in ship order. */ +export function readyBatch(repo, tickets, queue) { + const place = new Map(queue.map((id, i) => [id.toUpperCase(), i + 1])); + const ready = tickets + .map((t, boardIndex) => ({ t, boardIndex })) + .filter(({ t }) => t.stage === 'shipping' && !t.blocked && t.repos.includes(repo)); + const rank = ({ t, boardIndex }) => { + const p = place.get(t.id.toUpperCase()); + return p ? [0, p, 0] : [1, boardIndex, ticketNumber(t.id)]; + }; + ready.sort((a, b) => { + const [ra, rb] = [rank(a), rank(b)]; + return ra[0] - rb[0] || ra[1] - rb[1] || ra[2] - rb[2]; + }); + return ready.map(({ t }) => ({ + id: t.id, + project: t.project, + title: t.title, + position: place.get(t.id.toUpperCase()) ?? null, + hint: runHint(t.project, t.id, 'shipping'), + })); +} + +/** The lane file as { holder_session_id, holder_name, since, ... }, or null when the lane was never claimed. */ +export function readShipLane(studioRoot, repo) { + const file = shipLaneFile(studioRoot, repo); + if (!fs.existsSync(file)) return null; + 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)) throw new Error(`${file}: expected a mapping`); + if (parsed.repo !== repo) throw new Error(`${file}: "repo" must be ${repo}`); + const holder = parsed.holder_session_id; + if (holder !== null && (typeof holder !== 'string' || !holder)) { + throw new Error(`${file}: "holder_session_id" must be a session id or null`); + } + if (holder !== null && (typeof parsed.since !== 'string' || Number.isNaN(Date.parse(parsed.since)))) { + throw new Error(`${file}: a held lane needs an ISO "since"`); + } + return { + holder_session_id: holder, + holder_name: typeof parsed.holder_name === 'string' ? parsed.holder_name : null, + since: holder === null ? null : parsed.since, + released_at: parsed.released_at ?? null, + released_by: parsed.released_by ?? null, + }; +} + +function writeShipLane(studioRoot, repo, lane) { + const file = shipLaneFile(studioRoot, repo); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const body = YAML.stringify({ + repo, + holder_session_id: lane.holder_session_id, + holder_name: lane.holder_name, + since: lane.since, + released_at: lane.released_at ?? null, + released_by: lane.released_by ?? null, + }); + fs.writeFileSync(file, `# Written by \`bobby conductor ship claim|release\`. One serial ship lane per repo; never deleted.\n${body}`); + return file; +} + +/** + * How a recorded holder looks in `claude agents`: { live, why }. + * live: working or waiting on CC, or a terminal session whose process is alive. + * Otherwise stale, with the reason ("done", "stopped", "not in claude agents", ...). + */ +export function holderStatus(sessions, sessionId) { + const s = sessions.find(x => x.session_id === sessionId); + if (!s) return { live: false, why: 'not in `claude agents`' }; + if (s.state === 'working' || s.state === 'blocked') return { live: true, why: s.state === 'blocked' ? 'waiting on CC' : 'working' }; + if (s.state === 'unknown' && s.live) return { live: true, why: s.kind === 'interactive' ? 'terminal session, process alive' : `state ${s.raw_state ?? 'none'}, process alive` }; + return { live: false, why: `state ${s.raw_state ?? 'none'}` }; +} + +function ageText(since, now) { + const minutes = Math.max(0, Math.floor((now - Date.parse(since)) / 60_000)); + if (minutes < 60) return `${minutes}m`; + const hours = Math.floor(minutes / 60); + return hours < 48 ? `${hours}h` : `${Math.floor(hours / 24)}d`; +} + +function describeHolder(lane, now) { + return `${lane.holder_name || '(unnamed)'} (${lane.holder_session_id}) since ${lane.since} (${ageText(lane.since, now)} ago)`; +} + +function snapshot({ studioRoot, config, run, now }) { + const raw = readAgents({ run }); + return { + raw, + sessions: classifySessions(raw, { hookStateDir: config.hook_state_dir, now }), + tickets: shipBoardTickets(studioRoot, config.projects), + }; +} + +// The session acting: --session (name, sessionId or bg id) or the one running the command. +function actor(raw, session, env) { + const query = session || env.CLAUDE_CODE_SESSION_ID; + if (!query) return null; + return resolveRecipient(raw, query); +} + +/** + * `ship claim `. Returns { repo, holder: { session_id, name }, since, reclaimed, batch }. + * Throws (exit 1) on an unknown repo, an unknown claiming session, a live holder or a stale lock. + */ +export function claimShipLane({ studioRoot, config, repo, session = null, run = defaultRun, now = Date.now(), env = process.env }) { + const { raw, sessions, tickets } = snapshot({ studioRoot, config, run, now }); + assertKnownRepo(repo, tickets); + const me = actor(raw, session, env); + if (!me) throw new Error('Cannot tell which session is claiming (CLAUDE_CODE_SESSION_ID is not set); pass --session '); + + const lane = readShipLane(studioRoot, repo); + let since = new Date(now).toISOString(); + let reclaimed = false; + if (lane && lane.holder_session_id) { + if (lane.holder_session_id === me.sessionId) { + since = lane.since; + reclaimed = true; + } else { + const h = holderStatus(sessions, lane.holder_session_id); + if (h.live) { + throw new Error(`Ship lane ${repo} is held by ${describeHolder(lane, now)}, ${h.why}. Wait for it to release (\`bobby conductor ship release ${repo}\`).`); + } + throw new Error( + `Ship lane ${repo} has a stale lock held by ${describeHolder(lane, now)}: that session is ${h.why}. ` + + `The lane was not taken over. If that session is really finished, free it with \`bobby conductor ship release ${repo} --force\`, then claim again.`, + ); + } + } + const holder = { session_id: me.sessionId, name: me.name ?? null }; + writeShipLane(studioRoot, repo, { holder_session_id: holder.session_id, holder_name: holder.name, since }); + return { repo, holder, since, reclaimed, batch: readyBatch(repo, tickets, loadQueue(studioRoot)) }; +} + +/** + * `ship release `. Returns { repo, kind: 'released' | 'free' | 'forced', overrode }. + * `overrode` (forced) is what was held. A non-holder without `force` is an Error. + */ +export function releaseShipLane({ studioRoot, config, repo, session = null, force = false, run = defaultRun, now = Date.now(), env = process.env }) { + const { raw, sessions, tickets } = snapshot({ studioRoot, config, run, now }); + assertKnownRepo(repo, tickets); + const lane = readShipLane(studioRoot, repo); + if (!lane || !lane.holder_session_id) return { repo, kind: 'free', overrode: null }; + + const me = actor(raw, session, env); + const isHolder = Boolean(me) && me.sessionId === lane.holder_session_id; + if (!isHolder && !force) { + throw new Error( + `Ship lane ${repo} is held by ${describeHolder(lane, now)}, not by ${me ? (me.name || me.sessionId) : 'this caller'}. ` + + `Only the holder releases it; to override, pass --force.`, + ); + } + const by = me ? (me.name || me.sessionId) : 'forced (no session named)'; + writeShipLane(studioRoot, repo, { + holder_session_id: null, holder_name: null, since: null, released_at: new Date(now).toISOString(), released_by: by, + }); + if (isHolder) return { repo, kind: 'released', overrode: null }; + const h = holderStatus(sessions, lane.holder_session_id); + return { + repo, + kind: 'forced', + overrode: { holder_session_id: lane.holder_session_id, holder_name: lane.holder_name, since: lane.since, holder_live: h.live, holder_why: h.why }, + }; +} + +/** + * Rows for `status`: every repo whose lane is held or has a batch waiting. The batch is only + * counted here, so the queue file (which orders it) is not needed. + * [{ repo, holder: { session_id, name, since, age_ms, live, why } | null, batch (count), error? }] + * A malformed lane file is reported on its row instead of failing the whole board. + */ +export function shipLanesView({ studioRoot, sessions, tickets, now }) { + const dir = path.join(studioRoot, '.bobby', STATE_DIR); + const fromFiles = fs.existsSync(dir) + ? fs.readdirSync(dir).map(f => /^ship-(.+)\.yml$/.exec(f)).filter(Boolean).map(m => m[1]) + : []; + const repos = [...new Set([...knownRepos(tickets), ...fromFiles])].sort(); + const rows = []; + for (const repo of repos) { + const batch = readyBatch(repo, tickets, []).length; + let lane; + try { + lane = readShipLane(studioRoot, repo); + } catch (e) { + rows.push({ repo, holder: null, batch, error: e.message }); + continue; + } + const held = Boolean(lane && lane.holder_session_id); + if (!held && batch === 0) continue; + if (!held) { rows.push({ repo, holder: null, batch }); continue; } + const h = holderStatus(sessions, lane.holder_session_id); + rows.push({ + repo, + holder: { + session_id: lane.holder_session_id, + name: lane.holder_name, + since: lane.since, + age_ms: Math.max(0, now - Date.parse(lane.since)), + live: h.live, + why: h.why, + }, + batch, + }); + } + return rows; +} + +export function renderClaim(result) { + const lines = [ + `Ship lane ${result.repo} ${result.reclaimed ? 'already yours' : 'claimed'} by ${result.holder.name || result.holder.session_id} (since ${result.since}).`, + ]; + if (result.batch.length === 0) { + lines.push('Batch: none ready (no shipping-stage ticket lists this repo).'); + } else { + lines.push(`Batch (${result.batch.length}, ship in this order, one at a time; the full suite runs once per ticket):`); + result.batch.forEach((t, i) => lines.push(` ${i + 1}. ${t.id} ${t.title}`, ` ${t.hint}`)); + } + lines.push(`When done: bobby conductor ship release ${result.repo}`); + return lines.join('\n'); +} + +export function renderRelease(result) { + if (result.kind === 'free') return `Ship lane ${result.repo} is already free.`; + if (result.kind === 'released') return `Released ship lane ${result.repo}.`; + const o = result.overrode; + return [ + `Forced release of ship lane ${result.repo}.`, + ` overrode: held by ${o.holder_name || '(unnamed)'} (${o.holder_session_id}) since ${o.since}; that session was ${o.holder_live ? 'LIVE' : 'stale'} (${o.holder_why})`, + ].join('\n'); +} diff --git a/lib/conductor/status.js b/lib/conductor/status.js index b986c9e..3f44046 100644 --- a/lib/conductor/status.js +++ b/lib/conductor/status.js @@ -11,6 +11,7 @@ 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 { shipBoardTickets, shipLanesView } from './ship-lane.js'; import { bold, dim } from '../colors.js'; export function buildStatus(studioRoot, { run, now = Date.now() } = {}) { @@ -35,6 +36,7 @@ export function buildStatus(studioRoot, { run, now = Date.now() } = {}) { unknown: groups.unknown, handoffs: sessions.filter(s => s.handed_off), inbox: inboxStatus(inboxDir(studioRoot), sessions, { now, staleMinutes: config.inbox.stale_minutes }), + ship_lanes: shipLanesView({ studioRoot, sessions, tickets: shipBoardTickets(studioRoot, config.projects), now }), 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 }, @@ -124,6 +126,17 @@ export function renderStatus(status) { } lines.push(''); + lines.push(`${bold('SHIP LANES')} ${dim(`(${status.ship_lanes.length})`)}`); + if (status.ship_lanes.length === 0) lines.push(dim(' none held, nothing waiting')); + for (const l of status.ship_lanes) { + if (l.error) { lines.push(` ${l.repo} ${bold('unreadable lane')} ${dim(l.error)}`); continue; } + const holder = l.holder + ? `held by ${l.holder.name || '(unnamed)'} ${dim(`${formatAge(l.holder.age_ms)}`)}${l.holder.live ? '' : ` ${bold('stale lock')} ${dim(`(${l.holder.why})`)}`}` + : 'free'; + lines.push(` ${l.repo} ${holder} ${dim(`${l.batch} ready to ship`)}`); + } + 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/test/commands/conductor-ship.test.js b/test/commands/conductor-ship.test.js new file mode 100644 index 0000000..d22359f --- /dev/null +++ b/test/commands/conductor-ship.test.js @@ -0,0 +1,95 @@ +// End-to-end: `bobby conductor ship claim|release` and the status SHIP LANES section 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 { createTicket, moveTicket } from '../../lib/tickets.js'; +import { makeStudio, writeConductorYml, validYml, vmStatText } from '../lib/conductor/helpers.js'; + +const bobby = path.resolve('bin/bobby.js'); + +describe('bobby conductor ship / status SHIP LANES', () => { + let root; + let hookDir; + let fakeBin; + let agentsFile; + let vmFile; + let shipId; + + 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 bobbyIn = (args, { cpu = 'Apple M4 Max', session } = {}) => { + const env = { ...process.env, PATH: `${fakeBin}${path.delimiter}${process.env.PATH}`, FAKE_AGENTS_FILE: agentsFile, FAKE_VM_FILE: vmFile, FAKE_CPU: cpu, HOME: root, ...(session ? { CLAUDE_CODE_SESSION_ID: `${session}-0000-4000-8000-000000000000` } : {}) }; + 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)); + const dir = path.join(root, '.bobby', 'alpha', 'tickets'); + ({ id: shipId } = createTicket(dir, { prefix: 'AL', title: 'ship me', repos: ['api'] })); + moveTicket(dir, shipId, 'shipping', 'test'); + fs.writeFileSync(path.join(root, '.bobby', 'conductor-queue.yml'), 'queue: []\n'); + }); + afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); + + test('claim prints the batch, a second session is refused with exit 1, release frees it', () => { + setAgents([bg('aaaa1111', 'lane a', 'working'), bg('bbbb2222', 'lane b', 'working')]); + const ok = bobbyIn(['ship', 'claim', 'api'], { session: 'aaaa1111' }); + expect(ok.status).toBe(0); + expect(ok.stdout).toMatch(new RegExp(`claimed by lane a[\\s\\S]*1\\. ${shipId} ship me[\\s\\S]*BOBBY_PROJECT=alpha bobby run ship ${shipId}`)); + const second = bobbyIn(['ship', 'claim', 'api'], { session: 'bbbb2222' }); + expect(second.status).toBe(1); + expect(second.stderr).toMatch(/held by lane a .*working/); + const refused = bobbyIn(['ship', 'release', 'api'], { session: 'bbbb2222' }); + expect(refused.status).toBe(1); + expect(refused.stderr).toMatch(/--force/); + expect(bobbyIn(['ship', 'release', 'api'], { session: 'aaaa1111' }).stdout).toMatch(/Released ship lane api/); + expect(bobbyIn(['ship', 'claim', 'api'], { session: 'bbbb2222' }).status).toBe(0); + }); + + test('a stale lock exits 1 naming the holder; --force release reports the override; unknown repo exits 1', () => { + setAgents([bg('aaaa1111', 'lane a', 'working'), bg('bbbb2222', 'lane b', 'working')]); + expect(bobbyIn(['ship', 'claim', 'api'], { session: 'aaaa1111' }).status).toBe(0); + setAgents([bg('bbbb2222', 'lane b', 'working')]); + const stale = bobbyIn(['ship', 'claim', 'api'], { session: 'bbbb2222' }); + expect(stale.status).toBe(1); + expect(stale.stderr).toMatch(/stale lock held by lane a/); + const forced = bobbyIn(['ship', 'release', 'api', '--force'], { session: 'bbbb2222' }); + expect(forced.status).toBe(0); + expect(forced.stdout).toMatch(/overrode: held by lane a.*stale/); + const unknown = bobbyIn(['ship', 'claim', 'nope'], { session: 'bbbb2222' }); + expect(unknown.status).toBe(1); + expect(unknown.stderr).toMatch(/Unknown repo "nope"/); + }); + + test('ship refuses to run on a machine that is not the M4', () => { + setAgents([bg('aaaa1111', 'lane a', 'working')]); + const r = bobbyIn(['ship', 'claim', 'api'], { session: 'aaaa1111', cpu: 'Intel Core i7' }); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/M4 only/); + }); + + test('status has a SHIP LANES section and a ship_lanes key (holder, stale flag, batch size); it needs no queue file', () => { + setAgents([bg('aaaa1111', 'lane a', 'working')]); + fs.rmSync(path.join(root, '.bobby', 'conductor-queue.yml')); + expect(bobbyIn(['status']).stdout).toMatch(/SHIP LANES \(1\)\s+api\s+free\s+1 ready to ship/); + fs.writeFileSync(path.join(root, '.bobby', 'conductor-queue.yml'), 'queue: []\n'); + bobbyIn(['ship', 'claim', 'api'], { session: 'aaaa1111' }); + expect(bobbyIn(['status']).stdout).toMatch(/api\s+held by lane a .*1 ready to ship/); + const data = JSON.parse(bobbyIn(['status', '--json']).stdout); + expect(data.ship_lanes).toEqual([expect.objectContaining({ repo: 'api', batch: 1, holder: expect.objectContaining({ name: 'lane a', live: true }) })]); + setAgents([]); + expect(bobbyIn(['status']).stdout).toMatch(/api\s+held by lane a .*stale lock/); + }); +}); diff --git a/test/commands/conductor.test.js b/test/commands/conductor.test.js index 112688d..89dcd27 100644 --- a/test/commands/conductor.test.js +++ b/test/commands/conductor.test.js @@ -168,7 +168,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', 'interactive', 'unknown', 'handoffs', 'inbox', 'board', 'machine', 'stacks']); + expect(Object.keys(data)).toEqual(['generated_at', 'working', 'waiting_on_cc', 'done', 'stopped', 'interactive', 'unknown', 'handoffs', 'inbox', 'ship_lanes', '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']); diff --git a/test/lib/conductor/ship-lane.test.js b/test/lib/conductor/ship-lane.test.js new file mode 100644 index 0000000..30cfd19 --- /dev/null +++ b/test/lib/conductor/ship-lane.test.js @@ -0,0 +1,213 @@ +import fs from 'fs'; +import path from 'path'; +import { createTicket, moveTicket, updateTicket } from '../../../lib/tickets.js'; +import { + claimShipLane, releaseShipLane, readShipLane, shipLaneFile, readyBatch, shipBoardTickets, + shipLanesView, renderClaim, renderRelease, +} from '../../../lib/conductor/ship-lane.js'; +import { classifySessions } from '../../../lib/conductor/sessions.js'; +import { makeStudio } from './helpers.js'; + +const NOW = Date.parse('2026-11-08T12:00:00Z'); +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: 7, ...extra }); + +describe('conductor ship lane', () => { + let root; + let hookDir; + let config; + let agents; + const run = (cmd, args) => { + if (cmd === 'claude' && args.join(' ') === 'agents --json --all') return JSON.stringify(agents); + throw new Error(`unexpected exec ${cmd} ${args.join(' ')}`); + }; + const ticketsDir = (project) => path.join(root, '.bobby', project, 'tickets'); + const make = (project, prefix, title, { stage = 'shipping', repos = ['api'], blocked = false } = {}) => { + const { id } = createTicket(ticketsDir(project), { prefix, title, repos }); + if (stage !== 'backlog') moveTicket(ticketsDir(project), id, stage, 'test'); + if (blocked) updateTicket(ticketsDir(project), id, { blocked: true, blocked_reason: 'x' }); + return id; + }; + const setQueue = (ids) => fs.writeFileSync(path.join(root, '.bobby', 'conductor-queue.yml'), ids.length ? `queue:\n${ids.map(i => ` - ${i}`).join('\n')}\n` : 'queue: []\n'); + const claim = (repo, who, opts = {}) => claimShipLane({ studioRoot: root, config, repo, session: who, run, now: NOW, env: {}, ...opts }); + const release = (repo, who, opts = {}) => releaseShipLane({ studioRoot: root, config, repo, session: who, run, now: NOW, env: {}, ...opts }); + + beforeEach(() => { + ({ root, hookDir } = makeStudio()); + config = { projects: ['alpha', 'beta'], hook_state_dir: hookDir }; + agents = [bg('aaaa1111', 'lane a', 'working'), bg('bbbb2222', 'lane b', 'working'), bg('cccc3333', 'lane c', 'done')]; + setQueue([]); + }); + afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); + + describe('batch', () => { + test('is exactly the shipping, unblocked tickets listing the repo: queued first in queue order, then board order', () => { + const a1 = make('alpha', 'AL', 'one'); + const a2 = make('alpha', 'AL', 'two'); + const a3 = make('alpha', 'AL', 'three'); + const b1 = make('beta', 'BE', 'four'); + make('alpha', 'AL', 'other repo', { repos: ['ui'] }); + make('alpha', 'AL', 'not shipping yet', { stage: 'testing' }); + make('alpha', 'AL', 'blocked', { blocked: true }); + make('beta', 'BE', 'two repos', { repos: ['ui', 'api'] }); + setQueue([b1, a3]); + const out = claim('api', 'lane a'); + expect(out.batch.map(t => t.id)).toEqual([b1, a3, a1, a2, 'BE-002']); + expect(out.batch[0]).toMatchObject({ position: 1, project: 'beta', hint: `BOBBY_PROJECT=beta bobby run ship ${b1}` }); + expect(out.batch[2].position).toBeNull(); + expect(readyBatch('ui', shipBoardTickets(root, config.projects), []).map(t => t.title)).toEqual(['other repo', 'two repos']); + }); + + test('an empty batch still claims and says so', () => { + make('alpha', 'AL', 'x', { repos: ['ui'] }); + make('alpha', 'AL', 'y', { repos: ['api'], stage: 'building' }); + const out = claim('api', 'lane a'); + expect(out.batch).toEqual([]); + expect(renderClaim(out)).toMatch(/Batch: none ready/); + }); + + test('a missing queue file is an error', () => { + make('alpha', 'AL', 'x'); + fs.rmSync(path.join(root, '.bobby', 'conductor-queue.yml')); + expect(() => claim('api', 'lane a')).toThrow(/conductor-queue\.yml does not exist/); + }); + }); + + describe('claim', () => { + beforeEach(() => { make('alpha', 'AL', 'x'); make('alpha', 'AL', 'y', { repos: ['ui'] }); }); + + test('writes the lane file with holder and since; the batch is listed', () => { + const out = claim('api', 'lane a'); + expect(out).toMatchObject({ repo: 'api', reclaimed: false, since: new Date(NOW).toISOString(), holder: { session_id: sid('aaaa1111'), name: 'lane a' } }); + expect(readShipLane(root, 'api')).toMatchObject({ holder_session_id: sid('aaaa1111'), holder_name: 'lane a', since: new Date(NOW).toISOString() }); + expect(renderClaim(out)).toMatch(/claimed by lane a[\s\S]*1\. AL-001/); + }); + + test('a second claim while the holder is working fails naming the holder and age, and changes nothing', () => { + claim('api', 'lane a', { now: NOW - 90 * 60_000 }); + const before = fs.readFileSync(shipLaneFile(root, 'api'), 'utf8'); + expect(() => claim('api', 'lane b')).toThrow(/held by lane a \(aaaa1111-.*\) since .*\(1h ago\), working/); + expect(fs.readFileSync(shipLaneFile(root, 'api'), 'utf8')).toBe(before); + }); + + test('a holder waiting on CC or a live terminal session still holds the lane', () => { + claim('api', 'lane a'); + agents = [bg('aaaa1111', 'lane a', 'blocked'), bg('bbbb2222', 'lane b', 'working')]; + expect(() => claim('api', 'lane b')).toThrow(/waiting on CC/); + agents = [{ sessionId: sid('aaaa1111'), kind: 'interactive', status: 'idle', pid: 3, name: 'lane a' }, bg('bbbb2222', 'lane b', 'working')]; + expect(() => claim('api', 'lane b')).toThrow(/terminal session, process alive/); + }); + + test.each([ + ['done', (list) => list.map(a => (a.id === 'aaaa1111' ? { ...a, state: 'done', pid: undefined } : a)), /stale lock held by lane a.*state done/], + ['absent', (list) => list.filter(a => a.id !== 'aaaa1111'), /stale lock held by lane a.*not in `claude agents`/], + ])('a stale lock (holder %s) is an explicit error naming the holder; the lane is not taken over', (_n, change, re) => { + claim('api', 'lane a'); + const before = fs.readFileSync(shipLaneFile(root, 'api'), 'utf8'); + agents = change(agents); + expect(() => claim('api', 'lane b')).toThrow(re); + expect(() => claim('api', 'lane b')).toThrow(/ship release api --force/); + expect(fs.readFileSync(shipLaneFile(root, 'api'), 'utf8')).toBe(before); + }); + + test('after a forced release the next claim works, and the lane file is overwritten, never deleted', () => { + claim('api', 'lane a'); + agents = agents.filter(a => a.id !== 'aaaa1111'); + release('api', 'lane b', { force: true }); + expect(fs.existsSync(shipLaneFile(root, 'api'))).toBe(true); + claim('api', 'lane b'); + expect(readShipLane(root, 'api').holder_session_id).toBe(sid('bbbb2222')); + }); + + test('the holder claiming again keeps its original since and gets the batch again', () => { + claim('api', 'lane a', { now: NOW - 60_000 }); + const again = claim('api', 'lane a'); + expect(again).toMatchObject({ reclaimed: true, since: new Date(NOW - 60_000).toISOString() }); + expect(again.batch).toHaveLength(1); + }); + + test('different repos can be claimed at the same time', () => { + claim('api', 'lane a'); + expect(claim('ui', 'lane b').holder.name).toBe('lane b'); + expect(readShipLane(root, 'api').holder_name).toBe('lane a'); + }); + + test('an unknown repo is an error and writes nothing', () => { + expect(() => claim('nope', 'lane a')).toThrow(/Unknown repo "nope".*Known repos: api, ui/); + expect(() => claim('../x', 'lane a')).toThrow(/Unknown repo|not a repo name/); + expect(fs.existsSync(path.join(root, '.bobby', 'conductor'))).toBe(false); + }); + + test('the claiming session comes from --session or CLAUDE_CODE_SESSION_ID; neither is an error', () => { + expect(claim('api', null, { env: { CLAUDE_CODE_SESSION_ID: sid('bbbb2222') } }).holder.name).toBe('lane b'); + expect(() => claim('ui', null)).toThrow(/pass --session/); + expect(() => claim('ui', 'no such session')).toThrow(/No session matches/); + }); + + test('a malformed lane file is an error, never "free"', () => { + fs.mkdirSync(path.join(root, '.bobby', 'conductor'), { recursive: true }); + fs.writeFileSync(shipLaneFile(root, 'api'), 'repo: api\nholder_session_id: 7\n'); + expect(() => claim('api', 'lane a')).toThrow(/holder_session_id/); + }); + + test('claims never run anything but the read probe', () => { + const calls = []; + claim('api', 'lane a', { run: (cmd, args) => { calls.push([cmd, ...args]); return run(cmd, args); } }); + expect(calls).toEqual([['claude', 'agents', '--json', '--all']]); + }); + }); + + describe('release', () => { + beforeEach(() => { make('alpha', 'AL', 'x'); claim('api', 'lane a'); }); + + test('the holder releases; the file stays, with a free holder', () => { + expect(release('api', 'lane a').kind).toBe('released'); + expect(readShipLane(root, 'api')).toMatchObject({ holder_session_id: null, released_by: 'lane a' }); + expect(release('api', 'lane a').kind).toBe('free'); + expect(renderRelease({ repo: 'api', kind: 'free' })).toMatch(/already free/); + }); + + test('a non-holder is refused and the lock is unchanged', () => { + expect(() => release('api', 'lane b')).toThrow(/held by lane a.*not by lane b.*--force/); + expect(readShipLane(root, 'api').holder_session_id).toBe(sid('aaaa1111')); + }); + + test('--force succeeds and reports what it overrode, live or stale', () => { + const live = release('api', 'lane b', { force: true }); + expect(live).toMatchObject({ kind: 'forced', overrode: { holder_session_id: sid('aaaa1111'), holder_live: true } }); + expect(renderRelease(live)).toMatch(/overrode: held by lane a.*LIVE/); + expect(readShipLane(root, 'api')).toMatchObject({ holder_session_id: null, released_by: 'lane b' }); + claim('api', 'lane a'); + agents = agents.filter(a => a.id !== 'aaaa1111'); + expect(renderRelease(release('api', null, { force: true }))).toMatch(/stale.*not in `claude agents`/); + }); + + test('an unknown repo is an error', () => { + expect(() => release('nope', 'lane a')).toThrow(/Unknown repo/); + }); + }); + + describe('status rows', () => { + test('lists held lanes (live and stale) and repos with a batch waiting; omits idle repos', () => { + make('alpha', 'AL', 'x'); + make('alpha', 'AL', 'y', { repos: ['ui'] }); + make('alpha', 'AL', 'z', { repos: ['docs'], stage: 'building' }); + claim('api', 'lane a'); + const view = () => shipLanesView({ + studioRoot: root, + sessions: classifySessions(agents, { hookStateDir: hookDir, now: NOW }), + tickets: shipBoardTickets(root, config.projects), + now: NOW + 5 * 60_000, + }); + let rows = view(); + expect(rows.map(r => r.repo)).toEqual(['api', 'ui']); + expect(rows[0]).toMatchObject({ batch: 1, holder: { name: 'lane a', live: true, age_ms: 5 * 60_000 } }); + expect(rows[1]).toEqual({ repo: 'ui', holder: null, batch: 1 }); + agents = agents.filter(a => a.id !== 'aaaa1111'); + rows = view(); + expect(rows[0].holder).toMatchObject({ live: false, why: 'not in `claude agents`' }); + fs.writeFileSync(shipLaneFile(root, 'ui'), 'repo: ui\nholder_session_id: 5\n'); + expect(view().find(r => r.repo === 'ui').error).toMatch(/holder_session_id/); + }); + }); +}); From 447236ecbc5f4817b8550581d164ed91e8455693 Mon Sep 17 00:00:00 2001 From: CC Evans Date: Sun, 8 Nov 2026 10:45:33 -0500 Subject: [PATCH 2/2] BOB-181: review fixes (claim reads the queue before taking the lock; batch board order by ticket number) Co-Authored-By: Claude Sonnet 5.5 --- lib/conductor/ship-lane.js | 10 ++++++++-- test/lib/conductor/ship-lane.test.js | 9 +++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/conductor/ship-lane.js b/lib/conductor/ship-lane.js index 0fc3deb..ab218fe 100644 --- a/lib/conductor/ship-lane.js +++ b/lib/conductor/ship-lane.js @@ -88,8 +88,11 @@ function ticketNumber(id) { /** Ready batch for `repo`: [{ id, project, title, position (queue place or null), hint }] in ship order. */ export function readyBatch(repo, tickets, queue) { const place = new Map(queue.map((id, i) => [id.toUpperCase(), i + 1])); + // Board order is the order of the boards (conductor.yml `projects`), then ticket number: + // directory order would put RF-1005 before RF-999. + const projectOrder = [...new Set(tickets.map(t => t.project))]; const ready = tickets - .map((t, boardIndex) => ({ t, boardIndex })) + .map(t => ({ t, boardIndex: projectOrder.indexOf(t.project) })) .filter(({ t }) => t.stage === 'shipping' && !t.blocked && t.repos.includes(repo)); const rank = ({ t, boardIndex }) => { const p = place.get(t.id.toUpperCase()); @@ -219,9 +222,12 @@ export function claimShipLane({ studioRoot, config, repo, session = null, run = ); } } + // Read the queue before taking the lock: a missing or bad queue file is an error, and it + // must not leave the lane held by a claim that printed no batch. + const queue = loadQueue(studioRoot); const holder = { session_id: me.sessionId, name: me.name ?? null }; writeShipLane(studioRoot, repo, { holder_session_id: holder.session_id, holder_name: holder.name, since }); - return { repo, holder, since, reclaimed, batch: readyBatch(repo, tickets, loadQueue(studioRoot)) }; + return { repo, holder, since, reclaimed, batch: readyBatch(repo, tickets, queue) }; } /** diff --git a/test/lib/conductor/ship-lane.test.js b/test/lib/conductor/ship-lane.test.js index 30cfd19..77fa990 100644 --- a/test/lib/conductor/ship-lane.test.js +++ b/test/lib/conductor/ship-lane.test.js @@ -70,6 +70,15 @@ describe('conductor ship lane', () => { make('alpha', 'AL', 'x'); fs.rmSync(path.join(root, '.bobby', 'conductor-queue.yml')); expect(() => claim('api', 'lane a')).toThrow(/conductor-queue\.yml does not exist/); + // the failed claim must not have taken the lane + expect(fs.existsSync(path.join(root, '.bobby', 'conductor', 'ship-api.yml'))).toBe(false); + }); + + test('unqueued tickets ship in board order by ticket number, not directory order', () => { + const t = (id, project) => ({ id, project, title: id, stage: 'shipping', blocked: false, repos: ['api'] }); + // directory order puts RF-1005 before RF-999; boards stay in their listed order + const tickets = [t('RF-1005', 'alpha'), t('RF-999', 'alpha'), t('BE-002', 'beta'), t('BE-1000', 'beta')]; + expect(readyBatch('api', tickets, []).map(x => x.id)).toEqual(['RF-999', 'RF-1005', 'BE-002', 'BE-1000']); }); });