From d1979f4e5b66595ebde1448349adc0424370f92f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:12:46 +0000 Subject: [PATCH] fix(pm-dispatch): run dispatched sessions in their own worktree, never the primary clone A dispatched OpenCode session defaulted to the repo's primary clone (~/git/code for developing-today/code). Scheduled Bolt and Palette sessions branched and committed there on Nov 21, leaving the deploy clone off main and stalling pm-git-sync. Each launch now gets a detached worktree at the remote default branch under PM_DISPATCH_WORKTREE_ROOT (default ~/git/fleet; "off" restores the old behaviour), and the prompt tells the session the primary clone is off limits. A failed worktree fails the launch instead of falling back to the primary. The package wrapper now puts git on PATH. Closes #12213 Co-Authored-By: Claude Opus 5.5 --- pkgs/pm-dispatch/package.nix | 13 ++- pm-stack/dispatch/src/config.ts | 8 ++ pm-stack/dispatch/src/server.ts | 22 ++++- pm-stack/dispatch/src/worktree.ts | 95 +++++++++++++++++++ pm-stack/dispatch/test/worktree.test.ts | 119 ++++++++++++++++++++++++ 5 files changed, 252 insertions(+), 5 deletions(-) create mode 100644 pm-stack/dispatch/src/worktree.ts create mode 100644 pm-stack/dispatch/test/worktree.test.ts diff --git a/pkgs/pm-dispatch/package.nix b/pkgs/pm-dispatch/package.nix index 21c874fa7..30ac26ab2 100644 --- a/pkgs/pm-dispatch/package.nix +++ b/pkgs/pm-dispatch/package.nix @@ -14,13 +14,15 @@ # The package.json carries no runtime dependencies (only type-level # devDependencies), so there is no node_modules to fetch: the package # is the source plus a bun wrapper. The server shells out to `gh` -# (src/github.ts), so the wrapper pins gh on PATH instead of relying -# on the ambient profile. +# (src/github.ts) and to `git` for per-launch worktrees +# (src/worktree.ts, code#12213), so the wrapper pins both on PATH +# instead of relying on the ambient profile. { lib, stdenvNoCC, bun, gh, + git, makeWrapper, }: let @@ -54,7 +56,12 @@ stdenvNoCC.mkDerivation { makeWrapper ${lib.getExe bun} $out/bin/pm-dispatch \ --add-flags "run $out/libexec/pm-dispatch/src/server.ts" \ --set DISPATCH_BUILD_VERSION ${lib.escapeShellArg buildVersion} \ - --prefix PATH : ${lib.makeBinPath [ gh ]} + --prefix PATH : ${ + lib.makeBinPath [ + gh + git + ] + } runHook postInstall ''; diff --git a/pm-stack/dispatch/src/config.ts b/pm-stack/dispatch/src/config.ts index de16901d7..1380f4bdc 100644 --- a/pm-stack/dispatch/src/config.ts +++ b/pm-stack/dispatch/src/config.ts @@ -71,6 +71,10 @@ export interface Config { githubAppId: string | null; /** Decoded PEM for the GitHub App private key (memory only). */ githubAppPrivateKeyPem: string | null; + /** Where launches into a primary clone get their own worktree + * (PM_DISPATCH_WORKTREE_ROOT, default ~/git/fleet; "off" runs in the + * requested directory as before). code#12213. */ + worktreeRoot: string | null; } export function loadConfig(env: Record = process.env): Config { @@ -115,5 +119,9 @@ export function loadConfig(env: Record = process.env opencodeAuthFile: s(env.OPENCODE_AUTH_FILE, join(homedir(), ".local", "state", "opencode", "service-prod.json")), githubAppId: env.GITHUB_APP_ID?.trim() ? env.GITHUB_APP_ID.trim() : null, githubAppPrivateKeyPem: appPem, + worktreeRoot: + env.PM_DISPATCH_WORKTREE_ROOT?.trim().toLowerCase() === "off" + ? null + : s(env.PM_DISPATCH_WORKTREE_ROOT, join(homedir(), "git", "fleet")), }; } diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index dc48f43b9..758db31cc 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -48,6 +48,7 @@ import { import { annotateLaunch } from "./launch_annotations.ts"; import { GitHubClient } from "./github.ts"; import { OpenCodeClient, OpenCodeError } from "./opencode.ts"; +import { createDispatchWorktree, worktreeNotice } from "./worktree.ts"; const cfg: Config = loadConfig(); // #9028: the queue client talks to the fleet queue broker. Its token @@ -179,12 +180,29 @@ async function launchSession( warnings: string[], failureContext: LaunchFailureContext, ): Promise { + // code#12213: never run a dispatched session in the primary clone. + // A worktree failure throws here, before any session exists, so the + // launch fails and the task is cancelled like any pre-session error. + let sessionDirectory = directory; + let notice = ""; + if (cfg.worktreeRoot) { + const primary = resolveSessionDirectory("bearer", req.repo, undefined, REPO_DIRS); + const wt = await createDispatchWorktree({ + primary, + requestedDirectory: directory, + root: cfg.worktreeRoot, + repo: req.repo, + taskId: task.id, + }); + sessionDirectory = wt.directory; + notice = `\n${worktreeNotice(wt.worktree, primary)}`; + } const session = await opencode.createSession({ - directory, + directory: sessionDirectory, title: req.title ?? titleFromPrompt(req.prompt), model: req.model, }); - const prefix = `[dispatch] Queue task #${task.id} · Issue ${issue ? issue.url : "none"} · Repo ${req.repo}`; + 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}`); diff --git a/pm-stack/dispatch/src/worktree.ts b/pm-stack/dispatch/src/worktree.ts new file mode 100644 index 000000000..ec0532dc1 --- /dev/null +++ b/pm-stack/dispatch/src/worktree.ts @@ -0,0 +1,95 @@ +// Dispatch worktrees (code#12213). A dispatched session used to run in +// the repo's primary clone (~/git/code for developing-today/code). That +// clone is the deploy checkout pm-git-sync keeps on clean main, so a +// session that branched, committed or edited there stalled the laptop's +// code sync (2026-11-21: "Scheduled Bolt" and "Scheduled Palette" left +// ~/git/code on their PR branches). Each launch into a primary clone +// now gets its own detached worktree at the remote default branch +// instead, and the primary is never checked out, branched or edited. + +import { existsSync } from "node:fs"; +import { join, relative } from "node:path"; + +export class WorktreeError extends Error {} + +export interface GitResult { + code: number; + stdout: string; + stderr: string; +} + +export type GitRunner = (args: string[]) => Promise; + +export const runGit: GitRunner = async (args) => { + const proc = Bun.spawn(["git", ...args], { + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, + }); + const [stdout, stderr, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { code, stdout, stderr }; +}; + +/** Worktree directory name for one dispatched task: the repo name plus + * the task id, so two launches never share a tree and the path says + * which task it belongs to. */ +export function dispatchWorktreeName(repo: string, taskId: number | string): string { + const name = (repo.split("/").pop() ?? "repo").replace(/[^A-Za-z0-9._-]/g, "_"); + return `dispatch-${name}-${String(taskId).replace(/[^A-Za-z0-9._-]/g, "_")}`; +} + +/** Create a detached worktree of `primary` at its remote default branch + * and return the directory the session should run in: the worktree, + * or the same subdirectory inside it when the caller asked for one + * inside the primary. The fetch is best effort (a failed fetch still + * builds from the last fetched remote ref); every other failure throws, + * which fails the launch before any session exists, so a session never + * falls back to running in the primary clone. */ +export async function createDispatchWorktree(args: { + primary: string; + requestedDirectory: string; + root: string; + repo: string; + taskId: number | string; + git?: GitRunner; +}): Promise<{ directory: string; worktree: string; base: string }> { + const git = args.git ?? runGit; + const worktree = join(args.root, dispatchWorktreeName(args.repo, args.taskId)); + if (existsSync(worktree)) { + throw new WorktreeError(`dispatch worktree ${worktree} already exists; refusing to reuse it`); + } + await git(["-C", args.primary, "fetch", "--quiet", "origin"]); + let base = ""; + for (const ref of ["refs/remotes/origin/HEAD", "refs/remotes/origin/main", "refs/remotes/origin/master"]) { + const r = await git(["-C", args.primary, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`]); + if (r.code === 0 && r.stdout.trim()) { + base = r.stdout.trim(); + break; + } + } + if (!base) { + throw new WorktreeError(`no remote default branch found in ${args.primary}`); + } + const add = await git(["-C", args.primary, "worktree", "add", "--quiet", "--detach", worktree, base]); + if (add.code !== 0) { + throw new WorktreeError(`git worktree add ${worktree} failed: ${add.stderr.trim().slice(0, 300)}`); + } + const rel = relative(args.primary, args.requestedDirectory); + const directory = rel && !rel.startsWith("..") ? join(worktree, rel) : worktree; + return { directory, worktree, base }; +} + +/** The lines added to a dispatched prompt so the session knows where it + * is and that the primary clone is off limits. */ +export function worktreeNotice(worktree: string, primary: string): string { + return ( + `Worktree: you are running in ${worktree}, a detached worktree created for this task at the remote default branch. ` + + `Make every branch, edit and commit here. Never check out, branch, edit or commit in ${primary}: ` + + `it is the deploy clone kept on clean main, and changes there stall the laptop's code sync.` + ); +} diff --git a/pm-stack/dispatch/test/worktree.test.ts b/pm-stack/dispatch/test/worktree.test.ts new file mode 100644 index 000000000..62414b41e --- /dev/null +++ b/pm-stack/dispatch/test/worktree.test.ts @@ -0,0 +1,119 @@ +// Dispatch worktrees (code#12213): a launch into a primary clone gets +// its own detached worktree at the remote default branch, and the +// primary's branch, HEAD and working tree are left exactly as they were. +import { afterAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +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"; + +const tmp = mkdtempSync(join(tmpdir(), "dispatch-worktree-")); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +const env = { + ...process.env, + GIT_AUTHOR_NAME: "t", + GIT_AUTHOR_EMAIL: "t@example.invalid", + GIT_COMMITTER_NAME: "t", + GIT_COMMITTER_EMAIL: "t@example.invalid", + GIT_CONFIG_GLOBAL: "/dev/null", + GIT_CONFIG_NOSYSTEM: "1", +}; +function git(...args: string[]): string { + const r = Bun.spawnSync(["git", ...args], { env }); + if (r.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr.toString()}`); + return r.stdout.toString().trim(); +} + +// origin with two commits; the primary clone sits one commit behind, +// on a local branch, with an uncommitted edit. +const origin = join(tmp, "origin.git"); +const seed = join(tmp, "seed"); +const primary = join(tmp, "primary"); +git("init", "-q", "--bare", "-b", "main", origin); +git("clone", "-q", origin, seed); +mkdirSync(join(seed, "sub")); +writeFileSync(join(seed, "sub", "a.txt"), "one\n"); +git("-C", seed, "add", "."); +git("-C", seed, "commit", "-qm", "one"); +git("-C", seed, "push", "-q", "origin", "main"); +git("clone", "-q", origin, primary); +writeFileSync(join(seed, "sub", "a.txt"), "two\n"); +git("-C", seed, "commit", "-qam", "two"); +git("-C", seed, "push", "-q", "origin", "main"); +const originHead = git("-C", seed, "rev-parse", "HEAD"); +git("-C", primary, "checkout", "-q", "-b", "local-work"); +writeFileSync(join(primary, "sub", "a.txt"), "local edit\n"); +const primaryHead = git("-C", primary, "rev-parse", "HEAD"); + +describe("createDispatchWorktree", () => { + const root = join(tmp, "fleet"); + + test("builds a detached worktree at the fetched remote default branch", async () => { + const wt = await createDispatchWorktree({ + primary, + requestedDirectory: primary, + root, + repo: "developing-today/code", + taskId: 20901, + }); + expect(wt.worktree).toBe(join(root, "dispatch-code-20901")); + expect(wt.directory).toBe(wt.worktree); + expect(wt.base).toBe(originHead); + expect(git("-C", wt.worktree, "rev-parse", "HEAD")).toBe(originHead); + expect(git("-C", wt.worktree, "branch", "--show-current")).toBe(""); + expect(git("-C", wt.worktree, "status", "--porcelain")).toBe(""); + }); + + test("leaves the primary clone untouched", () => { + expect(git("-C", primary, "branch", "--show-current")).toBe("local-work"); + expect(git("-C", primary, "rev-parse", "HEAD")).toBe(primaryHead); + expect(git("-C", primary, "status", "--porcelain")).toBe("M sub/a.txt"); + }); + + test("maps a requested subdirectory of the primary into the worktree", async () => { + const wt = await createDispatchWorktree({ + primary, + requestedDirectory: join(primary, "sub"), + root, + repo: "developing-today/code", + taskId: 20902, + }); + expect(wt.directory).toBe(join(wt.worktree, "sub")); + expect(existsSync(join(wt.directory, "a.txt"))).toBe(true); + }); + + test("refuses to reuse an existing worktree path", async () => { + await expect( + createDispatchWorktree({ primary, requestedDirectory: primary, root, repo: "developing-today/code", taskId: 20901 }), + ).rejects.toBeInstanceOf(WorktreeError); + }); + + test("fails, rather than falling back, when the primary is not a git clone", async () => { + const notRepo = join(tmp, "not-a-repo"); + mkdirSync(notRepo); + await expect( + createDispatchWorktree({ primary: notRepo, requestedDirectory: notRepo, root, repo: "x/y", taskId: 1 }), + ).rejects.toBeInstanceOf(WorktreeError); + }); +}); + +describe("helpers and config", () => { + test("worktree names are path-safe", () => { + expect(dispatchWorktreeName("dezren39/darwin-nix", 7)).toBe("dispatch-darwin-nix-7"); + expect(dispatchWorktreeName("a/b c", "1/2")).toBe("dispatch-b_c-1_2"); + }); + + test("the notice names the worktree and puts the primary off limits", () => { + const n = worktreeNotice("/w/dispatch-code-1", "/home/user/git/code"); + expect(n).toContain("/w/dispatch-code-1"); + expect(n).toContain("Never check out, branch, edit or commit in /home/user/git/code"); + }); + + test("PM_DISPATCH_WORKTREE_ROOT defaults to ~/git/fleet, takes a path, and turns off with off", () => { + expect(loadConfig({}).worktreeRoot).toMatch(/\/git\/fleet$/); + expect(loadConfig({ PM_DISPATCH_WORKTREE_ROOT: "/srv/wt" }).worktreeRoot).toBe("/srv/wt"); + expect(loadConfig({ PM_DISPATCH_WORKTREE_ROOT: "off" }).worktreeRoot).toBeNull(); + }); +});