- Runner settings with inheritance system → project → story (settings rows): mode story (default, one runner per story) / queue, context fresh / continue, workspace shared / worktree, maxRunners. No rows = behaviour as before. - runner_tasks: a runner's story history and queue; sessions.name, sessions.workspace_path (migration 0007_runners). - moveTask → startTaskOnRunner; runnerTick in the watchdog moves free queue runners to their next story (fresh: same tmux, new generation without resume; continue: message), reassigns queues of dead runners, removes finished runners' worktrees (clean + pushed). - Free runners («Новый терминал»), rename, «Оформить стори»; the Stop hook doesn't ping for free runners or stories that left work. - Web: «Новый терминал» (runners page, project sessions tab) with voice input, project/story runner settings, runner stories in the details panel; CLI peppa runner … - e2e: packages/testkit/test/runners.test.ts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
120 lines
6.0 KiB
TypeScript
120 lines
6.0 KiB
TypeScript
// 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 { 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")) ?? "ветка занята" };
|
|
}
|
|
}
|
|
|
|
/** 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(`${main} — не git-репозиторий, worktree не создать`);
|
|
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: "в рабочей копии раннера незакоммиченные изменения" };
|
|
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: "не git-репозиторий" };
|
|
if (st.dirty) return { removed: false, reason: "незакоммиченные изменения" };
|
|
if (st.unpushed) return { removed: false, reason: `незапушенных коммитов: ${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 };
|
|
}
|