From 5eee1fe957d74acacf71367a46962b7d94e6093b Mon Sep 17 00:00:00 2001 From: CC Evans Date: Tue, 10 Nov 2026 13:49:34 -0500 Subject: [PATCH 1/2] BOB-193: reap --worktrees treats scratch folders as clean; --print-plist for an hourly timer reaper.worktree_scratch_paths (required; init: coverage/, tmp/, log/) lists folders whose changes do not keep a done ticket's worktree. Real diffs keep it and are listed in a short 'Done tickets kept for real changes' section. --print-plist prints a launchd job running reap --worktrees --apply every worktree_timer.interval_minutes (required; init: 60). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CYbcv4uMBkZT8H2W7Z9vzk --- CHANGELOG.md | 14 +++ commands/conductor.js | 13 ++- lib/conductor/config.js | 48 ++++++++- lib/conductor/worktree-reaper.js | 67 +++++++++--- lib/conductor/worktree-timer.js | 89 ++++++++++++++++ test/commands/conductor.test.js | 44 ++++++++ test/lib/conductor/config.test.js | 39 ++++++- test/lib/conductor/helpers.js | 7 +- test/lib/conductor/worktree-reaper.test.js | 112 ++++++++++++++++++++- test/lib/conductor/worktree-timer.test.js | 43 ++++++++ 10 files changed, 447 insertions(+), 29 deletions(-) create mode 100644 lib/conductor/worktree-timer.js create mode 100644 test/lib/conductor/worktree-timer.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c07690..9c74722 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ All notable changes to Bobby are documented here. The format is based on ## [Unreleased] +### Added +- **`conductor reap --worktrees` treats scratch folders as clean, and can run on a timer + (BOB-193).** Changes confined to the folders in the new required key + `reaper.worktree_scratch_paths` (init writes `coverage/`, `tmp/`, `log/`) no longer keep a + done ticket's worktree: rspec SimpleCov output and `tmp/**/.keep` deletions go with the + folder. A change with any path outside them (a move counts both paths) still keeps it, and + its row names the first changed files. The output ends with a short + `Done tickets kept for real changes` section the Conductor can relay, and starts with a + timestamp line. `bobby conductor reap --worktrees --print-plist` prints a launchd job that + runs `reap --worktrees --apply` every `worktree_timer.interval_minutes` (init: 60), logging to + `worktree_timer.log_file`; printing changes nothing, and a PATH without git, claude or + sysctl is an error. **Both keys are required**: add them to an existing `conductor.yml` + (`reaper.worktree_scratch_paths: []` keeps the old rule). Branches are always kept. + ### Changed - **Smaller skills at agent start (token budget).** Every agent step re-sends its whole context, so what an agent loads up front is paid on every step. diff --git a/commands/conductor.js b/commands/conductor.js index b09f894..847a8d1 100644 --- a/commands/conductor.js +++ b/commands/conductor.js @@ -14,6 +14,7 @@ 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 { buildWorktreeTimerPlist } from '../lib/conductor/worktree-timer.js'; import { readDisk } from '../lib/conductor/disk.js'; import { assertM4Host } from '../lib/conductor/host.js'; import { readAgents } from '../lib/conductor/sessions.js'; @@ -48,9 +49,10 @@ export function registerConductor(program) { 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}, 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(` reaper: stack_idle_hours ${values.reaper.stack_idle_hours}, worktree_scratch_paths ${values.reaper.worktree_scratch_paths.join(', ')}`)); 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}`)); + console.log(dim(` worktree_timer: interval_minutes ${values.worktree_timer.interval_minutes}, log_file ${values.worktree_timer.log_file}`)); } catch (e) { fail(e); } @@ -102,17 +104,24 @@ export function registerConductor(program) { .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)') + .option('--print-plist', 'With --worktrees: print a launchd job that runs `reap --worktrees --apply` every worktree_timer.interval_minutes (changes nothing)') .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.'); + if (opts.printPlist && !opts.worktrees) throw new Error('--print-plist only applies to --worktrees.'); + if (opts.printPlist && (opts.apply || opts.sizes)) throw new Error('--print-plist only prints; drop --apply and --sizes.'); assertM4Host(); const studioRoot = findStudioRoot(); const config = loadConductorConfig(studioRoot); const apply = Boolean(opts.apply); + if (opts.printPlist) { + process.stdout.write(buildWorktreeTimerPlist({ studioRoot, config })); + return; + } if (opts.worktrees) { const report = reapWorktrees({ studioRoot, config, apply, measure: Boolean(opts.sizes) }); - console.log(renderWorktreeReap(report, { apply })); + console.log(renderWorktreeReap(report, { apply, studioRoot })); if (report.failed > 0) { error(`${report.failed} worktree(s) could not be checked or removed`); process.exit(1); diff --git a/lib/conductor/config.js b/lib/conductor/config.js index 37b12b8..0b6dccc 100644 --- a/lib/conductor/config.js +++ b/lib/conductor/config.js @@ -20,7 +20,11 @@ export const CONDUCTOR_FILE = 'conductor.yml'; // 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-193: CC named coverage/, tmp/ and log/ as scratch (2026-11-10): changes confined to them do +// not keep a done ticket's worktree. +const INIT_REAPER = { stack_idle_hours: 2, worktree_scratch_paths: ['coverage/', 'tmp/', 'log/'] }; +// BOB-193: CC picked an hourly worktree reap on the M4 (2026-11-10). The log sits next to hook-state. +const INIT_WORKTREE_TIMER_MINUTES = 60; // BOB-180: CC set 6 lanes (BOB-173 decision, 2026-11-08). The claim TTL was not named by CC; // 30 minutes covers the gap between a lane pulling a ticket and its session showing the ID. const INIT_WIP = { max_lanes: 6 }; @@ -76,7 +80,8 @@ function validateConfig(parsed, file) { const wip = validatePositiveInt(parsed.wip, file, 'wip', 'max_lanes'); const claims = validatePositiveInt(parsed.claims, file, 'claims', 'ttl_minutes'); const inbox = validateInbox(parsed.inbox, file); - return { projects: [...projects], hook_state_dir: dir, governor, reaper, wip, claims, inbox }; + const worktree_timer = validateWorktreeTimer(parsed.worktree_timer, file); + return { projects: [...projects], hook_state_dir: dir, governor, reaper, wip, claims, inbox, worktree_timer }; } // A section with one required positive-integer key: { : n }. @@ -108,7 +113,38 @@ function validateReaper(reaper, file) { if (typeof h !== 'number' || !Number.isFinite(h) || h <= 0) { throw fail(file, 'reaper.stack_idle_hours', 'must be a positive number of hours'); } - return { stack_idle_hours: h }; + const scratch = validateScratchPaths(reaper, file); + return { stack_idle_hours: h, worktree_scratch_paths: scratch }; +} + +// Folders, relative to a worktree's root, whose changes `reap --worktrees` treats as clean. +// An empty list is a valid, explicit "nothing is scratch". Entries load exactly as written. +function validateScratchPaths(reaper, file) { + const key = 'reaper.worktree_scratch_paths'; + if (!('worktree_scratch_paths' in reaper) || reaper.worktree_scratch_paths === null) throw fail(file, key, 'is missing'); + const list = reaper.worktree_scratch_paths; + if (!Array.isArray(list)) throw fail(file, key, 'must be a list of folders relative to a worktree (e.g. coverage/)'); + return list.map((entry) => { + if (typeof entry !== 'string') throw fail(file, key, 'must list folder paths as strings'); + const p = entry.replace(/\/+$/, ''); + const parts = p.split('/'); + if (!p || p.startsWith('/') || parts.some(part => part === '' || part === '.' || part === '..')) { + throw fail(file, key, `has "${entry}": each entry must be a folder relative to the worktree root, without "." or ".."`); + } + return entry; + }); +} + +function validateWorktreeTimer(timer, file) { + if (timer === undefined || timer === null) throw fail(file, 'worktree_timer.interval_minutes', 'is missing'); + if (typeof timer !== 'object' || Array.isArray(timer)) throw fail(file, 'worktree_timer', 'must be a mapping'); + if (!('interval_minutes' in timer) || timer.interval_minutes === null) throw fail(file, 'worktree_timer.interval_minutes', 'is missing'); + const m = timer.interval_minutes; + if (!Number.isInteger(m) || m <= 0) throw fail(file, 'worktree_timer.interval_minutes', 'must be a positive integer'); + if (!('log_file' in timer) || timer.log_file === null) throw fail(file, 'worktree_timer.log_file', 'is missing'); + const log = timer.log_file; + if (typeof log !== 'string' || !path.isAbsolute(log)) throw fail(file, 'worktree_timer.log_file', 'must be an absolute file path'); + return { interval_minutes: m, log_file: log }; } const GOVERNOR_KEYS = ['min_free_ram_mb', 'max_docker_stacks', 'min_free_disk_gb']; @@ -164,6 +200,10 @@ export function initConductorConfig(studioRoot, { projects } = {}) { wip: { ...INIT_WIP }, claims: { ...INIT_CLAIMS }, inbox: { ...INIT_INBOX }, + worktree_timer: { + interval_minutes: INIT_WORKTREE_TIMER_MINUTES, + log_file: path.join(os.homedir(), '.bobby', 'conductor-reap-worktrees.log'), + }, }; const body = [ '# bobby conductor config. Written by `bobby conductor init`; every key is required.', @@ -174,9 +214,11 @@ export function initConductorConfig(studioRoot, { projects } = {}) { '# 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).', + '# reaper.worktree_scratch_paths: `conductor reap --worktrees` treats changes confined to these folders (relative to a worktree) as clean (CC, 2026-11-10).', '# wip.max_lanes: `conductor next` refuses when this many live lane sessions (working or waiting on CC) exist (CC, 2026-11-08).', '# claims.ttl_minutes: a ticket `conductor next` handed out is not handed out again for this long.', '# inbox.stale_minutes: `conductor status` flags a message undelivered this long (BOB-183).', + '# worktree_timer: `conductor reap --worktrees --print-plist` prints a launchd job that runs `reap --worktrees --apply` every interval_minutes, logging to log_file (CC, 2026-11-10).', YAML.stringify(values), ].join('\n'); fs.mkdirSync(path.dirname(file), { recursive: true }); diff --git a/lib/conductor/worktree-reaper.js b/lib/conductor/worktree-reaper.js index 5b175c6..307508d 100644 --- a/lib/conductor/worktree-reaper.js +++ b/lib/conductor/worktree-reaper.js @@ -25,6 +25,10 @@ // its process still running. // - it does not hold the directory this command runs from. // +// Changes confined to the scratch folders conductor.yml lists (reaper.worktree_scratch_paths, +// e.g. coverage/ and tmp/: rspec SimpleCov output, tmp/**/.keep deletions) do not count as +// changes (BOB-193). They go with the folder; a change with any path outside them still keeps it. +// // 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` @@ -56,6 +60,29 @@ function untrackedSummary(entries) { return entries.length > 2 ? `${shown} (+${entries.length - 2})` : shown; } +/** Unquote one porcelain path: git quotes a path with special characters as "a\\tb". */ +function unquote(p) { + if (p.length >= 2 && p.startsWith('"') && p.endsWith('"')) return p.slice(1, -1).replace(/\\(["\\])/g, '$1'); + return p; +} + +/** + * One `git status --porcelain` (v1) line into its paths: `XY path`, or `XY orig -> path` + * for a file git shows as moved or copied (R or C), where both paths count. + */ +export function porcelainPaths(line) { + return line.slice(3).split(' -> ').map(unquote); +} + +/** True when `p` (relative to the worktree root) is one of the scratch folders or inside one. */ +export function isScratch(p, scratch) { + const clean = p.replace(/\/+$/, ''); + return scratch.some((entry) => { + const dir = entry.replace(/\/+$/, ''); + return clean === dir || clean.startsWith(dir + '/'); + }); +} + function describe(w) { return { repo: w.repo, path: w.path, branch: w.branch, ticket: w.ticket_ids.join(', ') || null, stage: w.stage }; } @@ -67,7 +94,8 @@ function describe(w) { * 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, onBranch }) { +export function evaluateWorktrees(worktrees, { live, cwd, dirty, onBranch, scratch }) { + if (!Array.isArray(scratch)) throw new Error('evaluateWorktrees needs the scratch folder list (reaper.worktree_scratch_paths)'); const candidates = []; const kept = []; const here = real(cwd); @@ -89,15 +117,17 @@ export function evaluateWorktrees(worktrees, { live, cwd, dirty, onBranch }) { kept.push({ ...describe(w), why: 'git status failed', error: e.message, notable: true }); continue; } - const lines = changes.split('\n').filter(l => l.trim()); + const all = changes.split('\n').filter(l => l.trim()); + const lines = all.filter(l => !porcelainPaths(l).every(p => isScratch(p, scratch))); + const scratchOnly = all.length - lines.length; const untracked = lines.filter(l => l.startsWith('??')).map(l => l.slice(3)); - const tracked = lines.length - untracked.length; - if (tracked > 0) { - keep(`${tracked} tracked file(s) modified or staged`, { notable: true, group: 'tracked files modified or staged' }); + const tracked = lines.filter(l => !l.startsWith('??')).map(l => l.slice(3)); + if (tracked.length > 0) { + keep(`${tracked.length} tracked file(s) modified or staged: ${untrackedSummary(tracked)}`, { notable: true, real_diff: true, group: 'tracked files modified or staged' }); continue; } if (untracked.length > 0) { - keep(`untracked: ${untrackedSummary(untracked)}`, { notable: true, group: 'untracked files that are not ignored' }); + keep(`untracked: ${untrackedSummary(untracked)}`, { notable: true, real_diff: true, group: 'untracked files that are not ignored' }); continue; } if (w.detached) { @@ -110,7 +140,10 @@ export function evaluateWorktrees(worktrees, { live, cwd, dirty, onBranch }) { } 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, no uncommitted or untracked files, no live session inside` }); + const changed = scratchOnly + ? `only scratch changes (${scratchOnly} under ${scratch.join(', ')})` + : 'no uncommitted or untracked files'; + candidates.push({ ...describe(w), repo_path: w.repo_path, reason: `${w.ticket_ids.join(', ')} done, ${changed}, no live session inside` }); } return { candidates, kept }; } @@ -138,7 +171,8 @@ 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), onBranch: readOnBranch(run) }); + const scratch = config.reaper.worktree_scratch_paths; + const plan = evaluateWorktrees(scan.worktrees, { live: liveCwds(sessions), cwd, dirty: readDirty(run), onBranch: readOnBranch(run), scratch }); let sizes = null; if (measure) { const cache = measureSizes(plan.candidates.map(c => c.path), { hookStateDir: config.hook_state_dir, run }); @@ -153,7 +187,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), onBranch: readOnBranch(run) }); + const again = evaluateWorktrees(only, { live: liveCwds(fresh.sessions), cwd, dirty: readDirty(run), onBranch: readOnBranch(run), scratch }); still = again.candidates[0]; if (!still) { const why = again.kept[0]; @@ -179,8 +213,13 @@ export function reapWorktrees({ studioRoot, config, apply = false, measure = fal const sizeText = (c) => (c.size_kb === undefined ? '' : ` ${formatKb(c.size_kb)}`); /** Text for `bobby conductor reap --worktrees`. */ -export function renderWorktreeReap(report, { apply }) { - const lines = []; +export function renderWorktreeReap(report, { apply, studioRoot, now = new Date() }) { + const lines = [`${now.toISOString()} conductor reap --worktrees${apply ? ' --apply' : ''}`]; + const base = studioRoot ? real(studioRoot) : null; + const short = (p) => { + const rel = base ? path.relative(base, real(p)) : p; + return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : p; + }; 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.`); @@ -203,9 +242,13 @@ export function renderWorktreeReap(report, { apply }) { 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)) { + for (const k of report.kept.filter(x => x.notable && !x.real_diff)) { lines.push(` kept ${k.repo} ${k.path} ${k.ticket} ${k.why}${k.error ? `: ${k.error}` : ''}`); } + // The ones only a human or the lane can decide on: short enough for the Conductor to relay. + const realDiffs = report.kept.filter(x => x.real_diff); + lines.push(`Done tickets kept for real changes: ${realDiffs.length} (a human or the lane decides; reap never removes them)`); + for (const k of realDiffs) lines.push(` ${k.ticket} ${short(k.path)} ${k.why}`); 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/worktree-timer.js b/lib/conductor/worktree-timer.js new file mode 100644 index 0000000..bf3e54f --- /dev/null +++ b/lib/conductor/worktree-timer.js @@ -0,0 +1,89 @@ +// lib/conductor/worktree-timer.js +// +// `bobby conductor reap --worktrees --print-plist` (BOB-193). Prints a launchd job that runs +// `bobby conductor reap --worktrees --apply` every worktree_timer.interval_minutes on the M4, +// so done-ticket worktrees go away without a human. Printing changes nothing; CC (or a lane he +// names) installs it: +// +// bobby conductor reap --worktrees --print-plist > ~/Library/LaunchAgents/com.bobby.conductor.reap-worktrees.plist +// launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.bobby.conductor.reap-worktrees.plist +// +// launchd starts jobs with a bare environment, so the plist carries absolute paths for node and +// bobby, the studio as the working directory (findStudioRoot walks up from it), and the PATH of +// the shell that printed it. A PATH without git, claude or sysctl is an error here rather than +// a job that fails every hour. + +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +export const TIMER_LABEL = 'com.bobby.conductor.reap-worktrees'; + +// The reap reads `claude agents`, runs git, and checks the host with sysctl. +const NEEDED_ON_PATH = ['git', 'claude', 'sysctl']; + +const BOBBY_BIN = fileURLToPath(new URL('../../bin/bobby.js', import.meta.url)); + +function escapeXml(s) { + return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +} + +function onPath(name, pathEnv) { + return pathEnv.split(':').filter(Boolean).some((dir) => { + try { + fs.accessSync(path.join(dir, name), fs.constants.X_OK); + return true; + } catch { + return false; + } + }); +} + +/** + * The plist text. `env` is the printing shell's environment (PATH and HOME are required), + * `node` the node binary and `bobby` the bobby entry point, both made absolute. + */ +export function buildWorktreeTimerPlist({ studioRoot, config, env = process.env, node = process.execPath, bobby = BOBBY_BIN }) { + const { interval_minutes: minutes, log_file: log } = config.worktree_timer; + if (!env.PATH) throw new Error('PATH is not set; the launchd job needs it to find git and claude'); + if (!env.HOME) throw new Error('HOME is not set; the launchd job needs it for claude'); + const missing = NEEDED_ON_PATH.filter(name => !onPath(name, env.PATH)); + if (missing.length) { + throw new Error(`${missing.join(', ')} not found on PATH (${env.PATH}); the launchd job could not run the reap. Print the plist from a shell where they resolve.`); + } + const bin = fs.realpathSync(bobby); + const args = [fs.realpathSync(node), bin, 'conductor', 'reap', '--worktrees', '--apply']; + const str = (v) => `\t\t${escapeXml(v)}`; + return [ + '', + '', + '', + '', + '\tLabel', + `\t${TIMER_LABEL}`, + '\tProgramArguments', + '\t', + ...args.map(str), + '\t', + '\tWorkingDirectory', + `\t${escapeXml(studioRoot)}`, + '\tEnvironmentVariables', + '\t', + '\t\tHOME', + `\t\t${escapeXml(env.HOME)}`, + '\t\tPATH', + `\t\t${escapeXml(env.PATH)}`, + '\t', + '\tStartInterval', + `\t${minutes * 60}`, + '\tRunAtLoad', + '\t', + '\tStandardOutPath', + `\t${escapeXml(log)}`, + '\tStandardErrorPath', + `\t${escapeXml(log)}`, + '', + '', + '', + ].join('\n'); +} diff --git a/test/commands/conductor.test.js b/test/commands/conductor.test.js index 9a830c3..8c4af54 100644 --- a/test/commands/conductor.test.js +++ b/test/commands/conductor.test.js @@ -596,6 +596,50 @@ describe('bobby conductor', () => { expect(r.stderr).toMatch(/M4 only/); }); + test('--print-plist prints a launchd job for `reap --worktrees --apply` every interval and changes nothing', () => { + const r = bobbyIn(['reap', '--worktrees', '--print-plist']); + expect(r.status).toBe(0); + const xml = r.stdout; + expect(xml).toMatch(/^<\?xml version="1.0" encoding="UTF-8"\?>\ncom.bobby.conductor.reap-worktrees'); + const args = [...xml.match(/ProgramArguments<\/key>\s*([\s\S]*?)<\/array>/)[1].matchAll(/([^<]*)<\/string>/g)].map(m => m[1]); + expect(path.isAbsolute(args[0])).toBe(true); + expect(args[1]).toBe(fs.realpathSync(bobby)); + expect(args.slice(2)).toEqual(['conductor', 'reap', '--worktrees', '--apply']); + expect(xml).toMatch(/StartInterval<\/key>\s*3600<\/integer>/); + expect(xml).toMatch(new RegExp(`WorkingDirectory\\s*${fs.realpathSync(root)}`)); + expect(xml).toMatch(/StandardOutPath<\/key>\s*\/tmp\/bobby-reap-worktrees\.log<\/string>/); + expect(xml).toMatch(/StandardErrorPath<\/key>\s*\/tmp\/bobby-reap-worktrees\.log<\/string>/); + expect(xml).toMatch(new RegExp(`PATH\\s*${fakeBin}`)); + expect(fs.existsSync(doneWt)).toBe(true); + if (process.platform === 'darwin') { + const file = path.join(root, 'job.plist'); + fs.writeFileSync(file, xml); + expect(execFileSync('plutil', ['-lint', file], { encoding: 'utf8' })).toMatch(/OK/); + } + }); + + test('--print-plist with --apply or --sizes, or without --worktrees, is an error', () => { + expect(bobbyIn(['reap', '--worktrees', '--print-plist', '--apply']).stderr).toMatch(/--print-plist only prints; drop --apply and --sizes/); + expect(bobbyIn(['reap', '--worktrees', '--print-plist', '--sizes']).stderr).toMatch(/--print-plist only prints/); + const r = bobbyIn(['reap', '--print-plist']); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/--print-plist only applies to --worktrees/); + }); + + test('--print-plist refuses on a host that is not the M4', () => { + const r = bobbyIn(['reap', '--worktrees', '--print-plist'], { cpu: 'Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz' }); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/M4 only/); + }); + + test('a conductor.yml without worktree_timer is an error naming the key', () => { + writeConductorYml(root, validYml(hookDir).replace(/worktree_timer:[\s\S]*$/, '')); + const r = bobbyIn(['reap', '--worktrees', '--print-plist']); + expect(r.status).toBe(1); + expect(r.stderr).toMatch(/key "worktree_timer\.interval_minutes" is missing/); + }); + 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']); diff --git a/test/lib/conductor/config.test.js b/test/lib/conductor/config.test.js index e9beb07..788cc2f 100644 --- a/test/lib/conductor/config.test.js +++ b/test/lib/conductor/config.test.js @@ -20,10 +20,11 @@ describe('conductor config', () => { projects: ['alpha'], hook_state_dir: hookDir, governor: { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 1 }, - reaper: { stack_idle_hours: 2 }, + reaper: { stack_idle_hours: 2, worktree_scratch_paths: ['coverage/', 'tmp/', 'log/'] }, wip: { max_lanes: 6 }, claims: { ttl_minutes: 30 }, inbox: { stale_minutes: 30 }, + worktree_timer: { interval_minutes: 60, log_file: '/tmp/bobby-reap-worktrees.log' }, }); }); @@ -35,12 +36,21 @@ describe('conductor config', () => { ['reaper.stack_idle_hours', `${govYml}reaper:\n stack_idle_hours: 0\n`], ['reaper.stack_idle_hours', `${govYml}reaper:\n stack_idle_hours: soon\n`], ['reaper', `${govYml}reaper: 2\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths:\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: coverage/\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: [7]\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: ['']\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: [/tmp]\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: [../coverage]\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: [.]\n`], + ['reaper.worktree_scratch_paths', `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: [a//b]\n`], ])('a missing or invalid %s names the key', (key, yml) => { writeConductorYml(root, yml); expect(() => loadConductorConfig(root)).toThrow(new RegExp(`key "${key.replace('.', '\\.')}"`)); }); - const reaperYml = `${govYml}reaper:\n stack_idle_hours: 2\n`; + const reaperYml = `${govYml}reaper:\n stack_idle_hours: 2\n worktree_scratch_paths: [coverage/]\n`; test.each([ ['wip.max_lanes', reaperYml], ['wip.max_lanes', `${reaperYml}wip:\n other: 1\n`], @@ -69,6 +79,25 @@ describe('conductor config', () => { expect(() => loadConductorConfig(root)).toThrow(new RegExp(`key "${key.replace('.', '\\.')}"`)); }); + const inboxYml = `${wipYml}inbox:\n stale_minutes: 30\n`; + test.each([ + ['worktree_timer.interval_minutes', inboxYml], + ['worktree_timer', `${inboxYml}worktree_timer: 60\n`], + ['worktree_timer.interval_minutes', `${inboxYml}worktree_timer:\n log_file: /x.log\n`], + ['worktree_timer.interval_minutes', `${inboxYml}worktree_timer:\n interval_minutes: 0\n log_file: /x.log\n`], + ['worktree_timer.interval_minutes', `${inboxYml}worktree_timer:\n interval_minutes: 1.5\n log_file: /x.log\n`], + ['worktree_timer.log_file', `${inboxYml}worktree_timer:\n interval_minutes: 60\n`], + ['worktree_timer.log_file', `${inboxYml}worktree_timer:\n interval_minutes: 60\n log_file: reap.log\n`], + ])('a missing or invalid %s names the key (worktree timer)', (key, yml) => { + writeConductorYml(root, yml); + expect(() => loadConductorConfig(root)).toThrow(new RegExp(`key "${key.replace('.', '\\.')}"`)); + }); + + test('an empty reaper.worktree_scratch_paths is a valid, explicit "nothing is scratch"', () => { + writeConductorYml(root, `${wipYml}inbox:\n stale_minutes: 30\nworktree_timer:\n interval_minutes: 60\n log_file: /x.log\n`.replace('[coverage/]', '[]')); + expect(loadConductorConfig(root).reaper.worktree_scratch_paths).toEqual([]); + }); + test.each([ ['projects', `hook_state_dir: /x\n`], ['hook_state_dir', `projects:\n - alpha\n`], @@ -110,16 +139,18 @@ describe('conductor config', () => { projects: ['alpha'], hook_state_dir: path.join(os.homedir(), '.bobby', 'hook-state'), governor: { min_free_ram_mb: 4096, max_docker_stacks: 4, min_free_disk_gb: 50 }, - reaper: { stack_idle_hours: 2 }, + reaper: { stack_idle_hours: 2, worktree_scratch_paths: ['coverage/', 'tmp/', 'log/'] }, wip: { max_lanes: 6 }, claims: { ttl_minutes: 30 }, inbox: { stale_minutes: 30 }, + worktree_timer: { interval_minutes: 60, log_file: path.join(os.homedir(), '.bobby', 'conductor-reap-worktrees.log') }, }); 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 {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(/reaper:\n {2}stack_idle_hours: 2\n {2}worktree_scratch_paths:\n {4}- coverage\/\n {4}- tmp\/\n {4}- log\/\n/); + expect(fs.readFileSync(file, 'utf8')).toMatch(/worktree_timer:\n {2}interval_minutes: 60\n {2}log_file: \//); expect(fs.readFileSync(file, 'utf8')).toMatch(/inbox:\n {2}stale_minutes: 30\n/); }); diff --git a/test/lib/conductor/helpers.js b/test/lib/conductor/helpers.js index c5f8e6d..5c2fb5d 100644 --- a/test/lib/conductor/helpers.js +++ b/test/lib/conductor/helpers.js @@ -24,13 +24,14 @@ 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, min_free_disk_gb: 1 }, 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, worktree_scratch_paths: ['coverage/', 'tmp/', 'log/'] }, wip = { max_lanes: 6 }, claims = { ttl_minutes: 30 }, inbox = { stale_minutes: 30 }, worktreeTimer = { interval_minutes: 60, log_file: '/tmp/bobby-reap-worktrees.log' }) { 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 min_free_disk_gb: ${governor.min_free_disk_gb}\n` - + `reaper:\n stack_idle_hours: ${reaper.stack_idle_hours}\n` + + `reaper:\n stack_idle_hours: ${reaper.stack_idle_hours}\n worktree_scratch_paths: ${JSON.stringify(reaper.worktree_scratch_paths)}\n` + `wip:\n max_lanes: ${wip.max_lanes}\n` + `claims:\n ttl_minutes: ${claims.ttl_minutes}\n` - + `inbox:\n stale_minutes: ${inbox.stale_minutes}\n`; + + `inbox:\n stale_minutes: ${inbox.stale_minutes}\n` + + `worktree_timer:\n interval_minutes: ${worktreeTimer.interval_minutes}\n log_file: ${worktreeTimer.log_file}\n`; } /** vm_stat text for a 16 KB-page machine. Pages are given in MB so tests read in MB. */ diff --git a/test/lib/conductor/worktree-reaper.test.js b/test/lib/conductor/worktree-reaper.test.js index eb97b2d..e53a74b 100644 --- a/test/lib/conductor/worktree-reaper.test.js +++ b/test/lib/conductor/worktree-reaper.test.js @@ -7,7 +7,7 @@ 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 { reapWorktrees, renderWorktreeReap, evaluateWorktrees, porcelainPaths, isScratch } from '../../../lib/conductor/worktree-reaper.js'; import { readSizeCache } from '../../../lib/conductor/worktrees.js'; import { makeStudio, seedTickets } from './helpers.js'; @@ -60,7 +60,7 @@ describe('conductor worktree reaper', () => { 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: {} }; + config = { projects: ['alpha'], hook_state_dir: hookDir, governor: {}, reaper: { worktree_scratch_paths: ['coverage/', 'tmp/', 'log/'] }, claims: {} }; }); afterEach(() => { for (const d of [root, app, home]) fs.rmSync(d, { recursive: true, force: true }); @@ -141,7 +141,8 @@ describe('conductor worktree reaper', () => { expect(exists(path.join(many, 'd.txt'))).toBe(true); const text = renderWorktreeReap(report, { apply: false }); expect(text).toMatch(/2 {2}untracked files that are not ignored/); - expect(text).toMatch(/kept .*AL-1-ui.*untracked: review\.md, test-evidence\//); + expect(text).toMatch(/Done tickets kept for real changes: 2 /); + expect(text).toMatch(/AL-001 {2}\S*AL-1-ui {2}untracked: review\.md, test-evidence\//); }); test('a user setting status.showUntrackedFiles=no cannot hide untracked files from the check', () => { @@ -161,7 +162,7 @@ describe('conductor worktree reaper', () => { fs.appendFileSync(path.join(p, 'tracked.txt'), 'edit\n'); fs.writeFileSync(path.join(p, 'review.md'), 'x'); const report = go(mockRun()); - expect(report.kept[0].why).toBe('1 tracked file(s) modified or staged'); + expect(report.kept[0].why).toBe('1 tracked file(s) modified or staged: tracked.txt'); }); test('a session that has ended (done, no pid) does not keep a worktree; interactive and blocked ones do', () => { @@ -317,12 +318,113 @@ describe('conductor worktree reaper', () => { expect(renderWorktreeReap(report, { apply: false })).toMatch(/Size of the 1 candidate/); }); + describe('scratch folders (reaper.worktree_scratch_paths, BOB-193)', () => { + // coverage/ and tmp/**/.keep committed on main, the way a Rails repo carries them. + beforeEach(() => { + fs.mkdirSync(path.join(root, 'coverage')); + fs.writeFileSync(path.join(root, 'coverage', '.last_run.json'), '{}'); + fs.writeFileSync(path.join(root, 'coverage', '.resultset.json'), '{}'); + fs.mkdirSync(path.join(root, 'tmp', 'pids'), { recursive: true }); + fs.writeFileSync(path.join(root, 'tmp', 'pids', '.keep'), ''); + git(root, 'add', 'coverage', 'tmp'); + git(root, 'commit', '-q', '-m', 'coverage and tmp'); + }); + + test('a done worktree whose only changes are coverage/ deletions, tmp/**/.keep deletions and untracked tmp files is removed; branch kept', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + fs.rmSync(path.join(p, 'coverage'), { recursive: true }); + fs.rmSync(path.join(p, 'tmp', 'pids', '.keep')); + fs.mkdirSync(path.join(p, 'tmp', 'cache'), { recursive: true }); + fs.writeFileSync(path.join(p, 'tmp', 'cache', 'x.bin'), 'x'); + fs.mkdirSync(path.join(p, 'log')); + fs.writeFileSync(path.join(p, 'log', 'test.txt'), 'x'); + const m = mockRun(); + const report = go(m, { apply: true }); + expect(report.candidates.map(c => c.path)).toEqual([p]); + expect(report.candidates[0].reason).toMatch(/only scratch changes \(\d+ under coverage\/, tmp\/, log\/\)/); + expect(report.results.map(r => r.outcome)).toEqual(['removed']); + expect(m.removals()).toEqual([['git', '-C', root, 'worktree', 'remove', '--force', p]]); + expect(exists(p)).toBe(false); + expect(git(root, 'branch', '--list', 'br-AL-1-ui')).toMatch(/br-AL-1-ui/); + }); + + test('a scratch change plus a real one keeps the worktree, and the row names only the real files', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + fs.rmSync(path.join(p, 'coverage'), { recursive: true }); + fs.appendFileSync(path.join(p, 'tracked.txt'), 'edit\n'); + const report = go(mockRun(), { apply: true }); + expect(report.candidates).toEqual([]); + expect(report.kept[0]).toMatchObject({ why: '1 tracked file(s) modified or staged: tracked.txt', real_diff: true }); + expect(exists(p)).toBe(true); + const text = renderWorktreeReap(report, { apply: true, studioRoot: root }); + expect(text).toMatch(/Done tickets kept for real changes: 1 /); + expect(text).toContain(' AL-001 worktrees/AL-1-ui 1 tracked file(s) modified or staged: tracked.txt'); + }); + + test('a move out of a scratch folder counts both paths, so it keeps the worktree', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + git(p, 'mv', 'coverage/.last_run.json', 'last_run.json'); + const report = go(mockRun()); + expect(report.candidates).toEqual([]); + expect(report.kept[0].why).toMatch(/^1 tracked file\(s\) modified or staged: coverage\/\.last_run\.json -> last_run\.json$/); + }); + + test('a folder that only starts with a scratch name is not scratch', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + fs.mkdirSync(path.join(p, 'coverage-report')); + fs.writeFileSync(path.join(p, 'coverage-report', 'a.html'), 'x'); + expect(go(mockRun()).kept[0].why).toBe('untracked: coverage-report/'); + }); + + test('an empty list treats nothing as scratch (the old rule)', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + fs.rmSync(path.join(p, 'coverage', '.last_run.json')); + config.reaper.worktree_scratch_paths = []; + expect(go(mockRun()).kept[0].why).toBe('1 tracked file(s) modified or staged: coverage/.last_run.json'); + }); + + test('the apply-time re-check uses the scratch list too: a real edit made in between keeps the worktree', () => { + finish(1); + const p = wt(root, 'AL-1-ui'); + fs.rmSync(path.join(p, 'coverage'), { recursive: true }); + const m = mockRun({ agents: (reads) => { if (reads === 2) fs.appendFileSync(path.join(p, 'tracked.txt'), 'edit\n'); return []; } }); + const report = go(m, { apply: true }); + expect(report.candidates).toHaveLength(1); + expect(report.results[0]).toMatchObject({ outcome: 'skipped', detail: '1 tracked file(s) modified or staged: tracked.txt' }); + expect(m.removals()).toEqual([]); + }); + + test('porcelainPaths and isScratch read quoted and moved paths', () => { + expect(porcelainPaths(' D coverage/index.html')).toEqual(['coverage/index.html']); + expect(porcelainPaths('R "tmp/a b" -> "src/c\\"d"')).toEqual(['tmp/a b', 'src/c"d']); + expect(isScratch('tmp/', ['tmp/'])).toBe(true); + expect(isScratch('tmp', ['tmp'])).toBe(true); + expect(isScratch('tmpfile', ['tmp/'])).toBe(false); + expect(isScratch('spec/tmp/x', ['tmp/'])).toBe(false); + expect(isScratch('api/coverage/x', ['api/coverage'])).toBe(true); + }); + }); + + test('evaluateWorktrees without a scratch list is an explicit error', () => { + expect(() => evaluateWorktrees([], { live: [], cwd: '/x', dirty: () => '' })).toThrow(/reaper\.worktree_scratch_paths/); + }); + + test('every run starts with a timestamp line, so the timer log reads per run', () => { + const text = renderWorktreeReap({ candidates: [], kept: [], non_worktree_folders: [], results: [], sizes: null }, { apply: true, now: new Date('2026-11-10T12:00:00Z') }); + expect(text.split('\n')[0]).toBe('2026-11-10T12:00:00.000Z conductor reap --worktrees --apply'); + }); + 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 }, + { live: [], cwd: '/elsewhere', dirty, scratch: [] }, ); expect(candidates).toEqual([]); expect(kept).toHaveLength(3); diff --git a/test/lib/conductor/worktree-timer.test.js b/test/lib/conductor/worktree-timer.test.js new file mode 100644 index 0000000..db93247 --- /dev/null +++ b/test/lib/conductor/worktree-timer.test.js @@ -0,0 +1,43 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { buildWorktreeTimerPlist, TIMER_LABEL } from '../../../lib/conductor/worktree-timer.js'; + +describe('conductor worktree timer plist', () => { + let bin; + let studio; + const config = { worktree_timer: { interval_minutes: 15, log_file: '/logs/a&b.log' } }; + beforeEach(() => { + bin = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-timer-bin-')); + for (const name of ['git', 'claude', 'sysctl']) { + fs.writeFileSync(path.join(bin, name), '#!/bin/sh\n'); + fs.chmodSync(path.join(bin, name), 0o755); + } + studio = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-timer-studio-')); + }); + afterEach(() => { + for (const d of [bin, studio]) fs.rmSync(d, { recursive: true, force: true }); + }); + + const build = (env) => buildWorktreeTimerPlist({ studioRoot: studio, config, env: { HOME: '/home/cc', PATH: bin, ...env } }); + + test('interval in seconds, the label, and XML-escaped paths', () => { + const xml = build(); + expect(xml).toContain(`${TIMER_LABEL}`); + expect(xml).toMatch(/900<\/integer>/); + expect(xml).toContain('/logs/a&b.log'); + expect(xml).toContain('/home/cc'); + expect(xml).toMatch(/RunAtLoad<\/key>\s*/); + }); + + test('git, claude or sysctl missing from PATH is an error naming them; nothing is printed', () => { + fs.rmSync(path.join(bin, 'claude')); + fs.chmodSync(path.join(bin, 'sysctl'), 0o644); + expect(() => build()).toThrow(/claude, sysctl not found on PATH/); + }); + + test('no PATH or no HOME is an error', () => { + expect(() => build({ PATH: '' })).toThrow(/PATH is not set/); + expect(() => build({ HOME: '' })).toThrow(/HOME is not set/); + }); +}); From a2a5745c19ee79ab9b938393963181787fa251a5 Mon Sep 17 00:00:00 2001 From: CC Evans Date: Tue, 10 Nov 2026 13:54:32 -0500 Subject: [PATCH 2/2] BOB-193: review fixes (node from PATH not the Cellar path; log folder must exist) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CYbcv4uMBkZT8H2W7Z9vzk --- lib/conductor/worktree-timer.js | 31 +++++++++++++++-------- test/commands/conductor.test.js | 1 + test/lib/conductor/worktree-timer.test.js | 17 ++++++++++--- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/lib/conductor/worktree-timer.js b/lib/conductor/worktree-timer.js index bf3e54f..10d780f 100644 --- a/lib/conductor/worktree-timer.js +++ b/lib/conductor/worktree-timer.js @@ -19,7 +19,7 @@ import { fileURLToPath } from 'url'; export const TIMER_LABEL = 'com.bobby.conductor.reap-worktrees'; -// The reap reads `claude agents`, runs git, and checks the host with sysctl. +// The reap reads `claude agents`, runs git, and checks the host with sysctl (node runs bobby). const NEEDED_ON_PATH = ['git', 'claude', 'sysctl']; const BOBBY_BIN = fileURLToPath(new URL('../../bin/bobby.js', import.meta.url)); @@ -28,31 +28,40 @@ function escapeXml(s) { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } +/** The first executable `name` on PATH, as written there (not resolved), or null. */ function onPath(name, pathEnv) { - return pathEnv.split(':').filter(Boolean).some((dir) => { + for (const dir of pathEnv.split(':').filter(Boolean)) { + const file = path.join(dir, name); try { - fs.accessSync(path.join(dir, name), fs.constants.X_OK); - return true; + fs.accessSync(file, fs.constants.X_OK); + return file; } catch { - return false; + // not in this folder } - }); + } + return null; } /** - * The plist text. `env` is the printing shell's environment (PATH and HOME are required), - * `node` the node binary and `bobby` the bobby entry point, both made absolute. + * The plist text. `env` is the printing shell's environment (PATH and HOME are required). + * node is the first `node` on that PATH, kept as written: Homebrew's /opt/homebrew/opt/node@22 + * link survives `brew upgrade`, the Cellar path it resolves to does not. `bobby` is the bobby + * entry point of the checkout that prints the plist, resolved. */ -export function buildWorktreeTimerPlist({ studioRoot, config, env = process.env, node = process.execPath, bobby = BOBBY_BIN }) { +export function buildWorktreeTimerPlist({ studioRoot, config, env = process.env, bobby = BOBBY_BIN }) { const { interval_minutes: minutes, log_file: log } = config.worktree_timer; if (!env.PATH) throw new Error('PATH is not set; the launchd job needs it to find git and claude'); if (!env.HOME) throw new Error('HOME is not set; the launchd job needs it for claude'); - const missing = NEEDED_ON_PATH.filter(name => !onPath(name, env.PATH)); + const missing = [...NEEDED_ON_PATH, 'node'].filter(name => !onPath(name, env.PATH)); if (missing.length) { throw new Error(`${missing.join(', ')} not found on PATH (${env.PATH}); the launchd job could not run the reap. Print the plist from a shell where they resolve.`); } + // launchd does not create the log's folder; a missing one would lose every run's output. + if (!fs.existsSync(path.dirname(log))) { + throw new Error(`worktree_timer.log_file: folder ${path.dirname(log)} does not exist; launchd will not create it`); + } const bin = fs.realpathSync(bobby); - const args = [fs.realpathSync(node), bin, 'conductor', 'reap', '--worktrees', '--apply']; + const args = [onPath('node', env.PATH), bin, 'conductor', 'reap', '--worktrees', '--apply']; const str = (v) => `\t\t${escapeXml(v)}`; return [ '', diff --git a/test/commands/conductor.test.js b/test/commands/conductor.test.js index 8c4af54..d37eb84 100644 --- a/test/commands/conductor.test.js +++ b/test/commands/conductor.test.js @@ -604,6 +604,7 @@ describe('bobby conductor', () => { expect(xml).toContain('com.bobby.conductor.reap-worktrees'); const args = [...xml.match(/ProgramArguments<\/key>\s*([\s\S]*?)<\/array>/)[1].matchAll(/([^<]*)<\/string>/g)].map(m => m[1]); expect(path.isAbsolute(args[0])).toBe(true); + expect(path.basename(args[0])).toBe('node'); expect(args[1]).toBe(fs.realpathSync(bobby)); expect(args.slice(2)).toEqual(['conductor', 'reap', '--worktrees', '--apply']); expect(xml).toMatch(/StartInterval<\/key>\s*3600<\/integer>/); diff --git a/test/lib/conductor/worktree-timer.test.js b/test/lib/conductor/worktree-timer.test.js index db93247..5b58c7f 100644 --- a/test/lib/conductor/worktree-timer.test.js +++ b/test/lib/conductor/worktree-timer.test.js @@ -6,14 +6,15 @@ import { buildWorktreeTimerPlist, TIMER_LABEL } from '../../../lib/conductor/wor describe('conductor worktree timer plist', () => { let bin; let studio; - const config = { worktree_timer: { interval_minutes: 15, log_file: '/logs/a&b.log' } }; + let config; beforeEach(() => { bin = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-timer-bin-')); - for (const name of ['git', 'claude', 'sysctl']) { + for (const name of ['git', 'claude', 'sysctl', 'node']) { fs.writeFileSync(path.join(bin, name), '#!/bin/sh\n'); fs.chmodSync(path.join(bin, name), 0o755); } studio = fs.mkdtempSync(path.join(os.tmpdir(), 'bobby-timer-studio-')); + config = { worktree_timer: { interval_minutes: 15, log_file: path.join(studio, 'a&b.log') } }; }); afterEach(() => { for (const d of [bin, studio]) fs.rmSync(d, { recursive: true, force: true }); @@ -25,7 +26,9 @@ describe('conductor worktree timer plist', () => { const xml = build(); expect(xml).toContain(`${TIMER_LABEL}`); expect(xml).toMatch(/900<\/integer>/); - expect(xml).toContain('/logs/a&b.log'); + expect(xml).toContain(`${path.join(studio, 'a&b.log')}`); + // node is taken from PATH as written, so a Homebrew opt/ link is not pinned to its Cellar version + expect(xml).toContain(`${path.join(bin, 'node')}`); expect(xml).toContain('/home/cc'); expect(xml).toMatch(/RunAtLoad<\/key>\s*/); }); @@ -36,6 +39,14 @@ describe('conductor worktree timer plist', () => { expect(() => build()).toThrow(/claude, sysctl not found on PATH/); }); + test('node missing from PATH, or a log folder that does not exist, is an error', () => { + fs.rmSync(path.join(bin, 'node')); + expect(() => build()).toThrow(/node not found on PATH/); + fs.writeFileSync(path.join(bin, 'node'), '#!/bin/sh\n', { mode: 0o755 }); + config.worktree_timer.log_file = path.join(studio, 'missing', 'reap.log'); + expect(() => build()).toThrow(/worktree_timer\.log_file: folder .*missing does not exist/); + }); + test('no PATH or no HOME is an error', () => { expect(() => build({ PATH: '' })).toThrow(/PATH is not set/); expect(() => build({ HOME: '' })).toThrow(/HOME is not set/);