diff --git a/bin/scratch-worktree.mjs b/bin/scratch-worktree.mjs new file mode 100755 index 0000000000..cbadbc4f43 --- /dev/null +++ b/bin/scratch-worktree.mjs @@ -0,0 +1,158 @@ +#!/usr/bin/env node +// Per-run scratch worktrees for scheduled fleet tasks (#11348). +// +// The improvement-issue-creator briefs built their scratch path from the +// date and a per-day counter, guarded it with `test -d … || worktree add`, +// and cleaned up with `git worktree remove --force`. A crashed run left its +// tree behind; the next run computing the same counter adopted it (skipping +// fetch and base checks) and then force-removed a tree it never created. +// +// This helper replaces that shape: +// +// add names the path with a per-run unique id (UTC timestamp plus +// random suffix), refuses loudly if the path already exists, +// fetches the base, runs `git worktree add` without masking its +// exit status, and records an owner token in the worktree's own +// git dir (so the tree stays clean). +// remove removes a scratch worktree only when the caller presents the +// token `add` printed and the tree is clean; never --force. It +// prints what it removed. +// +// Usage: +// node bin/scratch-worktree.mjs add --repo --prefix +// [--root ] [--base origin/main] [--no-fetch] +// prints JSON {"path": …, "token": …, "base": …, "head": …} +// node bin/scratch-worktree.mjs remove --path --token +// +// Exit codes: 0 ok, 2 usage, 3 refused (path exists, wrong owner, dirty), +// 4 git failed. + +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export const OWNER_FILE = 'scratch-worktree-owner'; + +export class ScratchError extends Error { + constructor(code, message) { + super(message); + this.code = code; + } +} + +const git = (args, cwd) => { + const result = spawnSync('git', args, { cwd, encoding: 'utf8' }); + if (result.error) throw new ScratchError(4, `git ${args.join(' ')}: ${result.error.message}`); + if (result.status !== 0) { + throw new ScratchError( + 4, + `git ${args.join(' ')} exited ${result.status}: ${(result.stderr || result.stdout).trim()}` + ); + } + return result.stdout.trim(); +}; + +// A prefix names the task, not the run: plain path-segment characters only. +export const validatePrefix = (prefix) => { + if (typeof prefix !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(prefix)) { + throw new ScratchError(2, `--prefix "${prefix}" must be letters, digits, '.', '_' or '-'`); + } + return prefix; +}; + +export const runId = (now = new Date(), random = randomBytes(4)) => { + const stamp = now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z'); + return `${stamp}-${random.toString('hex')}`; +}; + +export const scratchPath = (root, prefix, id) => path.join(root, `${validatePrefix(prefix)}-${id}`); + +const ownerFile = (worktree) => { + const gitDir = git(['rev-parse', '--absolute-git-dir'], worktree); + return path.join(gitDir, OWNER_FILE); +}; + +export const add = ({ repo, prefix, root, base = 'origin/main', fetch = true, now, random }) => { + if (!repo) throw new ScratchError(2, '--repo is required'); + validatePrefix(prefix); + const scratchRoot = root ?? path.join(os.homedir(), 'git', 'fleet'); + const target = scratchPath(scratchRoot, prefix, runId(now, random)); + if (fs.existsSync(target)) { + throw new ScratchError(3, `refusing to adopt existing scratch path ${target}`); + } + if (fetch) { + const slash = base.indexOf('/'); + if (slash > 0) git(['fetch', '-q', base.slice(0, slash), base.slice(slash + 1)], repo); + } + const baseSha = git(['rev-parse', '--verify', `${base}^{commit}`], repo); + fs.mkdirSync(scratchRoot, { recursive: true }); + git(['worktree', 'add', '--detach', '-q', target, baseSha], repo); + const head = git(['rev-parse', 'HEAD'], target); + if (head !== baseSha) { + throw new ScratchError(4, `worktree ${target} is at ${head}, expected ${base} ${baseSha}`); + } + const token = randomBytes(16).toString('hex'); + fs.writeFileSync(ownerFile(target), `${token}\n`, { mode: 0o600 }); + return { path: target, token, base, head }; +}; + +export const remove = ({ path: target, token }) => { + if (!target) throw new ScratchError(2, '--path is required'); + if (!token) throw new ScratchError(2, '--token is required'); + if (!fs.existsSync(target)) throw new ScratchError(3, `no worktree at ${target}`); + let recorded; + try { + recorded = fs.readFileSync(ownerFile(target), 'utf8').trim(); + } catch { + throw new ScratchError(3, `refusing to remove ${target}: it has no scratch owner record, so this run did not create it`); + } + if (recorded !== token) { + throw new ScratchError(3, `refusing to remove ${target}: it belongs to another run`); + } + const status = git(['status', '--porcelain', '--untracked-files=all'], target); + if (status !== '') { + throw new ScratchError(3, `refusing to remove ${target}: it has uncommitted changes:\n${status}`); + } + const head = git(['rev-parse', 'HEAD'], target); + git(['worktree', 'remove', target], target); + return { removed: target, head }; +}; + +export const parseArgs = (argv) => { + const [command, ...rest] = argv; + const options = {}; + for (let i = 0; i < rest.length; i += 1) { + const flag = rest[i]; + if (flag === '--no-fetch') { + options.fetch = false; + continue; + } + const match = /^--(repo|prefix|root|base|path|token)$/.exec(flag); + if (!match || i + 1 >= rest.length) throw new ScratchError(2, `unknown or incomplete option ${flag}`); + options[match[1]] = rest[i + 1]; + i += 1; + } + if (command !== 'add' && command !== 'remove') { + throw new ScratchError(2, 'usage: scratch-worktree.mjs add|remove [options]'); + } + return { command, options }; +}; + +export const main = (argv) => { + try { + const { command, options } = parseArgs(argv); + const result = command === 'add' ? add(options) : remove(options); + process.stdout.write(`${JSON.stringify(result)}\n`); + return 0; + } catch (err) { + process.stderr.write(`scratch-worktree: ${err.message}\n`); + return err instanceof ScratchError ? err.code : 4; + } +}; + +if (process.argv[1] && fileURLToPath(import.meta.url) === fs.realpathSync(process.argv[1])) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/bin/scratch-worktree.test.mjs b/bin/scratch-worktree.test.mjs new file mode 100644 index 0000000000..ed1baed715 --- /dev/null +++ b/bin/scratch-worktree.test.mjs @@ -0,0 +1,138 @@ +// Tests for per-run scratch worktrees (#11348). +// Run: node --test bin/scratch-worktree.test.mjs +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { add, remove, runId, parseArgs, validatePrefix, ScratchError } from './scratch-worktree.mjs'; + +const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'scratch-worktree.mjs'); + +const sh = (args, cwd) => { + const result = spawnSync('git', args, { cwd, encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + return result.stdout.trim(); +}; + +// A bare "origin" with one commit on main, and a clone of it. +const fixture = () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scratch-worktree-')); + const origin = path.join(dir, 'origin.git'); + const seed = path.join(dir, 'seed'); + const repo = path.join(dir, 'repo'); + sh(['init', '-q', '--bare', '-b', 'main', origin], dir); + sh(['init', '-q', '-b', 'main', seed], dir); + fs.writeFileSync(path.join(seed, 'README'), 'seed\n'); + sh(['add', 'README'], seed); + sh(['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'seed'], seed); + sh(['push', '-q', origin, 'main'], seed); + sh(['clone', '-q', origin, repo], dir); + return { dir, seed, repo, root: path.join(dir, 'fleet') }; +}; + +const refused = (code, fragment) => (err) => + err instanceof ScratchError && err.code === code && err.message.includes(fragment); + +test('run ids carry a UTC timestamp and a random suffix', () => { + const id = runId(new Date('2026-11-17T18:32:08.123Z'), Buffer.from('a1b2c3d4', 'hex')); + assert.equal(id, '20261117T183208Z-a1b2c3d4'); + assert.notEqual(runId(), runId()); +}); + +test('prefixes are a single plain path segment', () => { + assert.equal(validatePrefix('improvement-issue-creator-code-lane-b'), 'improvement-issue-creator-code-lane-b'); + for (const bad of ['', '../x', 'a/b', '-x', 'a b', undefined]) { + assert.throws(() => validatePrefix(bad), refused(2, '--prefix')); + } +}); + +test('two runs of the same task in the same second never share a path', () => { + const { repo, root } = fixture(); + const now = new Date('2026-11-17T18:32:08Z'); + const first = add({ repo, prefix: 'creator', root, now }); + const second = add({ repo, prefix: 'creator', root, now }); + assert.notEqual(first.path, second.path); + assert.notEqual(first.token, second.token); + assert.equal(first.head, sh(['rev-parse', 'origin/main'], repo)); +}); + +test('an existing path is refused, never adopted', () => { + const { repo, root } = fixture(); + const now = new Date('2026-11-17T18:32:08Z'); + const random = Buffer.from('00000000', 'hex'); + const crashed = add({ repo, prefix: 'creator', root, now, random }); + assert.throws(() => add({ repo, prefix: 'creator', root, now, random }), refused(3, `refusing to adopt existing scratch path ${crashed.path}`)); +}); + +test('add starts from the freshly fetched base', () => { + const { dir, seed, repo, root } = fixture(); + fs.writeFileSync(path.join(seed, 'README'), 'newer\n'); + sh(['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-am', 'newer'], seed); + sh(['push', '-q', path.join(dir, 'origin.git'), 'main'], seed); + const created = add({ repo, prefix: 'creator', root }); + assert.equal(created.head, sh(['rev-parse', 'HEAD'], seed)); +}); + +test('a worktree add failure is reported, not masked', () => { + const { repo, root } = fixture(); + assert.throws(() => add({ repo, prefix: 'creator', root, base: 'origin/no-such-branch' }), refused(4, 'git fetch')); +}); + +test('remove needs the owning token and a clean tree, and never forces', () => { + const { repo, root } = fixture(); + const mine = add({ repo, prefix: 'creator', root }); + const theirs = add({ repo, prefix: 'creator', root }); + + assert.throws(() => remove({ path: theirs.path, token: mine.token }), refused(3, 'belongs to another run')); + + fs.writeFileSync(path.join(mine.path, 'notes.txt'), 'unsaved work\n'); + assert.throws(() => remove({ path: mine.path, token: mine.token }), refused(3, 'uncommitted changes')); + assert.ok(fs.existsSync(path.join(mine.path, 'notes.txt'))); + + fs.rmSync(path.join(mine.path, 'notes.txt')); + assert.deepEqual(remove({ path: mine.path, token: mine.token }), { removed: mine.path, head: mine.head }); + assert.ok(!fs.existsSync(mine.path)); + assert.ok(fs.existsSync(theirs.path)); +}); + +test('a worktree this helper did not create is never removed', () => { + const { repo, root } = fixture(); + const foreign = path.join(root, 'creator-20261117-lane-b-3'); + fs.mkdirSync(root, { recursive: true }); + sh(['worktree', 'add', '--detach', '-q', foreign, 'origin/main'], repo); + assert.throws(() => remove({ path: foreign, token: 'anything' }), refused(3, 'no scratch owner record')); + assert.ok(fs.existsSync(foreign)); +}); + +test('the owner record does not dirty the tree', () => { + const { repo, root } = fixture(); + const created = add({ repo, prefix: 'creator', root }); + assert.equal(sh(['status', '--porcelain', '--untracked-files=all'], created.path), ''); +}); + +test('argument parsing rejects unknown commands and options', () => { + assert.deepEqual(parseArgs(['add', '--repo', 'r', '--prefix', 'p', '--no-fetch']), { + command: 'add', + options: { repo: 'r', prefix: 'p', fetch: false } + }); + assert.throws(() => parseArgs(['adopt']), refused(2, 'usage')); + assert.throws(() => parseArgs(['add', '--force']), refused(2, '--force')); + assert.throws(() => parseArgs(['remove', '--token']), refused(2, '--token')); +}); + +test('the CLI prints JSON and exits with the refusal code', () => { + const { repo, root } = fixture(); + const run = (args) => spawnSync(process.execPath, [script, ...args], { encoding: 'utf8' }); + const added = run(['add', '--repo', repo, '--prefix', 'creator', '--root', root]); + assert.equal(added.status, 0, added.stderr); + const { path: created, token } = JSON.parse(added.stdout); + const wrong = run(['remove', '--path', created, '--token', 'nope']); + assert.equal(wrong.status, 3); + assert.match(wrong.stderr, /belongs to another run/); + const removed = run(['remove', '--path', created, '--token', token]); + assert.equal(removed.status, 0, removed.stderr); + assert.equal(JSON.parse(removed.stdout).removed, created); +}); diff --git a/doc/agents/parallel-writers-and-subsessions.md b/doc/agents/parallel-writers-and-subsessions.md index c206d0a96b..83bee46321 100644 --- a/doc/agents/parallel-writers-and-subsessions.md +++ b/doc/agents/parallel-writers-and-subsessions.md @@ -23,6 +23,16 @@ design-mill protocol. parent's route: launch children from the directory their work belongs in, and state the directory and route in the launch prompt anyway, so the record shows intent. +- **Scratch worktrees are per run (#11348).** A scheduled task that + needs a throwaway tree gets it from `node bin/scratch-worktree.mjs add + --repo --prefix `, which names the path with a + UTC timestamp and random suffix, fetches the base, refuses to adopt a + path that already exists, and prints the path and an owner token as + JSON. Clean up with `node bin/scratch-worktree.mjs remove --path + --token `: it removes only a clean tree this run created and + never forces. Never build the path from the date or a per-day counter, + never guard with `test -d … ||`, never pipe `worktree add` through + `tail`, and never `git worktree remove --force` a scratch tree. - **Scope the task to the context it needs.** A child gets a crisp spec and only the context that task requires; the parent keeps the whole picture. Independent tasks launch in parallel. Follow up with a finished