// peppa-hook : called by the Claude Code hooks in the per-run settings file // (run-settings.ts), and as Codex's notify program (`peppa-hook codex-notify `). Reads the hook JSON from stdin and updates the Peppa session that // PEPPA_SESSION_ID / PEPPA_GENERATION point to. Must never break the Claude session: // always exits 0, errors go to ~/.peppa/hook.log, and blocking hooks fall back to // Claude's own terminal dialog when the PM doesn't answer in time. import { asIs, m } from "@peppa/shared/i18n"; import { limitDelay, TURN_RETRY_MAX } from "./limit-delay.ts"; import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { answerQuestion, describeStep, recordStep, describeUsage, getAutonomy, mayAutoAcceptTask, getBudgetState, parseStatusLine, recordStatusLine, recordTranscriptUsage, setDefaultActor, transcriptUsage, usageTotals, getQuestion, getReviewSettings, latestReview, pendingReview, getPendingAccept, sendReviewCard, reviewNote, buildReviewCard, fitAgentText, reviewPreview, reviewPreviewNote, demoNote, reviewRejections, getSession, getProject, needsPerson, reportProgress, logSessionEvent, peppaInput, pendingSessionQuestions, isServiceInput, userText, reportPlatformError, raiseSessionQuestion, getPlatformDelay, sessionDelay, releaseHookQuestion, updateSession, type Question, type SessionView, } from "@peppa/core"; import { createDb, projects, tasks, type Db } from "@peppa/db"; import { eq } from "drizzle-orm"; import { peppaHome } from "@peppa/shared"; import { HOOK_WAIT_SEC, MAX_AUTO_NUDGES } from "./run-settings.ts"; import { getReviewWanted } from "./review-wanted-state.ts"; import { recordLimit } from "./limits.ts"; interface HookInput { session_id?: string; transcript_path?: string; hook_event_name?: string; message?: string; notification_type?: string; prompt?: string; reason?: string; source?: string; error?: string; error_details?: string; last_assistant_message?: string; tool_name?: string; tool_input?: Record; cwd?: string; permission_suggestions?: unknown[]; } interface AskQuestionItem { question: string; header?: string; options?: Array<{ label: string; description?: string }>; multiSelect?: boolean; } const LOG = join(peppaHome(), "hook.log"); const log = (msg: string) => { try { appendFileSync(LOG, `${new Date().toISOString()} ${msg}\n`); } catch {} }; const clip = (s: string, n = 1500) => (s.length > n ? `${s.slice(0, n)}…` : s); const output = (o: unknown) => process.stdout.write(JSON.stringify(o)); /** Last assistant text from the transcript JSONL — fallback when the hook omits it. */ export function lastAssistantText(transcriptPath?: string): string | null { if (!transcriptPath) return null; try { const lines = readFileSync(transcriptPath, "utf8").trimEnd().split("\n"); for (let i = lines.length - 1; i >= 0; i--) { const entry = JSON.parse(lines[i]!); if (entry.type !== "assistant") continue; const content = entry.message?.content; const text = Array.isArray(content) ? content.filter((c: { type: string }) => c.type === "text").map((c: { text: string }) => c.text).join("\n") : typeof content === "string" ? content : ""; if (text.trim()) return text.trim(); } } catch (e) { log(`transcript read failed: ${(e as Error).message}`); } return null; } /** Polls until every question is answered, or returns null after HOOK_WAIT_SEC. */ async function waitForAnswers(db: Db, ids: number[]): Promise { const deadline = Date.now() + HOOK_WAIT_SEC * 1000; while (Date.now() < deadline) { const qs = await Promise.all(ids.map((id) => getQuestion(db, id))); if (qs.every((q) => q.answeredAt)) return qs; await new Promise((r) => setTimeout(r, 1500)); } // Give up: answers that still arrive go to the terminal instead. const settled = await Promise.all(ids.map((id) => releaseHookQuestion(db, id))); return settled.every(Boolean) ? (settled as Question[]) : null; } function describeTool(name = "?", input: Record = {}): string { const main = input.command ?? input.file_path ?? input.url ?? input.pattern ?? input.prompt; const detail = typeof main === "string" ? main : JSON.stringify(input); return `${name}: ${clip(detail, 600)}${typeof input.description === "string" ? `\n(${input.description})` : ""}`; } async function permissionRequest(db: Db, s: SessionView, input: HookInput) { await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); const q = await raiseSessionQuestion( db, s, "permission", m("Разрешить {tool}", { tool: describeTool(input.tool_name, input.tool_input) }), ["allow", "always", "deny"], true, ); const [answered] = (await waitForAnswers(db, [q.id])) ?? []; if (!answered) return log(`permission #${q.id}: no answer in ${HOOK_WAIT_SEC}s, falling back to terminal`); const a = answered.answer!.trim().toLowerCase(); await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() }); if (a === "allow" || a === "always") { output({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow", ...(a === "always" && input.permission_suggestions?.length ? { updatedPermissions: input.permission_suggestions } : {}), }, }, }); } else { const reason = a === "deny" ? "PM запретил это действие." : `PM запретил это действие: ${answered.answer}`; output({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "deny", message: reason } } }); } } /** Routes Claude's built-in AskUserQuestion to the PM and fills in the answers. */ async function askQuestion(db: Db, s: SessionView, input: HookInput) { const items = (input.tool_input?.questions as AskQuestionItem[] | undefined) ?? []; if (!items.length) return; await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); const qs: Question[] = []; for (const item of items) { const opts = item.options?.map((o) => o.label); const text = [item.question, ...(item.options ?? []).map((o) => `• ${o.label}${o.description ? ` — ${o.description}` : ""}`)].join("\n"); qs.push(await raiseSessionQuestion(db, s, "question", text, opts, true)); } const answered = await waitForAnswers(db, qs.map((q) => q.id)); if (!answered) { // The questions stay pending; the PM's answer will be typed into the terminal. output({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: `Вопрос переслан PM через FORGE (${qs.map((q) => `#${q.id}`).join(", ")}). Закончи ход — ответ придёт следующим сообщением.`, }, }); return; } await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() }); const answers = Object.fromEntries(items.map((item, i) => [item.question, answered[i]!.answer ?? ""])); output({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...input.tool_input, answers }, }, }); } const NUDGE = (key: string) => `Продолжай работу над ${key} по tasks.md и правилам FORGE, не жди PM. Когда стори готова — PR и update_task(status: review). Ждёшь проверок, ревьюера или мержа — просто закончи ход: FORGE разбудит тебя сама, PM об этом писать не нужно. Не можешь продолжать — report_blocker (что мешает, что пробовал) и закончи ход.`; /** * The agent finished a turn. Pending question → PM already has it. Task in review → * "ready for review" (accept / comment). Task still in work → ask the agent to keep going * (Claude only, via the Stop hook's block decision), at most MAX_AUTO_NUDGES in a row. * Otherwise (PEP-149) the last reply becomes a `progress` record — the person is not woken. * Returns the Stop-hook output to print, if any. */ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise { await logSessionEvent(db, s, "turn_end", { text }); // PEP-154: a reply that is service text only (a tag block, command output) says nothing to a person. if (text && !userText(text)) text = null; // PEP-43: the story's budget is spent — the PM was asked; don't push the agent further. if (s.taskId && (await getBudgetState(db, s.taskId))) { await logSessionEvent(db, s, "budget_hold", {}); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } // PEP-39: the subscription is near its limit — end the turn here (no nudge, no ping); // the watchdog moves the session to a free subscription at this boundary. if (s.rotateReason && (await pendingSessionQuestions(db, s.id)).length === 0) { await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() }); return null; } // PEP-149: only what a person must answer holds the agent; a factory message does not. if ((await pendingSessionQuestions(db, s.id)).some((q) => needsPerson(q, s.taskStatus))) { await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } // PEP-53: a free runner belongs to the person in the terminal — no nudge, no ping. if (!s.taskId) { await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() }); return null; } const [task] = await db.select().from(tasks).where(eq(tasks.id, s.taskId)); // PEP-10: the story is done — a queue runner waits for its next one without a ping. if (task?.status === "done") { await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() }); return null; } if (task?.status === "review" && (await getPendingAccept(db, task.id))) { // PEP-127: the PM accepted already — the watchdog merges after green checks, no new review message. await logSessionEvent(db, s, "awaiting_accept_merge", { pr: task.prUrl }); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } if (task?.status === "review" && (await getAutonomy(db, task.projectId)).merge === "auto" && (await mayAutoAcceptTask(db, task))) { // PEP-25: Peppa merges this PR itself (watchdog); the PM hears only if it can't. await logSessionEvent(db, s, "awaiting_automerge", { pr: task.prUrl }); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } if (task?.status === "review") { // PEP-26: what the reviewer agent said (approved, findings left after the limit, failed). const settings = await getReviewSettings(db, task.projectId); const note = settings.enabled ? reviewNote(await latestReview(db, task.id), (await reviewRejections(db, task.id)) >= settings.maxIterations) : ""; const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId)); if (project) { // PEP-152: «готово» in the common format — the preview, the diff, the checks (PEP-44), the // reviewer's note and the agent's last reply are details under «Подробнее». const ref = { project, task, key: s.taskKey ?? "" }; // PEP-127: the PM gets it only when the PR can be merged now; otherwise the watchdog sends it later. await sendReviewCard(db, ref, await buildReviewCard(db, ref, { note, agentText: text }), s); } else await raiseSessionQuestion(db, s, "attention", m("✅ Задача {key} готова к ревью", { key: s.taskKey }), undefined, false, { details: asIs(text?.trim()) || null }); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } const working = task && ["proposing", "in_progress"].includes(task.status); // PEP-26: the reviewer agent is checking the PR — its result comes to the agent or the PM by itself. if (working && (await pendingReview(db, task.id))) { await logSessionEvent(db, s, "awaiting_review", {}); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } // PEP-205: the agent asked for review while the checks run — nothing to nudge, the platform moves the story on green. if (working && (await getReviewWanted(db, task.id))) { await logSessionEvent(db, s, "awaiting_checks", {}); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } if (canContinue && working && s.autoNudges < MAX_AUTO_NUDGES) { await updateSession(db, s.id, { autoNudges: s.autoNudges + 1, status: "running", lastActivityAt: new Date() }); await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 }); return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") }; } // PEP-149: the end of a turn is progress, not a question — a record in the story thread // («События агентов»); nobody is woken. Peppa wakes the agent when there is something to do // (checks passed or failed, the reviewer, a rebase, a comment of the person). // PEP-152: a reply that is plain enough goes as it is; otherwise the gist is the platform's // and the reply itself opens under «Подробнее». if (text && task) await reportProgress(db, { project: await getProject(db, s.projectKey), task, key: s.taskKey ?? "" }, fitAgentText(clip(text)), s.id); await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() }); return null; } /** PEP-5: token totals of the conversation, from its transcript. */ function saveTranscriptUsage(db: Db, s: SessionView, input: HookInput) { const u = transcriptUsage(input.transcript_path); const conv = input.session_id ?? s.conversationId; if (u && conv) recordTranscriptUsage(db, s.id, conv, u); } /** * PEP-5: Claude's statusLine command. Prints the status line (one line, must be quick) and * records cost / context / limit windows. Never throws: a broken status line is still a line. */ async function statusLine(input: Record): Promise { const sessionId = Number(process.env.PEPPA_SESSION_ID); const data = parseStatusLine(input); let line = "FORGE"; try { if (sessionId) { const db = createDb(); const s = await getSession(db, sessionId); if (Number(process.env.PEPPA_GENERATION) === s.generation) { await recordStatusLine(db, s, data); line = `FORGE ${s.taskKey ?? `#${s.id}`}`; const fresh = await getSession(db, sessionId); if (usageTotals(fresh.usage).hasData) line += ` · ${describeUsage(fresh.usage)}`; } } } catch (e) { log(`statusline session=${sessionId}: ${(e as Error).message}`); } const w = data.windows; if (w.fiveHour) line += ` · 5ч ${Math.round(w.fiveHour.pct)}%`; if (w.sevenDay) line += ` · 7д ${Math.round(w.sevenDay.pct)}%`; process.stdout.write(`${line}\n`); } async function handle(event: string, input: HookInput): Promise { const sessionId = Number(process.env.PEPPA_SESSION_ID); if (!sessionId) return; // manual `claude`, not started by Peppa const db = createDb(); const s = await getSession(db, sessionId); // A hook from an earlier run of this session (before a resume) is stale. if (Number(process.env.PEPPA_GENERATION) !== s.generation) { return log(`${event}: stale generation ${process.env.PEPPA_GENERATION} != ${s.generation} for session #${s.id}`); } const now = new Date(); switch (event) { case "session-start": // Also fires after /clear and /resume, with a new Claude session id. await updateSession(db, s.id, { conversationId: input.session_id ?? null, status: "running", lastActivityAt: now }); await logSessionEvent(db, s, "claude_session", { source: input.source, conversationId: input.session_id }); break; case "prompt": // Someone typed into the terminal (or Peppa pasted an answer): anything still // pending for this session is now answered — except hook-held questions, and, // when Peppa typed this text itself, questions raised after it did (e.g. a CI // failure pasted while the PM is being asked about the next one). // PEP-154: a service notification of the CLI (…) is nobody's answer — // the questions stay open and the nudge counter keeps counting. if (isServiceInput(input.prompt ?? "")) { await updateSession(db, s.id, { status: "running", lastActivityAt: now }); break; } const sent = input.prompt ? await peppaInput(db, s.id, input.prompt) : null; for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sent?.at })) { // What Peppa typed itself (a red check, «лимит сброшен») makes earlier messages stale; it is not an answer. if (sent && !sent.person) await answerQuestion(db, q.id, m("(неактуально: агент продолжил работу)"), "system").catch(() => {}); else await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); } await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now }); break; case "permission-request": await permissionRequest(db, s, input); break; case "ask-question": await askQuestion(db, s, input); break; case "tool-use": { // PEP-33: one step of the live feed (PostToolUse / PostToolUseFailure, async hook). const d = describeStep(input.tool_name ?? "", input.tool_input, input.cwd); if (d) await recordStep(db, s, { tool: input.tool_name!, ...d, ok: input.hook_event_name !== "PostToolUseFailure" }, now); break; } case "notification": await logSessionEvent(db, s, "notification", { type: input.notification_type, message: input.message }); break; case "stop": { saveTranscriptUsage(db, s, input); const res = await turnEnd(db, s, input.last_assistant_message?.trim() || lastAssistantText(input.transcript_path), true); if (res) output(res); break; } case "codex-notify": { // Codex passes one JSON argument; only completed turns are reported. const n = JSON.parse(process.argv[3] ?? "{}") as Record; if (n.type !== "agent-turn-complete") break; const thread = typeof n["thread-id"] === "string" ? n["thread-id"] : null; if (thread && thread !== s.conversationId) await updateSession(db, s.id, { conversationId: thread }); await turnEnd(db, s, String(n["last-assistant-message"] ?? "").slice(0, 8000).trim() || null, false); break; } case "stop-failure": { const limited = input.error === "rate_limit"; await logSessionEvent(db, s, "stop_failure", { error: input.error, details: input.error_details }); if (limited) { // Stores when to continue; the watchdog resumes the runner then (PEP-56). // PEP-39: null = another subscription of the pool is free, the watchdog switches to it. const msg = await recordLimit(db, s, input.error_details ?? input.last_assistant_message ?? ""); // PEP-150: no message to the owner — the delay line, the superadmin once. if (msg) await limitDelay(db, s, msg); break; } await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now }); // PEP-150: a broken turn is the platform's to retry (the watchdog tells the agent to go on); // the superadmin hears once, and again when the retries have run out. const broke = s.taskId ? ((await getPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "turn"))?.attempts ?? 0) + 1 : 1; await sessionDelay(db, s, { reason: "turn", state: broke > TURN_RETRY_MAX ? "stopped" : "retrying", exhausted: broke > TURN_RETRY_MAX, ttlMin: 30, details: `${m("{who}: ход оборвался с ошибкой {error}.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), error: input.error ?? "unknown" })}${input.error_details ? `\n${asIs(clip(input.error_details, 400))}` : ""}`, }); break; } case "session-end": saveTranscriptUsage(db, s, input); // /clear and /resume end a Claude session inside a live process, so this is not // the process exiting; the watchdog decides that from the tmux pane. await logSessionEvent(db, s, "claude_session_end", { reason: input.reason }); break; default: log(`unknown event ${event}`); } } const event = process.argv[2] ?? ""; let raw = ""; // Codex notify passes its payload as an argument and may leave stdin attached to the tty. if (event !== "codex-notify") { try { raw = readFileSync(0, "utf8"); } catch {} } // PEP-3: raw payloads as the CLI sent them, for checking the contract against a live Claude Code. if (process.env.PEPPA_HOOK_CAPTURE_DIR && raw) { try { mkdirSync(process.env.PEPPA_HOOK_CAPTURE_DIR, { recursive: true }); writeFileSync(join(process.env.PEPPA_HOOK_CAPTURE_DIR, `${Date.now()}-${process.pid}-${event}.json`), raw); } catch (e) { log(`capture ${event}: ${(e as Error).message}`); } } // PEP-48: hooks act as the session's agent (answers typed into the terminal are a person's). setDefaultActor({ kind: "agent", channel: "hook" }); try { if (event === "statusline") await statusLine(raw ? JSON.parse(raw) : {}); else await handle(event, raw ? (JSON.parse(raw) as HookInput) : {}); } catch (e) { log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`); // PEP-154: the hook's own failure goes to the error tracker, never to the project owner. // A clear refusal (PeppaError) is not a failure of the platform. if ((e as Error)?.name !== "PeppaError") await reportPlatformError(createDb(), e, { service: "hook", where: event }).catch(() => {}); } process.exit(0);