peppa/packages/runner/src/runners.ts
Асель 6b75324971 PEP-10/27/53: runners with a story queue, a git worktree per runner, free runners
- 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>
2026-11-14 06:38:02 +05:00

269 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-10/27/53: a runner (tmux session with an agent) as a long-lived thing — a queue of
// stories, fresh context or one conversation between them, its own worktree, free runners.
import { existsSync } from "node:fs";
import {
activateRunnerTask,
agentAutonomyNote,
createTask,
dropQueuedTask,
enqueueRunnerTask,
finishRunnerTask,
FINISHED_SESSION_STATUSES,
getAutonomy,
getSession,
listSessions,
logSessionEvent,
nextQueued,
PeppaError,
pendingSessionQuestions,
queuedItems,
raiseSessionQuestion,
resolveRunnerSettings,
updateSession,
updateTask,
type SessionView,
type TaskRef,
} from "@peppa/core";
import { events, projects, type Db } from "@peppa/db";
import { and, eq } from "drizzle-orm";
import * as tmux from "./tmux.ts";
import { relaunchFresh, resolveTaskById, resumeSession, sendToSession, startRunner, startSession, type StartOptions } from "./sessions.ts";
import { removeWorktree, switchWorktreeStory } from "./worktree.ts";
/** Task statuses of the "in progress" board column: the runner is busy with the story. */
const WORKING = ["proposing", "awaiting_approval", "in_progress", "blocked"];
const isWorking = (status: string | null) => status != null && WORKING.includes(status);
/** The agent's turn is over (nothing is being typed or generated). */
const turnOver = (s: SessionView) => s.status === "idle" || s.status === "waiting_input";
async function projectOf(db: Db, projectId: number) {
const [p] = await db.select().from(projects).where(eq(projects.id, projectId));
if (!p) throw new PeppaError(`Project #${projectId} not found`);
return p;
}
/**
* A live queue runner that can take a story now: it has worked on stories (free runners
* belong to the person in the terminal), its story left work, its turn is over and it is
* not about to switch subscriptions.
*/
async function canTakeNow(db: Db, s: SessionView): Promise<boolean> {
if (FINISHED_SESSION_STATUSES.includes(s.status) || s.tmuxName.startsWith("pending-") || s.rotateReason) return false;
if (s.taskId == null || isWorking(s.taskStatus) || !turnOver(s)) return false;
return (await resolveRunnerSettings(db, s.projectId, s.taskId)).mode === "queue";
}
export interface AssignResult {
/** A new runner was started for the story. */
started?: number;
/** An existing runner took the story (now or from its queue). */
runner?: number;
queued?: boolean;
}
/**
* The story goes into work (board, dispatcher, CI, reviewer): by the runner settings —
* "story": a new runner (as before PEP-10); "queue": a free live runner of the project
* takes it, else a new runner while the limit allows, else the shortest queue.
*/
export async function startTaskOnRunner(db: Db, ref: TaskRef, opts: StartOptions = {}): Promise<AssignResult> {
const rs = await resolveRunnerSettings(db, ref.project.id, ref.task.id);
if (rs.mode === "story") return { started: (await startSession(db, ref.key, opts)).id };
if ((await queuedItems(db, { taskId: ref.task.id })).length) return { queued: true };
const live = await listSessions(db, { active: true, projectId: ref.project.id });
for (const s of live) {
if (!(await canTakeNow(db, s))) continue;
await enqueueRunnerTask(db, s.id, ref.task.id, { prompt: opts.prompt });
await advanceRunner(db, s.id);
return { runner: s.id, queued: false };
}
if (rs.maxRunners == null || live.length < rs.maxRunners) return { started: (await startSession(db, ref.key, opts)).id };
const hosts = live.filter((s) => s.taskId != null && !s.tmuxName.startsWith("pending-"));
if (!hosts.length) throw new PeppaError(`Лимит раннеров проекта: ${rs.maxRunners}, очередь вести некому`);
const queues = await queuedItems(db, { sessionIds: hosts.map((s) => s.id) });
const load = (id: number) => queues.filter((q) => q.sessionId === id).length;
const host = hosts.sort((a, b) => load(a.id) - load(b.id) || a.id - b.id)[0]!;
await enqueueRunnerTask(db, host.id, ref.task.id, { prompt: opts.prompt });
await logSessionEvent(db, host, "task_queued", { taskId: ref.task.id, key: ref.key });
return { runner: host.id, queued: true };
}
/** PM puts a story into a runner's queue explicitly (web, CLI); taken when the runner is free. */
export async function queueTaskOnRunner(db: Db, sessionId: number, ref: TaskRef, prompt?: string): Promise<void> {
const s = await getSession(db, sessionId);
if (s.projectId !== ref.project.id) throw new PeppaError("Раннер из другого проекта");
if (FINISHED_SESSION_STATUSES.includes(s.status)) throw new PeppaError(`Раннер #${s.id} не работает`);
if (s.taskId === ref.task.id) throw new PeppaError(`Раннер #${s.id} уже ведёт ${ref.key}`);
if ((await listSessions(db, { active: true, taskId: ref.task.id })).length) throw new PeppaError(`${ref.key} уже ведёт другой раннер`);
await enqueueRunnerTask(db, s.id, ref.task.id, { prompt });
await logSessionEvent(db, s, "task_queued", { taskId: ref.task.id, key: ref.key });
await advanceRunner(db, s.id);
}
/**
* "Done" in queue mode: the runner is released instead of stopped — it takes the next
* story of its queue, or stays idle without bothering the PM.
*/
export async function releaseRunner(db: Db, sessionId: number, taskId: number): Promise<void> {
const s = await getSession(db, sessionId);
await finishRunnerTask(db, s.id, taskId);
await logSessionEvent(db, s, "task_released", { taskId });
if (s.status === "waiting_input" && (await pendingSessionQuestions(db, s.id)).length === 0) await updateSession(db, s.id, { status: "idle" });
await advanceRunner(db, s.id);
}
/** True when the runner should leave its story for the next one (by its own settings). */
export async function runnerFollowsQueue(db: Db, s: SessionView): Promise<boolean> {
return (await resolveRunnerSettings(db, s.projectId, s.taskId)).mode === "queue";
}
/**
* Moves a free runner to the next story of its queue. Fresh context: a new run of the agent
* in the same tmux session and working copy; one conversation: a message to the live agent.
* In its own worktree the runner first switches to the story's branch (clean tree only).
*/
export async function advanceRunner(db: Db, sessionId: number, log: (m: string) => void = () => {}): Promise<boolean> {
let s = await getSession(db, sessionId);
if (FINISHED_SESSION_STATUSES.includes(s.status) || s.rotateReason || !turnOver(s) || isWorking(s.taskStatus)) return false;
for (;;) {
const item = await nextQueued(db, s.id);
if (!item) return false;
const ref = await resolveTaskById(db, item.taskId).catch(() => null);
if (!ref || ref.task.status === "done" || (await listSessions(db, { active: true, taskId: item.taskId })).some((x) => x.id !== s.id)) {
await dropQueuedTask(db, item.taskId);
continue;
}
const project = await projectOf(db, s.projectId);
let branch: string | null = null;
if (s.workspacePath && existsSync(s.workspacePath)) {
const sw = await switchWorktreeStory(project, s.workspacePath, ref.key);
if (!sw.ok) {
const told = await db.select().from(events).where(and(eq(events.sessionId, s.id), eq(events.type, "switch_blocked"), eq(events.taskId, ref.task.id)));
if (!told.length) {
await db.insert(events).values({ projectId: s.projectId, taskId: ref.task.id, sessionId: s.id, type: "switch_blocked", payload: { reason: sw.reason } });
await raiseSessionQuestion(db, s, "attention", `Раннер #${s.id} не может перейти к ${ref.key}: ${sw.reason}. Закоммить или убери изменения — раннер возьмёт стори сам.`);
}
log(`#${s.id}: switch to ${ref.key} blocked — ${sw.reason}`);
return false;
}
branch = sw.branch;
}
const from = s.taskKey;
if (!isWorking(ref.task.status)) await updateTask(db, ref, { status: "in_progress" });
await activateRunnerTask(db, s.id, ref.task.id, item.id);
await updateSession(db, s.id, { taskId: ref.task.id, autoNudges: 0 });
const rs = await resolveRunnerSettings(db, s.projectId, ref.task.id);
const note = agentAutonomyNote(await getAutonomy(db, s.projectId));
const work = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, note, item.prompt].filter(Boolean).join("\n\n");
s = await getSession(db, s.id);
const alive = (await tmux.hasSession(s.tmuxName)) && !(await tmux.paneState(s.tmuxName)).dead;
if (rs.context === "continue") {
const text = `${from ? `Стори ${from} закончена. ` : ""}Следующая стори в этом же разговоре. ${work}`;
if (alive) await sendToSession(db, s.id, text);
else await resumeSession(db, s.id, { prompt: text });
} else {
await relaunchFresh(db, s.id, work);
}
await logSessionEvent(db, await getSession(db, s.id), "task_switched", { from, to: ref.key, context: rs.context, branch });
log(`#${s.id}: ${from ?? "—"} → ${ref.key} (${rs.context})`);
return true;
}
}
const keptLogged = new Set<number>();
/**
* Watchdog part (PEP-10/27): free queue runners take their next story; stories queued on a
* runner that died move to another/new one; finished runners' worktrees are removed when
* nothing would be lost.
*/
export async function runnerTick(db: Db, opts: { log?: (m: string) => void } = {}): Promise<void> {
const log = opts.log ?? (() => {});
const all = await listSessions(db);
const live = all.filter((s) => !FINISHED_SESSION_STATUSES.includes(s.status));
const liveIds = new Set(live.map((s) => s.id));
const queued = await queuedItems(db);
for (const id of new Set(queued.filter((q) => liveIds.has(q.sessionId)).map((q) => q.sessionId))) {
await advanceRunner(db, id, log).catch((e) => log(`runner #${id}: ${(e as Error).message}`));
}
// Orphans: the runner is gone — the story is assigned again (a new or another runner).
for (const q of queued.filter((q) => !liveIds.has(q.sessionId))) {
const ref = await resolveTaskById(db, q.taskId).catch(() => null);
if (!ref || !isWorking(ref.task.status)) {
await dropQueuedTask(db, q.taskId);
continue;
}
try {
await dropQueuedTask(db, q.taskId);
const r = await startTaskOnRunner(db, ref, { prompt: q.prompt ?? undefined });
log(`${ref.key}: runner #${q.sessionId} is gone, reassigned (${r.started ? `new #${r.started}` : `#${r.runner}`})`);
} catch (e) {
await enqueueRunnerTask(db, q.sessionId, q.taskId, { prompt: q.prompt, front: q.front });
log(`${ref.key}: reassign failed — ${(e as Error).message}`);
}
}
// PEP-27: worktrees of finished runners.
for (const s of all.filter((s) => FINISHED_SESSION_STATUSES.includes(s.status) && s.workspacePath && existsSync(s.workspacePath))) {
await cleanupWorktree(db, s, log).catch((e) => log(`worktree #${s.id}: ${(e as Error).message}`));
}
}
/** Removes a finished runner's worktree; logs `worktree_kept` once if something would be lost. */
export async function cleanupWorktree(db: Db, s: SessionView, log: (m: string) => void = () => {}): Promise<boolean> {
if (!s.workspacePath || !existsSync(s.workspacePath)) return true;
const project = await projectOf(db, s.projectId);
const r = await removeWorktree(project, s.workspacePath);
if (r.removed) {
await logSessionEvent(db, s, "worktree_removed", { path: s.workspacePath });
log(`#${s.id}: worktree removed`);
return true;
}
if (!keptLogged.has(s.id)) {
keptLogged.add(s.id);
const told = await db.select().from(events).where(and(eq(events.sessionId, s.id), eq(events.type, "worktree_kept")));
if (!told.length) await logSessionEvent(db, s, "worktree_kept", { path: s.workspacePath, reason: r.reason });
}
return false;
}
// ── PEP-53: free runners ─────────────────────────────────────────────────────
export interface FreeRunnerOptions extends Pick<StartOptions, "provider" | "subscriptionIds" | "poolId" | "model" | "permissionMode"> {
name?: string;
prompt?: string;
}
/** «Новый терминал»: a runner in the project without a story, driven by a person. */
export async function startFreeRunner(db: Db, projectId: number, opts: FreeRunnerOptions = {}): Promise<SessionView> {
const project = await projectOf(db, projectId);
const intro = `Это свободный раннер в проекте ${project.key} без стори: работай по просьбам человека в терминале, правила Пеппы (AGENTS.md) в силе. Стори, OpenSpec и PR — только если попросят.`;
const prompt = opts.prompt?.trim() ? `${intro}\n\n${opts.prompt.trim()}` : `${intro}\n\nПока просто жди указаний.`;
return startRunner(db, project, null, { ...opts, name: opts.name?.trim() || "Новый терминал", prompt });
}
export async function renameRunner(db: Db, sessionId: number, name: string): Promise<void> {
const s = await getSession(db, sessionId);
const clean = name.trim().slice(0, 80);
await updateSession(db, s.id, { name: clean || null });
await logSessionEvent(db, s, "renamed", { name: clean || null });
}
/**
* «Оформить стори»: a story is created from the free runner's work and goes into work on
* that runner; the agent is told to carry on by Peppa's rules.
*/
export async function promoteRunner(db: Db, sessionId: number, t: { title: string; description?: string; goalId?: number | null }): Promise<TaskRef> {
const s = await getSession(db, sessionId);
if (s.taskId) throw new PeppaError(`Раннер #${s.id} уже ведёт стори ${s.taskKey}`);
if (t.title.trim().length < 3) throw new PeppaError("Нужно название стори");
const created = await createTask(db, { projectId: s.projectId, title: t.title.trim(), description: t.description?.trim() || `Оформлено из раннера #${s.id}${s.name ? ` «${s.name}»` : ""}.`, goalId: t.goalId ?? undefined });
const ref: TaskRef = { ...created, task: await updateTask(db, created, { status: "in_progress" }, s.id) };
await updateSession(db, s.id, { taskId: ref.task.id, autoNudges: 0 });
await activateRunnerTask(db, s.id, ref.task.id);
await logSessionEvent(db, await getSession(db, s.id), "task_promoted", { key: ref.key });
if (!FINISHED_SESSION_STATUSES.includes(s.status) && (await tmux.hasSession(s.tmuxName))) {
await sendToSession(db, s.id, `Эта работа оформлена как стори ${ref.key} «${ref.task.title}». Дальше веди её по правилам Пеппы (peppa.get_task, OpenSpec change, PR, update_task(status: review)).`);
}
return ref;
}