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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 11 additions & 2 deletions commands/conductor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
Expand Down
48 changes: 45 additions & 3 deletions lib/conductor/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -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: { <key>: n }.
Expand Down Expand Up @@ -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'];
Expand Down Expand Up @@ -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.',
Expand All @@ -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 });
Expand Down
67 changes: 55 additions & 12 deletions lib/conductor/worktree-reaper.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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 };
}
Expand All @@ -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);
Expand All @@ -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) {
Expand All @@ -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 };
}
Expand Down Expand Up @@ -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 });
Expand All @@ -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];
Expand All @@ -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.`);
Expand All @@ -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');
Expand Down
Loading
Loading