peppa/packages/core/src/openspec.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

169 lines
6.0 KiB
TypeScript

// An OpenSpec change of a story as the web shows it (PEP-32) and its tasks.md progress
// (PEP-33): read from the project's working copy, active or archived.
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import type { Project } from "./projects.ts";
export type DeltaOp = "ADDED" | "MODIFIED" | "REMOVED" | "RENAMED";
export interface SpecScenario {
name: string;
body: string;
}
export interface SpecRequirement {
name: string;
body: string;
scenarios: SpecScenario[];
}
export interface DeltaSpec {
/** Capability: the folder under the change's specs/. */
capability: string;
sections: Array<{ op: DeltaOp; requirements: SpecRequirement[] }>;
text: string;
}
export interface TaskItem {
text: string;
done: boolean;
}
export interface TasksProgress {
done: number;
total: number;
/** The first unchecked item — what the agent is on now. */
current: string | null;
sections: Array<{ title: string; items: TaskItem[] }>;
}
export interface ChangeArtifacts {
id: string;
dir: string;
archived: boolean;
proposal: string | null;
design: string | null;
tasks: string | null;
specs: DeltaSpec[];
}
/** openspec/changes/<id>, or openspec/changes/archive/<date>-<id> once archived. */
export function findChangeDir(workspacePath: string, change: string): { dir: string; archived: boolean } | null {
if (!change || /[/\\]|^\.\.?$/.test(change)) return null;
const changes = join(workspacePath, "openspec", "changes");
const dir = join(changes, change);
if (existsSync(dir)) return { dir, archived: false };
const archive = join(changes, "archive");
if (!existsSync(archive)) return null;
const hit = readdirSync(archive)
.filter((d) => d === change || d.endsWith(`-${change}`))
.sort()
.pop();
return hit ? { dir: join(archive, hit), archived: true } : null;
}
const readIf = (path: string) => (existsSync(path) ? readFileSync(path, "utf8") : null);
export function readChange(project: Pick<Project, "workspacePath">, change: string | null, runnerDirs: Array<string | null> = []): ChangeArtifacts | null {
if (!change) return null;
// PEP-27: a story runner's own worktree has the change before it reaches main.
const found = runnerDirs.filter((d): d is string => !!d).map((d) => findChangeDir(d, change)).find((f) => f && !f.archived) ?? findChangeDir(project.workspacePath, change);
if (!found) return null;
const specsDir = join(found.dir, "specs");
const specs = existsSync(specsDir)
? readdirSync(specsDir, { withFileTypes: true })
.filter((d) => d.isDirectory() && existsSync(join(specsDir, d.name, "spec.md")))
.map((d) => parseDeltaSpec(d.name, readFileSync(join(specsDir, d.name, "spec.md"), "utf8")))
.sort((a, b) => a.capability.localeCompare(b.capability))
: [];
return {
id: change,
dir: found.dir,
archived: found.archived,
proposal: readIf(join(found.dir, "proposal.md")),
design: readIf(join(found.dir, "design.md")),
tasks: readIf(join(found.dir, "tasks.md")),
specs,
};
}
/** `## ADDED Requirements` → `### Requirement: …` → `#### Scenario: …`. */
export function parseDeltaSpec(capability: string, text: string): DeltaSpec {
const sections: DeltaSpec["sections"] = [];
let req: SpecRequirement | null = null;
let scen: SpecScenario | null = null;
for (const line of text.split("\n")) {
const op = line.match(/^##\s+(ADDED|MODIFIED|REMOVED|RENAMED)\b/i);
if (op) {
sections.push({ op: op[1]!.toUpperCase() as DeltaOp, requirements: [] });
req = scen = null;
continue;
}
const r = line.match(/^###\s+Requirement:\s*(.*)$/);
if (r) {
if (!sections.length) sections.push({ op: "ADDED", requirements: [] });
req = { name: r[1]!.trim(), body: "", scenarios: [] };
sections.at(-1)!.requirements.push(req);
scen = null;
continue;
}
const s = line.match(/^####\s+Scenario:\s*(.*)$/);
if (s && req) {
scen = { name: s[1]!.trim(), body: "" };
req.scenarios.push(scen);
continue;
}
if (scen) scen.body += `${line}\n`;
else if (req) req.body += `${line}\n`;
}
for (const sec of sections)
for (const r of sec.requirements) {
r.body = r.body.trim();
for (const s of r.scenarios) s.body = s.body.trim();
}
return { capability, sections, text };
}
/** Checklist of tasks.md: `## 1. Section` headings and `- [ ]` / `- [x]` items. */
export function parseTasks(text: string): TasksProgress {
const sections: TasksProgress["sections"] = [];
for (const line of text.split("\n")) {
const h = line.match(/^#{2,3}\s+(.*)$/);
if (h) {
sections.push({ title: h[1]!.trim(), items: [] });
continue;
}
const item = line.match(/^\s*[-*]\s+\[([ xX])\]\s+(.*)$/);
if (!item) continue;
if (!sections.length) sections.push({ title: "", items: [] });
sections.at(-1)!.items.push({ text: item[2]!.trim(), done: item[1] !== " " });
}
const items = sections.flatMap((s) => s.items);
return {
done: items.filter((i) => i.done).length,
total: items.length,
current: items.find((i) => !i.done)?.text ?? null,
sections: sections.filter((s) => s.items.length),
};
}
const progressCache = new Map<string, { mtimeMs: number; progress: TasksProgress }>();
/** tasks.md progress of a story's change (cached by file mtime: the board reads many). */
export function taskProgress(project: Pick<Project, "workspacePath">, change: string | null): TasksProgress | null {
if (!change) return null;
const found = findChangeDir(project.workspacePath, change);
if (!found) return null;
const path = join(found.dir, "tasks.md");
let mtimeMs: number;
try {
mtimeMs = statSync(path).mtimeMs;
} catch {
return null;
}
const hit = progressCache.get(path);
let progress = hit?.mtimeMs === mtimeMs ? hit.progress : null;
if (!progress) {
progress = parseTasks(readFileSync(path, "utf8"));
progressCache.set(path, { mtimeMs, progress });
}
return progress.total ? progress : null;
}