// PEP-32/33/37: story page data (OpenSpec change incl. archived, delta specs, tasks.md // progress, PM comments, accept-and-merge), agent steps from the PostToolUse hook, and the // live change hub with its SSE stream. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { after, describe, test } from "node:test"; import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; after(teardown); const HOOK = process.env.PEPPA_MOCK_MCP_BIN!.replace("mcp/bin/peppa-mcp", "runner/bin/peppa-hook"); let seq = 0; const user = (login: string) => core.upsertUserFromGitea(db, { id: 7000 + seq++, login }, { access_token: "x" }); const DELTA = `## ADDED Requirements ### Requirement: Оплата картой Покупатель SHALL оплачивать заказ картой. #### Scenario: Успешная оплата - **WHEN** покупатель вводит карту - **THEN** заказ оплачен #### Scenario: Отказ банка - **THEN** заказ не оплачен ## MODIFIED Requirements ### Requirement: Корзина Корзина SHALL хранить товары 7 дней. `; const TASKS = `## 1. Бэкенд - [x] 1.1 Модель платежа - [x] 1.2 API ## 2. Веб - [ ] 2.1 Кнопка оплаты - [ ] 2.2 Экран успеха `; function writeChange(dir: string, change: string, archived: boolean) { const base = archived ? join(dir, "openspec/changes/archive", `2026-11-01-${change}`) : join(dir, "openspec/changes", change); mkdirSync(join(base, "specs/checkout"), { recursive: true }); writeFileSync(join(base, "proposal.md"), "## Why\n\nНужна **оплата**.\n"); writeFileSync(join(base, "tasks.md"), TASKS); writeFileSync(join(base, "specs/checkout/spec.md"), DELTA); return base; } async function story() { const p = await project({ turns: [] }); const ref = await core.resolveTask(db, p.taskKey); return { p, ref, proj: ref.project }; } describe("OpenSpec change of a story (PEP-32)", () => { test("archived change: artifacts, delta specs with scenarios, tasks.md progress", async () => { const { p, ref } = await story(); writeChange(p.dir, "pay-1-checkout", true); await core.updateTask(db, ref, { openspecChange: "pay-1-checkout" }); const c = core.readChange(ref.project, "pay-1-checkout")!; assert.ok(c.archived); assert.match(c.proposal!, /оплата/); assert.equal(c.design, null); assert.equal(c.specs.length, 1); const spec = c.specs[0]!; assert.equal(spec.capability, "checkout"); assert.deepEqual(spec.sections.map((s) => s.op), ["ADDED", "MODIFIED"]); const req = spec.sections[0]!.requirements[0]!; assert.equal(req.name, "Оплата картой"); assert.deepEqual(req.scenarios.map((s) => s.name), ["Успешная оплата", "Отказ банка"]); assert.match(req.scenarios[0]!.body, /заказ оплачен/); const pr = core.taskProgress(ref.project, "pay-1-checkout")!; assert.equal(pr.done, 2); assert.equal(pr.total, 4); assert.equal(pr.current, "2.1 Кнопка оплаты"); assert.deepEqual(pr.sections.map((s) => s.title), ["1. Бэкенд", "2. Веб"]); }); test("active change wins over an archived one; unknown or unsafe ids give nothing", async () => { const { p, ref } = await story(); writeChange(p.dir, "pay-2", true); writeChange(p.dir, "pay-2", false); assert.equal(core.readChange(ref.project, "pay-2")!.archived, false); assert.equal(core.readChange(ref.project, "nope"), null); assert.equal(core.readChange(ref.project, "../etc"), null); assert.equal(core.taskProgress(ref.project, null), null); }); test("PM comment: stored with the login, shown to the agent in get_task", async () => { const { ref } = await story(); const pm = await user("pm-comment"); await assert.rejects(core.addStoryComment(db, ref, pm, " "), /Пустой/); await core.addStoryComment(db, ref, pm, "Кнопку сделать зелёной"); const d = await core.getTaskDetails(db, ref); assert.equal(d.comments.length, 1); assert.equal(d.comments[0]!.login, "pm-comment"); const { formatTask } = await import("../../mcp/src/format.ts"); assert.match(formatTask(d), /## Комментарии PM\n\n- .* pm-comment: Кнопку сделать зелёной/); }); test("edit from the web is logged with the PM's login", async () => { const { ref } = await story(); await core.updateTask(db, ref, { title: "Новое имя" }, undefined, "pm-edit"); const [e] = (await core.getTaskDetails(db, await core.resolveTask(db, ref.key))).recentEvents.filter((x) => x.type === "task_updated").slice(-1); assert.equal((e!.payload as { login: string }).login, "pm-edit"); }); test("accept and merge: answers the ready-for-review message, story done", async () => { const { ref } = await story(); await core.updateTask(db, ref, { status: "review" }); await assert.rejects(runner.acceptStory(db, await core.resolveTask(db, ref.key).then((r) => ({ ...r, task: { ...r.task, status: "in_progress" as const } }))), /не в ревью/); const q = await core.askPm(db, ref, { kind: "attention", text: "✅ готово к ревью" }); await runner.acceptStory(db, await core.resolveTask(db, ref.key)); assert.equal((await core.resolveTask(db, ref.key)).task.status, "done"); assert.ok((await core.getQuestion(db, q.id)).answeredAt); }); test("accept and merge without a review message (no PR): done", async () => { const { ref } = await story(); await core.updateTask(db, ref, { status: "review" }); await runner.acceptStory(db, await core.resolveTask(db, ref.key)); assert.equal((await core.resolveTask(db, ref.key)).task.status, "done"); }); }); describe("agent steps (PEP-33)", () => { test("describeStep classifies tool calls", () => { assert.deepEqual(core.describeStep("Bash", { command: "pnpm test --filter web\nmore" }), { kind: "test", text: "pnpm test --filter web" }); assert.deepEqual(core.describeStep("Bash", { command: "git status" }), { kind: "command", text: "git status" }); assert.deepEqual(core.describeStep("Edit", { file_path: "/w/src/a.ts" }, "/w"), { kind: "edit", text: "src/a.ts" }); assert.deepEqual(core.describeStep("Grep", { pattern: "TODO" }), { kind: "search", text: "TODO" }); assert.deepEqual(core.describeStep("mcp__peppa__update_task", {}), { kind: "mcp", text: "peppa · update_task" }); assert.equal(core.describeStep("AskUserQuestion", {}), null); assert.equal(core.describeStep("mcp__peppa__get_task", {}), null); }); test("run settings register the async PostToolUse hooks", () => { const path = runner.writeRunSettings(9999, 0); const s = JSON.parse(execFileSync("cat", [path], { encoding: "utf8" })); for (const ev of ["PostToolUse", "PostToolUseFailure"]) { const h = s.hooks[ev][0].hooks[0]; assert.match(h.command, /peppa-hook tool-use$/); assert.equal(h.async, true); } }); test("hook writes steps; failure is marked; a stale generation is ignored; steps stay out of the journal", async () => { const { p, ref, proj } = await story(); const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id }); const hook = (input: object, gen = 0) => execFileSync("bash", ["-c", `${HOOK} tool-use`], { input: JSON.stringify(input), env: { ...process.env, PEPPA_SESSION_ID: String(s.id), PEPPA_GENERATION: String(gen) } }); hook({ hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "pnpm run ci" }, cwd: p.dir }); hook({ hook_event_name: "PostToolUseFailure", tool_name: "Write", tool_input: { file_path: join(p.dir, "src/x.ts") }, cwd: p.dir }); hook({ hook_event_name: "PostToolUse", tool_name: "Read", tool_input: { file_path: "/x" } }, 5); const steps = await core.sessionSteps(db, s.id); assert.deepEqual( steps.map((x) => [x.kind, x.text, x.ok]), [ ["edit", "src/x.ts", false], ["test", "pnpm run ci", true], ], ); assert.ok((await core.getSession(db, s.id)).lastActivityAt, "activity time updated"); const d = await core.getTaskDetails(db, ref); assert.ok(!d.recentEvents.some((e) => e.type === "step"), "get_task has no steps"); }); test("only the last MAX_STEPS steps of a session are kept", async () => { const { ref, proj } = await story(); const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id }); for (let i = 0; i < core.MAX_STEPS + 15; i++) await core.recordStep(db, s, { tool: "Bash", kind: "command", text: `cmd ${i}`, ok: true }); const all = await core.sessionSteps(db, s.id, 1000); assert.equal(all.length, core.MAX_STEPS); assert.equal(all[0]!.text, `cmd ${core.MAX_STEPS + 14}`); assert.equal(all.at(-1)!.text, "cmd 15"); }); }); describe("live hub and SSE (PEP-37)", () => { test("parseScopes", () => { assert.deepEqual(runner.parseScopes("home, task:3,steps:9"), ["home", "task:3", "steps:9"]); assert.throws(() => runner.parseScopes("task:abc"), runner.LiveError); assert.throws(() => runner.parseScopes(""), runner.LiveError); }); test("a scope changes on its own writes only; steps arrive as data", async () => { const a = await story(); const b = await story(); const hub = runner.liveHub(db); const got: import("@peppa/runner").LiveEvent[] = []; const s = await core.createSession(db, { projectId: a.proj.id, taskId: a.ref.task.id }); const stop = hub.subscribe([`task:${a.ref.task.id}`, `steps:${s.id}`], (e) => got.push(e)); try { // Noise: a heartbeat, another story, a step (not a change of the story). await core.setSetting(db, "heartbeat:test", { at: Date.now() }); await core.updateTask(db, b.ref, { status: "in_progress" }); await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "ls", ok: true }); await hub.check(); assert.deepEqual(got.map((e) => e.type), ["step"]); assert.equal(got[0]!.type === "step" && got[0]!.step.text, "ls"); // A question on the story: change (via the check the notify() poke schedules). await core.askPm(db, a.ref, { kind: "question", text: "Какой цвет?" }); await waitFor("change event", async () => got.some((e) => e.type === "change"), 5000); const n = got.length; await hub.check(); assert.equal(got.length, n, "no repeat without a new write"); } finally { stop(); } assert.deepEqual(hub.watched, []); }); test("SSE: headers for Cloudflare, ready + change events, 404 for an outsider", async () => { const owner = await user("live-owner"); const outsider = await user("live-outsider"); const { ref, proj } = await story(); await core.setProjectOwner(db, proj.id, owner.id); await assert.rejects(runner.liveSse(db, outsider, [`task:${ref.task.id}`], new AbortController().signal), (e: unknown) => e instanceof runner.LiveError && e.status === 404); await assert.rejects(runner.liveSse(db, owner, ["task:999999"], new AbortController().signal), (e: unknown) => e instanceof runner.LiveError && e.status === 404); const ac = new AbortController(); const res = await runner.liveSse(db, owner, [`task:${ref.task.id}`], ac.signal); assert.equal(res.headers.get("content-type"), "text/event-stream; charset=utf-8"); assert.match(res.headers.get("cache-control")!, /no-transform/); assert.equal(res.headers.get("x-accel-buffering"), "no"); const reader = res.body!.getReader(); const dec = new TextDecoder(); let buf = ""; const until = async (re: RegExp) => { const deadline = Date.now() + 5000; while (!re.test(buf)) { if (Date.now() > deadline) throw new Error(`no ${re} in ${buf}`); const { value, done } = await reader.read(); if (done) break; buf += dec.decode(value); } }; await until(/event: ready/); await core.updateTask(db, ref, { title: "Переименовано" }, undefined, "live-owner"); await until(/event: change\ndata: \{"type":"change","scope":"task:\d+","v":"[\w-]+","parts":\[[^\]]*"t"[^\]]*\],"tasks":\[\{"id":\d+,"status":"[a-z_]+","title":"Переименовано"/); ac.abort(); await reader.cancel().catch(() => {}); }); });