From c764e5f29fcafb56b96da64b88547e0e7b2c140f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 03:25:48 -0600 Subject: [PATCH 1/4] fix(pm-dispatch): retire safe task worktrees --- pm-stack/dispatch/src/config.ts | 20 + pm-stack/dispatch/src/launch_failure.ts | 60 ++- pm-stack/dispatch/src/server.ts | 74 ++- pm-stack/dispatch/src/worktree_cleanup.ts | 436 ++++++++++++++++++ pm-stack/dispatch/test/launch_failure.test.ts | 2 +- pm-stack/dispatch/test/worktree.test.ts | 135 ++++++ 6 files changed, 714 insertions(+), 13 deletions(-) create mode 100644 pm-stack/dispatch/src/worktree_cleanup.ts diff --git a/pm-stack/dispatch/src/config.ts b/pm-stack/dispatch/src/config.ts index 1380f4bdca..bea23176c7 100644 --- a/pm-stack/dispatch/src/config.ts +++ b/pm-stack/dispatch/src/config.ts @@ -75,6 +75,14 @@ export interface Config { * (PM_DISPATCH_WORKTREE_ROOT, default ~/git/fleet; "off" runs in the * requested directory as before). code#12213. */ worktreeRoot: string | null; + /** Registry file holding the worktree <-> task/session association + * the cleanup lifecycle retires trees from (code#12217). Only + * meaningful when worktreeRoot is set. */ + worktreeRegistryFile: string; + /** Seconds between worktree cleanup sweeps (PM_DISPATCH_WORKTREE_ + * SWEEP_SECONDS, default 900; "off" disables the timer — the + * failure-path cleanup still runs). code#12217. */ + worktreeSweepSeconds: number | null; } export function loadConfig(env: Record = process.env): Config { @@ -123,5 +131,17 @@ export function loadConfig(env: Record = process.env env.PM_DISPATCH_WORKTREE_ROOT?.trim().toLowerCase() === "off" ? null : s(env.PM_DISPATCH_WORKTREE_ROOT, join(homedir(), "git", "fleet")), + worktreeRegistryFile: s( + env.PM_DISPATCH_WORKTREE_REGISTRY, + join(homedir(), ".local", "state", "pm-dispatch", "worktree-registry.json"), + ), + worktreeSweepSeconds: (() => { + const v = s(env.PM_DISPATCH_WORKTREE_SWEEP_SECONDS, "900"); + if (v.toLowerCase() === "off") return null; + if (!/^\d+$/.test(v) || Number(v) < 1) { + throw new Error(`Invalid PM_DISPATCH_WORKTREE_SWEEP_SECONDS "${v}": expected a positive integer or "off"`); + } + return Number(v); + })(), }; } diff --git a/pm-stack/dispatch/src/launch_failure.ts b/pm-stack/dispatch/src/launch_failure.ts index 6ea8df67eb..cf5c9825be 100644 --- a/pm-stack/dispatch/src/launch_failure.ts +++ b/pm-stack/dispatch/src/launch_failure.ts @@ -73,8 +73,19 @@ export async function compensateOrphanedIssue( /** Mutable context shared by launchSession and its failure handler. */ export interface LaunchFailureContext { sessionId: string | null; + /** The dispatch worktree created for this launch, if any (#12217). + * Set the moment the tree exists — before the session — so a failure + * at session creation can still clean the tree up. */ + worktree: string | null; } +/** Run once the launch's session is CONFIRMED gone (dispatch itself + * deleted it), or — when no session was ever recorded — after the + * failure was established. Returns the cleanup outcome for the note, + * or null when there is nothing to retire. Never throws: a worktree + * outcome must not mask the launch failure being reported. */ +export type RetireWorktree = () => Promise<{ worktree: string; removed: boolean; reason: string } | null>; + /** * Run the part of a launch that follows successful session creation. * Retain the new session ID so the failure handler can record it before @@ -98,8 +109,20 @@ export async function handleLaunchFailure( e: unknown, sessionId: string | null = null, deleteSession?: (sessionId: string) => Promise, + retireWorktree?: RetireWorktree, ): Promise { const msg = e instanceof Error ? e.message : String(e); + // #12217: best-effort worktree retirement, reported, never thrown — + // and never attempted while the session may still be live. + const retireSafely = async (): Promise<{ worktree: string; removed: boolean; reason: string } | null> => { + if (!retireWorktree) return null; + try { + return await retireWorktree(); + } catch (re) { + const reason = re instanceof Error ? re.message : String(re); + return { worktree: "unknown", removed: false, reason }; + } + }; if (e instanceof ClaimLostError) { // Lost the claim race (#10737): the task and its issue now belong // to the worker that claimed it, so neither is cancelled, noted or @@ -107,6 +130,7 @@ export async function handleLaunchFailure( if (sessionId != null && deleteSession) { try { await deleteSession(sessionId); + await retireSafely(); } catch { /* best-effort: the session never received the task's claim */ } @@ -122,15 +146,31 @@ export async function handleLaunchFailure( cancelError = ce instanceof Error ? ce.message : String(ce); } let cleanupError: string | null = null; - if (sessionId != null) { - if (!deleteSession) { - cleanupError = "session deletion callback unavailable"; - } else { - try { - await deleteSession(sessionId); - } catch (de) { - cleanupError = de instanceof Error ? de.message : String(de); + let worktreeNote = ""; + if (sessionId == null) { + // No session was ever recorded: nothing to wait for on the session + // side, so the worktree decision runs on its own evidence now. + const outcome = await retireSafely(); + if (outcome) { + worktreeNote = outcome.removed + ? `\n\nTask worktree ${outcome.worktree} was removed after the failed launch.` + : `\n\nTask worktree ${outcome.worktree} was retained: ${outcome.reason}.`; + } + } else if (!deleteSession) { + cleanupError = "session deletion callback unavailable"; + } else { + try { + await deleteSession(sessionId); + // The session is confirmed gone: only now may the worktree be + // considered for retirement (#12217). + const outcome = await retireSafely(); + if (outcome) { + worktreeNote = outcome.removed + ? `\n\nTask worktree ${outcome.worktree} was removed after the failed launch.` + : `\n\nTask worktree ${outcome.worktree} was retained: ${outcome.reason}.`; } + } catch (de) { + cleanupError = de instanceof Error ? de.message : String(de); } } if (issueNumber != null) { @@ -142,8 +182,8 @@ export async function handleLaunchFailure( : `\n\nOpenCode session ${sessionId} may still be live; session cleanup failed: ${cleanupError}`; const note = cancelError == null - ? `Dispatch launch FAILED and queue task #${taskId} was cancelled.${sessionNote}\n\nError: ${msg}` - : `Dispatch launch FAILED and cancelling queue task #${taskId} FAILED — the task may still be queued or claimed and needs cleanup.${sessionNote}\n\nError: ${msg}\nCancellation error: ${cancelError}`; + ? `Dispatch launch FAILED and queue task #${taskId} was cancelled.${sessionNote}${worktreeNote}\n\nError: ${msg}` + : `Dispatch launch FAILED and cancelling queue task #${taskId} FAILED — the task may still be queued or claimed and needs cleanup.${sessionNote}${worktreeNote}\n\nError: ${msg}\nCancellation error: ${cancelError}`; try { await github.comment(repo, issueNumber, note); } catch { diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index 758db31cc6..27188f014a 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -49,6 +49,7 @@ import { annotateLaunch } from "./launch_annotations.ts"; import { GitHubClient } from "./github.ts"; import { OpenCodeClient, OpenCodeError } from "./opencode.ts"; import { createDispatchWorktree, worktreeNotice } from "./worktree.ts"; +import { WorktreeRegistry, cleanupDispatchWorktree, sweepDispatchWorktrees } from "./worktree_cleanup.ts"; const cfg: Config = loadConfig(); // #9028: the queue client talks to the fleet queue broker. Its token @@ -67,6 +68,29 @@ const brokerToken = loadBrokerToken(); const queue = brokerToken ? new QueueClient(cfg.queueBrokerUrl, brokerToken) : null; const github = new GitHubClient(cfg.githubAppId, cfg.githubAppPrivateKeyPem); const opencode = new OpenCodeClient(cfg.opencodeUrl, cfg.opencodeAuthFile); +const worktreeRegistry = new WorktreeRegistry(cfg.worktreeRegistryFile); + +/** Best-effort periodic cleanup. A failed upstream read or unsafe tree is + * retained by the cleanup module; cleanup outcomes never affect dispatch. */ +async function sweepWorktrees(): Promise { + if (!cfg.worktreeRoot) return; + const outcomes = await sweepDispatchWorktrees({ + registry: worktreeRegistry, + getSession: (id) => opencode.getSession(id), + listSessions: () => opencode.listSessions(), + }); + for (const outcome of outcomes) { + console.info(`[dispatch-worktree] ${outcome.removed ? "removed" : "retained"} ${outcome.worktree}: ${outcome.reason}`); + } +} + +function startWorktreeSweep(): void { + if (!cfg.worktreeRoot || cfg.worktreeSweepSeconds == null) return; + const interval = setInterval(() => void sweepWorktrees(), cfg.worktreeSweepSeconds * 1000); + interval.unref(); + // One startup pass catches trees from before this process restarted. + void sweepWorktrees(); +} const MAX_BODY_BYTES = 256 * 1024; const LEASE_SECONDS = 6 * 60 * 60; @@ -171,6 +195,26 @@ async function maybeCreateIssue( // POST /v1/sessions // --------------------------------------------------------------------------- +/** Failure-path retirement looks up only the exact recorded worktree. + * Missing/bad registry state is an explicit retained outcome rather + * than a guessed path or an exception that could replace the launch + * error. */ +async function retireFailedWorktree(worktree: string | null) { + if (!worktree) return null; + try { + const record = (await worktreeRegistry.load()).find((r) => r.worktree === worktree && r.state === "active"); + if (!record) return { worktree, removed: false, reason: "no active registry record; retained" }; + return await cleanupDispatchWorktree({ + record, + registry: worktreeRegistry, + getSession: (id) => opencode.getSession(id), + listSessions: () => opencode.listSessions(), + }); + } catch (e) { + return { worktree, removed: false, reason: `cleanup unavailable: ${e instanceof Error ? e.message : String(e)}` }; + } +} + async function launchSession( caller: CallerIdentity, req: SessionRequest, @@ -185,6 +229,7 @@ async function launchSession( // launch fails and the task is cancelled like any pre-session error. let sessionDirectory = directory; let notice = ""; + let createdWorktree: { directory: string; worktree: string; base: string } | null = null; if (cfg.worktreeRoot) { const primary = resolveSessionDirectory("bearer", req.repo, undefined, REPO_DIRS); const wt = await createDispatchWorktree({ @@ -194,14 +239,36 @@ async function launchSession( repo: req.repo, taskId: task.id, }); + createdWorktree = wt; + failureContext.worktree = wt.worktree; sessionDirectory = wt.directory; notice = `\n${worktreeNotice(wt.worktree, primary)}`; + try { + await worktreeRegistry.add({ + taskId: task.id, + sessionId: null, + repo: req.repo, + primary, + worktree: wt.worktree, + base: wt.base, + createdAt: new Date().toISOString(), + }); + } catch (e) { + warnings.push(`dispatch worktree registry write failed; cleanup will retain this tree: ${e instanceof Error ? e.message : String(e)}`); + } } const session = await opencode.createSession({ directory: sessionDirectory, title: req.title ?? titleFromPrompt(req.prompt), model: req.model, }); + if (createdWorktree) { + try { + await worktreeRegistry.setSessionId(createdWorktree.worktree, session.id); + } catch (e) { + warnings.push(`dispatch worktree session binding failed; cleanup will retain this tree: ${e instanceof Error ? e.message : String(e)}`); + } + } const prefix = `[dispatch] Queue task #${task.id} · Issue ${issue ? issue.url : "none"} · Repo ${req.repo}${notice}`; await withCreatedSession(session.id, failureContext, async () => { await opencode.sendPrompt(session.id, `${prefix}\n\n${req.prompt}`); @@ -300,7 +367,7 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise { try { await launchSession(caller, body, task, issue, directory, warnings, failureContext); @@ -317,6 +384,7 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise opencode.deleteSession(sessionId), + () => retireFailedWorktree(failureContext.worktree), ); } })(); @@ -330,7 +398,7 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise opencode.deleteSession(sessionId), + () => retireFailedWorktree(failureContext.worktree), ); // A lost claim race is a conflict, not an upstream failure: the // task is running under the worker that claimed it (#10737). @@ -852,4 +921,5 @@ if (import.meta.main) { for (const server of servers) { console.log(`dispatch listening on http://${server.hostname}:${server.port} (version: ${cfg.buildVersion})`); } + startWorktreeSweep(); } diff --git a/pm-stack/dispatch/src/worktree_cleanup.ts b/pm-stack/dispatch/src/worktree_cleanup.ts new file mode 100644 index 0000000000..11a76ce29c --- /dev/null +++ b/pm-stack/dispatch/src/worktree_cleanup.ts @@ -0,0 +1,436 @@ +// Dispatch worktree cleanup lifecycle (code#12217). +// +// createDispatchWorktree gives each launch its own detached tree under +// the fleet worktree root, and nothing removed those trees afterwards. +// The generic worktree-reaper deliberately retains detached trees +// (detached-v1 policy), so dispatch owns the lifecycle of the trees it +// creates. This module is that lifecycle: +// +// - a registry file records the exact tree created for a launch +// (task, session, primary, base commit). A cleanup target is ONLY +// a registered path — never a directory scan, never a name guess; +// - a tree is retired only after confirmed session termination: the +// recorded session is gone (404 from the OpenCode server, or +// deleted by dispatch itself), and no other session listed by the +// server occupies the tree. An unreachable server, a transport +// failure or an unreadable session list is AMBIGUOUS state — the +// tree is retained (fail closed); +// - before removal the tree must be a registered worktree of its +// primary, unlocked, unoccupied (no process cwd inside it), +// exactly clean, and still at the base commit it was created at. +// Anything else — uncommitted changes, untracked files, commits +// beyond base, a lock, an occupant, a git error — retains the +// tree: user work is never discarded; +// - removal is idempotent (an already-absent tree simply completes +// its record) and every cleanup failure is reported as an outcome, +// never thrown past the caller, so it can never mask a +// dispatch/session result. +import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { runGit, type GitRunner } from "./worktree.ts"; + +export class WorktreeCleanupError extends Error {} + +const msg = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const nowIso = (): string => new Date().toISOString(); + +// --------------------------------------------------------------------------- +// Registry: the durable worktree <-> task/session association +// --------------------------------------------------------------------------- + +/** One launch's worktree record. `state` is "active" until the tree is + * confirmed gone; retention reasons are recorded on `lastCheck`, never + * acted on destructively. */ +export interface WorktreeRecord { + taskId: number; + /** The OpenCode session bound to the tree, or null when the launch + * died before the session id was recorded (the session-list check + * still protects that tree — see worktreeSessionEvidence). */ + sessionId: string | null; + repo: string; + /** The primary clone the tree was created from (git -C target). */ + primary: string; + worktree: string; + /** The commit the tree was created at; HEAD must still equal it. */ + base: string; + createdAt: string; + state: "active" | "removed"; + lastCheck: { at: string; outcome: "removed" | "retained"; reason: string } | null; +} + +export type NewWorktreeRecord = Omit; + +function parseRecords(raw: string, file: string): WorktreeRecord[] { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new WorktreeCleanupError(`worktree registry ${file} is not valid JSON`); + } + if (!Array.isArray(parsed)) { + throw new WorktreeCleanupError(`worktree registry ${file} does not hold a JSON array`); + } + const str = (v: unknown): string | null => (typeof v === "string" ? v : null); + const records: WorktreeRecord[] = []; + for (const entry of parsed) { + if (typeof entry !== "object" || entry === null) { + throw new WorktreeCleanupError(`worktree registry ${file} holds a non-object entry`); + } + const e = entry as Record; + const worktree = str(e.worktree); + const primary = str(e.primary); + const base = str(e.base); + if (worktree === null || primary === null || base === null) { + throw new WorktreeCleanupError(`worktree registry ${file} holds an entry without worktree/primary/base`); + } + const state = e.state === "removed" ? "removed" : "active"; + const last = (e.lastCheck as Record | null) ?? null; + records.push({ + taskId: typeof e.taskId === "number" ? e.taskId : 0, + sessionId: str(e.sessionId), + repo: str(e.repo) ?? "unknown", + primary, + worktree, + base, + createdAt: str(e.createdAt) ?? "", + state, + lastCheck: + last !== null && typeof last === "object" && (last.outcome === "removed" || last.outcome === "retained") + ? { at: str(last.at) ?? "", outcome: last.outcome, reason: str(last.reason) ?? "" } + : null, + }); + } + return records; +} + +/** Durable registry of launch worktrees. Mutations are serialized + * inside this process (load-modify-save with an atomic tmp+rename), so + * concurrent launches can never clobber each other's records. A load + * failure THROWS (WorktreeCleanupError): callers fail closed — a sweep + * that cannot read its records touches nothing, and a launch that + * cannot record its tree still launches (the tree is simply never + * auto-removed). */ +export class WorktreeRegistry { + private chain: Promise = Promise.resolve(); + + constructor(readonly file: string) {} + + async load(): Promise { + let raw: string; + try { + raw = readFileSync(this.file, "utf8"); + } catch { + return []; // no file yet: nothing was ever registered under this path + } + return parseRecords(raw, this.file); + } + + /** Register a freshly created tree. A record at the same path is + * replaced wholesale: the path names a brand-new tree (the creator + * refuses to reuse an existing directory), so any old record for it + * describes a tree that no longer exists. */ + async add(record: NewWorktreeRecord): Promise { + return this.serialized(async () => { + const records = await this.load(); + const full: WorktreeRecord = { ...record, state: "active", lastCheck: null }; + const existing = records.findIndex((r) => r.worktree === full.worktree); + if (existing >= 0) records[existing] = full; + else records.push(full); + this.save(records); + return full; + }); + } + + /** Bind the launch's session id onto the record (called right after + * session creation; a crash before this leaves sessionId null, which + * the session-list evidence check still handles conservatively). */ + async setSessionId(worktree: string, sessionId: string): Promise { + await this.serialized(async () => { + const records = await this.load(); + const record = records.find((r) => r.worktree === worktree); + if (!record) return; + record.sessionId = sessionId; + this.save(records); + }); + } + + /** Record the outcome of one cleanup check. */ + async mark(worktree: string, outcome: "removed" | "retained", reason: string, at: string = nowIso()): Promise { + await this.serialized(async () => { + const records = await this.load(); + const record = records.find((r) => r.worktree === worktree); + if (!record) return; + record.lastCheck = { at, outcome, reason }; + if (outcome === "removed") record.state = "removed"; + this.save(records); + }); + } + + private serialized(fn: () => Promise): Promise { + const run = this.chain.then(fn, fn); + this.chain = run.catch(() => {}); + return run; + } + + private save(records: WorktreeRecord[]): void { + mkdirSync(dirname(this.file), { recursive: true }); + const tmp = `${this.file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`; + writeFileSync(tmp, JSON.stringify(records, null, 2) + "\n"); + renameSync(tmp, this.file); + } +} + +// --------------------------------------------------------------------------- +// Session termination evidence +// --------------------------------------------------------------------------- + +export interface SessionEvidence { + /** True only when termination is CONFIRMED; every unknown is retained. */ + terminated: boolean; + /** How the decision was reached — recorded on the record either way. */ + reason: string; +} + +/** The directory a raw session object runs in (the v2 envelope is + * already unwrapped by the client; the object carries either + * `directory` or `location.directory`, like sessionStatusView). */ +function sessionDirectory(raw: unknown): string | null { + if (typeof raw !== "object" || raw === null) return null; + const obj = raw as Record; + if (typeof obj.directory === "string") return obj.directory; + const loc = obj.location as Record | undefined; + return typeof loc?.directory === "string" ? loc.directory : null; +} + +function sessionIdOf(raw: unknown): string | null { + if (typeof raw === "object" && raw !== null && typeof (raw as Record).id === "string") { + return (raw as Record).id as string; + } + return null; +} + +function containsPath(dir: string, treeReal: string): boolean { + let d: string; + try { + d = realpathSync(dir); + } catch { + d = dir; // the session's directory may be recorded but gone; compare literally + } + return d === treeReal || d.startsWith(treeReal + "/"); +} + +/** Evidence that no live or resumable session occupies the worktree. + * + * - recorded session id: the OpenCode server must report it gone (the + * client's getSession resolves null on 404); a live object or any + * error (server down, auth, 5xx) retains the tree; + * - `confirmedTerminated` skips that first lookup when the caller itself + * deleted the session (the launch-failure path) — the occupancy + * cross-check below still runs; + * - the session-list cross-check then proves no OTHER session (one + * dispatch never recorded, e.g. created by a human) runs in the tree; + * a failed or unreadable list is ambiguous state and retains it. + * For records with no session id at all (a launch that died between + * worktree creation and session creation) this list is the ONLY + * evidence either way. */ +export async function worktreeSessionEvidence(args: { + record: Pick; + getSession: (sessionId: string) => Promise; + listSessions: () => Promise; + confirmedTerminated?: boolean; +}): Promise { + if (args.confirmedTerminated !== true && args.record.sessionId != null) { + let session: unknown; + try { + session = await args.getSession(args.record.sessionId); + } catch (e) { + return { terminated: false, reason: `session ${args.record.sessionId} state unknown: ${msg(e)} — retained` }; + } + if (session != null) { + return { terminated: false, reason: `session ${args.record.sessionId} exists (live or resumable)` }; + } + } + if (args.confirmedTerminated !== true && args.record.sessionId == null) { + // No session id recorded: a crash between worktree creation and + // session creation may still have left a live session in the tree, + // so the session list below decides — nothing else can. + } + try { + const sessions = await args.listSessions(); + if (!Array.isArray(sessions)) { + return { terminated: false, reason: "session list returned an ambiguous shape; retained" }; + } + const list = sessions; + let treeReal = args.record.worktree; + try { + treeReal = realpathSync(args.record.worktree); + } catch { + /* tree already gone: any session directory still inside the + * recorded path (compared literally) counts as an occupant */ + } + for (const raw of list) { + const dir = sessionDirectory(raw); + if (dir !== null && containsPath(dir, treeReal)) { + const id = sessionIdOf(raw) ?? "(unknown id)"; + return { terminated: false, reason: `session ${id} still occupies the worktree` }; + } + } + return { + terminated: true, + reason: "recorded session confirmed gone; no session occupies the worktree", + }; + } catch (e) { + return { + terminated: false, + reason: `session list unavailable; cannot rule out a live session in the worktree: ${msg(e)} — retained`, + }; + } +} + +// --------------------------------------------------------------------------- +// Filesystem, process-occupancy and Git safety gates +// --------------------------------------------------------------------------- + +export interface CleanupOutcome { + worktree: string; + removed: boolean; + reason: string; +} + +function isProcessUsingPath(worktree: string): boolean { + let treeReal: string; + try { + treeReal = realpathSync(worktree); + } catch { + return false; + } + let pids: string[]; + try { + pids = readdirSync("/proc").filter((entry) => /^\d+$/.test(entry)); + } catch { + // Cannot prove unoccupied on non-Linux or an inaccessible procfs. + return true; + } + for (const pid of pids) { + try { + const cwd = readlinkSync(`/proc/${pid}/cwd`); + if (containsPath(cwd, treeReal)) return true; + } catch { + // A process exiting during the scan is harmless; unreadable cwd + // for an existing PID is handled by the next pass / session list. + } + } + return false; +} + +function isLocked(primary: string, worktree: string): boolean { + const r = Bun.spawnSync(["git", "-C", primary, "worktree", "list", "--porcelain"]); + if (r.exitCode !== 0) throw new WorktreeCleanupError(`git worktree list failed: ${r.stderr.toString().trim()}`); + const lines = r.stdout.toString().split("\n"); + let selected = false; + let found = false; + let target = worktree; + try { target = realpathSync(worktree); } catch { /* compare literal path */ } + for (const line of lines) { + if (line.startsWith("worktree ")) { + let listed = line.slice(9); + try { listed = realpathSync(listed); } catch { /* compare literal path */ } + selected = listed === target; + found ||= selected; + } + else if (selected && line === "locked") return true; + } + return !found; // not registered with this primary: fail closed +} + +/** Clean only the exact registered target. The caller supplies + * termination evidence and may pass `confirmedTerminated` when the + * session was deleted by dispatch itself; all other uncertainty is a + * retained outcome. This helper never throws cleanup errors. */ +export async function cleanupDispatchWorktree(args: { + record: WorktreeRecord; + registry: WorktreeRegistry; + getSession: (sessionId: string) => Promise; + listSessions: () => Promise; + confirmedTerminated?: boolean; + git?: GitRunner; + isOccupied?: (worktree: string) => boolean; + at?: string; +}): Promise { + const { record, registry } = args; + const finish = async (removed: boolean, reason: string): Promise => { + try { + await registry.mark(record.worktree, removed ? "removed" : "retained", reason, args.at); + } catch (e) { + // Registry writes are best-effort after safety evaluation; report + // the error but never throw into a launch/session caller. + return { worktree: record.worktree, removed: false, reason: `${reason}; registry update failed: ${msg(e)}` }; + } + return { worktree: record.worktree, removed, reason }; + }; + try { + if (record.state === "removed") return { worktree: record.worktree, removed: true, reason: "already removed" }; + if (!existsSync(record.worktree)) return finish(true, "worktree already absent"); + + const evidence = await worktreeSessionEvidence({ + record, + getSession: args.getSession, + listSessions: args.listSessions, + confirmedTerminated: args.confirmedTerminated, + }); + if (!evidence.terminated) return finish(false, evidence.reason); + + const occupied = args.isOccupied ?? isProcessUsingPath; + if (occupied(record.worktree)) return finish(false, "a process has its cwd in the worktree"); + if (isLocked(record.primary, record.worktree)) return finish(false, "worktree is locked"); + + const git = args.git ?? runGit; + const head = await git(["-C", record.worktree, "rev-parse", "--verify", "HEAD"]); + if (head.code !== 0 || head.stdout.trim() !== record.base) { + return finish(false, `HEAD is not the recorded base commit (${head.stdout.trim() || "unavailable"}); retained`); + } + const status = await git(["-C", record.worktree, "status", "--porcelain", "--untracked-files=all"]); + if (status.code !== 0) return finish(false, `git status failed: ${status.stderr.trim()}; retained`); + if (status.stdout.trim()) return finish(false, `worktree has uncommitted or untracked work; retained`); + + const remove = await git(["-C", record.primary, "worktree", "remove", record.worktree]); + if (remove.code !== 0) return finish(false, `git worktree remove failed: ${remove.stderr.trim().slice(0, 300)}; retained`); + return finish(true, "session ended and worktree was clean, unoccupied, unlocked, and at its recorded base commit; removed"); + } catch (e) { + return finish(false, `cleanup check failed: ${msg(e)} — retained`); + } +} + +/** Sweep every active registry record. Each result is isolated so one + * malformed or unsafe tree cannot prevent later records being checked. + * A registry that cannot be read surfaces as a single retained + * outcome naming the problem — never a throw, never a removal. */ +export async function sweepDispatchWorktrees(args: { + registry: WorktreeRegistry; + getSession: (sessionId: string) => Promise; + listSessions: () => Promise; + git?: GitRunner; + isOccupied?: (worktree: string) => boolean; +}): Promise { + let records: WorktreeRecord[]; + try { + records = await args.registry.load(); + } catch (e) { + return [{ worktree: args.registry.file, removed: false, reason: `registry unavailable: ${msg(e)}` }]; + } + const outcomes: CleanupOutcome[] = []; + for (const record of records) { + if (record.state === "removed") continue; + outcomes.push( + await cleanupDispatchWorktree({ + record, + registry: args.registry, + getSession: args.getSession, + listSessions: args.listSessions, + git: args.git, + isOccupied: args.isOccupied, + }), + ); + } + return outcomes; +} diff --git a/pm-stack/dispatch/test/launch_failure.test.ts b/pm-stack/dispatch/test/launch_failure.test.ts index 111a5775b6..fcd1346166 100644 --- a/pm-stack/dispatch/test/launch_failure.test.ts +++ b/pm-stack/dispatch/test/launch_failure.test.ts @@ -141,7 +141,7 @@ describe("handleLaunchFailure", () => { async function assertCreatedSessionFailure(stage: "sendPrompt" | "claim") { const sessionId = "session/created-42"; const launchError = new Error(`${stage} failed`); - const context = { sessionId: null as string | null }; + const context = { sessionId: null as string | null, worktree: null as string | null }; const calls = { deleted: [] as string[], cancels: [] as [number, string][], diff --git a/pm-stack/dispatch/test/worktree.test.ts b/pm-stack/dispatch/test/worktree.test.ts index 62414b41ee..6750d8bc11 100644 --- a/pm-stack/dispatch/test/worktree.test.ts +++ b/pm-stack/dispatch/test/worktree.test.ts @@ -7,6 +7,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { loadConfig } from "../src/config.ts"; import { createDispatchWorktree, dispatchWorktreeName, worktreeNotice, WorktreeError } from "../src/worktree.ts"; +import { cleanupDispatchWorktree, WorktreeRegistry, type WorktreeRecord } from "../src/worktree_cleanup.ts"; const tmp = mkdtempSync(join(tmpdir(), "dispatch-worktree-")); afterAll(() => rmSync(tmp, { recursive: true, force: true })); @@ -117,3 +118,137 @@ describe("helpers and config", () => { expect(loadConfig({ PM_DISPATCH_WORKTREE_ROOT: "off" }).worktreeRoot).toBeNull(); }); }); + +describe("dispatch worktree cleanup (#12217)", () => { + const root = join(tmp, "cleanup-fleet"); + const registry = new WorktreeRegistry(join(tmp, "state", "worktrees.json")); + let nextId = 1; + + async function registeredTree(): Promise { + const id = 22000 + nextId++; + const wt = await createDispatchWorktree({ + primary, + requestedDirectory: primary, + root, + repo: "developing-today/code", + taskId: id, + }); + return registry.add({ + taskId: id, + sessionId: `ses_${id}`, + repo: "developing-today/code", + primary, + worktree: wt.worktree, + base: wt.base, + createdAt: new Date().toISOString(), + }); + } + + const emptyList = async () => []; + const goneSession = async () => null; + const unoccupied = () => false; + + test("removes a clean tree only after the session is confirmed gone; repeat is idempotent", async () => { + const record = await registeredTree(); + const result = await cleanupDispatchWorktree({ + record, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(result.removed).toBe(true); + expect(existsSync(record.worktree)).toBe(false); + const again = await cleanupDispatchWorktree({ + record: { ...record, state: "removed" }, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(again.removed).toBe(true); + expect(again.reason).toBe("already removed"); + }); + + test("retains an active session and an ambiguous session lookup", async () => { + const active = await registeredTree(); + const activeResult = await cleanupDispatchWorktree({ + record: active, + registry, + getSession: async () => ({ id: active.sessionId, directory: active.worktree }), + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(activeResult.removed).toBe(false); + expect(existsSync(active.worktree)).toBe(true); + + const unknown = await registeredTree(); + const unknownResult = await cleanupDispatchWorktree({ + record: unknown, + registry, + getSession: async () => { throw new Error("server unavailable"); }, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(unknownResult.removed).toBe(false); + expect(unknownResult.reason).toContain("state unknown"); + expect(existsSync(unknown.worktree)).toBe(true); + }); + + test("retains uncommitted, untracked, and unpublished work", async () => { + const dirty = await registeredTree(); + writeFileSync(join(dirty.worktree, "untracked.txt"), "keep me\n"); + const dirtyResult = await cleanupDispatchWorktree({ + record: dirty, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(dirtyResult.removed).toBe(false); + expect(existsSync(join(dirty.worktree, "untracked.txt"))).toBe(true); + + const unpublished = await registeredTree(); + writeFileSync(join(unpublished.worktree, "commit.txt"), "keep commit\n"); + git("-C", unpublished.worktree, "add", "commit.txt"); + git("-C", unpublished.worktree, "commit", "-qm", "unpublished"); + const unpublishedResult = await cleanupDispatchWorktree({ + record: unpublished, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(unpublishedResult.removed).toBe(false); + expect(existsSync(unpublished.worktree)).toBe(true); + expect(unpublishedResult.reason).toContain("HEAD is not the recorded base"); + }); + + test("retains on an occupied tree and reports git removal failure without throwing", async () => { + const occupied = await registeredTree(); + const occupiedResult = await cleanupDispatchWorktree({ + record: occupied, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: () => true, + }); + expect(occupiedResult.removed).toBe(false); + expect(occupiedResult.reason).toContain("process has its cwd"); + + const broken = await registeredTree(); + const failed = await cleanupDispatchWorktree({ + record: broken, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + git: async (args) => args.includes("remove") + ? { code: 1, stdout: "", stderr: "injected removal failure" } + : await (await import("../src/worktree.ts")).runGit(args), + }); + expect(failed.removed).toBe(false); + expect(failed.reason).toContain("injected removal failure"); + expect(existsSync(broken.worktree)).toBe(true); + }); +}); From 1210a88e40d103ff4994b1b03f015827ce75c27a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 08:22:11 -0600 Subject: [PATCH 2/4] fix(pm-dispatch): harden worktree cleanup safety --- pm-stack/dispatch/src/config.ts | 6 +- pm-stack/dispatch/src/launch_failure.ts | 50 ++++-- pm-stack/dispatch/src/server.ts | 10 +- pm-stack/dispatch/src/worktree_cleanup.ts | 75 ++++++--- pm-stack/dispatch/test/launch_failure.test.ts | 110 +++++++++++++ pm-stack/dispatch/test/worktree.test.ts | 146 ++++++++++++++++++ 6 files changed, 365 insertions(+), 32 deletions(-) diff --git a/pm-stack/dispatch/src/config.ts b/pm-stack/dispatch/src/config.ts index bea23176c7..d3a855a18b 100644 --- a/pm-stack/dispatch/src/config.ts +++ b/pm-stack/dispatch/src/config.ts @@ -138,8 +138,10 @@ export function loadConfig(env: Record = process.env worktreeSweepSeconds: (() => { const v = s(env.PM_DISPATCH_WORKTREE_SWEEP_SECONDS, "900"); if (v.toLowerCase() === "off") return null; - if (!/^\d+$/.test(v) || Number(v) < 1) { - throw new Error(`Invalid PM_DISPATCH_WORKTREE_SWEEP_SECONDS "${v}": expected a positive integer or "off"`); + if (!/^\d+$/.test(v) || Number(v) < 1 || Number(v) > 2_147_483) { + throw new Error( + `Invalid PM_DISPATCH_WORKTREE_SWEEP_SECONDS "${v}": expected a positive integer from 1 to 2147483, or "off"`, + ); } return Number(v); })(), diff --git a/pm-stack/dispatch/src/launch_failure.ts b/pm-stack/dispatch/src/launch_failure.ts index cf5c9825be..ebd64757b7 100644 --- a/pm-stack/dispatch/src/launch_failure.ts +++ b/pm-stack/dispatch/src/launch_failure.ts @@ -84,7 +84,8 @@ export interface LaunchFailureContext { * failure was established. Returns the cleanup outcome for the note, * or null when there is nothing to retire. Never throws: a worktree * outcome must not mask the launch failure being reported. */ -export type RetireWorktree = () => Promise<{ worktree: string; removed: boolean; reason: string } | null>; +export type RetireWorktree = (sessionId?: string | null) => Promise<{ worktree: string; removed: boolean; reason: string } | null>; +export type ReportRetirement = (outcome: { worktree: string; removed: boolean; reason: string }) => void; /** * Run the part of a launch that follows successful session creation. @@ -110,17 +111,33 @@ export async function handleLaunchFailure( sessionId: string | null = null, deleteSession?: (sessionId: string) => Promise, retireWorktree?: RetireWorktree, + reportRetirement: ReportRetirement = (outcome) => { + if (!outcome.removed) { + console.warn(`[pm-dispatch] task worktree ${outcome.worktree} retained: ${outcome.reason}`); + } + }, ): Promise { const msg = e instanceof Error ? e.message : String(e); // #12217: best-effort worktree retirement, reported, never thrown — // and never attempted while the session may still be live. - const retireSafely = async (): Promise<{ worktree: string; removed: boolean; reason: string } | null> => { + const retireSafely = async (retiredSessionId: string | null = sessionId): Promise<{ worktree: string; removed: boolean; reason: string } | null> => { if (!retireWorktree) return null; try { - return await retireWorktree(); + const outcome = await retireWorktree(retiredSessionId); + if (outcome && !outcome.removed) safelyReportRetirement(outcome); + return outcome; } catch (re) { const reason = re instanceof Error ? re.message : String(re); - return { worktree: "unknown", removed: false, reason }; + const outcome = { worktree: "unknown", removed: false, reason }; + safelyReportRetirement(outcome); + return outcome; + } + }; + const safelyReportRetirement = (outcome: { worktree: string; removed: boolean; reason: string }) => { + try { + reportRetirement(outcome); + } catch { + /* reporting must not mask the original launch failure */ } }; if (e instanceof ClaimLostError) { @@ -130,9 +147,11 @@ export async function handleLaunchFailure( if (sessionId != null && deleteSession) { try { await deleteSession(sessionId); - await retireSafely(); + await retireSafely(sessionId); } catch { - /* best-effort: the session never received the task's claim */ + // Deletion may have failed while the session is still live. Run + // the fail-closed evidence check so the retained worktree is visible. + await retireSafely(sessionId); } } return msg; @@ -148,9 +167,16 @@ export async function handleLaunchFailure( let cleanupError: string | null = null; let worktreeNote = ""; if (sessionId == null) { - // No session was ever recorded: nothing to wait for on the session - // side, so the worktree decision runs on its own evidence now. - const outcome = await retireSafely(); + // createSession can time out or lose its response after the server + // accepted the request. The session may still come up later, so the + // tree cannot be retired on an empty session-list snapshot. + const outcome = retireWorktree + ? await retireSafely(null) ?? { + worktree: "unknown", + removed: false, + reason: "session creation outcome is unknown; a session may still be live", + } + : null; if (outcome) { worktreeNote = outcome.removed ? `\n\nTask worktree ${outcome.worktree} was removed after the failed launch.` @@ -171,6 +197,12 @@ export async function handleLaunchFailure( } } catch (de) { cleanupError = de instanceof Error ? de.message : String(de); + const outcome = await retireSafely(sessionId); + if (outcome) { + worktreeNote = outcome.removed + ? `\n\nTask worktree ${outcome.worktree} was removed after the failed launch.` + : `\n\nTask worktree ${outcome.worktree} was retained: ${outcome.reason}.`; + } } } if (issueNumber != null) { diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index 27188f014a..31d94bd698 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -199,9 +199,13 @@ async function maybeCreateIssue( * Missing/bad registry state is an explicit retained outcome rather * than a guessed path or an exception that could replace the launch * error. */ -async function retireFailedWorktree(worktree: string | null) { +async function retireFailedWorktree(worktree: string | null, sessionId: string | null = null) { if (!worktree) return null; try { + // A previous registry bind may have failed even though createSession + // returned. Retry the durable binding after the failure handler has + // deleted that known session, so cleanup can use confirmed evidence. + if (sessionId != null) await worktreeRegistry.setSessionId(worktree, sessionId); const record = (await worktreeRegistry.load()).find((r) => r.worktree === worktree && r.state === "active"); if (!record) return { worktree, removed: false, reason: "no active registry record; retained" }; return await cleanupDispatchWorktree({ @@ -384,7 +388,7 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise opencode.deleteSession(sessionId), - () => retireFailedWorktree(failureContext.worktree), + (sessionId) => retireFailedWorktree(failureContext.worktree, sessionId), ); } })(); @@ -414,7 +418,7 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise opencode.deleteSession(sessionId), - () => retireFailedWorktree(failureContext.worktree), + (failedSessionId) => retireFailedWorktree(failureContext.worktree, failedSessionId), ); // A lost claim race is a conflict, not an upstream failure: the // task is running under the worker that claimed it (#10737). diff --git a/pm-stack/dispatch/src/worktree_cleanup.ts b/pm-stack/dispatch/src/worktree_cleanup.ts index 11a76ce29c..d4e71dec12 100644 --- a/pm-stack/dispatch/src/worktree_cleanup.ts +++ b/pm-stack/dispatch/src/worktree_cleanup.ts @@ -25,8 +25,8 @@ // its record) and every cleanup failure is reported as an outcome, // never thrown past the caller, so it can never mask a // dispatch/session result. -import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; import { runGit, type GitRunner } from "./worktree.ts"; export class WorktreeCleanupError extends Error {} @@ -34,6 +34,10 @@ export class WorktreeCleanupError extends Error {} const msg = (e: unknown): string => (e instanceof Error ? e.message : String(e)); const nowIso = (): string => new Date().toISOString(); +// A sweep, startup pass, or launch-failure handler may arrive at the same +// record concurrently. Serialize destructive checks per exact registered path. +const cleanupClaims = new Set(); + // --------------------------------------------------------------------------- // Registry: the durable worktree <-> task/session association // --------------------------------------------------------------------------- @@ -43,9 +47,9 @@ const nowIso = (): string => new Date().toISOString(); * acted on destructively. */ export interface WorktreeRecord { taskId: number; - /** The OpenCode session bound to the tree, or null when the launch - * died before the session id was recorded (the session-list check - * still protects that tree — see worktreeSessionEvidence). */ + /** The OpenCode session bound to the tree. Null means session creation + * may be pending or its outcome was lost; such records are never + * auto-removed, including after a dispatch restart. */ sessionId: string | null; repo: string; /** The primary clone the tree was created from (git -C target). */ @@ -119,8 +123,9 @@ export class WorktreeRegistry { let raw: string; try { raw = readFileSync(this.file, "utf8"); - } catch { - return []; // no file yet: nothing was ever registered under this path + } catch (e) { + if (typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT") return []; + throw new WorktreeCleanupError(`cannot read worktree registry ${this.file}: ${msg(e)}`); } return parseRecords(raw, this.file); } @@ -250,10 +255,11 @@ export async function worktreeSessionEvidence(args: { return { terminated: false, reason: `session ${args.record.sessionId} exists (live or resumable)` }; } } - if (args.confirmedTerminated !== true && args.record.sessionId == null) { - // No session id recorded: a crash between worktree creation and - // session creation may still have left a live session in the tree, - // so the session list below decides — nothing else can. + if (args.record.sessionId == null) { + // An empty list cannot prove that an in-flight/timed-out createSession + // request will not complete after this read. Retain indefinitely; an + // operator can reconcile these records separately after restart. + return { terminated: false, reason: "session creation is unbound or uncertain; retained" }; } try { const sessions = await args.listSessions(); @@ -270,7 +276,10 @@ export async function worktreeSessionEvidence(args: { } for (const raw of list) { const dir = sessionDirectory(raw); - if (dir !== null && containsPath(dir, treeReal)) { + if (dir === null || dir.trim() === "") { + return { terminated: false, reason: "session list contains an entry without a usable directory; retained" }; + } + if (containsPath(dir, treeReal)) { const id = sessionIdOf(raw) ?? "(unknown id)"; return { terminated: false, reason: `session ${id} still occupies the worktree` }; } @@ -302,7 +311,7 @@ function isProcessUsingPath(worktree: string): boolean { try { treeReal = realpathSync(worktree); } catch { - return false; + return true; } let pids: string[]; try { @@ -315,9 +324,11 @@ function isProcessUsingPath(worktree: string): boolean { try { const cwd = readlinkSync(`/proc/${pid}/cwd`); if (containsPath(cwd, treeReal)) return true; - } catch { - // A process exiting during the scan is harmless; unreadable cwd - // for an existing PID is handled by the next pass / session list. + } catch (e) { + const code = typeof e === "object" && e !== null && "code" in e ? e.code : null; + // Only confirmed process disappearance is harmless. EACCES and + // other ambiguous inspection failures retain the tree. + if (code !== "ENOENT" && code !== "ESRCH") return true; } } return false; @@ -368,8 +379,14 @@ export async function cleanupDispatchWorktree(args: { } return { worktree: record.worktree, removed, reason }; }; + if (record.state === "removed") return { worktree: record.worktree, removed: true, reason: "already removed" }; + if (cleanupClaims.has(record.worktree)) { + return { worktree: record.worktree, removed: false, reason: "cleanup already in progress; retained" }; + } + cleanupClaims.add(record.worktree); + let headLockPath: string | null = null; + let headLockFd: number | null = null; try { - if (record.state === "removed") return { worktree: record.worktree, removed: true, reason: "already removed" }; if (!existsSync(record.worktree)) return finish(true, "worktree already absent"); const evidence = await worktreeSessionEvidence({ @@ -385,11 +402,25 @@ export async function cleanupDispatchWorktree(args: { if (isLocked(record.primary, record.worktree)) return finish(false, "worktree is locked"); const git = args.git ?? runGit; + const headPathResult = await git(["-C", record.worktree, "rev-parse", "--git-path", "HEAD"]); + if (headPathResult.code !== 0 || !headPathResult.stdout.trim()) { + return finish(false, `cannot locate worktree HEAD for locking: ${headPathResult.stderr.trim() || "unavailable"}; retained`); + } + const headPath = resolve(record.worktree, headPathResult.stdout.trim()); + const candidateLockPath = `${headPath}.lock`; + try { + headLockFd = openSync(candidateLockPath, "wx", 0o600); + headLockPath = candidateLockPath; + writeFileSync(headLockFd, `${process.pid}\n`); + } catch (e) { + return finish(false, `cannot lock worktree HEAD: ${msg(e)}; retained`); + } + const head = await git(["-C", record.worktree, "rev-parse", "--verify", "HEAD"]); if (head.code !== 0 || head.stdout.trim() !== record.base) { return finish(false, `HEAD is not the recorded base commit (${head.stdout.trim() || "unavailable"}); retained`); } - const status = await git(["-C", record.worktree, "status", "--porcelain", "--untracked-files=all"]); + const status = await git(["-C", record.worktree, "status", "--porcelain", "--untracked-files=all", "--ignored"]); if (status.code !== 0) return finish(false, `git status failed: ${status.stderr.trim()}; retained`); if (status.stdout.trim()) return finish(false, `worktree has uncommitted or untracked work; retained`); @@ -398,6 +429,14 @@ export async function cleanupDispatchWorktree(args: { return finish(true, "session ended and worktree was clean, unoccupied, unlocked, and at its recorded base commit; removed"); } catch (e) { return finish(false, `cleanup check failed: ${msg(e)} — retained`); + } finally { + if (headLockFd !== null) { + try { closeSync(headLockFd); } catch { /* best effort; do not replace the cleanup outcome */ } + } + if (headLockPath !== null) { + try { unlinkSync(headLockPath); } catch { /* worktree removal may already have removed its administrative directory */ } + } + cleanupClaims.delete(record.worktree); } } diff --git a/pm-stack/dispatch/test/launch_failure.test.ts b/pm-stack/dispatch/test/launch_failure.test.ts index fcd1346166..fa8bc8873a 100644 --- a/pm-stack/dispatch/test/launch_failure.test.ts +++ b/pm-stack/dispatch/test/launch_failure.test.ts @@ -65,6 +65,116 @@ describe("handleLaunchFailure", () => { expect(calls.closes).toHaveLength(0); }); + test("reports the exact worktree retained after an uncertain session-creation outcome", async () => { + const { calls, queue, github } = stubs(); + const retirements: { worktree: string; removed: boolean; reason: string }[] = []; + let retirementChecked = false; + const retireWorktree = async (sessionId?: string | null) => { + retirementChecked = true; + expect(sessionId).toBe(null); + return { + worktree: "/trees/task-7", + removed: false, + reason: "session creation is unbound or uncertain; retained", + }; + }; + const error = new Error("createSession timed out"); + const msg = await handleLaunchFailure( + queue, + github, + "developing-today/code", + 7, + null, + error, + null, + undefined, + retireWorktree, + (outcome) => retirements.push(outcome), + ); + expect(msg).toBe(error.message); + expect(retirementChecked).toBe(true); + expect(retirements).toEqual([ + { + worktree: "/trees/task-7", + removed: false, + reason: "session creation is unbound or uncertain; retained", + }, + ]); + expect(calls.cancels).toHaveLength(1); + expect(calls.comments).toHaveLength(0); + }); + + test("reports retained retirement after confirmed session deletion without replacing launch error", async () => { + const { calls, queue, github } = stubs(); + const events: string[] = []; + const error = new Error("prompt failed"); + const msg = await handleLaunchFailure( + queue, + github, + "developing-today/code", + 7, + 9, + error, + "ses-failed", + async () => { events.push("delete"); }, + async () => { + events.push("retire"); + throw new Error("git worktree remove failed"); + }, + (outcome) => events.push(`report:${outcome.reason}`), + ); + expect(msg).toBe(error.message); + expect(events).toEqual(["delete", "retire", "report:git worktree remove failed"]); + expect(calls.comments[0][2]).toContain("worktree unknown was retained: git worktree remove failed"); + }); + + test("retires after successful session deletion and reports a retained outcome", async () => { + const { calls, queue, github } = stubs(); + const events: string[] = []; + const msg = await handleLaunchFailure( + queue, + github, + "developing-today/code", + 7, + 9, + new Error("prompt failed"), + "ses-failed", + async () => { events.push("delete"); }, + async () => { + events.push("retire"); + return { worktree: "/trees/task-7", removed: false, reason: "worktree is dirty" }; + }, + (outcome) => events.push(`report:${outcome.reason}`), + ); + expect(msg).toBe("prompt failed"); + expect(events).toEqual(["delete", "retire", "report:worktree is dirty"]); + expect(calls.comments[0][2]).toContain("worktree /trees/task-7 was retained: worktree is dirty"); + }); + + test("reports the retained worktree when session deletion fails", async () => { + const { calls, queue, github } = stubs(); + const reported: string[] = []; + const msg = await handleLaunchFailure( + queue, + github, + "developing-today/code", + 7, + 9, + new Error("prompt failed"), + "ses-live", + async () => { throw new Error("delete unavailable"); }, + async (sessionId) => { + expect(sessionId).toBe("ses-live"); + return { worktree: "/trees/task-7", removed: false, reason: "session still exists" }; + }, + (outcome) => reported.push(outcome.worktree), + ); + expect(msg).toBe("prompt failed"); + expect(reported).toEqual(["/trees/task-7"]); + expect(calls.comments[0][2]).toContain("may still be live; session cleanup failed: delete unavailable"); + expect(calls.comments[0][2]).toContain("worktree /trees/task-7 was retained: session still exists"); + }); + test("still notes the issue when the cancellation itself fails", async () => { const { calls, queue, github } = stubs(true); const msg = await handleLaunchFailure(queue, github, "developing-today/code", 7, 9, "string failure"); diff --git a/pm-stack/dispatch/test/worktree.test.ts b/pm-stack/dispatch/test/worktree.test.ts index 6750d8bc11..dd9b414551 100644 --- a/pm-stack/dispatch/test/worktree.test.ts +++ b/pm-stack/dispatch/test/worktree.test.ts @@ -117,6 +117,11 @@ describe("helpers and config", () => { expect(loadConfig({ PM_DISPATCH_WORKTREE_ROOT: "/srv/wt" }).worktreeRoot).toBe("/srv/wt"); expect(loadConfig({ PM_DISPATCH_WORKTREE_ROOT: "off" }).worktreeRoot).toBeNull(); }); + + test("worktree sweep interval fits setInterval's supported millisecond range", () => { + expect(loadConfig({ PM_DISPATCH_WORKTREE_SWEEP_SECONDS: "2147483" }).worktreeSweepSeconds).toBe(2147483); + expect(() => loadConfig({ PM_DISPATCH_WORKTREE_SWEEP_SECONDS: "2147484" })).toThrow("2147483"); + }); }); describe("dispatch worktree cleanup (#12217)", () => { @@ -195,6 +200,56 @@ describe("dispatch worktree cleanup (#12217)", () => { expect(existsSync(unknown.worktree)).toBe(true); }); + test("retains an unbound session record without querying the session server", async () => { + const existing = await registeredTree(); + const record = await registry.add({ ...existing, sessionId: null }); + let queried = false; + const result = await cleanupDispatchWorktree({ + record, + registry, + getSession: async () => { queried = true; return null; }, + listSessions: async () => { queried = true; return []; }, + isOccupied: unoccupied, + }); + expect(result.removed).toBe(false); + expect(result.worktree).toBe(record.worktree); + expect(result.reason).toContain("unbound or uncertain"); + expect(queried).toBe(false); + expect(existsSync(record.worktree)).toBe(true); + }); + + test("retains a session list containing an entry without a usable directory", async () => { + const record = await registeredTree(); + const result = await cleanupDispatchWorktree({ + record, + registry, + getSession: goneSession, + listSessions: async () => [{ id: "session-without-directory" }], + isOccupied: unoccupied, + }); + expect(result.removed).toBe(false); + expect(result.reason).toContain("without a usable directory"); + expect(existsSync(record.worktree)).toBe(true); + }); + + test("a corrupt registry produces one retained sweep outcome without touching sessions", async () => { + const file = join(tmp, "corrupt-registry", "worktrees.json"); + mkdirSync(join(tmp, "corrupt-registry"), { recursive: true }); + writeFileSync(file, "{broken json\n"); + const brokenRegistry = new WorktreeRegistry(file); + let queried = false; + const { sweepDispatchWorktrees } = await import("../src/worktree_cleanup.ts"); + const results = await sweepDispatchWorktrees({ + registry: brokenRegistry, + getSession: async () => { queried = true; return null; }, + listSessions: async () => { queried = true; return []; }, + }); + expect(results).toHaveLength(1); + expect(results[0].removed).toBe(false); + expect(results[0].reason).toContain("not valid JSON"); + expect(queried).toBe(false); + }); + test("retains uncommitted, untracked, and unpublished work", async () => { const dirty = await registeredTree(); writeFileSync(join(dirty.worktree, "untracked.txt"), "keep me\n"); @@ -224,6 +279,97 @@ describe("dispatch worktree cleanup (#12217)", () => { expect(unpublishedResult.reason).toContain("HEAD is not the recorded base"); }); + test("retains ignored files instead of deleting them with the worktree", async () => { + const ignored = await registeredTree(); + writeFileSync(join(ignored.worktree, ".gitignore"), ".env\n"); + writeFileSync(join(ignored.worktree, ".env"), "keep this secret\n"); + const result = await cleanupDispatchWorktree({ + record: ignored, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(result.removed).toBe(false); + expect(result.reason).toContain("uncommitted or untracked work"); + expect(existsSync(join(ignored.worktree, ".env"))).toBe(true); + }); + + test("only one concurrent cleanup can remove a registered tree", async () => { + const record = await registeredTree(); + let unblock!: () => void; + const paused = new Promise((resolve) => { unblock = resolve; }); + let entered!: () => void; + const inList = new Promise((resolve) => { entered = resolve; }); + const first = cleanupDispatchWorktree({ + record, + registry, + getSession: goneSession, + listSessions: async () => { entered(); await paused; return []; }, + isOccupied: unoccupied, + }); + await inList; + const second = await cleanupDispatchWorktree({ + record, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(second.removed).toBe(false); + expect(second.reason).toContain("already in progress"); + unblock(); + const firstResult = await first; + expect(firstResult.removed).toBe(true); + expect(existsSync(record.worktree)).toBe(false); + }); + + test("holds the worktree HEAD lock through git worktree removal", async () => { + const record = await registeredTree(); + const { runGit } = await import("../src/worktree.ts"); + let sawLockDuringRemove = false; + let blockedExternalHeadMove = false; + const result = await cleanupDispatchWorktree({ + record, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + git: async (args) => { + if (args.includes("status")) { + const attempt = Bun.spawnSync(["git", "-C", record.worktree, "reset", "--hard", "HEAD"], { env }); + blockedExternalHeadMove = attempt.exitCode !== 0; + } + if (args.includes("remove")) { + const head = git("-C", record.worktree, "rev-parse", "--git-path", "HEAD"); + sawLockDuringRemove = existsSync(`${head}.lock`); + } + return runGit(args); + }, + }); + expect(result.removed).toBe(true); + expect(blockedExternalHeadMove).toBe(true); + expect(sawLockDuringRemove).toBe(true); + }); + + test("retains an existing HEAD lock without deleting another process's lock", async () => { + const record = await registeredTree(); + const head = git("-C", record.worktree, "rev-parse", "--git-path", "HEAD"); + const lock = `${head}.lock`; + writeFileSync(lock, "owned elsewhere\n"); + const result = await cleanupDispatchWorktree({ + record, + registry, + getSession: goneSession, + listSessions: emptyList, + isOccupied: unoccupied, + }); + expect(result.removed).toBe(false); + expect(result.reason).toContain("cannot lock worktree HEAD"); + expect(await Bun.file(lock).text()).toBe("owned elsewhere\n"); + expect(existsSync(record.worktree)).toBe(true); + }); + test("retains on an occupied tree and reports git removal failure without throwing", async () => { const occupied = await registeredTree(); const occupiedResult = await cleanupDispatchWorktree({ From 33718dd96f267652f544d7118e3ec3dfe6529ba6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 14:19:01 -0600 Subject: [PATCH 3/4] fix(pm-dispatch): prove session list completeness --- doc/fleet-schedule-registry.md | 11 +++---- pm-stack/dispatch/src/opencode.ts | 15 +++++++++- pm-stack/dispatch/test/opencode.test.ts | 39 +++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index a182501f5a..9812ecfcd6 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -374,15 +374,16 @@ registered. The primary user's repos are maintained by git's own per-user launchd agents, which `git maintenance start` installs outside Nix; they are not recorded here until a review reads them on the Mac. -## Surface 6 — PM-stack process intervals (1 entry) +## Surface 6 — PM-stack process intervals (2 entries) -Recurring loops owned by the PM-stack aggregator process. These are not +Recurring loops owned by PM-stack processes. These are not external scheduler surfaces; this inventory records timers that run only while the service is alive. -| name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review | -| --------------------------- | --------------------- | ---------------- | ---------------------------- | ------------- | -------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ---------- | ----------- | -| SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 | +| name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review | +| -------------------------------- | --------------------- | --------------------------------------------------- | ----------------------------- | ------------- | ---------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | ----------- | +| SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 | +| dispatch worktree sweep (#12217) | developing-today/code | `PM_DISPATCH_WORKTREE_SWEEP_SECONDS` (default 900s) | live dispatch process only | issue #12217 | `pm-stack/dispatch/src/server.ts` (`startWorktreeSweep()`; config in `src/config.ts`) | not recorded | Set to `off` or remove/disable the sweep if registry/session safety checks become unavailable; timer is unref'd and does not keep the process alive | 2026-11-21 | 2026-11-21 | ## Surface 7 — Cloudflare Worker cron triggers (1 entry) diff --git a/pm-stack/dispatch/src/opencode.ts b/pm-stack/dispatch/src/opencode.ts index 478a84ba8d..ac68ff1f62 100644 --- a/pm-stack/dispatch/src/opencode.ts +++ b/pm-stack/dispatch/src/opencode.ts @@ -6,6 +6,8 @@ import { readFile } from "node:fs/promises"; import type { ModelRef } from "./validate.ts"; import { outboundTimeout } from "./fetchTimeout.ts"; +const SESSION_LIST_LIMITS = [1_000, 10_000, 100_000] as const; + export class OpenCodeError extends Error { status = 502; constructor( @@ -111,7 +113,18 @@ export class OpenCodeClient { } async listSessions(): Promise { - return this.api("GET", "/api/session"); + for (const limit of SESSION_LIST_LIMITS) { + const data = await this.api("GET", `/api/session?limit=${limit}`); + // OpenCode silently truncates the default session list at 50. A + // response below its requested limit is the only completeness proof + // this endpoint offers; if the largest supported probe is still full, + // do not let cleanup infer that an omitted session is absent. + if (!Array.isArray(data)) return data; + if (data.length < limit) return data; + } + throw new OpenCodeError( + `opencode session list reached the maximum completeness limit (${SESSION_LIST_LIMITS.at(-1)})`, + ); } /** Read one session's current state (issue #5555): the raw session diff --git a/pm-stack/dispatch/test/opencode.test.ts b/pm-stack/dispatch/test/opencode.test.ts index cd0839c8e2..23b53f5976 100644 --- a/pm-stack/dispatch/test/opencode.test.ts +++ b/pm-stack/dispatch/test/opencode.test.ts @@ -151,3 +151,42 @@ describe("OpenCodeClient.getSession (#5555)", () => { await expect(client.getSession("ses_any")).rejects.toBeInstanceOf(OpenCodeError); }); }); + +describe("OpenCodeClient.listSessions completeness", () => { + let stub: ReturnType; + let stubUrl = ""; + let requestedLimits: number[] = []; + let responseAtLimit = 0; + beforeAll(() => { + stub = Bun.serve({ + port: 0, + fetch(req) { + const limit = Number(new URL(req.url).searchParams.get("limit")); + requestedLimits.push(limit); + const count = responseAtLimit >= limit ? limit : Math.min(60, limit - 1); + return Response.json({ data: Array.from({ length: count }, (_, i) => ({ id: `ses-${i}` })) }); + }, + }); + stubUrl = `http://127.0.0.1:${stub.port}`; + }); + afterAll(() => { + stub.stop(true); + }); + + test("escalates limits until a response proves the list is complete", async () => { + requestedLimits = []; + responseAtLimit = 1_000; + const client = new OpenCodeClient(stubUrl, authFile("ls-complete.json", JSON.stringify({ password: "pw" }))); + const sessions = (await client.listSessions()) as unknown[]; + expect(requestedLimits).toEqual([1_000, 10_000]); + expect(sessions).toHaveLength(60); + }); + + test("fails closed when the maximum limit is still full", async () => { + requestedLimits = []; + responseAtLimit = 100_000; + const client = new OpenCodeClient(stubUrl, authFile("ls-full.json", JSON.stringify({ password: "pw" }))); + await expect(client.listSessions()).rejects.toThrow(/maximum completeness limit/); + expect(requestedLimits).toEqual([1_000, 10_000, 100_000]); + }); +}); From 830660fc0851a03ed950fc3aefa5c4c1a4f9de5c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 14:25:34 -0600 Subject: [PATCH 4/4] fix(pm-dispatch): ignore inaccessible root process cwd --- pm-stack/dispatch/src/worktree_cleanup.ts | 33 ++++++++++++++--- pm-stack/dispatch/test/worktree.test.ts | 45 ++++++++++++++++++++++- 2 files changed, 72 insertions(+), 6 deletions(-) diff --git a/pm-stack/dispatch/src/worktree_cleanup.ts b/pm-stack/dispatch/src/worktree_cleanup.ts index d4e71dec12..ec4533c3f8 100644 --- a/pm-stack/dispatch/src/worktree_cleanup.ts +++ b/pm-stack/dispatch/src/worktree_cleanup.ts @@ -25,7 +25,7 @@ // its record) and every cleanup failure is reported as an outcome, // never thrown past the caller, so it can never mask a // dispatch/session result. -import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { runGit, type GitRunner } from "./worktree.ts"; @@ -306,7 +306,22 @@ export interface CleanupOutcome { reason: string; } -function isProcessUsingPath(worktree: string): boolean { +export interface ProcessOccupancyProbe { + listPids(): string[]; + ownerUid(pid: string): number; + cwd(pid: string): string; +} + +const systemProcessOccupancyProbe: ProcessOccupancyProbe = { + listPids: () => readdirSync("/proc").filter((entry) => /^\d+$/.test(entry)), + ownerUid: (pid) => statSync(`/proc/${pid}`).uid, + cwd: (pid) => readlinkSync(`/proc/${pid}/cwd`), +}; + +export function isProcessUsingPath( + worktree: string, + probe: ProcessOccupancyProbe = systemProcessOccupancyProbe, +): boolean { let treeReal: string; try { treeReal = realpathSync(worktree); @@ -315,19 +330,27 @@ function isProcessUsingPath(worktree: string): boolean { } let pids: string[]; try { - pids = readdirSync("/proc").filter((entry) => /^\d+$/.test(entry)); + pids = probe.listPids(); } catch { // Cannot prove unoccupied on non-Linux or an inaccessible procfs. return true; } for (const pid of pids) { try { - const cwd = readlinkSync(`/proc/${pid}/cwd`); + const ownerUid = probe.ownerUid(pid); + // Root-owned host processes (notably PID 1) are outside the user + // service's worktree-access boundary, and ptrace restrictions make + // their cwd links unreadable to this service. Ignore those system + // processes; every non-root process remains subject to the + // fail-closed cwd check below. + if (ownerUid === 0) continue; + const cwd = probe.cwd(pid); if (containsPath(cwd, treeReal)) return true; } catch (e) { const code = typeof e === "object" && e !== null && "code" in e ? e.code : null; // Only confirmed process disappearance is harmless. EACCES and - // other ambiguous inspection failures retain the tree. + // other ambiguous inspection failures on non-root processes retain + // the tree. if (code !== "ENOENT" && code !== "ESRCH") return true; } } diff --git a/pm-stack/dispatch/test/worktree.test.ts b/pm-stack/dispatch/test/worktree.test.ts index dd9b414551..a2a0f9a17d 100644 --- a/pm-stack/dispatch/test/worktree.test.ts +++ b/pm-stack/dispatch/test/worktree.test.ts @@ -7,7 +7,13 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { loadConfig } from "../src/config.ts"; import { createDispatchWorktree, dispatchWorktreeName, worktreeNotice, WorktreeError } from "../src/worktree.ts"; -import { cleanupDispatchWorktree, WorktreeRegistry, type WorktreeRecord } from "../src/worktree_cleanup.ts"; +import { + cleanupDispatchWorktree, + isProcessUsingPath, + WorktreeRegistry, + type ProcessOccupancyProbe, + type WorktreeRecord, +} from "../src/worktree_cleanup.ts"; const tmp = mkdtempSync(join(tmpdir(), "dispatch-worktree-")); afterAll(() => rmSync(tmp, { recursive: true, force: true })); @@ -124,6 +130,43 @@ describe("helpers and config", () => { }); }); +describe("process occupancy permissions", () => { + test("ignores unreadable root-owned system cwd links but detects user processes in the tree", () => { + const probe: ProcessOccupancyProbe = { + listPids: () => ["1", "42"], + ownerUid: (pid) => (pid === "1" ? 0 : 1000), + cwd: (pid) => { + if (pid === "1") throw Object.assign(new Error("permission denied"), { code: "EACCES" }); + return primary; + }, + }; + expect(isProcessUsingPath(primary, probe)).toBe(true); + }); + + test("does not let root's unreadable cwd block otherwise unoccupied worktrees", () => { + const probe: ProcessOccupancyProbe = { + listPids: () => ["1", "42"], + ownerUid: (pid) => (pid === "1" ? 0 : 1000), + cwd: (pid) => { + if (pid === "1") throw Object.assign(new Error("permission denied"), { code: "EACCES" }); + return join(tmp, "outside"); + }, + }; + expect(isProcessUsingPath(primary, probe)).toBe(false); + }); + + test("retains when a non-root process cwd cannot be inspected", () => { + const probe: ProcessOccupancyProbe = { + listPids: () => ["42"], + ownerUid: () => 1000, + cwd: () => { + throw Object.assign(new Error("permission denied"), { code: "EACCES" }); + }, + }; + expect(isProcessUsingPath(primary, probe)).toBe(true); + }); +}); + describe("dispatch worktree cleanup (#12217)", () => { const root = join(tmp, "cleanup-fleet"); const registry = new WorktreeRegistry(join(tmp, "state", "worktrees.json"));