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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions pkgs/pm-dispatch/package.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
'';

Expand Down
8 changes: 8 additions & 0 deletions pm-stack/dispatch/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string | undefined> = process.env): Config {
Expand Down Expand Up @@ -115,5 +119,9 @@ export function loadConfig(env: Record<string, string | undefined> = 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")),
};
}
22 changes: 20 additions & 2 deletions pm-stack/dispatch/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -179,12 +180,29 @@ async function launchSession(
warnings: string[],
failureContext: LaunchFailureContext,
): Promise<string> {
// 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}`);
Comment on lines +205 to 207

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update bundled prompts to match the new worktree context

For launches using the bundled Bolt, Palette, Suggestions, or CI-fix prompts, req.prompt still 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}.md alongside the launch change so they consistently require working in the assigned worktree.

AGENTS.md reference: AGENTS.md:L126-L127

Useful? React with 👍 / 👎.


Expand Down
95 changes: 95 additions & 0 deletions pm-stack/dispatch/src/worktree.ts
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"]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the pre-launch fetch with a subprocess timeout

If the remote connection stalls during this fetch, every affected launch remains blocked before session creation: runGit awaits the output streams and proc.exited without any deadline or cancellation. Consequently, the advertised best-effort fetch never reaches its cached-ref fallback while the child remains stuck; wait:true requests cannot return a launch result, and wait:false launches leave queued tasks without sessions. Unlike the bounded outbound requests in src/fetchTimeout.ts, this newly introduced network operation has no application-level time limit. Add a timeout that terminates the child and lets the fetch failure proceed to cached-ref resolution.

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.`
);
}
119 changes: 119 additions & 0 deletions pm-stack/dispatch/test/worktree.test.ts
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();
});
});