peppa/packages/runner/src/worktree.ts
2026-11-16 09:52:35 +05:00

122 lines
6.2 KiB
TypeScript

// glossary-ignore-file: причины про рабочую копию читает инженер
// PEP-27: a git worktree per runner, so parallel stories of one project don't switch each
// other's branches. Lives in $PEPPA_HOME/worktrees/<slug>/s<id>; removed once nothing is lost.
import { m } from "@peppa/shared/i18n";
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Project } from "@peppa/core";
import { peppaHome } from "@peppa/shared";
import { git } from "./git.ts";
export const storyBranch = (taskKey: string) => `task/${taskKey.toLowerCase()}`;
export function worktreePath(project: Pick<Project, "slug">, sessionId: number): string {
return join(peppaHome(), "worktrees", project.slug, `s${sessionId}`);
}
const ok = (p: Promise<unknown>) => p.then(() => true, () => false);
const out = async (dir: string, ...args: string[]) => (await git(dir, ...args)).stdout.trim();
/** origin/<default> after a best-effort fetch; else the local default branch; else HEAD. */
async function baseRef(dir: string, def: string): Promise<string> {
await git(dir, "fetch", "--prune", "origin").catch(() => {});
for (const ref of [`origin/${def}`, def]) if (await ok(git(dir, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`))) return ref;
return "HEAD";
}
/**
* Puts the worktree on the story's branch: the local branch if it exists (never reset — it
* may hold unpushed commits), else from origin's branch, else a new branch from `base`.
* A branch checked out in another worktree can't be used twice: stays detached.
*/
async function checkoutStory(wt: string, branch: string, base: string): Promise<{ branch: string | null; note?: string }> {
const local = await ok(git(wt, "rev-parse", "--verify", "--quiet", `refs/heads/${branch}`));
const remote = await ok(git(wt, "rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`));
try {
if (local) await git(wt, "checkout", branch);
else await git(wt, "checkout", "-b", branch, remote ? `origin/${branch}` : base);
return { branch };
} catch (e) {
await git(wt, "checkout", "--detach", base).catch(() => {});
return { branch: null, note: (e as Error).message.split("\n").find((l) => l.includes("fatal")) ?? m("ветка занята") };
}
}
/** Untracked Peppa files the agent, hooks and MCP need (when the repo doesn't track them). */
function copyPeppaFiles(main: string, wt: string) {
for (const f of [".peppa/project.json", ".mcp.json"]) {
const src = join(main, f);
const dst = join(wt, f);
if (existsSync(src) && !existsSync(dst)) {
mkdirSync(dirname(dst), { recursive: true });
copyFileSync(src, dst);
}
}
}
/**
* Creates the runner's worktree unless it is there: detached at the fresh default branch,
* then on the story's branch (free runner: stays detached).
*/
export async function ensureWorktree(
project: Pick<Project, "slug" | "workspacePath" | "defaultBranch">,
sessionId: number,
taskKey: string | null,
): Promise<{ path: string; created: boolean; branch: string | null; note?: string }> {
const path = worktreePath(project, sessionId);
const main = project.workspacePath;
if (existsSync(join(path, ".git"))) return { path, created: false, branch: (await out(path, "branch", "--show-current").catch(() => "")) || null };
if (!existsSync(join(main, ".git"))) throw new Error(m("{path} — не git-репозиторий, worktree не создать", { path: main }));
await git(main, "worktree", "prune").catch(() => {});
mkdirSync(dirname(path), { recursive: true });
const base = await baseRef(main, project.defaultBranch);
await git(main, "worktree", "add", "--detach", path, base);
const res = taskKey ? await checkoutStory(path, storyBranch(taskKey), base) : { branch: null };
copyPeppaFiles(main, path);
return { path, created: true, ...res };
}
/** Uncommitted changes, or commits not on any remote. */
export async function worktreeState(path: string): Promise<{ dirty: boolean; unpushed: number }> {
const dirty = !!(await out(path, "status", "--porcelain"));
const unpushed = Number((await out(path, "rev-list", "--count", "HEAD", "--not", "--remotes").catch(() => "0")) || 0);
return { dirty, unpushed };
}
/**
* A queue runner moves to the next story in its own worktree: clean tree required; the
* branch of the next story from the fresh default branch; the previous branch is deleted if merged.
*/
export async function switchWorktreeStory(
project: Pick<Project, "workspacePath" | "defaultBranch">,
path: string,
taskKey: string,
): Promise<{ ok: true; branch: string | null; note?: string } | { ok: false; reason: string }> {
if (await out(path, "status", "--porcelain")) return { ok: false, reason: m("в рабочей копии раннера незакоммиченные изменения") };
const prev = await out(path, "branch", "--show-current").catch(() => "");
const base = await baseRef(path, project.defaultBranch);
await git(path, "checkout", "--detach", base);
const res = await checkoutStory(path, storyBranch(taskKey), base);
if (prev && prev !== res.branch) await git(path, "branch", "-d", prev).catch(() => {});
return { ok: true, ...res };
}
/**
* Removes a finished runner's worktree when nothing would be lost (clean, all pushed);
* deletes its local branch if merged. Returns why it was kept otherwise.
*/
export async function removeWorktree(
project: Pick<Project, "workspacePath">,
path: string,
): Promise<{ removed: true } | { removed: false; reason: string }> {
if (!existsSync(path)) return { removed: true };
const st = await worktreeState(path).catch(() => null);
if (!st) return { removed: false, reason: m("не git-репозиторий") };
if (st.dirty) return { removed: false, reason: m("незакоммиченные изменения") };
if (st.unpushed) return { removed: false, reason: m("незапушенных коммитов: {n}", { n: st.unpushed }) };
const branch = await out(path, "branch", "--show-current").catch(() => "");
await git(project.workspacePath, "worktree", "remove", path);
if (branch) await git(project.workspacePath, "branch", "-d", branch).catch(() => {});
return { removed: true };
}