From 67832bfafa1712b84571eea04586db833232c6a9 Mon Sep 17 00:00:00 2001 From: CC Evans Date: Sun, 8 Nov 2026 14:59:16 -0500 Subject: [PATCH 1/3] BOB-189: conductor disk floor in the governor, worktree counts in status, reap --worktrees Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 10 + commands/conductor.js | 34 ++- lib/conductor/config.js | 6 +- lib/conductor/disk.js | 29 +++ lib/conductor/governor.js | 26 ++- lib/conductor/queue.js | 5 +- lib/conductor/status.js | 36 ++- lib/conductor/worktree-reaper.js | 175 ++++++++++++++ lib/conductor/worktrees.js | 253 +++++++++++++++++++++ test/commands/conductor.test.js | 121 +++++++++- test/lib/conductor/config.test.js | 12 +- test/lib/conductor/disk.test.js | 31 +++ test/lib/conductor/governor.test.js | 42 +++- test/lib/conductor/helpers.js | 7 +- test/lib/conductor/queue.test.js | 7 + test/lib/conductor/read-only.test.js | 26 +++ test/lib/conductor/worktree-reaper.test.js | 245 ++++++++++++++++++++ test/lib/conductor/worktrees.test.js | 136 +++++++++++ 18 files changed, 1159 insertions(+), 42 deletions(-) create mode 100644 lib/conductor/disk.js create mode 100644 lib/conductor/worktree-reaper.js create mode 100644 lib/conductor/worktrees.js create mode 100644 test/lib/conductor/disk.test.js create mode 100644 test/lib/conductor/worktree-reaper.test.js create mode 100644 test/lib/conductor/worktrees.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 56bfa19..79af32f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,16 @@ All notable changes to Bobby are documented here. The format is based on `dashboard.executor` and sending you to an absolute path that key never takes. ### Added +- **Disk floor and worktree reaper in `bobby conductor` (BOB-189).** New required key + `governor.min_free_disk_gb`: `check lane|stack` and `conductor next` refuse below it + (free space of the volume holding the studio, one `statfs` call), and `status` MACHINE shows + `DISK`. `status` also lists WORKTREES by ticket stage (every repo in `.bobbyrc.yml` plus the + studio repo, from `git worktree list --porcelain`); sizes (`du`, slow) show only from the cache + or after `status --sizes`. `conductor reap --worktrees` (dry run unless `--apply`, M4 only) + removes a worktree with `git worktree remove --force` (branch kept) only when every ticket named + in its folder name is done, `git status --porcelain -uno` is empty and no live session's cwd is + inside it; folders that are not git worktrees are listed, never touched. `--sizes` measures the + candidates. A failing git or claude is an error. - **`bobby conductor` (BOB-174): read-only studio status board.** `bobby conductor init` writes `.bobby/conductor.yml` with every key explicit and refuses to overwrite it; `bobby conductor status [--json]` lists background and interactive sessions from diff --git a/commands/conductor.js b/commands/conductor.js index 359420a..b09f894 100644 --- a/commands/conductor.js +++ b/commands/conductor.js @@ -3,7 +3,7 @@ // `bobby conductor`: the studio's control board. `init` writes conductor.yml; // `status` and `check` only read (they never change a session, a ticket or a // container). `reap` is dry-run unless `--apply`, and is the one command that -// ends sessions (see lib/conductor/reaper.js). +// ends sessions (see lib/conductor/reaper.js), stops stacks and removes worktrees. import path from 'path'; import { findStudioRoot, initConductorConfig, loadConductorConfig } from '../lib/conductor/config.js'; @@ -13,6 +13,8 @@ import { readStacks } from '../lib/conductor/stacks.js'; import { checkLane, checkStack } from '../lib/conductor/governor.js'; import { reap, renderReap } from '../lib/conductor/reaper.js'; import { reapStacks, renderStackReap } from '../lib/conductor/stack-reaper.js'; +import { reapWorktrees, renderWorktreeReap } from '../lib/conductor/worktree-reaper.js'; +import { readDisk } from '../lib/conductor/disk.js'; import { assertM4Host } from '../lib/conductor/host.js'; import { readAgents } from '../lib/conductor/sessions.js'; import { @@ -45,7 +47,7 @@ export function registerConductor(program) { success(`Wrote ${path.relative(root, file)}`); console.log(dim(` projects: ${values.projects.join(', ')}`)); 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(` governor: min_free_ram_mb ${values.governor.min_free_ram_mb}, max_docker_stacks ${values.governor.max_docker_stacks}, min_free_disk_gb ${values.governor.min_free_disk_gb}`)); 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}`)); @@ -56,11 +58,12 @@ export function registerConductor(program) { conductor .command('status') - .description('Lanes by state, WAITING ON CC, handoff markers, ticket counts, free RAM and docker stacks') + .description('Lanes by state, WAITING ON CC, handoff markers, ticket counts, free RAM and disk, worktrees by stage, docker stacks') .option('--json', 'Print the same data as JSON') + .option('--sizes', 'Measure worktree sizes with du (slow: minutes) and cache them; without it only cached sizes show') .action((opts) => { try { - const status = buildStatus(findStudioRoot()); + const status = buildStatus(findStudioRoot(), { sizes: Boolean(opts.sizes) }); console.log(opts.json ? JSON.stringify(status, null, 2) : renderStatus(status)); } catch (e) { fail(e); @@ -75,11 +78,13 @@ export function registerConductor(program) { if (kind !== 'lane' && kind !== 'stack') { throw new Error(`Unknown check "${kind}". Use: bobby conductor check lane | stack`); } - const config = loadConductorConfig(findStudioRoot()); + const studioRoot = findStudioRoot(); + const config = loadConductorConfig(studioRoot); const memory = readMemory(); + const disk = readDisk(studioRoot); const result = kind === 'lane' - ? checkLane(config, memory) - : checkStack(config, memory, readStacks().stacks.length); + ? checkLane(config, memory, disk) + : checkStack(config, memory, disk, readStacks().stacks.length); if (!result.ok) { error(`${kind} refused: ${result.reason}`); process.exit(1); @@ -92,15 +97,28 @@ export function registerConductor(program) { conductor .command('reap') - .description('List finished background sessions to end, keeping their transcripts (--stacks: idle per-ticket docker stacks instead). Dry run unless --apply. M4 only') + .description('List finished background sessions to end, keeping their transcripts (--stacks: idle docker stacks; --worktrees: clean worktrees of done tickets). Dry run unless --apply. M4 only') .option('--apply', 'Do it (default: print the list and change nothing)') .option('--stacks', 'Reap idle per-ticket docker stacks (compose project, containers kept) instead of sessions') + .option('--worktrees', 'Remove git worktrees of done tickets (clean tracked files, no live session inside; branches kept) instead of sessions') + .option('--sizes', 'With --worktrees: measure the candidates with du (slow)') .action((opts) => { try { + if (opts.stacks && opts.worktrees) throw new Error('Pick one of --stacks and --worktrees.'); + if (opts.sizes && !opts.worktrees) throw new Error('--sizes only applies to --worktrees.'); assertM4Host(); const studioRoot = findStudioRoot(); const config = loadConductorConfig(studioRoot); const apply = Boolean(opts.apply); + if (opts.worktrees) { + const report = reapWorktrees({ studioRoot, config, apply, measure: Boolean(opts.sizes) }); + console.log(renderWorktreeReap(report, { apply })); + if (report.failed > 0) { + error(`${report.failed} worktree(s) could not be checked or removed`); + process.exit(1); + } + return; + } if (opts.stacks) { const report = reapStacks({ studioRoot, config, apply }); console.log(renderStackReap(report, { apply, idleHours: config.reaper.stack_idle_hours })); diff --git a/lib/conductor/config.js b/lib/conductor/config.js index e0f7aaa..37b12b8 100644 --- a/lib/conductor/config.js +++ b/lib/conductor/config.js @@ -17,7 +17,8 @@ export const CONDUCTOR_FILE = 'conductor.yml'; // The numbers `conductor init` writes. CC's decision, recorded on BOB-173 (2026-11-08), // for the M4 (48 GB). This is the only place they are chosen; loading never falls back to them. -const INIT_GOVERNOR = { min_free_ram_mb: 4096, max_docker_stacks: 4 }; +// BOB-189: CC set 50 GB free disk (2026-11-08, the day the disk hit 99%). +const INIT_GOVERNOR = { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 50 }; // 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; @@ -110,7 +111,7 @@ function validateReaper(reaper, file) { return { stack_idle_hours: h }; } -const GOVERNOR_KEYS = ['min_free_ram_mb', 'max_docker_stacks']; +const GOVERNOR_KEYS = ['min_free_ram_mb', 'max_docker_stacks', 'min_free_disk_gb']; function validateGovernor(governor, file) { if (governor === undefined || governor === null) throw fail(file, `governor.${GOVERNOR_KEYS[0]}`, 'is missing'); @@ -171,6 +172,7 @@ export function initConductorConfig(studioRoot, { projects } = {}) { '# hook_state_dir: where session hooks write .handoff markers.', '# 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).', + '# governor.min_free_disk_gb: `conductor check` and `conductor next` refuse below this much free disk on the studio volume (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.', diff --git a/lib/conductor/disk.js b/lib/conductor/disk.js new file mode 100644 index 0000000..2c25f95 --- /dev/null +++ b/lib/conductor/disk.js @@ -0,0 +1,29 @@ +// lib/conductor/disk.js +// +// Free disk on the volume that holds the studio (BOB-189). Read-only: one statfs call, +// which is instant (unlike measuring directory sizes). `bavail` is what a normal process +// can still write, so APFS purgeable space is not counted as free. +// +// Any unreadable or implausible figure throws; there is no fallback value. + +import fs from 'fs'; + +const GB = 1024 ** 3; + +/** { path, total_gb, free_gb } for the volume holding `studioRoot`, GB with one decimal. */ +export function readDisk(studioRoot, { statfs = fs.statfsSync } = {}) { + let st; + try { + st = statfs(studioRoot); + } catch (e) { + throw new Error(`Cannot read free disk space for ${studioRoot}: ${e.message}`); + } + const free = Number(st.bavail) * Number(st.bsize); + const total = Number(st.blocks) * Number(st.bsize); + if (!Number.isFinite(free) || !Number.isFinite(total) || total <= 0 || free < 0 || free > total) { + throw new Error(`statfs of ${studioRoot} returned implausible figures (free ${free} bytes of ${total} bytes); refusing to trust the reading`); + } + // Free is floored to a tenth, so a reading never passes the floor by rounding up. + const tenths = (bytes, round) => round((bytes / GB) * 10) / 10; + return { path: studioRoot, total_gb: tenths(total, Math.round), free_gb: tenths(free, Math.floor) }; +} diff --git a/lib/conductor/governor.js b/lib/conductor/governor.js index 7bcac49..219f130 100644 --- a/lib/conductor/governor.js +++ b/lib/conductor/governor.js @@ -3,20 +3,28 @@ // Yes/no answers for "may I start a lane / a docker stack?". It only answers; it // never acts on the machine. -/** { ok, reason, numbers } for starting a lane: free RAM must reach governor.min_free_ram_mb. */ -export function checkLane(config, memory) { - const min = config.governor.min_free_ram_mb; - const ok = memory.free_mb >= min; +/** + * { ok, reason, numbers } for starting a lane: free RAM must reach governor.min_free_ram_mb + * and free disk on the studio volume must reach governor.min_free_disk_gb (BOB-189). + * Both numbers are always reported, so a refusal for one never hides the other. + */ +export function checkLane(config, memory, disk) { + const minRam = config.governor.min_free_ram_mb; + const minDisk = config.governor.min_free_disk_gb; + const ramOk = memory.free_mb >= minRam; + const diskOk = disk.free_gb >= minDisk; + const ramText = `free RAM ${memory.free_mb} MB ${ramOk ? '>=' : '<'} min ${minRam} MB`; + const diskText = `free disk ${disk.free_gb} GB ${diskOk ? '>=' : '<'} min ${minDisk} GB`; return { - ok, - reason: ok ? `free RAM ${memory.free_mb} MB >= min ${min} MB` : `free RAM ${memory.free_mb} MB < min ${min} MB`, - numbers: { free_ram_mb: memory.free_mb, min_free_ram_mb: min }, + ok: ramOk && diskOk, + reason: `${ramText}; ${diskText}`, + numbers: { free_ram_mb: memory.free_mb, min_free_ram_mb: minRam, free_disk_gb: disk.free_gb, min_free_disk_gb: minDisk }, }; } /** { ok, reason, numbers } for starting a docker stack: the lane check, then stack count < governor.max_docker_stacks. */ -export function checkStack(config, memory, stackCount) { - const lane = checkLane(config, memory); +export function checkStack(config, memory, disk, stackCount) { + const lane = checkLane(config, memory, disk); const cap = config.governor.max_docker_stacks; const numbers = { ...lane.numbers, docker_stacks: stackCount, max_docker_stacks: cap }; if (!lane.ok) return { ok: false, reason: lane.reason, numbers }; diff --git a/lib/conductor/queue.js b/lib/conductor/queue.js index 4159ac7..06badcb 100644 --- a/lib/conductor/queue.js +++ b/lib/conductor/queue.js @@ -27,6 +27,7 @@ import YAML from 'yaml'; import { readAgents, classifySessions } from './sessions.js'; import { boardTickets, laneStateFor } from './stacks.js'; import { checkLane } from './governor.js'; +import { readDisk } from './disk.js'; import { readMemory } from './resources.js'; import { run as defaultRun } from './exec.js'; import { STAGE_ORDER } from '../tickets.js'; @@ -174,7 +175,7 @@ function snapshot({ studioRoot, config, run, now }) { * { 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 }) { +export function pickNext({ studioRoot, config, run = defaultRun, now = Date.now(), lane = null, memory = null, disk = null }) { const { sessions, resolved } = snapshot({ studioRoot, config, run, now }); if (resolved.length === 0) return { kind: 'empty' }; @@ -183,7 +184,7 @@ export function pickNext({ studioRoot, config, run = defaultRun, now = Date.now( 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 })); + const governor = checkLane(config, memory || readMemory({ run }), disk || readDisk(studioRoot)); if (!governor.ok) return { kind: 'refused', reason: governor.reason }; const claims = readClaims(studioRoot); diff --git a/lib/conductor/status.js b/lib/conductor/status.js index 3f44046..015cfc6 100644 --- a/lib/conductor/status.js +++ b/lib/conductor/status.js @@ -9,16 +9,27 @@ import { readAgents, classifySessions, groupSessions } from './sessions.js'; import { boardCounts } from './board.js'; import { loadConductorConfig } from './config.js'; import { readMemory } from './resources.js'; +import { readDisk } from './disk.js'; +import { scanWorktrees, readSizeCache, measureSizes, worktreeSummary, formatKb } from './worktrees.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() } = {}) { +/** + * `sizes: true` runs `du` over every worktree (slow, minutes) and refreshes the cache; without it + * the worktree section shows only the sizes already cached and never measures anything. + */ +export function buildStatus(studioRoot, { run, now = Date.now(), sizes = false, home, statfs } = {}) { const config = loadConductorConfig(studioRoot); const sessions = classifySessions(readAgents({ run }), { hookStateDir: config.hook_state_dir, now }); const groups = groupSessions(sessions); const memory = readMemory({ run }); + const disk = readDisk(studioRoot, { statfs }); + const scan = scanWorktrees(studioRoot, { run, home }); + const sizeCache = sizes + ? measureSizes(scan.worktrees.map(w => w.path), { hookStateDir: config.hook_state_dir, run, now }) + : readSizeCache(config.hook_state_dir); const docker = readStacks({ run, now }); const tickets = boardTickets(studioRoot, config.projects); const stacks = mapStacks(docker.stacks, { tickets, sessions }); @@ -38,7 +49,14 @@ export function buildStatus(studioRoot, { run, now = Date.now() } = {}) { 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 }, + machine: { + ...memory, + min_free_ram_mb: config.governor.min_free_ram_mb, + disk_total_gb: disk.total_gb, + disk_free_gb: disk.free_gb, + min_free_disk_gb: config.governor.min_free_disk_gb, + }, + worktrees: worktreeSummary(scan, sizeCache), stacks: { max: config.governor.max_docker_stacks, standalone_containers: docker.standalone_containers, list: stacks, stopped }, }; } @@ -148,9 +166,23 @@ export function renderStatus(status) { const m = status.machine; lines.push(bold('MACHINE')); lines.push(` RAM free ${m.free_mb} MB of ${m.total_mb} MB ${dim(`(lane floor ${m.min_free_ram_mb} MB)`)}`); + lines.push(` DISK free ${m.disk_free_gb} GB of ${m.disk_total_gb} GB ${dim(`(lane floor ${m.min_free_disk_gb} GB)`)}${m.disk_free_gb < m.min_free_disk_gb ? ` ${bold('below the floor: lanes refused')}` : ''}`); lines.push(` compressor holds ${m.compressed_mb} MB, takes ${m.compressor_mb} MB of RAM`); lines.push(''); + const wt = status.worktrees; + lines.push(`${bold('WORKTREES')} ${dim(`(${wt.total} across ${wt.repos} repos; ${wt.non_worktree_folders.length} other folder(s) that are not git worktrees; reap with \`conductor reap --worktrees\`)`)}`); + if (wt.by_stage.length === 0) lines.push(dim(' none')); + for (const g of wt.by_stage) { + let size = ''; + if (g.sized === g.count) size = ` ${dim(formatKb(g.size_kb))}`; + else if (g.sized > 0) size = ` ${dim(`${formatKb(g.size_kb)} (${g.sized} of ${g.count} sized)`)}`; + lines.push(` ${g.stage} ${g.count}${size}`); + } + if (wt.sizes_measured_at) lines.push(dim(` sizes: du, nominal, cached ${wt.sizes_measured_at}; refresh with \`conductor status --sizes\` (slow)`)); + else lines.push(dim(' sizes: not measured; `conductor status --sizes` measures them (slow) and caches the result')); + lines.push(''); + const st = status.stacks; lines.push(`${bold('STACKS')} ${dim(`(${st.list.length} of max ${st.max})`)}`); if (st.list.length === 0) lines.push(dim(' none')); diff --git a/lib/conductor/worktree-reaper.js b/lib/conductor/worktree-reaper.js new file mode 100644 index 0000000..21dbd94 --- /dev/null +++ b/lib/conductor/worktree-reaper.js @@ -0,0 +1,175 @@ +// lib/conductor/worktree-reaper.js +// +// `conductor reap --worktrees` (BOB-189). The conductor's only code that removes a worktree, +// and it does exactly one thing: +// +// git -C worktree remove --force +// +// which deletes the folder and git's record of it and KEEPS the branch. Nothing here runs +// a recursive delete of its own. +// +// A worktree is removed only when every rule holds: +// - it is a linked worktree git lists (worktrees.js); main checkouts are never listed as +// candidates and a locked or prunable one (folder already gone) is kept. +// - the ticket ID in its folder name is on a studio board and EVERY ticket named is done. +// No ticket in the name, or one that is not on a board, keeps it. +// - `git status --porcelain -uno` is empty: no modified or staged tracked file. Untracked +// and ignored files (node_modules, .next, logs) do not block it and go with the folder; +// committed work is on the branch, which stays. +// - no live session's cwd is inside it. Live means any session `claude agents` lists that +// is not already ended: working, waiting on CC, interactive, unknown, or finished with +// its process still running. +// - it does not hold the directory this command runs from. +// +// Candidates come from one snapshot. Right before each removal the sessions, the ticket +// boards and `git status` are read again and the full rule re-run, so a lane that started in +// between keeps its folder. If git or claude fails, that is an explicit error or a `failed` +// row; it is never read as "clean" or "no sessions". + +import path from 'path'; +import fs from 'fs'; +import { readAgents, classifySessions, groupSessions } from './sessions.js'; +import { run as defaultRun } from './exec.js'; +import { scanWorktrees, measureSizes, formatKb } from './worktrees.js'; + +const real = (p) => { + try { return fs.realpathSync(p); } catch { return path.resolve(p); } +}; + +const inside = (child, parent) => child === parent || child.startsWith(parent + path.sep); + +/** Folders of every session that has not ended. */ +export function liveCwds(sessions) { + const ended = new Set(groupSessions(sessions).stopped); + return sessions.filter(s => !ended.has(s) && s.cwd).map(s => ({ cwd: real(s.cwd), name: s.name })); +} + +function describe(w) { + return { repo: w.repo, path: w.path, branch: w.branch, ticket: w.ticket_ids.join(', ') || null, stage: w.stage }; +} + +/** + * Sort classified worktrees (worktrees.js classifyWorktrees) into candidates and kept + * ones, each kept one with its reason. `dirty(path)` returns the porcelain text of + * `git status -uno` for a path; it is only called for a worktree that passed every other rule. + */ +export function evaluateWorktrees(worktrees, { live, cwd, dirty }) { + const candidates = []; + const kept = []; + const here = real(cwd); + for (const w of worktrees) { + const keep = (why, extra = {}) => kept.push({ ...describe(w), why, ...extra }); + if (w.bare) { keep('bare repository'); continue; } + if (w.locked) { keep(`locked (${w.locked})`); continue; } + if (w.prunable) { keep(`folder is gone, git marks it prunable (${w.prunable})`); continue; } + if (w.ticket_ids.length === 0) { keep('no ticket on a board in the folder name'); continue; } + if (w.stage !== 'done') { keep(`ticket ${w.ticket_ids.join(', ')} is ${w.stage}`, { group: `ticket is ${w.stage}` }); continue; } + const target = real(w.path); + if (inside(here, target)) { keep('this command is running inside it', { notable: true }); continue; } + const session = live.find(s => inside(s.cwd, target)); + if (session) { keep(`live session "${session.name || '(unnamed)'}" is inside it`, { notable: true }); continue; } + let changes; + try { + changes = dirty(w.path); + } catch (e) { + kept.push({ ...describe(w), why: 'git status failed', error: e.message, notable: true }); + continue; + } + if (changes.trim()) { + const n = changes.trim().split('\n').length; + keep(`${n} tracked file(s) modified or staged`, { notable: true, group: 'tracked files modified or staged' }); + continue; + } + candidates.push({ ...describe(w), repo_path: w.repo_path, reason: `${w.ticket_ids.join(', ')} done, tracked files clean, no live session inside` }); + } + return { candidates, kept }; +} + +function readDirty(run) { + return (p) => run('git', ['-C', p, 'status', '--porcelain', '-uno']); +} + +function snapshot({ studioRoot, config, run, home }) { + const sessions = classifySessions(readAgents({ run }), { hookStateDir: config.hook_state_dir, now: Date.now() }); + const scan = scanWorktrees(studioRoot, { run, home }); + return { sessions, scan }; +} + +/** + * Plan a worktree reap; with `apply`, remove each candidate once. Returns { candidates, + * kept, non_worktree_folders, results, failed, sizes }. `results` is empty on a dry run: + * only read commands ran (`git worktree list`, `git status`, `claude agents`, and `du` + * when `measure` is set). + */ +export function reapWorktrees({ studioRoot, config, apply = false, measure = false, run = defaultRun, cwd = process.cwd(), home }) { + const { sessions, scan } = snapshot({ studioRoot, config, run, home }); + const plan = evaluateWorktrees(scan.worktrees, { live: liveCwds(sessions), cwd, dirty: readDirty(run) }); + let sizes = null; + if (measure) { + const cache = measureSizes(plan.candidates.map(c => c.path), { hookStateDir: config.hook_state_dir, run }); + sizes = { kb: plan.candidates.reduce((sum, c) => sum + cache[c.path].kb, 0), measured: plan.candidates.length }; + for (const c of plan.candidates) c.size_kb = cache[c.path].kb; + } + const results = []; + if (apply) { + for (const c of plan.candidates) { + let still; + try { + const fresh = snapshot({ studioRoot, config, run, home }); + const again = evaluateWorktrees(fresh.scan.worktrees, { live: liveCwds(fresh.sessions), cwd, dirty: readDirty(run) }); + still = again.candidates.find(x => x.path === c.path); + if (!still) { + const why = again.kept.find(k => k.path === c.path); + results.push({ ...c, outcome: 'skipped', detail: why ? why.why : 'no longer a git worktree' }); + continue; + } + } catch (e) { + results.push({ ...c, outcome: 'failed', detail: `could not re-check it: ${e.message}` }); + continue; + } + try { + run('git', ['-C', still.repo_path, 'worktree', 'remove', '--force', still.path]); + results.push({ ...c, outcome: 'removed' }); + } catch (e) { + results.push({ ...c, outcome: 'failed', detail: e.message }); + } + } + } + const failed = results.filter(r => r.outcome === 'failed').length + plan.kept.filter(k => k.error).length; + return { ...plan, non_worktree_folders: scan.non_worktree_folders, results, failed, sizes }; +} + +const sizeText = (c) => (c.size_kb === undefined ? '' : ` ${formatKb(c.size_kb)}`); + +/** Text for `bobby conductor reap --worktrees`. */ +export function renderWorktreeReap(report, { apply }) { + const lines = []; + const row = (label, c, extra) => lines.push(` ${label} ${c.repo} ${c.path} ${extra}${sizeText(c)}`); + if (!apply) { + lines.push(`Dry run: ${report.candidates.length} worktree(s) would be removed (git worktree remove --force; the branches are kept). Nothing was changed; add --apply to remove them.`); + for (const c of report.candidates) row('would remove', c, c.reason); + } else if (report.candidates.length === 0) { + lines.push('No worktrees to remove.'); + } else { + for (const r of report.results) row(r.outcome, r, r.detail ? `${r.reason}; ${r.detail}` : r.reason); + } + if (report.sizes) { + lines.push(`Size of the ${report.sizes.measured} candidate(s): ${formatKb(report.sizes.kb)} (du; a hardlinked node_modules counts in each worktree, so the space freed can be less).`); + } else if (report.candidates.length) { + lines.push('Sizes not measured (du is slow); add --sizes to measure the candidates.'); + } + const byReason = new Map(); + for (const k of report.kept) { + const reason = k.group || k.why; + byReason.set(reason, (byReason.get(reason) || 0) + 1); + } + lines.push(`Kept: ${report.kept.length} worktree(s).`); + for (const [reason, n] of [...byReason.entries()].sort((a, b) => b[1] - a[1])) lines.push(` ${n} ${reason}`); + // A worktree of a done ticket that was kept is the one worth reading about; list it. + for (const k of report.kept.filter(x => x.notable)) { + lines.push(` kept ${k.repo} ${k.path} ${k.ticket} ${k.why}${k.error ? `: ${k.error}` : ''}`); + } + lines.push(`Folders that are not git worktrees (listed, never touched): ${report.non_worktree_folders.length}`); + for (const f of report.non_worktree_folders) lines.push(` ${f}`); + return lines.join('\n'); +} diff --git a/lib/conductor/worktrees.js b/lib/conductor/worktrees.js new file mode 100644 index 0000000..52f5633 --- /dev/null +++ b/lib/conductor/worktrees.js @@ -0,0 +1,253 @@ +// lib/conductor/worktrees.js +// +// Read-only view of every git worktree in the studio (BOB-189). Worktrees are found with +// `git worktree list --porcelain` in the studio repo and in every repo named in the studio's +// .bobbyrc.yml `repos:`, never by guessing directories. Lanes hand-scaffold worktrees in +// several places (worktrees/, worktrees/robinflow/, repos//worktrees/, +// .claude/worktrees/, ~/worktrees), so the folders in those places that git does not +// know are listed too (and never touched). +// +// A worktree maps to a ticket by the ticket ID in its FOLDER name (RF-1123-ui, bob-189, +// LR-141-api), matched case-insensitively against the tickets on every studio board. The +// stage of that ticket is the stage the worktree is counted under. +// +// Sizes are NOT measured here unless asked: `du` over ~200 worktrees takes minutes, and +// `status` has to stay fast. measureSizes() is the slow path; the result is cached in +// /worktree-sizes.json and status shows the cached figures. + +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import YAML from 'yaml'; +import { run as defaultRun } from './exec.js'; +import { boardTickets } from './stacks.js'; +import { listStudioProjects } from '../config.js'; + +const SIZE_CACHE_FILE = 'worktree-sizes.json'; +const TICKET_TOKEN_RE = /(? { + try { return fs.realpathSync(p); } catch { return path.resolve(p); } +}; + +/** + * The repos whose worktrees are in scope: the studio repo itself, then every `repos:` entry + * of the studio's .bobbyrc.yml. [{ name, path }] with absolute paths. A listed repo whose + * folder is missing is an error, not a skip. + */ +export function studioRepos(studioRoot) { + const out = [{ name: '(studio)', path: studioRoot }]; + const rc = path.join(studioRoot, '.bobbyrc.yml'); + const parsed = YAML.parse(fs.readFileSync(rc, 'utf8')) || {}; + const repos = parsed.repos === undefined || parsed.repos === null ? {} : parsed.repos; + if (typeof repos !== 'object' || Array.isArray(repos)) throw new Error(`${rc}: key "repos" must be a mapping`); + const seen = new Set([real(studioRoot)]); + for (const [name, entry] of Object.entries(repos)) { + if (!entry || typeof entry.path !== 'string' || !entry.path.trim()) { + throw new Error(`${rc}: repos.${name} has no "path"`); + } + const abs = path.resolve(studioRoot, entry.path); + if (!fs.existsSync(abs)) throw new Error(`${rc}: repos.${name} path ${abs} does not exist`); + if (seen.has(real(abs))) continue; + seen.add(real(abs)); + out.push({ name, path: abs }); + } + return out; +} + +/** Parse `git worktree list --porcelain` text. The first block is the repo's main worktree. */ +export function parseWorktreeList(text, repoLabel = 'repo') { + const blocks = text.split(/\n\s*\n/).map(b => b.trim()).filter(Boolean); + const entries = blocks.map((block) => { + const e = { path: null, branch: null, bare: false, detached: false, locked: null, prunable: null }; + for (const line of block.split('\n')) { + const [key, ...rest] = line.split(' '); + const value = rest.join(' '); + if (key === 'worktree') e.path = value; + else if (key === 'branch') e.branch = value.replace(/^refs\/heads\//, ''); + else if (key === 'bare') e.bare = true; + else if (key === 'detached') e.detached = true; + else if (key === 'locked') e.locked = value || 'locked'; + else if (key === 'prunable') e.prunable = value || 'prunable'; + } + if (!e.path) throw new Error(`git worktree list for ${repoLabel} returned a block with no "worktree" line`); + if (e.path.startsWith('"')) throw new Error(`git worktree list for ${repoLabel} returned a quoted path (${e.path}); refusing to guess its real name`); + return e; + }); + if (entries.length === 0) throw new Error(`git worktree list for ${repoLabel} returned nothing`); + return entries; +} + +/** + * Every linked worktree of every repo: [{ repo, repo_path, path, branch, detached, bare, + * locked, prunable }], plus `registered`, the set of every registered path (main ones too). + * A failing git throws with git's message. + */ +export function listWorktrees(repos, { run = defaultRun } = {}) { + const worktrees = []; + const registered = new Set(); + for (const repo of repos) { + const entries = parseWorktreeList(run('git', ['-C', repo.path, 'worktree', 'list', '--porcelain']), repo.name); + entries.forEach((e, i) => { + registered.add(real(e.path)); + if (i === 0) return; + worktrees.push({ repo: repo.name, repo_path: repo.path, ...e }); + }); + } + return { worktrees, registered }; +} + +/** Ticket keys (PREFIX-n, zero padding dropped) named in a folder name that sit on a board. */ +export function ticketsInName(name, tickets) { + const found = []; + for (const m of name.matchAll(TICKET_TOKEN_RE)) { + const hit = tickets.get(`${m[1].toUpperCase()}-${Number(m[2])}`); + if (hit && !found.some(f => f.id === hit.id)) found.push(hit); + } + return found; +} + +/** + * Decorate worktrees with the ticket(s) their folder name carries and one `stage` to count + * them under: 'no ticket' when the name has no ticket on a board; 'done' only when every + * ticket named is done; otherwise the stage of the first ticket that is not done. + */ +export function classifyWorktrees(worktrees, tickets) { + return worktrees.map((w) => { + const found = ticketsInName(path.basename(w.path), tickets); + const open = found.find(t => t.stage !== 'done'); + return { + ...w, + ticket_ids: found.map(t => t.id), + stage: found.length === 0 ? 'no ticket' : (open ? open.stage : 'done'), + }; + }); +} + +/** The places lanes put worktrees by hand (see the file header). */ +export function containerDirs(studioRoot, repos, home = os.homedir()) { + return [ + path.join(studioRoot, 'worktrees'), + path.join(studioRoot, 'worktrees', 'robinflow'), + ...repos.filter(r => r.path !== studioRoot).map(r => path.join(r.path, 'worktrees')), + path.join(studioRoot, '.claude', 'worktrees'), + path.join(home, 'worktrees'), + ]; +} + +/** Directories one level inside the container dirs that git does not register as a worktree or repo. */ +export function nonWorktreeFolders(containers, registered) { + const containerReal = new Set(containers.map(real)); + const out = []; + const seen = new Set(); + for (const dir of containers) { + if (!fs.existsSync(dir)) continue; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const full = path.join(dir, entry.name); + const r = real(full); + if (registered.has(r) || containerReal.has(r) || seen.has(r)) continue; + seen.add(r); + out.push(full); + } + } + return out; +} + +/** The studio's boards: every project, not only the ones counted by `status`. */ +export function allBoardTickets(studioRoot) { + return boardTickets(studioRoot, listStudioProjects(studioRoot)); +} + +/** Everything read-only the status board and the reaper both need. */ +export function scanWorktrees(studioRoot, { run = defaultRun, home = os.homedir() } = {}) { + const repos = studioRepos(studioRoot); + const { worktrees, registered } = listWorktrees(repos, { run }); + const classified = classifyWorktrees(worktrees, allBoardTickets(studioRoot)); + return { + repos, + worktrees: classified, + non_worktree_folders: nonWorktreeFolders(containerDirs(studioRoot, repos, home), registered), + }; +} + +// ---- sizes (slow path, cached) ---- + +export function sizeCachePath(hookStateDir) { + return path.join(hookStateDir, SIZE_CACHE_FILE); +} + +/** { : { kb, measured_at } }. A missing file is an empty cache; an unreadable one is an error. */ +export function readSizeCache(hookStateDir) { + const file = sizeCachePath(hookStateDir); + if (!fs.existsSync(file)) return {}; + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(file, 'utf8')); + } catch (e) { + throw new Error(`${file}: unreadable size cache (${e.message}); delete it and re-measure with --sizes`); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) + || !Object.values(parsed).every(v => v && Number.isFinite(v.kb) && Number.isFinite(Date.parse(v.measured_at)))) { + throw new Error(`${file}: size cache has an unexpected shape; delete it and re-measure with --sizes`); + } + return parsed; +} + +function writeSizeCache(hookStateDir, cache) { + const file = sizeCachePath(hookStateDir); + const tmp = `${file}.${process.pid}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(cache, null, 2)); + fs.renameSync(tmp, file); +} + +/** + * `du -sk` each path (nominal size: a hardlinked node_modules counts in every worktree that + * holds it, so the sum is more than the space removing them frees). Updates the cache and + * returns it. A `du` failure throws naming the path. + */ +export function measureSizes(paths, { hookStateDir, run = defaultRun, now = Date.now() }) { + const cache = readSizeCache(hookStateDir); + for (const p of paths) { + const out = run('du', ['-sk', p]); + const kb = Number(out.split(/\s+/)[0]); + if (!Number.isFinite(kb)) throw new Error(`\`du -sk ${p}\` returned "${out.trim()}"`); + cache[p] = { kb, measured_at: new Date(now).toISOString() }; + } + writeSizeCache(hookStateDir, cache); + return cache; +} + +/** + * Worktree counts by stage for `status`: { repos, total, by_stage: [{ stage, count, + * sized, size_kb }], non_worktree_folders, sizes_measured_at }. `sized` is how many of the + * stage's worktrees have a cached size and `size_kb` their sum (null when none). + */ +export function worktreeSummary(scan, cache) { + const groups = new Map(); + let newest = null; + for (const w of scan.worktrees) { + const g = groups.get(w.stage) || { stage: w.stage, count: 0, sized: 0, size_kb: null }; + g.count += 1; + const c = cache[w.path]; + if (c) { + g.sized += 1; + g.size_kb = (g.size_kb || 0) + c.kb; + if (!newest || c.measured_at > newest) newest = c.measured_at; + } + groups.set(w.stage, g); + } + const by_stage = [...groups.values()].sort((a, b) => (a.stage === 'done' ? -1 : b.stage === 'done' ? 1 : b.count - a.count)); + return { + repos: scan.repos.length, + total: scan.worktrees.length, + by_stage, + non_worktree_folders: scan.non_worktree_folders, + sizes_measured_at: newest, + }; +} + +export function formatKb(kb) { + const gb = kb / (1024 * 1024); + return gb >= 1 ? `${gb.toFixed(1)} GB` : `${Math.round(kb / 1024)} MB`; +} diff --git a/test/commands/conductor.test.js b/test/commands/conductor.test.js index 89dcd27..aad3f5b 100644 --- a/test/commands/conductor.test.js +++ b/test/commands/conductor.test.js @@ -1,9 +1,10 @@ // End-to-end: `bobby conductor init|status` in a temp studio, with a fake `claude` // on PATH so no real session list is touched. -import { spawnSync } from 'child_process'; +import { spawnSync, execFileSync } from 'child_process'; import fs from 'fs'; import path from 'path'; import { STAGES } from '../../lib/stages.js'; +import { moveTicket, listTickets } from '../../lib/tickets.js'; import { makeStudio, writeConductorYml, validYml, seedTickets, agentsFixture, vmStatText, psLine } from '../lib/conductor/helpers.js'; const bobby = path.resolve('bin/bobby.js'); @@ -168,7 +169,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', 'ship_lanes', 'board', 'machine', 'stacks']); + expect(Object.keys(data)).toEqual(['generated_at', 'working', 'waiting_on_cc', 'done', 'stopped', 'interactive', 'unknown', 'handoffs', 'inbox', 'ship_lanes', 'board', 'machine', 'worktrees', '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']); @@ -278,6 +279,28 @@ describe('bobby conductor', () => { expect(ok.stdout).toMatch(/free RAM 7000 MB >= min 4096 MB/); }); + test('lane: refuses below governor.min_free_disk_gb with the disk numbers; the same volume passes with a 1 GB floor', () => { + setVm({ freeMb: 8000 }); + writeConductorYml(root, validYml(hookDir, ['alpha', 'beta'], { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 999999999 })); + const low = bobbyIn(['check', 'lane']); + expect(low.status).toBe(1); + expect(low.stderr).toMatch(/free RAM \d+ MB >= min 4096 MB; free disk [\d.]+ GB < min 999999999 GB/); + expect(bobbyIn(['check', 'stack']).status).toBe(1); + writeConductorYml(root, validYml(hookDir)); + const ok = bobbyIn(['check', 'lane']); + expect(ok.status).toBe(0); + expect(ok.stdout).toMatch(/free disk [\d.]+ GB >= min 1 GB/); + }); + + test('a conductor.yml without governor.min_free_disk_gb is an error naming the key', () => { + writeConductorYml(root, validYml(hookDir).replace(/ {2}min_free_disk_gb: \d+\n/, '')); + for (const args of [['check', 'lane'], ['status']]) { + const r = bobbyIn(args); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/key "governor\.min_free_disk_gb" is missing/); + } + }); + test('lane check does not need docker', () => { setVm({ freeMb: 8000 }); expect(bobbyIn(['check', 'lane'], { docker: 'fail' }).status).toBe(0); @@ -324,6 +347,33 @@ describe('bobby conductor', () => { }); }); + test('status shows DISK in MACHINE and WORKTREES by stage, with sizes only when asked', () => { + const dir = path.join(root, '.bobby', 'alpha', 'tickets'); + const [a, b] = ['AL-001', 'AL-002']; // beforeEach seeded AL-001 backlog, AL-002 and AL-003 building + moveTicket(dir, a, 'done', 'test'); + execFileSync('git', ['-C', root, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '--allow-empty', '-q', '-m', 'init']); + for (const name of [`${a}-ui`, `${a}-api`, `${b}-ui`, 'scratch']) execFileSync('git', ['-C', root, 'worktree', 'add', '-q', '-b', `br-${name}`, path.join(root, 'worktrees', name)]); + fs.mkdirSync(path.join(root, 'worktrees', 'plain-dir')); + const text = bobbyIn(['status']).stdout; + const machine = text.slice(text.indexOf('MACHINE'), text.indexOf('WORKTREES')); + expect(machine).toMatch(/DISK {2}free [\d.]+ GB of [\d.]+ GB {2}\(lane floor 1 GB\)/); + const wt = text.slice(text.indexOf('WORKTREES'), text.indexOf('STACKS')); + expect(wt).toMatch(/\(4 across 1 repos; 1 other folder\(s\) that are not git worktrees/); + expect(wt).toMatch(/done {2}2\n/); + expect(wt).toMatch(/building {2}1\n/); + expect(wt).toMatch(/no ticket {2}1\n/); + expect(wt).toMatch(/sizes: not measured/); + const data = JSON.parse(bobbyIn(['status', '--json']).stdout); + expect(data.worktrees).toMatchObject({ total: 4, repos: 1, sizes_measured_at: null }); + expect(data.machine).toMatchObject({ min_free_disk_gb: 1 }); + expect(data.machine.disk_free_gb).toBeGreaterThan(0); + const sized = bobbyIn(['status', '--sizes']); + expect(sized.status).toBe(0); + expect(sized.stdout).toMatch(/done {2}2 {2}.*(MB|GB)/); + expect(sized.stdout).toMatch(/sizes: du, nominal, cached /); + expect(bobbyIn(['status']).stdout).toMatch(/done {2}2 {2}.*(MB|GB)/); + }); + test('status works from a checkout nested under the studio', () => { const nested = path.join(root, 'worktrees', 'X'); fs.mkdirSync(nested, { recursive: true }); @@ -476,4 +526,71 @@ describe('bobby conductor', () => { expect(r.stderr).toMatch(/key "reaper\.stack_idle_hours" is missing/); }); }); + + describe('reap --worktrees', () => { + let doneWt; + let busyWt; + beforeEach(() => { + writeConductorYml(root, validYml(hookDir)); + const dir = path.join(root, '.bobby', 'alpha', 'tickets'); + seedTickets(root, 'alpha', [{ title: 'a' }, { title: 'b' }]); + const [a, b] = listTickets(dir).map(t => t.id); + moveTicket(dir, a, 'done', 'test'); + execFileSync('git', ['-C', root, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '--allow-empty', '-q', '-m', 'init']); + doneWt = path.join(root, 'worktrees', `${a}-ui`); + busyWt = path.join(root, 'worktrees', `${b}-ui`); + for (const p of [doneWt, busyWt]) execFileSync('git', ['-C', root, 'worktree', 'add', '-q', '-b', `br-${path.basename(p)}`, p]); + }); + + test('dry run lists the done worktree, removes nothing, exits 0', () => { + const r = bobbyIn(['reap', '--worktrees']); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/Dry run: 1 worktree\(s\) would be removed/); + expect(r.stdout).toMatch(/would remove .*AL-001-ui/); + expect(r.stdout).toMatch(/Sizes not measured/); + expect(fs.existsSync(doneWt)).toBe(true); + }); + + test('--apply removes it and keeps the branch; the open ticket worktree stays', () => { + const r = bobbyIn(['reap', '--worktrees', '--apply']); + expect(r.status).toBe(0); + expect(fs.existsSync(doneWt)).toBe(false); + expect(fs.existsSync(busyWt)).toBe(true); + expect(execFileSync('git', ['-C', root, 'branch', '--list', 'br-AL-001-ui'], { encoding: 'utf8' })).toMatch(/br-AL-001-ui/); + }); + + test('--sizes measures the candidates', () => { + expect(bobbyIn(['reap', '--worktrees', '--sizes']).stdout).toMatch(/Size of the 1 candidate/); + }); + + test('a live session inside the worktree keeps it', () => { + const agents = agentsFixture(); + agents.push({ id: 'ffff6666', sessionId: 'ffff6666-0000-4000-8000-000000000000', name: 'lane', cwd: doneWt, kind: 'background', startedAt: 1, state: 'working', pid: 5 }); + fs.writeFileSync(agentsFile, JSON.stringify(agents)); + const r = bobbyIn(['reap', '--worktrees', '--apply']); + expect(r.status).toBe(0); + expect(fs.existsSync(doneWt)).toBe(true); + expect(r.stdout).toMatch(/live session "lane" is inside it/); + }); + + test('claude failing is a non-zero exit and nothing is removed', () => { + const r = bobbyIn(['reap', '--worktrees', '--apply'], { claude: 'fail' }); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/claude is down/); + expect(fs.existsSync(doneWt)).toBe(true); + }); + + test('it refuses on a host that is not the M4, even without --apply', () => { + const r = bobbyIn(['reap', '--worktrees'], { cpu: 'Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz' }); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/M4 only/); + }); + + test('--stacks with --worktrees, and --sizes without --worktrees, are errors', () => { + expect(bobbyIn(['reap', '--stacks', '--worktrees']).stderr).toMatch(/Pick one of --stacks and --worktrees/); + const r = bobbyIn(['reap', '--sizes']); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/--sizes only applies to --worktrees/); + }); + }); }); diff --git a/test/lib/conductor/config.test.js b/test/lib/conductor/config.test.js index bc76a34..e9beb07 100644 --- a/test/lib/conductor/config.test.js +++ b/test/lib/conductor/config.test.js @@ -19,7 +19,7 @@ describe('conductor config', () => { expect(loadConductorConfig(root)).toEqual({ projects: ['alpha'], hook_state_dir: hookDir, - governor: { min_free_ram_mb: 4096, max_docker_stacks: 4 }, + governor: { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 1 }, reaper: { stack_idle_hours: 2 }, wip: { max_lanes: 6 }, claims: { ttl_minutes: 30 }, @@ -27,7 +27,7 @@ describe('conductor config', () => { }); }); - const govYml = 'projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n max_docker_stacks: 4\n'; + const govYml = 'projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n max_docker_stacks: 4\n min_free_disk_gb: 50\n'; test.each([ ['reaper.stack_idle_hours', govYml], ['reaper.stack_idle_hours', `${govYml}reaper:\n other: 1\n`], @@ -75,6 +75,8 @@ describe('conductor config', () => { ['governor.min_free_ram_mb', `projects:\n - alpha\nhook_state_dir: /x\n`], ['governor.min_free_ram_mb', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n max_docker_stacks: 4\n`], ['governor.max_docker_stacks', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n`], + ['governor.min_free_disk_gb', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n max_docker_stacks: 4\n`], + ['governor.min_free_disk_gb', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n max_docker_stacks: 4\n min_free_disk_gb:\n`], ])('missing key "%s" throws naming the key and the file; no default applied', (key, yml) => { writeConductorYml(root, yml); expect(() => loadConductorConfig(root)).toThrow(new RegExp(`conductor\\.yml: key "${key}" is missing`)); @@ -89,6 +91,8 @@ describe('conductor config', () => { ['governor.min_free_ram_mb', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 0\n max_docker_stacks: 4\n`], ['governor.min_free_ram_mb', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: lots\n max_docker_stacks: 4\n`], ['governor.max_docker_stacks', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n max_docker_stacks: 2.5\n`], + ['governor.min_free_disk_gb', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n max_docker_stacks: 4\n min_free_disk_gb: 0\n`], + ['governor.min_free_disk_gb', `projects:\n - alpha\nhook_state_dir: /x\ngovernor:\n min_free_ram_mb: 4096\n max_docker_stacks: 4\n min_free_disk_gb: lots\n`], ])('invalid "%s" throws naming the key', (key, yml) => { writeConductorYml(root, yml); expect(() => loadConductorConfig(root)).toThrow(new RegExp(`key "${key}" must be`)); @@ -105,7 +109,7 @@ describe('conductor config', () => { expect(values).toEqual({ projects: ['alpha'], hook_state_dir: path.join(os.homedir(), '.bobby', 'hook-state'), - governor: { min_free_ram_mb: 4096, max_docker_stacks: 4 }, + governor: { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 50 }, reaper: { stack_idle_hours: 2 }, wip: { max_lanes: 6 }, claims: { ttl_minutes: 30 }, @@ -114,7 +118,7 @@ describe('conductor config', () => { 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(/governor:\n {2}min_free_ram_mb: 4096\n {2}max_docker_stacks: 4\n {2}min_free_disk_gb: 50\n/); expect(fs.readFileSync(file, 'utf8')).toMatch(/reaper:\n {2}stack_idle_hours: 2\n/); expect(fs.readFileSync(file, 'utf8')).toMatch(/inbox:\n {2}stale_minutes: 30\n/); }); diff --git a/test/lib/conductor/disk.test.js b/test/lib/conductor/disk.test.js new file mode 100644 index 0000000..2d637b8 --- /dev/null +++ b/test/lib/conductor/disk.test.js @@ -0,0 +1,31 @@ +import { readDisk } from '../../../lib/conductor/disk.js'; + +const GB = 1024 ** 3; +const fake = (over = {}) => () => ({ bsize: 4096, blocks: (926 * GB) / 4096, bavail: (14.27 * GB) / 4096, ...over }); + +describe('conductor disk probe', () => { + test('reports total and free GB of the volume holding the studio', () => { + expect(readDisk('/studio', { statfs: fake() })).toEqual({ path: '/studio', total_gb: 926, free_gb: 14.2 }); + }); + + test('free is floored to a tenth, never rounded up past the floor', () => { + expect(readDisk('/studio', { statfs: fake({ bavail: (49.99 * GB) / 4096 }) }).free_gb).toBe(49.9); + }); + + test('a failing statfs is an error naming the path', () => { + const statfs = () => { throw new Error('ENOENT: no such file'); }; + expect(() => readDisk('/studio', { statfs })).toThrow(/Cannot read free disk space for \/studio: ENOENT/); + }); + + test('implausible figures are refused, not trusted', () => { + expect(() => readDisk('/studio', { statfs: fake({ blocks: 0 }) })).toThrow(/implausible/); + expect(() => readDisk('/studio', { statfs: fake({ bavail: (2000 * GB) / 4096 }) })).toThrow(/implausible/); + expect(() => readDisk('/studio', { statfs: fake({ bavail: undefined }) })).toThrow(/implausible/); + }); + + test('the real probe reads this machine', () => { + const d = readDisk(process.cwd()); + expect(d.total_gb).toBeGreaterThan(0); + expect(d.free_gb).toBeLessThanOrEqual(d.total_gb); + }); +}); diff --git a/test/lib/conductor/governor.test.js b/test/lib/conductor/governor.test.js index f5766c6..4182612 100644 --- a/test/lib/conductor/governor.test.js +++ b/test/lib/conductor/governor.test.js @@ -1,22 +1,42 @@ import { checkLane, checkStack } from '../../../lib/conductor/governor.js'; -const config = { governor: { min_free_ram_mb: 4096, max_docker_stacks: 4 } }; +const config = { governor: { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 50 } }; +const roomy = { free_gb: 200 }; describe('conductor governor', () => { - test('lane: refuses below the floor with both numbers, passes at and above it', () => { - expect(checkLane(config, { free_mb: 1200 })).toMatchObject({ ok: false, reason: 'free RAM 1200 MB < min 4096 MB' }); - expect(checkLane(config, { free_mb: 4095 }).ok).toBe(false); - expect(checkLane(config, { free_mb: 4096 }).ok).toBe(true); - expect(checkLane(config, { free_mb: 9000 })).toMatchObject({ ok: true, numbers: { free_ram_mb: 9000, min_free_ram_mb: 4096 } }); + test('lane: refuses below the RAM floor with both numbers, passes at and above it', () => { + expect(checkLane(config, { free_mb: 1200 }, roomy)).toMatchObject({ ok: false, reason: expect.stringMatching(/^free RAM 1200 MB < min 4096 MB/) }); + expect(checkLane(config, { free_mb: 4095 }, roomy).ok).toBe(false); + expect(checkLane(config, { free_mb: 4096 }, roomy).ok).toBe(true); + expect(checkLane(config, { free_mb: 9000 }, roomy)).toMatchObject({ + ok: true, + numbers: { free_ram_mb: 9000, min_free_ram_mb: 4096, free_disk_gb: 200, min_free_disk_gb: 50 }, + }); + }); + + test('lane: refuses below the disk floor with both numbers, passes at it', () => { + expect(checkLane(config, { free_mb: 9000 }, { free_gb: 14.2 })).toMatchObject({ + ok: false, + reason: 'free RAM 9000 MB >= min 4096 MB; free disk 14.2 GB < min 50 GB', + }); + expect(checkLane(config, { free_mb: 9000 }, { free_gb: 49.9 }).ok).toBe(false); + expect(checkLane(config, { free_mb: 9000 }, { free_gb: 50 }).ok).toBe(true); + }); + + test('lane: when RAM and disk are both short the reason names both', () => { + const r = checkLane(config, { free_mb: 100 }, { free_gb: 3 }); + expect(r.ok).toBe(false); + expect(r.reason).toBe('free RAM 100 MB < min 4096 MB; free disk 3 GB < min 50 GB'); }); test('stack: refuses at the cap (>=) with the count and the cap', () => { - expect(checkStack(config, { free_mb: 9000 }, 4)).toMatchObject({ ok: false, reason: 'docker stacks 4 >= max 4' }); - expect(checkStack(config, { free_mb: 9000 }, 11).ok).toBe(false); - expect(checkStack(config, { free_mb: 9000 }, 3)).toMatchObject({ ok: true, numbers: { docker_stacks: 3, max_docker_stacks: 4 } }); + expect(checkStack(config, { free_mb: 9000 }, roomy, 4)).toMatchObject({ ok: false, reason: 'docker stacks 4 >= max 4' }); + expect(checkStack(config, { free_mb: 9000 }, roomy, 11).ok).toBe(false); + expect(checkStack(config, { free_mb: 9000 }, roomy, 3)).toMatchObject({ ok: true, numbers: { docker_stacks: 3, max_docker_stacks: 4 } }); }); - test('stack: low RAM refuses first, even with room for stacks', () => { - expect(checkStack(config, { free_mb: 100 }, 0)).toMatchObject({ ok: false, reason: 'free RAM 100 MB < min 4096 MB' }); + test('stack: low RAM or low disk refuses first, even with room for stacks', () => { + expect(checkStack(config, { free_mb: 100 }, roomy, 0)).toMatchObject({ ok: false, reason: expect.stringMatching(/^free RAM 100 MB < min 4096 MB/) }); + expect(checkStack(config, { free_mb: 9000 }, { free_gb: 10 }, 0)).toMatchObject({ ok: false, reason: expect.stringMatching(/free disk 10 GB < min 50 GB/) }); }); }); diff --git a/test/lib/conductor/helpers.js b/test/lib/conductor/helpers.js index a9383e7..c5f8e6d 100644 --- a/test/lib/conductor/helpers.js +++ b/test/lib/conductor/helpers.js @@ -2,6 +2,7 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; +import { execFileSync } from 'child_process'; import { initStudio, createProject } from '../../../lib/studio.js'; import { createTicket, moveTicket, updateTicket } from '../../../lib/tickets.js'; @@ -9,6 +10,8 @@ import { createTicket, moveTicket, updateTicket } from '../../../lib/tickets.js' export function makeStudio() { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-conductor-')); initStudio(root); + // The studio is itself a git repo: `status` lists its worktrees. + execFileSync('git', ['init', '-q', root]); createProject(root, 'alpha', { prefix: 'AL' }); createProject(root, 'beta', { prefix: 'BE' }); const hookDir = path.join(root, 'hook-state'); @@ -21,9 +24,9 @@ export function writeConductorYml(root, text) { fs.writeFileSync(path.join(root, '.bobby', 'conductor.yml'), text); } -export function validYml(hookDir, projects = ['alpha', 'beta'], governor = { min_free_ram_mb: 4096, max_docker_stacks: 4 }, reaper = { stack_idle_hours: 2 }, wip = { max_lanes: 6 }, claims = { ttl_minutes: 30 }, inbox = { stale_minutes: 30 }) { +export function validYml(hookDir, projects = ['alpha', 'beta'], governor = { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 1 }, reaper = { stack_idle_hours: 2 }, wip = { max_lanes: 6 }, claims = { ttl_minutes: 30 }, inbox = { stale_minutes: 30 }) { return `projects:\n${projects.map(p => ` - ${p}`).join('\n')}\nhook_state_dir: ${hookDir}\n` - + `governor:\n min_free_ram_mb: ${governor.min_free_ram_mb}\n max_docker_stacks: ${governor.max_docker_stacks}\n` + + `governor:\n min_free_ram_mb: ${governor.min_free_ram_mb}\n max_docker_stacks: ${governor.max_docker_stacks}\n min_free_disk_gb: ${governor.min_free_disk_gb}\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` diff --git a/test/lib/conductor/queue.test.js b/test/lib/conductor/queue.test.js index 7766bde..57bde2c 100644 --- a/test/lib/conductor/queue.test.js +++ b/test/lib/conductor/queue.test.js @@ -126,6 +126,13 @@ describe('conductor queue and next', () => { expect(r.reason).toMatch(/free RAM 100 MB < min 4096 MB/); }); + test('refuses with the disk reason when free disk is under governor.min_free_disk_gb', () => { + writeQueue([idOf('shipping one')]); + const r = next({ disk: { free_gb: 0.5 } }).result(); + expect(r.kind).toBe('refused'); + expect(r.reason).toMatch(/free disk 0\.5 GB < min 1 GB/); + }); + 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/); diff --git a/test/lib/conductor/read-only.test.js b/test/lib/conductor/read-only.test.js index cbd2dd5..8f8c481 100644 --- a/test/lib/conductor/read-only.test.js +++ b/test/lib/conductor/read-only.test.js @@ -2,6 +2,7 @@ // ticket allow-lists exactly its one command here. BOB-176: lib/conductor/reaper.js // may name `claude stop` (and only that); see the reaper block below. BOB-177: // lib/conductor/stack-reaper.js may name `docker compose -p stop` (and only that). +// BOB-189: lib/conductor/worktree-reaper.js may name `git -C worktree remove --force ` (and only that). import fs from 'fs'; import path from 'path'; @@ -75,3 +76,28 @@ describe('the stack reaper does exactly one docker thing', () => { } }); }); + +describe('the worktree reaper does exactly one removal', () => { + const src = fs.readFileSync(path.resolve('lib/conductor/worktree-reaper.js'), 'utf8'); + const code = src.split('\n').filter(l => !l.trim().startsWith('//')).join('\n'); + + test('`git -C worktree remove --force ` is the only exec that changes anything', () => { + const runs = [...code.matchAll(/\brun\(([^)]*)\)/g)].map(m => m[1].replace(/\s+/g, ' ')); + expect(runs).toEqual([ + "'git', ['-C', p, 'status', '--porcelain', '-uno']", + "'git', ['-C', still.repo_path, 'worktree', 'remove', '--force', still.path]", + ]); + }); + + test('no rm, prune, branch delete, recursive delete or file write in it or in worktrees.js beyond the size cache', () => { + for (const re of [/\brm\b/, /rmSync/, /unlink/, /prune/i, /\bbranch\b.*['"]-[dD]['"]/, /['"]clean['"]/, /['"]reset['"]/, /recursive/, /writeFile/, /rename/]) { + expect(code).not.toMatch(re); + } + const lib = fs.readFileSync(path.resolve('lib/conductor/worktrees.js'), 'utf8').split('\n').filter(l => !l.trim().startsWith('//')).join('\n'); + expect(lib).not.toMatch(/\brm\b|rmSync|unlink|prune|recursive/i); + expect([...lib.matchAll(/\brun\(([^)]*)\)/g)].map(m => m[1].replace(/\s+/g, ' '))).toEqual([ + "'git', ['-C', repo.path, 'worktree', 'list', '--porcelain']", + "'du', ['-sk', p]", + ]); + }); +}); diff --git a/test/lib/conductor/worktree-reaper.test.js b/test/lib/conductor/worktree-reaper.test.js new file mode 100644 index 0000000..e8d0195 --- /dev/null +++ b/test/lib/conductor/worktree-reaper.test.js @@ -0,0 +1,245 @@ +// Real git in a temp studio (and a second temp repo), with only `claude agents` mocked. +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { execFileSync } from 'child_process'; +import YAML from 'yaml'; +import { jest } from '@jest/globals'; +import { run as realRun } from '../../../lib/conductor/exec.js'; +import { moveTicket, listTickets } from '../../../lib/tickets.js'; +import { reapWorktrees, renderWorktreeReap, evaluateWorktrees } from '../../../lib/conductor/worktree-reaper.js'; +import { readSizeCache } from '../../../lib/conductor/worktrees.js'; +import { makeStudio, seedTickets } from './helpers.js'; + +const git = (cwd, ...args) => execFileSync('git', ['-C', cwd, '-c', 'user.email=t@t', '-c', 'user.name=t', ...args], { encoding: 'utf8' }); +const sid = (id) => `${id}-0000-4000-8000-000000000000`; +const bg = (id, name, state, cwd, extra = {}) => ({ id, sessionId: sid(id), name, cwd, kind: 'background', startedAt: 1, state, pid: 99, ...extra }); + +describe('conductor worktree reaper', () => { + let root; + let hookDir; + let config; + let app; + let home; + const ticketsDir = () => path.join(root, '.bobby', 'alpha', 'tickets'); + const finish = (n) => moveTicket(ticketsDir(), listTickets(ticketsDir()).find(t => Number(t.id.split('-')[1]) === n).id, 'done', 'test'); + const wt = (repo, name) => { + const p = path.join(repo, 'worktrees', name); + git(repo, 'worktree', 'add', '-q', '-b', `br-${name}`, p); + return fs.realpathSync(p); + }; + + /** run: real exec for everything but `claude agents`; every call recorded. */ + function mockRun({ agents = [], failList = false, failStatus = null } = {}) { + const calls = []; + let reads = 0; + const run = (cmd, args) => { + calls.push([cmd, ...args]); + if (cmd === 'claude') { reads += 1; return JSON.stringify(typeof agents === 'function' ? agents(reads) : agents); } + if (failList && args.includes('list')) throw new Error('`git worktree list` failed: fatal: not a git repository'); + if (failStatus && args.includes('status') && args[1] === failStatus) throw new Error('`git status` failed: index.lock exists'); + return realRun(cmd, args); + }; + return { run, calls, removals: () => calls.filter(c => c.includes('remove')) }; + } + + const go = (m, opts = {}) => reapWorktrees({ studioRoot: root, config, run: m.run, cwd: os.tmpdir(), home, ...opts }); + const exists = (p) => fs.existsSync(p); + + beforeEach(() => { + ({ root, hookDir } = makeStudio()); + fs.writeFileSync(path.join(root, 'tracked.txt'), 'a\n'); + git(root, 'add', 'tracked.txt'); + git(root, 'commit', '-q', '-m', 'init'); + app = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-wt-app-')); + execFileSync('git', ['init', '-q', app]); + git(app, 'commit', '--allow-empty', '-q', '-m', 'init'); + const rc = path.join(root, '.bobbyrc.yml'); + const parsed = YAML.parse(fs.readFileSync(rc, 'utf8')); + fs.writeFileSync(rc, YAML.stringify({ ...parsed, repos: { ...(parsed.repos || {}), app: { path: app } } })); + home = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-wt-home-')); + seedTickets(root, 'alpha', [{ title: 'one' }, { title: 'two' }, { title: 'three' }, { title: 'four' }, { title: 'five' }]); + config = { projects: ['alpha'], hook_state_dir: hookDir, governor: {}, reaper: {}, claims: {} }; + }); + afterEach(() => { + for (const d of [root, app, home]) fs.rmSync(d, { recursive: true, force: true }); + }); + + test('dry run lists only done, clean worktrees with no live session; every other case is kept with its reason; nothing changes', () => { + finish(1); finish(3); finish(4); + const clean = wt(root, 'AL-1-ui'); + const building = wt(root, 'AL-2-ui'); + const dirty = wt(root, 'AL-3-ui'); + const live = wt(root, 'AL-4-ui'); + const scratch = wt(root, 'scratchpad'); + fs.appendFileSync(path.join(dirty, 'tracked.txt'), 'edit\n'); + const m = mockRun({ agents: [bg('aaaa1111', 'lane for four', 'working', path.join(live, 'src'))] }); + const report = go(m); + expect(report.candidates.map(c => c.path)).toEqual([clean]); + const why = Object.fromEntries(report.kept.map(k => [path.basename(k.path), k.why])); + expect(why['AL-2-ui']).toBe('ticket AL-002 is backlog'); + expect(why['AL-3-ui']).toMatch(/1 tracked file\(s\) modified or staged/); + expect(why['AL-4-ui']).toMatch(/live session "lane for four" is inside it/); + expect(why.scratchpad).toMatch(/no ticket on a board/); + expect(m.removals()).toEqual([]); + for (const p of [clean, building, dirty, live, scratch]) expect(exists(p)).toBe(true); + const text = renderWorktreeReap(report, { apply: false }); + expect(text).toMatch(/Dry run: 1 worktree\(s\) would be removed/); + expect(text).toMatch(/would remove .*AL-1-ui/); + }); + + test('--apply runs only `git -C
worktree remove --force `, keeps the branch, and covers every repo', () => { + finish(1); finish(5); + const a = wt(root, 'al-1-studio'); + const b = wt(app, 'AL-5-app'); + const keep = wt(root, 'AL-2-ui'); + const m = mockRun(); + const report = go(m, { apply: true }); + expect(report.results.map(r => [path.basename(r.path), r.outcome])).toEqual([['al-1-studio', 'removed'], ['AL-5-app', 'removed']]); + expect(m.removals()).toEqual([ + ['git', '-C', root, 'worktree', 'remove', '--force', a], + ['git', '-C', app, 'worktree', 'remove', '--force', b], + ]); + expect(exists(a)).toBe(false); + expect(exists(b)).toBe(false); + expect(exists(keep)).toBe(true); + expect(git(root, 'branch', '--list', 'br-al-1-studio')).toMatch(/br-al-1-studio/); + expect(git(app, 'branch', '--list', 'br-AL-5-app')).toMatch(/br-AL-5-app/); + expect(git(root, 'worktree', 'list')).not.toMatch(/al-1-studio/); + expect(report.failed).toBe(0); + }); + + test('untracked and ignored files do not block removal (only tracked changes do)', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + fs.writeFileSync(path.join(p, 'scratch.log'), 'x'); + const report = go(mockRun(), { apply: true }); + expect(report.results[0].outcome).toBe('removed'); + expect(exists(p)).toBe(false); + }); + + test('a session that has ended (done, no pid) does not keep a worktree; interactive and blocked ones do', () => { + finish(1); finish(3); finish(4); + const ended = wt(root, 'AL-1-ui'); + const blocked = wt(root, 'AL-3-ui'); + const terminal = wt(root, 'AL-4-ui'); + const m = mockRun({ + agents: [ + bg('aaaa1111', 'ended', 'done', ended, { pid: undefined }), + bg('bbbb2222', 'waits', 'blocked', blocked), + { sessionId: sid('cccc3333'), name: 'terminal', cwd: terminal, kind: 'interactive', startedAt: 1, status: 'idle', pid: 7 }, + ], + }); + expect(go(m).candidates.map(c => path.basename(c.path))).toEqual(['AL-1-ui']); + }); + + test('a lane that starts between the plan and the removal keeps its worktree', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + const m = mockRun({ agents: (reads) => (reads === 1 ? [] : [bg('aaaa1111', 'late lane', 'working', p)]) }); + const report = go(m, { apply: true }); + expect(report.candidates).toHaveLength(1); + expect(report.results[0]).toMatchObject({ outcome: 'skipped' }); + expect(report.results[0].detail).toMatch(/live session "late lane"/); + expect(m.removals()).toEqual([]); + expect(exists(p)).toBe(true); + }); + + test('the folder this command runs from is never removed', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + const report = go(mockRun(), { cwd: path.join(p, 'sub') }); + expect(report.candidates).toEqual([]); + expect(report.kept[0].why).toMatch(/running inside it/); + }); + + test('a locked worktree and a prunable one (folder already gone) are kept', () => { + finish(1); finish(3); + const locked = wt(root, 'AL-1-ui'); + git(root, 'worktree', 'lock', locked); + const gone = wt(root, 'AL-3-ui'); + fs.rmSync(gone, { recursive: true }); + const report = go(mockRun(), { apply: true }); + expect(report.candidates).toEqual([]); + expect(report.kept.map(k => k.why).join('\n')).toMatch(/locked[\s\S]*prunable/); + expect(exists(locked)).toBe(true); + }); + + test('folders that are not git worktrees are listed and never touched', () => { + finish(1); + const plain = path.join(root, 'worktrees', 'AL-1-leftover'); + fs.mkdirSync(plain, { recursive: true }); + fs.writeFileSync(path.join(plain, 'keep.txt'), 'x'); + fs.mkdirSync(path.join(home, 'worktrees', 'old-thing'), { recursive: true }); + const m = mockRun(); + const report = go(m, { apply: true }); + expect(report.candidates).toEqual([]); + expect(report.non_worktree_folders).toEqual([plain, path.join(home, 'worktrees', 'old-thing')]); + expect(exists(path.join(plain, 'keep.txt'))).toBe(true); + expect(m.removals()).toEqual([]); + expect(renderWorktreeReap(report, { apply: true })).toMatch(/not git worktrees .*: 2\n\s+.*AL-1-leftover/); + }); + + test('a failing git is an explicit error, never "no worktrees"', () => { + expect(() => go(mockRun({ failList: true }))).toThrow(/git worktree list. failed/); + }); + + test('a failing git status keeps the worktree, is reported, and makes the run fail', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + const m = mockRun({ failStatus: p }); + const report = go(m, { apply: true }); + expect(report.candidates).toEqual([]); + expect(report.failed).toBe(1); + expect(report.kept[0]).toMatchObject({ why: 'git status failed', error: expect.stringMatching(/index\.lock/) }); + expect(exists(p)).toBe(true); + }); + + test('a failing claude is an explicit error and nothing is removed', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + const run = (cmd, args) => { if (cmd === 'claude') throw new Error('`claude agents --json --all` failed: down'); return realRun(cmd, args); }; + expect(() => reapWorktrees({ studioRoot: root, config, run, apply: true, cwd: os.tmpdir(), home })).toThrow(/claude agents/); + expect(exists(p)).toBe(true); + }); + + test('a failing removal is reported as failed with the git message', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + const run = (cmd, args) => { + if (args.includes('remove')) throw new Error('`git worktree remove` failed: contains modified or untracked files'); + return mockRun().run(cmd, args); + }; + const report = reapWorktrees({ studioRoot: root, config, run, apply: true, cwd: os.tmpdir(), home }); + expect(report.results[0]).toMatchObject({ outcome: 'failed' }); + expect(report.failed).toBe(1); + expect(exists(p)).toBe(true); + }); + + test('--sizes measures the candidates with du and caches them; without it no du runs', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + fs.writeFileSync(path.join(p, 'big.bin'), Buffer.alloc(2 * 1024 * 1024)); + const plain = mockRun(); + expect(go(plain).sizes).toBeNull(); + expect(plain.calls.filter(c => c[0] === 'du')).toEqual([]); + const m = mockRun(); + const report = go(m, { measure: true }); + expect(m.calls.filter(c => c[0] === 'du')).toEqual([['du', '-sk', p]]); + expect(report.sizes.kb).toBeGreaterThanOrEqual(2048); + expect(readSizeCache(hookDir)[p].kb).toBe(report.sizes.kb); + expect(renderWorktreeReap(report, { apply: false })).toMatch(/Size of the 1 candidate/); + }); + + test('evaluateWorktrees never asks git for a worktree an earlier rule already kept', () => { + const dirty = jest.fn(() => ''); + const w = (over) => ({ repo: 'r', path: '/w/x', branch: 'b', ticket_ids: ['AL-1'], stage: 'done', ...over }); + const { candidates, kept } = evaluateWorktrees( + [w({ stage: 'building' }), w({ ticket_ids: [], stage: 'no ticket' }), w({ locked: 'x' })], + { live: [], cwd: '/elsewhere', dirty }, + ); + expect(candidates).toEqual([]); + expect(kept).toHaveLength(3); + expect(dirty).not.toHaveBeenCalled(); + }); +}); diff --git a/test/lib/conductor/worktrees.test.js b/test/lib/conductor/worktrees.test.js new file mode 100644 index 0000000..04bd6f1 --- /dev/null +++ b/test/lib/conductor/worktrees.test.js @@ -0,0 +1,136 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { + parseWorktreeList, ticketsInName, classifyWorktrees, studioRepos, nonWorktreeFolders, + readSizeCache, measureSizes, worktreeSummary, formatKb, sizeCachePath, +} from '../../../lib/conductor/worktrees.js'; + +const tickets = new Map([ + ['RF-1123', { id: 'RF-1123', stage: 'done' }], + ['BOB-189', { id: 'BOB-189', stage: 'building' }], + ['LR-141', { id: 'LR-141', stage: 'done' }], +]); + +describe('conductor worktrees', () => { + let dir; + beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-wt-')); }); + afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + + describe('parseWorktreeList', () => { + const text = [ + 'worktree /s', 'HEAD aaa', 'branch refs/heads/main', '', + 'worktree /s/worktrees/RF-1', 'HEAD bbb', 'branch refs/heads/tkt-rf-1', '', + 'worktree /s/worktrees/x', 'HEAD ccc', 'detached', 'locked on a usb stick', '', + 'worktree /gone', 'HEAD ddd', 'branch refs/heads/old', 'prunable gitdir file points to non-existent location', '', + ].join('\n'); + + test('first block is the main worktree; flags are read', () => { + const e = parseWorktreeList(text); + expect(e.map(x => x.path)).toEqual(['/s', '/s/worktrees/RF-1', '/s/worktrees/x', '/gone']); + expect(e[1].branch).toBe('tkt-rf-1'); + expect(e[2]).toMatchObject({ detached: true, locked: 'on a usb stick', branch: null }); + expect(e[3].prunable).toMatch(/non-existent/); + }); + + test('an empty list or a quoted path is an error', () => { + expect(() => parseWorktreeList('')).toThrow(/returned nothing/); + expect(() => parseWorktreeList('worktree "/s/we\\303\\251ird"\nHEAD a\n')).toThrow(/quoted path/); + }); + }); + + describe('ticket mapping', () => { + test('finds the ticket ID in the folder name, case-insensitively and ignoring zero padding', () => { + expect(ticketsInName('RF-1123-ui', tickets).map(t => t.id)).toEqual(['RF-1123']); + expect(ticketsInName('rf-1123-api', tickets).map(t => t.id)).toEqual(['RF-1123']); + expect(ticketsInName('listrobin-ui-lr-0141', tickets).map(t => t.id)).toEqual(['LR-141']); + expect(ticketsInName('RF-11234-ui', tickets)).toEqual([]); + expect(ticketsInName('BUNDLE-AL-api', tickets)).toEqual([]); + expect(ticketsInName('RF-9999-ui', tickets)).toEqual([]); + }); + + test('stage: done only when every named ticket is done; otherwise the open ticket; none = no ticket', () => { + const wt = (p) => ({ path: p }); + const out = classifyWorktrees([wt('/w/RF-1123-ui'), wt('/w/RF-1123-BOB-189'), wt('/w/scratch'), wt('/w/RF-1123-LR-141')], tickets); + expect(out.map(w => w.stage)).toEqual(['done', 'building', 'no ticket', 'done']); + expect(out[1].ticket_ids).toEqual(['RF-1123', 'BOB-189']); + }); + }); + + describe('studioRepos', () => { + const write = (yml) => fs.writeFileSync(path.join(dir, '.bobbyrc.yml'), yml); + test('the studio first, then every repos: path, resolved against the studio', () => { + fs.mkdirSync(path.join(dir, 'repos', 'app'), { recursive: true }); + write('studio: s\nrepos:\n app:\n path: repos/app\n'); + expect(studioRepos(dir)).toEqual([{ name: '(studio)', path: dir }, { name: 'app', path: path.join(dir, 'repos', 'app') }]); + }); + test('a studio with no repos: lists only itself', () => { + write('studio: s\n'); + expect(studioRepos(dir)).toEqual([{ name: '(studio)', path: dir }]); + }); + test('a listed repo whose folder is missing, or has no path, is an error', () => { + write('studio: s\nrepos:\n app:\n path: repos/app\n'); + expect(() => studioRepos(dir)).toThrow(/repos\.app path .* does not exist/); + write('studio: s\nrepos:\n app:\n url: x\n'); + expect(() => studioRepos(dir)).toThrow(/repos\.app has no "path"/); + }); + }); + + test('nonWorktreeFolders lists directories git does not know, not files, containers or registered worktrees', () => { + const top = path.join(dir, 'worktrees'); + const robin = path.join(top, 'robinflow'); + for (const d of ['registered', 'plain', 'robinflow/inner']) fs.mkdirSync(path.join(top, d), { recursive: true }); + fs.writeFileSync(path.join(top, 'run.log'), 'x'); + const registered = new Set([fs.realpathSync(path.join(top, 'registered'))]); + expect(nonWorktreeFolders([top, robin, path.join(dir, 'missing')], registered)) + .toEqual([path.join(top, 'plain'), path.join(robin, 'inner')]); + }); + + test('a container reached by two spellings of one path (symlink) lists a folder once', () => { + const top = path.join(dir, 'worktrees'); + fs.mkdirSync(path.join(top, 'plain'), { recursive: true }); + fs.symlinkSync(top, path.join(dir, 'alias')); + expect(nonWorktreeFolders([top, path.join(dir, 'alias')], new Set())).toEqual([path.join(top, 'plain')]); + }); + + describe('sizes cache', () => { + test('a missing cache is empty; a corrupt one is an error', () => { + expect(readSizeCache(dir)).toEqual({}); + fs.writeFileSync(sizeCachePath(dir), '{nope'); + expect(() => readSizeCache(dir)).toThrow(/unreadable size cache/); + fs.writeFileSync(sizeCachePath(dir), JSON.stringify({ '/a': { kb: 'big' } })); + expect(() => readSizeCache(dir)).toThrow(/unexpected shape/); + }); + + test('measureSizes runs du -sk per path and caches; a du failure names the path', () => { + const calls = []; + const run = (cmd, args) => { calls.push([cmd, ...args]); return `2048\t${args[1]}\n`; }; + const cache = measureSizes(['/a', '/b'], { hookStateDir: dir, run, now: Date.parse('2026-11-08T00:00:00Z') }); + expect(calls).toEqual([['du', '-sk', '/a'], ['du', '-sk', '/b']]); + expect(cache['/a']).toEqual({ kb: 2048, measured_at: '2026-11-08T00:00:00.000Z' }); + expect(readSizeCache(dir)).toEqual(cache); + expect(() => measureSizes(['/c'], { hookStateDir: dir, run: () => { throw new Error('`du -sk /c` failed: denied'); } })).toThrow(/du -sk \/c/); + }); + + test('summary counts by stage and sums only what is cached', () => { + const scan = { + repos: [1, 2], + non_worktree_folders: ['/x'], + worktrees: [ + { path: '/a', stage: 'done' }, { path: '/b', stage: 'done' }, { path: '/c', stage: 'building' }, { path: '/d', stage: 'no ticket' }, + ], + }; + const cache = { '/a': { kb: 1024, measured_at: '2026-11-08T01:00:00.000Z' }, '/c': { kb: 2048, measured_at: '2026-11-08T02:00:00.000Z' } }; + const s = worktreeSummary(scan, cache); + expect(s).toMatchObject({ repos: 2, total: 4, non_worktree_folders: ['/x'], sizes_measured_at: '2026-11-08T02:00:00.000Z' }); + expect(s.by_stage[0]).toEqual({ stage: 'done', count: 2, sized: 1, size_kb: 1024 }); + expect(s.by_stage.find(g => g.stage === 'no ticket')).toMatchObject({ sized: 0, size_kb: null }); + expect(worktreeSummary(scan, {}).sizes_measured_at).toBeNull(); + }); + + test('formatKb', () => { + expect(formatKb(512 * 1024)).toBe('512 MB'); + expect(formatKb(3 * 1024 * 1024)).toBe('3.0 GB'); + }); + }); +}); From 33c10afeab88f5aab1e02fa8a424d1bc30fbab49 Mon Sep 17 00:00:00 2001 From: CC Evans Date: Sun, 8 Nov 2026 14:59:33 -0500 Subject: [PATCH 2/3] BOB-189: re-check only the candidate's worktree before each removal Co-Authored-By: Claude Sonnet 5.5 --- lib/conductor/worktree-reaper.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/conductor/worktree-reaper.js b/lib/conductor/worktree-reaper.js index 21dbd94..85236ff 100644 --- a/lib/conductor/worktree-reaper.js +++ b/lib/conductor/worktree-reaper.js @@ -116,10 +116,12 @@ export function reapWorktrees({ studioRoot, config, apply = false, measure = fal let still; try { const fresh = snapshot({ studioRoot, config, run, home }); - const again = evaluateWorktrees(fresh.scan.worktrees, { live: liveCwds(fresh.sessions), cwd, dirty: readDirty(run) }); - still = again.candidates.find(x => x.path === c.path); + // Only this worktree is re-evaluated: `git status` on every other one is not needed. + const only = fresh.scan.worktrees.filter(w => w.path === c.path); + const again = evaluateWorktrees(only, { live: liveCwds(fresh.sessions), cwd, dirty: readDirty(run) }); + still = again.candidates[0]; if (!still) { - const why = again.kept.find(k => k.path === c.path); + const why = again.kept[0]; results.push({ ...c, outcome: 'skipped', detail: why ? why.why : 'no longer a git worktree' }); continue; } From decf55cc53f9d6f8d22b12776cac4715a9c47b25 Mon Sep 17 00:00:00 2001 From: CC Evans Date: Sun, 8 Nov 2026 15:06:23 -0500 Subject: [PATCH 3/3] BOB-189: review fixes Keep a detached worktree whose HEAD is on no branch, match session cwds case-insensitively via native realpath, and skip prunable worktrees in status --sizes. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 4 ++-- lib/conductor/status.js | 4 ++-- lib/conductor/worktree-reaper.js | 28 ++++++++++++++++++---- lib/conductor/worktrees.js | 3 ++- test/commands/conductor.test.js | 10 ++++++++ test/lib/conductor/read-only.test.js | 1 + test/lib/conductor/worktree-reaper.test.js | 28 ++++++++++++++++++++++ 7 files changed, 69 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79af32f..b23853d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,8 +54,8 @@ All notable changes to Bobby are documented here. The format is based on studio repo, from `git worktree list --porcelain`); sizes (`du`, slow) show only from the cache or after `status --sizes`. `conductor reap --worktrees` (dry run unless `--apply`, M4 only) removes a worktree with `git worktree remove --force` (branch kept) only when every ticket named - in its folder name is done, `git status --porcelain -uno` is empty and no live session's cwd is - inside it; folders that are not git worktrees are listed, never touched. `--sizes` measures the + in its folder name is done, `git status --porcelain -uno` is empty, no live session's cwd is + inside it and a detached HEAD is already on a branch; folders that are not git worktrees are listed, never touched. `--sizes` measures the candidates. A failing git or claude is an error. - **`bobby conductor` (BOB-174): read-only studio status board.** `bobby conductor init` writes `.bobby/conductor.yml` with every key explicit and refuses to overwrite it; diff --git a/lib/conductor/status.js b/lib/conductor/status.js index 015cfc6..e74262e 100644 --- a/lib/conductor/status.js +++ b/lib/conductor/status.js @@ -17,7 +17,7 @@ import { shipBoardTickets, shipLanesView } from './ship-lane.js'; import { bold, dim } from '../colors.js'; /** - * `sizes: true` runs `du` over every worktree (slow, minutes) and refreshes the cache; without it + * `sizes: true` runs `du` over every worktree whose folder exists (slow, minutes; a prunable one is gone and `du` on it fails) and refreshes the cache; without it * the worktree section shows only the sizes already cached and never measures anything. */ export function buildStatus(studioRoot, { run, now = Date.now(), sizes = false, home, statfs } = {}) { @@ -28,7 +28,7 @@ export function buildStatus(studioRoot, { run, now = Date.now(), sizes = false, const disk = readDisk(studioRoot, { statfs }); const scan = scanWorktrees(studioRoot, { run, home }); const sizeCache = sizes - ? measureSizes(scan.worktrees.map(w => w.path), { hookStateDir: config.hook_state_dir, run, now }) + ? measureSizes(scan.worktrees.filter(w => !w.prunable).map(w => w.path), { hookStateDir: config.hook_state_dir, run, now }) : readSizeCache(config.hook_state_dir); const docker = readStacks({ run, now }); const tickets = boardTickets(studioRoot, config.projects); diff --git a/lib/conductor/worktree-reaper.js b/lib/conductor/worktree-reaper.js index 85236ff..0671bdd 100644 --- a/lib/conductor/worktree-reaper.js +++ b/lib/conductor/worktree-reaper.js @@ -16,6 +16,8 @@ // - `git status --porcelain -uno` is empty: no modified or staged tracked file. Untracked // and ignored files (node_modules, .next, logs) do not block it and go with the folder; // committed work is on the branch, which stays. +// - a detached HEAD must already be on some local or remote branch: a detached worktree has +// no branch of its own to keep, so removing it would orphan commits made on it. // - no live session's cwd is inside it. Live means any session `claude agents` lists that // is not already ended: working, waiting on CC, interactive, unknown, or finished with // its process still running. @@ -32,8 +34,10 @@ import { readAgents, classifySessions, groupSessions } from './sessions.js'; import { run as defaultRun } from './exec.js'; import { scanWorktrees, measureSizes, formatKb } from './worktrees.js'; +// .native: macOS volumes are case-insensitive and only the native realpath returns the on-disk +// case, so a session cwd typed as `.../rf-1815-staging` still matches git's `.../RF-1815-staging`. const real = (p) => { - try { return fs.realpathSync(p); } catch { return path.resolve(p); } + try { return fs.realpathSync.native(p); } catch { return path.resolve(p); } }; const inside = (child, parent) => child === parent || child.startsWith(parent + path.sep); @@ -52,8 +56,9 @@ function describe(w) { * Sort classified worktrees (worktrees.js classifyWorktrees) into candidates and kept * ones, each kept one with its reason. `dirty(path)` returns the porcelain text of * `git status -uno` for a path; it is only called for a worktree that passed every other rule. + * `onBranch(path)` says whether a detached HEAD is already on a branch; only asked for detached ones. */ -export function evaluateWorktrees(worktrees, { live, cwd, dirty }) { +export function evaluateWorktrees(worktrees, { live, cwd, dirty, onBranch }) { const candidates = []; const kept = []; const here = real(cwd); @@ -80,6 +85,16 @@ export function evaluateWorktrees(worktrees, { live, cwd, dirty }) { keep(`${n} tracked file(s) modified or staged`, { notable: true, group: 'tracked files modified or staged' }); continue; } + if (w.detached) { + let safe; + try { + safe = onBranch(w.path); + } catch (e) { + kept.push({ ...describe(w), why: 'git branch check failed', error: e.message, notable: true }); + continue; + } + if (!safe) { keep('detached HEAD is on no branch: removing it would orphan its commits', { notable: true }); continue; } + } candidates.push({ ...describe(w), repo_path: w.repo_path, reason: `${w.ticket_ids.join(', ')} done, tracked files clean, no live session inside` }); } return { candidates, kept }; @@ -89,6 +104,11 @@ function readDirty(run) { return (p) => run('git', ['-C', p, 'status', '--porcelain', '-uno']); } +/** True when a detached HEAD is contained in at least one local or remote branch. */ +function readOnBranch(run) { + return (p) => run('git', ['-C', p, 'for-each-ref', '--contains', 'HEAD', 'refs/heads', 'refs/remotes']).trim() !== ''; +} + function snapshot({ studioRoot, config, run, home }) { const sessions = classifySessions(readAgents({ run }), { hookStateDir: config.hook_state_dir, now: Date.now() }); const scan = scanWorktrees(studioRoot, { run, home }); @@ -103,7 +123,7 @@ function snapshot({ studioRoot, config, run, home }) { */ export function reapWorktrees({ studioRoot, config, apply = false, measure = false, run = defaultRun, cwd = process.cwd(), home }) { const { sessions, scan } = snapshot({ studioRoot, config, run, home }); - const plan = evaluateWorktrees(scan.worktrees, { live: liveCwds(sessions), cwd, dirty: readDirty(run) }); + const plan = evaluateWorktrees(scan.worktrees, { live: liveCwds(sessions), cwd, dirty: readDirty(run), onBranch: readOnBranch(run) }); let sizes = null; if (measure) { const cache = measureSizes(plan.candidates.map(c => c.path), { hookStateDir: config.hook_state_dir, run }); @@ -118,7 +138,7 @@ export function reapWorktrees({ studioRoot, config, apply = false, measure = fal const fresh = snapshot({ studioRoot, config, run, home }); // Only this worktree is re-evaluated: `git status` on every other one is not needed. const only = fresh.scan.worktrees.filter(w => w.path === c.path); - const again = evaluateWorktrees(only, { live: liveCwds(fresh.sessions), cwd, dirty: readDirty(run) }); + const again = evaluateWorktrees(only, { live: liveCwds(fresh.sessions), cwd, dirty: readDirty(run), onBranch: readOnBranch(run) }); still = again.candidates[0]; if (!still) { const why = again.kept[0]; diff --git a/lib/conductor/worktrees.js b/lib/conductor/worktrees.js index 52f5633..05c1ea2 100644 --- a/lib/conductor/worktrees.js +++ b/lib/conductor/worktrees.js @@ -26,8 +26,9 @@ import { listStudioProjects } from '../config.js'; const SIZE_CACHE_FILE = 'worktree-sizes.json'; const TICKET_TOKEN_RE = /(? { - try { return fs.realpathSync(p); } catch { return path.resolve(p); } + try { return fs.realpathSync.native(p); } catch { return path.resolve(p); } }; /** diff --git a/test/commands/conductor.test.js b/test/commands/conductor.test.js index aad3f5b..9a830c3 100644 --- a/test/commands/conductor.test.js +++ b/test/commands/conductor.test.js @@ -374,6 +374,16 @@ describe('bobby conductor', () => { expect(bobbyIn(['status']).stdout).toMatch(/done {2}2 {2}.*(MB|GB)/); }); + test('status --sizes skips a prunable worktree whose folder is gone instead of failing on du', () => { + execFileSync('git', ['-C', root, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '--allow-empty', '-q', '-m', 'init']); + for (const name of ['AL-001-ui', 'AL-002-ui']) execFileSync('git', ['-C', root, 'worktree', 'add', '-q', '-b', `br-${name}`, path.join(root, 'worktrees', name)]); + fs.rmSync(path.join(root, 'worktrees', 'AL-002-ui'), { recursive: true }); + const r = bobbyIn(['status', '--sizes']); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/\(2 across 1 repos/); + expect(r.stdout).toMatch(/sizes: du, nominal, cached /); + }); + test('status works from a checkout nested under the studio', () => { const nested = path.join(root, 'worktrees', 'X'); fs.mkdirSync(nested, { recursive: true }); diff --git a/test/lib/conductor/read-only.test.js b/test/lib/conductor/read-only.test.js index 8f8c481..aea09cb 100644 --- a/test/lib/conductor/read-only.test.js +++ b/test/lib/conductor/read-only.test.js @@ -85,6 +85,7 @@ describe('the worktree reaper does exactly one removal', () => { const runs = [...code.matchAll(/\brun\(([^)]*)\)/g)].map(m => m[1].replace(/\s+/g, ' ')); expect(runs).toEqual([ "'git', ['-C', p, 'status', '--porcelain', '-uno']", + "'git', ['-C', p, 'for-each-ref', '--contains', 'HEAD', 'refs/heads', 'refs/remotes']", "'git', ['-C', still.repo_path, 'worktree', 'remove', '--force', still.path]", ]); }); diff --git a/test/lib/conductor/worktree-reaper.test.js b/test/lib/conductor/worktree-reaper.test.js index e8d0195..10ce569 100644 --- a/test/lib/conductor/worktree-reaper.test.js +++ b/test/lib/conductor/worktree-reaper.test.js @@ -165,6 +165,34 @@ describe('conductor worktree reaper', () => { expect(exists(locked)).toBe(true); }); + test('a detached worktree is removed only when its HEAD is already on a branch', () => { + finish(1); finish(3); + const onBranch = wt(root, 'AL-1-ui'); + git(onBranch, 'checkout', '-q', '--detach'); + const orphan = wt(root, 'AL-3-ui'); + git(orphan, 'checkout', '-q', '--detach'); + fs.writeFileSync(path.join(orphan, 'work.txt'), 'w\n'); + git(orphan, 'add', 'work.txt'); + git(orphan, 'commit', '-q', '-m', 'detached work'); + const report = go(mockRun(), { apply: true }); + expect(report.results.map(r => [path.basename(r.path), r.outcome])).toEqual([['AL-1-ui', 'removed']]); + expect(report.kept.find(k => k.path === orphan).why).toMatch(/detached HEAD is on no branch/); + expect(exists(orphan)).toBe(true); + expect(exists(onBranch)).toBe(false); + }); + + test('a session whose cwd differs only in letter case still keeps the worktree (case-insensitive volumes)', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + const swapped = path.join(path.dirname(p), 'al-1-UI'); + if (!fs.existsSync(swapped)) return; // case-sensitive filesystem: the two paths are different folders + const m = mockRun({ agents: [bg('aaaa1111', 'lane', 'working', swapped)] }); + const report = go(m, { apply: true }); + expect(report.candidates).toEqual([]); + expect(m.removals()).toEqual([]); + expect(exists(p)).toBe(true); + }); + test('folders that are not git worktrees are listed and never touched', () => { finish(1); const plain = path.join(root, 'worktrees', 'AL-1-leftover');