Repository navigation
fix(pm-dispatch): run dispatched sessions in their own worktree, never the primary clone #12214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<GitResult>; | ||
|
|
||
| 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"]); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If the remote connection stalls during this fetch, every affected launch remains blocked before session creation: Useful? React with 👍 / 👎. |
||
| 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.` | ||
| ); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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(); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For launches using the bundled Bolt, Palette, Suggestions, or CI-fix prompts,
req.promptstill explicitly says the session is running in the primary laptop checkout and instructs it to “Work there”; Bolt and Palette additionally label those instructions as overriding conflicting guidance. Appending that unchanged prompt after the new worktree notice gives dispatched agents contradictory working-directory instructions and can direct them back into the deploy clone this change is intended to protect. Update.github/actions/pm-dispatch-task/prompts/{bolt,palette,suggestions,ci-fix}.mdalongside the launch change so they consistently require working in the assigned worktree.AGENTS.md reference: AGENTS.md:L126-L127
Useful? React with 👍 / 👎.