Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256// Workspaces: Pilot keeps one jj clone of each Repo. Each Task gets a jj workspace of its own from it (tasks.ts),// in a folder of its own, so two Tasks never share one: <reposFolder>/.workspaces/<owner>/<name>/<workspace name>.// Next to each workspace's folder: the setup command's log, the process group of the programs it left running, and the other repositories// cloned for the Task. They all go with the workspace (deleteWorkspace).// The setup command can leave programs running after it ends, so it runs with spawn, not exec. deleteWorkspace ends its process group.// ast-grep-ignore: child-process-through-execimport { spawn } from "node:child_process";import { existsSync, writeFileSync } from "node:fs";import { mkdir, open, readdir, readFile, rename, rm, rmdir, stat } from "node:fs/promises";import { uptime } from "node:os";import { dirname, join } from "node:path";import { exec } from "./exec.ts";
/** The folder of a Repo's clone, for a Repo name "owner/name". */export const cloneFolder = (reposFolder: string, repo: string) => join(reposFolder, repo);/** The folder of a Repo's workspaces. Owner names have no dots, so ".workspaces" is no Repo's folder. */const workspacesFolder = (reposFolder: string, repo: string) => join(reposFolder, ".workspaces", repo);/** The folder of one workspace of a Repo, by the workspace's name. */export const workspaceFolder = (reposFolder: string, repo: string, name: string) => join(workspacesFolder(reposFolder, repo), name);/** The folder of the other repositories cloned for a workspace's Task (task-delivery.ts), next to the workspace's folder. */export const workspaceRepos = (folder: string) => folder + ".repos";/** The setup command's log of a workspace, next to the workspace's folder. */const setupLog = (folder: string) => folder + ".setup.log";
/** Clones a repository with jj into the Repo's folder. A clone that stops half-way leaves nothing there: jj clones into a * folder of its own first, and the clone moves into place once it is complete. Owner names have no dots, so ".cloning" is no Repo's folder. * Throws an Error that says why, in plain words. signal stops jj, as when the Daemon stops: then nothing is said. */export async function cloneRepo(options: { reposFolder: string; repo: string; url: string; signal: AbortSignal }): Promise<void> { const folder = cloneFolder(options.reposFolder, options.repo); // A crash after the clone moved into place, and before the Daemon wrote it down: the clone is complete. if (existsSync(folder)) return; const partial = join(options.reposFolder, ".cloning", options.repo); await rm(partial, { recursive: true, force: true }); await mkdir(dirname(partial), { recursive: true }); try { // Colocated, so that git and gh work in the clone too. await exec("jj", ["git", "clone", "--colocate", options.url, partial], { signal: options.signal }); } catch (error) { await rm(partial, { recursive: true, force: true }); await removeIfEmpty(dirname(partial)); const failure = error as NodeJS.ErrnoException & { stderr?: string }; if (options.signal.aborted) throw options.signal.reason; if (failure.code === "ENOENT") throw new Error("Pilot could not run jj. Install jj, then try again."); throw new Error("jj could not clone it: " + jjReason(failure.stderr ?? "")); } await mkdir(dirname(folder), { recursive: true }); await rename(partial, folder); await removeIfEmpty(dirname(partial));}
/** Deletes a Repo's clone, and what a clone that stopped half-way left. */export async function deleteClone(options: { reposFolder: string; repo: string }): Promise<void> { // The workspaces go first: they belong to the clone. The programs that their setup commands left running end with them. const workspaces = workspacesFolder(options.reposFolder, options.repo); for (const file of await readdir(workspaces).catch(() => [])) { if (file.endsWith(GROUP_SUFFIX)) await stopSetup(join(workspaces, file.slice(0, -GROUP_SUFFIX.length))); } await rm(workspaces, { recursive: true, force: true }); await removeIfEmpty(dirname(workspacesFolder(options.reposFolder, options.repo))); await removeIfEmpty(join(options.reposFolder, ".workspaces")); await rm(cloneFolder(options.reposFolder, options.repo), { recursive: true, force: true }); await rm(join(options.reposFolder, ".cloning", options.repo), { recursive: true, force: true }); await removeIfEmpty(dirname(cloneFolder(options.reposFolder, options.repo))); await removeIfEmpty(dirname(join(options.reposFolder, ".cloning", options.repo)));}
/** Deletes a Task's workspace once the Task is Done or its Mission is cancelled: ends the programs that its setup command left running, forgets it in the Repo's clone, * and deletes its folder, its setup log and the other repositories cloned for the Task. The Task's branches stay. * A workspace that is gone already, in part or in full, is no error. */export async function deleteWorkspace(options: { reposFolder: string; repo: string; name: string }): Promise<void> { const folder = workspaceFolder(options.reposFolder, options.repo, options.name); await stopSetup(folder); const clone = cloneFolder(options.reposFolder, options.repo); await onRepoClone(clone, () => exec("jj", ["workspace", "forget", options.name], { cwd: clone }).catch(() => {})); for (const path of [folder, setupLog(folder), workspaceRepos(folder)]) await rm(path, { recursive: true, force: true });}
/** Removes an owner's folder once it holds no clone. Another clone of the same owner keeps it. */const removeIfEmpty = (folder: string) => rmdir(folder).catch(() => {});
/** The jj work queued on each clone, by the clone's folder. jj writes the clone's Git refs, and two jj commands that change one clone at * the same moment can fail with "Could not commit packed-ref transaction", as when two Tasks of a Repo make their workspace together. */const cloneWork = new Map<string, Promise<unknown>>();/** Runs work on a clone once the work queued before it on that clone has ended, passed or failed. The work takes a fraction of a second. */function onRepoClone<T>(clone: string, work: () => Promise<T>): Promise<T> { const turn = (cloneWork.get(clone) ?? Promise.resolve()).then(work); const ended = turn.catch(() => {}); cloneWork.set(clone, ended); void ended.then(() => cloneWork.get(clone) === ended && cloneWork.delete(clone)); return turn;}
/** What a setup command did. command: the command that ran. failed: why it failed, in plain words, or null when it passed. * output: the end of what it wrote. log: the file with all it wrote, next to the workspace, outside of it. */export type SetupRun = { command: string; failed: string | null; output: string; log: string };
/** What an agent reads first in a workspace: its first message, then, when the setup command failed, that it failed and where its log is. */export const withSetupFailure = (text: string, setup: SetupRun | null) => setup?.failed ? text + "\n\nThe Repo's setup command failed in your workspace. Its log: `" + setup.log + "`" : text;
/** The setup command as the Chat shows it first, as a tool row (HarnessHost's shownFirst). undefined when the Repo has none. */export const shownSetup = (setup: SetupRun | null) => setup ? { name: "setup", input: setup.command, output: setup.output, failed: setup.failed !== null } : undefined;
/** Makes a workspace ready to work in: a jj workspace of the Repo's clone, named name, on the newest main branch, * where the Repo's setup command ran. Gives its folder, and what the setup command did: null when the Repo has none. * A failed setup command is no error: the workspace is still there. A workspace that an earlier try left, as when the Daemon * stopped half-way, is made again from the start. Throws an Error that says why jj failed, in plain words. * signal stops jj or the setup command, as when the Daemon stops: then it throws too. */export async function prepareWorkspace(options: { reposFolder: string; repo: string; name: string; setupCommand: string; signal: AbortSignal;}): Promise<{ folder: string; setup: SetupRun | null }> { const folder = await addWorkspace(options); const setup = options.setupCommand ? await runSetup({ folder, command: options.setupCommand, signal: options.signal }) : null; return { folder, setup };}
/** Makes the jj workspace: fetches the Repo, forgets what an earlier try left, then adds it on trunk(). Gives its folder. * The jj commands wait for the other work on the clone (onRepoClone). The setup command that follows does not. */async function addWorkspace(options: { reposFolder: string; repo: string; name: string; signal: AbortSignal }): Promise<string> { const clone = cloneFolder(options.reposFolder, options.repo); const folder = workspaceFolder(options.reposFolder, options.repo, options.name); // Programs that an earlier setup command left running, or a setup command that a hard kill of the Daemon cut off, // would work in the old workspace at the same time as the new one. await stopSetup(folder); const jj = (doing: string, ...args: string[]) => run(doing, "jj", args, { cwd: clone, signal: options.signal }); await onRepoClone(clone, async () => { await jj("could not fetch " + options.repo, "git", "fetch"); await exec("jj", ["workspace", "forget", options.name], { cwd: clone, signal: options.signal }).catch(() => {}); await rm(folder, { recursive: true, force: true }); await mkdir(dirname(folder), { recursive: true }); await jj("could not make the workspace", "workspace", "add", "--name", options.name, "--revision", "trunk()", folder); }); return folder;}
/** How long the setup command may run, in milliseconds. */const SETUP_MS = 30 * 60 * 1000;/** How much of the setup command's output Pilot keeps in memory: its end. The log file holds all of it. */const SETUP_OUTPUT_CHARS = 4000;
/** Runs a Repo's setup command in a workspace, with sh, and writes its output to a log file next to the workspace. * It may run for 30 minutes. signal stops it, as when the Daemon stops: then it throws. * It runs in a process group of its own, so a stop ends every program it started. The group's id waits in a file next to * the workspace while it runs, so that stopSetup can end it after a hard kill of the Daemon. When the command ends and leaves programs * running in its group, such as a dev server, the file stays until the workspace goes. */async function runSetup(options: { folder: string; command: string; signal: AbortSignal }): Promise<SetupRun> { const log = setupLog(options.folder); const group = groupFile(options.folder); const file = await open(log, "w"); let late = false; let pid: number | undefined; let ended: number | string; try { ended = await new Promise<number | string>((resolve, reject) => { if (options.signal.aborted) return reject(options.signal.reason); const child = spawn("/bin/sh", ["-c", options.command], { cwd: options.folder, stdio: ["ignore", file.fd, file.fd], detached: true }); pid = child.pid; const stop = () => { if (child.pid !== undefined) killGroup(child.pid); }; // Written before anything else can run, so a hard kill never misses it. if (child.pid !== undefined) writeFileSync(group, String(child.pid)); const aborted = () => { stop(); reject(options.signal.reason); }; options.signal.addEventListener("abort", aborted, { once: true }); const timer = setTimeout(() => { late = true; stop(); }, SETUP_MS); const done = () => { clearTimeout(timer); options.signal.removeEventListener("abort", aborted); }; child.on("error", (error) => { done(); reject(error); }); child.on("exit", (code, signal) => { done(); resolve(code ?? signal ?? "unknown"); }); }); } finally { await file.close(); if (pid === undefined || !groupRuns(pid)) await rm(group, { force: true }); } const written = await readFile(log, "utf8"); const output = written.length > SETUP_OUTPUT_CHARS ? "…" + written.slice(-SETUP_OUTPUT_CHARS) : written; const failed = ended === 0 ? null : late ? "it ran for more than 30 minutes" : "it ended with code " + ended; return { command: options.command, failed, output, log };}
/** The file that holds the process group id of a workspace's setup command while it runs, or while programs that it left running still run. */const GROUP_SUFFIX = ".setup.pid";const groupFile = (folder: string) => folder + GROUP_SUFFIX;
/** Ends the setup command of this workspace, or the programs it left running, as when an earlier Daemon left it running. * A file written before the Mac last started names a process group that has ended, or a new one: it is only deleted. */async function stopSetup(folder: string) { const file = groupFile(folder); const written = await stat(file).catch(() => null); if (!written) return; const booted = Date.now() - uptime() * 1000; const group = Number(await readFile(file, "utf8")); if (written.mtimeMs > booted && Number.isInteger(group) && group > 1) killGroup(group); await rm(file, { force: true });}
/** Ends a process group at once. A group that has ended already is no error. */function killGroup(group: number) { try { process.kill(-group, "SIGKILL"); } catch { // It ended already. }}
/** Whether a program of this process group still runs. */function groupRuns(group: number) { try { process.kill(-group, 0); return true; } catch { return false; }}
/** Runs a program in a folder. Throws an Error that says what Pilot was doing and what failed, in plain words. */async function run(doing: string, program: string, args: string[], options: { cwd: string; signal: AbortSignal }) { try { await exec(program, args, options); } catch (error) { const failure = error as NodeJS.ErrnoException & { stderr?: string }; if (options.signal.aborted) throw options.signal.reason; if (failure.code === "ENOENT") throw new Error("Pilot could not run " + program + ". Install " + program + ", then try again."); throw new Error(program + " " + doing + ": " + jjReason(failure.stderr ?? "")); }}
/** What jj said went wrong: its "Error:" line, else its last line. */function jjReason(stderr: string) { const lines = stderr .split("\n") .map((line) => line.trim()) .filter(Boolean); const error = lines.find((line) => line.startsWith("Error: ")); return error ? error.slice("Error: ".length) : (lines.at(-1) ?? "jj gave no reason.");}