// PEP-3: the contract of the live Claude Code CLI (2.1.323), captured on the dev stand with // PEPPA_HOOK_CAPTURE_DIR (fixtures/claude-live/*). The real peppa-hook is replayed on those // payloads, statusLine/transcript are parsed from them, and the permission dialog keys are // read off the menus the live TUI drew. import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, describe, test } from "node:test"; import { events } from "@peppa/db"; import { and, asc, eq } from "drizzle-orm"; import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; after(teardown); const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const FIX = join(ROOT, "packages/testkit/fixtures/claude-live"); const fixture = (name: string) => JSON.parse(readFileSync(join(FIX, `${name}.json`), "utf8")) as Record; const PM = "telegram" as const; /** Runs the real peppa-hook like Claude Code does: payload on stdin, JSON (maybe) on stdout. */ function hook(event: string, payload: unknown, sessionId: number, generation: number): Promise { return new Promise((done) => { const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], { env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: String(generation) }, stdio: ["pipe", "pipe", "inherit"], }); let out = ""; p.stdout.on("data", (d) => (out += d)); p.on("close", (code) => { assert.equal(code, 0); done(out.trim() ? JSON.parse(out) : null); }); p.stdin.end(JSON.stringify(payload)); }); } describe("Живой Claude Code: statusLine и transcript", () => { test("statusLine 2.1.323: стоимость, контекст, окна; total_*_tokens — не сумма за сессию", () => { const raw = fixture("statusline"); const d = core.parseStatusLine(raw); assert.equal(d.costUsd, raw.cost.total_cost_usd); const cu = raw.context_window.current_usage; const used = cu.input_tokens + cu.cache_read_input_tokens + cu.cache_creation_input_tokens; assert.equal(used, raw.context_window.total_input_tokens, "total_input_tokens = the last request's context"); assert.deepEqual(d.context, { used, size: raw.context_window.context_window_size, pct: raw.context_window.used_percentage }); assert.equal(d.tokens, undefined, "session tokens come from the transcript, not from the status line"); assert.deepEqual(d.windows.fiveHour, { pct: raw.rate_limits.five_hour.used_percentage, resetsAt: raw.rate_limits.five_hour.resets_at * 1000 }); assert.deepEqual(d.windows.sevenDay, { pct: raw.rate_limits.seven_day.used_percentage, resetsAt: raw.rate_limits.seven_day.resets_at * 1000 }); assert.equal(d.model, raw.model.id); }); test("statusLine до первого ответа API: current_usage null, rate_limits нет", () => { const d = core.parseStatusLine(fixture("statusline-first")); assert.equal(d.context, undefined); assert.deepEqual(d.windows, {}); assert.equal(d.costUsd, 0); }); test("transcript: одно сообщение — несколько записей с тем же id и usage", () => { const path = join(FIX, "transcript.jsonl"); const byId = new Map(); for (const line of readFileSync(path, "utf8").trim().split("\n")) { const e = JSON.parse(line); if (e.type === "assistant") byId.set(e.message.id, e.message.usage); } const sum = (k: string) => [...byId.values()].reduce((a, u) => a + u[k], 0); const u = core.transcriptUsage(path)!; assert.deepEqual(u.tokens, { input: sum("input_tokens"), output: sum("output_tokens"), cacheRead: sum("cache_read_input_tokens"), cacheWrite: sum("cache_creation_input_tokens") }); assert.equal(u.model, "claude-haiku-5-5"); }); }); describe("Живой Claude Code: диалог разрешений", () => { // Menus as the live TUI drew them (tmux capture-pane), all three seen in one session. const menu = (...opts: string[]) => [" Bash command", "", " touch two.txt", "", " Do you want to proceed?", ...opts.map((o, i) => `${i ? " " : " ❯ "}${i + 1}. ${o}`), "", " Esc to cancel · Tab to amend"].join("\n"); const full = menu("Yes", "Yes, and always allow access to /w/live from this project", "Yes, and switch to auto mode · auto mode handles these prompts for you", "No"); const noAlways = menu("Yes", "Yes, and switch to auto mode · auto mode handles these prompts for you", "No"); const noAuto = menu("Yes", "Yes, and don't ask again for peppa — Get Task commands in /w/live", "No"); test("клавиша читается с экрана: «No» не всегда 3, «2» не всегда «всегда»", () => { const k = runner.permissionKey; assert.deepEqual(["allow", "always", "deny"].map((a) => k(full, a)), ["1", "2", "4"]); // No "always" line: "2" would switch the session to auto mode — answer plain "Yes". assert.deepEqual(["allow", "always", "deny"].map((a) => k(noAlways, a)), ["1", "1", "3"]); assert.deepEqual(["allow", "always", "deny"].map((a) => k(noAuto, a)), ["1", "2", "3"]); // No dialog on the screen: Yes / Yes / Escape (cancel), never a guessed number for deny. assert.deepEqual(["allow", "always", "deny"].map((a) => k("❯ ", a)), ["1", "1", "Escape"]); assert.equal(k(full, "можно, но аккуратно"), null); // The last dialog wins when an old one is still in the scrollback. assert.equal(k(`${noAlways}\n\n${full}`, "deny"), "4"); }); for (const [answer, key] of [ ["allow", "1"], ["always", "2"], ["deny", "4"], ] as const) { test(`нет ответа вовремя → диалог в терминале; поздний «${answer}» жмёт «${key}»`, async () => { const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "touch two.txt" } } }, { say: "Создал." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "permission"); await waitFor("hook released", async () => !(await core.getQuestion(db, q.id)).awaitingHook, 15000); await p.waitLog("dialog drawn", (e) => e.ev === "dialog"); assert.ok((await runner.answerAndDeliver(db, q.id, answer, PM)).delivered); const e = await p.waitLog("decision in terminal", (x) => x.ev === "permission"); assert.equal(e.via, "terminal"); assert.equal(e.key, key); assert.equal(e.mode, undefined, "never switches the session to auto mode"); if (answer === "deny") { // Live: "No" interrupts the turn without a Stop hook — FORGE tells the agent why. const note = await p.waitLog("deny note typed", (x) => x.ev === "prompt" && String(x.prompt).startsWith("PM запретил")); assert.equal(note.prompt, runner.PERMISSION_DENIED_NOTE); assert.equal(p.log().some((x) => x.ev === "action" && JSON.stringify(x.action).includes("Создал")), false); } else await p.waitLog("turn went on", (x) => x.ev === "action" && JSON.stringify(x.action).includes("Создал")); await runner.stopSession(db, sid); }); } }); describe("Живой Claude Code: peppa-hook на снятых payload'ах", () => { test("SessionStart, Notification, PostToolUse(Failure), SessionEnd", async () => { const p = await project({ turns: [[{ sleep: 60_000 }]] }); const sid = await p.start(); await p.waitLog("mock started", (e) => e.ev === "prompt"); const s = await p.session(sid); const start = fixture("session-start"); await hook("session-start", start, sid, s.generation); assert.equal((await p.session(sid)).conversationId, start.session_id); await hook("notification", fixture("notification-permission-prompt"), sid, s.generation); await hook("tool-use", fixture("post-tool-use"), sid, s.generation); await hook("tool-use", fixture("post-tool-use-failure"), sid, s.generation); await hook("session-end", fixture("session-end"), sid, s.generation); const evs = (await db.select().from(events).where(eq(events.sessionId, sid)).orderBy(asc(events.id))).map((e) => ({ type: e.type, payload: e.payload as Record })); assert.deepEqual(evs.find((e) => e.type === "notification")?.payload, { type: "permission_prompt", message: "Claude needs your permission" }); const steps = evs.filter((e) => e.type === "step").map((e) => [e.payload.text, e.payload.ok]); assert.deepEqual(steps, [ ["touch two.txt", true], ["ls /nonexistent-peppa", false], ]); assert.equal(evs.find((e) => e.type === "claude_session_end")?.payload.reason, "prompt_input_exit"); await runner.stopSession(db, sid); }); test("PermissionRequest: «Всегда» возвращает permission_suggestions живого CLI", async () => { const p = await project({ turns: [[{ sleep: 60_000 }]] }); const sid = await p.start(); const s = await p.session(sid); const raw = fixture("permission-request"); const out = hook("permission-request", raw, sid, s.generation); const q = await p.waitQuestion(sid, "permission"); assert.match(q.text, /touch two\.txt/); await runner.answerAndDeliver(db, q.id, "always", PM); assert.deepEqual(await out, { hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow", updatedPermissions: raw.permission_suggestions } }, }); await runner.stopSession(db, sid); }); test("PreToolUse AskUserQuestion: ответ PM уходит в updatedInput.answers", async () => { const p = await project({ turns: [[{ sleep: 60_000 }]] }); const sid = await p.start(); const s = await p.session(sid); const raw = fixture("pre-tool-use-ask-user-question"); const out = hook("ask-question", raw, sid, s.generation); const q = await p.waitQuestion(sid, "question"); assert.deepEqual(q.options, ["Go", "Rust"]); await runner.answerAndDeliver(db, q.id, "Go", PM); const res = await out; assert.equal(res.hookSpecificOutput.permissionDecision, "allow"); assert.deepEqual(res.hookSpecificOutput.updatedInput, { ...raw.tool_input, answers: { "Какой язык?": "Go" } }); await runner.stopSession(db, sid); }); test("Stop: стори в работе → decision block; после двух — ход работы, PM не зовём", async () => { const p = await project({ turns: [[{ sleep: 60_000 }]] }); const sid = await p.start(); // The prompt hook resets auto_nudges; let it finish before the Stop hooks are counted. await p.waitLog("mock started", (e) => e.ev === "prompt_hooked"); await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" }); const s = await p.session(sid); const stop = fixture("stop"); const first = await hook("stop", stop, sid, s.generation); assert.equal(first.decision, "block"); assert.match(first.reason, new RegExp(p.taskKey)); assert.equal((await hook("stop", fixture("stop-after-block"), sid, s.generation)).decision, "block"); assert.equal(await hook("stop", fixture("stop-after-block"), sid, s.generation), null); // PEP-149: the last reply becomes a progress record — the PM is not asked. assert.deepEqual(await p.pending(sid), []); const [progress] = await db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, "progress"))); // PEP-152: in the common format — a plain reply is the gist, a technical one is under «Подробнее». const said = progress!.payload as { text: string; details?: string }; assert.ok(`${said.text}\n${said.details ?? ""}`.includes(String(fixture("stop-after-block").last_assistant_message).trim())); assert.ok(said.text.split("\n").length <= core.MAIN_MAX_LINES); await runner.stopSession(db, sid); }); });