From 967f70ac09293cb44ec4d18427325a3cf2b59469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 19:28:07 +0500 Subject: [PATCH] Add runner: tmux sessions, Claude hook ingestion and watchdog - startSession: trusts the workspace in ~/.claude.json, runs interactive claude in tmux with PEPPA_SESSION_ID, remain-on-exit for crash status - answerAndDeliver: PM answers go into the terminal (permission menu keys, approval -> task status + instruction, free text via bracketed paste) - peppa-hook: session-start/prompt/notification/stop/session-end update session status and raise PM questions; never fails the Claude session - watchdog: detects dead panes, vanished sessions, stalls, usage limits; launchd agent under caffeinate (scripts/install-launchd.sh) - CLI: peppa session start|list|send|attach|stop, peppa watchdog Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 7 +- packages/cli/package.json | 12 ++- packages/cli/src/index.ts | 58 +++++++++++- packages/core/src/index.ts | 1 + packages/core/src/notify.ts | 3 +- packages/core/src/sessions.ts | 103 +++++++++++++++++++++ packages/runner/bin/peppa-hook | 7 ++ packages/runner/package.json | 17 +++- packages/runner/src/claude-config.ts | 22 +++++ packages/runner/src/hook.ts | 124 +++++++++++++++++++++++++ packages/runner/src/index.ts | 6 +- packages/runner/src/sessions.ts | 130 +++++++++++++++++++++++++++ packages/runner/src/tmux.ts | 81 +++++++++++++++++ packages/runner/src/watchdog.ts | 110 +++++++++++++++++++++++ pnpm-lock.yaml | 9 ++ scripts/install-launchd.sh | 32 +++++++ 16 files changed, 708 insertions(+), 14 deletions(-) create mode 100644 packages/core/src/sessions.ts create mode 100755 packages/runner/bin/peppa-hook create mode 100644 packages/runner/src/claude-config.ts create mode 100644 packages/runner/src/hook.ts create mode 100644 packages/runner/src/sessions.ts create mode 100644 packages/runner/src/tmux.ts create mode 100644 packages/runner/src/watchdog.ts create mode 100755 scripts/install-launchd.sh diff --git a/CLAUDE.md b/CLAUDE.md index 3b9836e8..cebcd195 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,15 +11,18 @@ - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё - `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба -- `packages/runner` — запуск claude в tmux, `peppa-hook`, вачдог +- `packages/runner` — запуск claude в tmux (`peppa--s`, env `PEPPA_SESSION_ID`), доставка ответов PM в терминал, `peppa-hook` (хуки Claude Code → БД), вачдог (смерть/зависание/лимит) - `template/` — содержимое репо `peppa/template` (AGENTS.md и т.д.), копируется в каждый проект -- `scripts/` — push-template.sh, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin) +- `scripts/` — push-template.sh, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) ## Команды - `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate` - `pnpm typecheck` - `tsx packages/mcp/scripts/smoke.ts ` — смоук MCP-сервера - `pnpm dev:web` +- `peppa session start PEP-42` / `peppa session list` / `peppa session attach ` / `peppa q answer ` +- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` +- Тест раннера без настоящего claude: `PEPPA_CLAUDE_BIN=`, `PEPPA_CLAUDE_CONFIG=` TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`. Сама Пеппа тоже ведётся по OpenSpec (`openspec/`). diff --git a/packages/cli/package.json b/packages/cli/package.json index 9bf9c7d9..09fa8af9 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -3,11 +3,17 @@ "version": "0.0.0", "private": true, "type": "module", - "bin": { "peppa": "./bin/peppa" }, - "scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." }, + "bin": { + "peppa": "./bin/peppa" + }, + "scripts": { + "start": "tsx src/index.ts", + "typecheck": "tsc -p ." + }, "dependencies": { "@peppa/core": "workspace:*", "@peppa/db": "workspace:*", - "@peppa/shared": "workspace:*" + "@peppa/shared": "workspace:*", + "@peppa/runner": "workspace:*" } } diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index f1d33a01..dc4b9a29 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -2,13 +2,14 @@ import { parseArgs } from "node:util"; import { resolve } from "node:path"; import { - answerQuestion, createGoal, createProject, createTask, findProjectFile, getProject, + getSession, getTaskDetails, + listSessions, listGoals, listProjects, listTasks, @@ -20,6 +21,8 @@ import { type TaskStatus, } from "@peppa/core"; import { createDb } from "@peppa/db"; +import { answerAndDeliver, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { spawnSync } from "node:child_process"; import { loadEnv } from "@peppa/shared"; const USAGE = `peppa — Peppa software factory CLI @@ -33,7 +36,13 @@ const USAGE = `peppa — Peppa software factory CLI peppa task show peppa task set -s peppa q list [KEY] - peppa q answer + peppa q answer (delivered into the session's terminal) + peppa session start [-p ] [--mode ] [--model ] + peppa session list [--all] + peppa session send + peppa session attach + peppa session stop + peppa watchdog [--once] [--interval ] [--stall ] KEY defaults to the project of the current directory (.peppa/project.json). Statuses: ${TASK_STATUSES.join(", ")}`; @@ -48,6 +57,13 @@ const { values: opts, positionals } = parseArgs({ goal: { type: "string", short: "g" }, status: { type: "string", short: "s" }, help: { type: "boolean", short: "h" }, + prompt: { type: "string", short: "p" }, + mode: { type: "string" }, + model: { type: "string" }, + all: { type: "boolean" }, + once: { type: "boolean" }, + interval: { type: "string", default: "30" }, + stall: { type: "string", default: "15" }, }, }); @@ -140,8 +156,42 @@ async function main(): Promise { } case "q answer": { const [id, ...answer] = args; - const q = await answerQuestion(db, Number(id), answer.join(" "), "terminal"); - console.log(`Answered #${q.id}`); + const { delivered, question } = await answerAndDeliver(db, Number(id), answer.join(" "), "terminal"); + console.log(`Answered #${question.id}${delivered ? " (sent to session)" : ""}`); + break; + } + case "session start": { + const s = await startSession(db, args[0] ?? "", { prompt: opts.prompt, permissionMode: opts.mode, model: opts.model, defaultProjectKey: here }); + console.log(`Session #${s.id} for ${s.taskKey} → tmux attach -t ${s.tmuxName}`); + break; + } + case "session list": + for (const s of await listSessions(db, { active: !opts.all })) { + const ago = s.lastActivityAt ? `${Math.round((Date.now() - s.lastActivityAt.getTime()) / 60000)}m ago` : "-"; + console.log(`#${String(s.id).padEnd(4)} ${(s.taskKey ?? "-").padEnd(10)} ${s.status.padEnd(14)} ${ago.padEnd(9)} ${s.tmuxName}`); + } + break; + case "session send": + await sendToSession(db, Number(args[0]), args.slice(1).join(" ")); + console.log("sent"); + break; + case "session attach": { + const s = await getSession(db, Number(args[0])); + spawnSync("tmux", ["attach", "-t", s.tmuxName], { stdio: "inherit" }); + break; + } + case "session stop": + await stopSession(db, Number(args[0])); + console.log("stopped"); + break; + case "watchdog": { + const wopts = { + intervalMs: Number(opts.interval) * 1000, + stallMs: Number(opts.stall) * 60000, + log: (m: string) => console.log(`${new Date().toISOString()} ${m}`), + }; + if (opts.once) await tick(db, wopts); + else await runWatchdog(db, wopts); break; } default: diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 73afc6d0..9b7aa761 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,3 +3,4 @@ export * from "./notify.ts"; export * from "./project-file.ts"; export * from "./projects.ts"; export * from "./tasks.ts"; +export * from "./sessions.ts"; diff --git a/packages/core/src/notify.ts b/packages/core/src/notify.ts index 3d412ddd..b9733be7 100644 --- a/packages/core/src/notify.ts +++ b/packages/core/src/notify.ts @@ -7,7 +7,8 @@ export type PeppaNotification = | { type: "question"; questionId: number } | { type: "question_answered"; questionId: number } | { type: "task_updated"; taskId: number } - | { type: "progress"; eventId: number }; + | { type: "progress"; eventId: number } + | { type: "session_updated"; sessionId: number }; /** Broadcasts via Postgres NOTIFY; the bot and web listen on EVENTS_CHANNEL. */ export async function notify(db: Db, n: PeppaNotification): Promise { diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts new file mode 100644 index 00000000..34be5ee6 --- /dev/null +++ b/packages/core/src/sessions.ts @@ -0,0 +1,103 @@ +import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { and, desc, eq, isNull, notInArray } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { notify } from "./notify.ts"; +import type { Question, QuestionKind } from "./tasks.ts"; + +export type Session = typeof sessions.$inferSelect; +export type SessionStatus = (typeof sessionStatus.enumValues)[number]; +export const FINISHED_SESSION_STATUSES: SessionStatus[] = ["done", "failed"]; + +export interface SessionView extends Session { + projectKey: string; + taskKey: string | null; + taskTitle: string | null; +} + +export async function createSession(db: Db, s: { projectId: number; taskId?: number }): Promise { + // tmux name needs the id, so insert with a unique placeholder first. + const [row] = await db + .insert(sessions) + .values({ ...s, tmuxName: `pending-${crypto.randomUUID()}` }) + .returning(); + return row!; +} + +export async function getSession(db: Db, id: number): Promise { + const [row] = await sessionQuery(db).where(eq(sessions.id, id)); + if (!row) throw new PeppaError(`Session #${id} not found`); + return toView(row); +} + +export async function listSessions(db: Db, opts: { active?: boolean; taskId?: number } = {}): Promise { + const rows = await sessionQuery(db) + .where( + and( + opts.active ? notInArray(sessions.status, FINISHED_SESSION_STATUSES) : undefined, + opts.taskId != null ? eq(sessions.taskId, opts.taskId) : undefined, + ), + ) + .orderBy(desc(sessions.id)); + return rows.map(toView); +} + +export async function updateSession( + db: Db, + id: number, + patch: Partial>, +): Promise { + const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning(); + if (!row) throw new PeppaError(`Session #${id} not found`); + if (patch.status) await notify(db, { type: "session_updated", sessionId: id }); + return row; +} + +export async function logSessionEvent(db: Db, s: Session, type: string, payload?: unknown) { + const [row] = await db + .insert(events) + .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type, payload }) + .returning(); + return row!; +} + +/** Unanswered questions raised by a session (ask_pm, approvals, hook/watchdog alerts). */ +export async function pendingSessionQuestions(db: Db, sessionId: number): Promise { + return db + .select() + .from(questions) + .where(and(eq(questions.sessionId, sessionId), isNull(questions.answeredAt))); +} + +/** Raises a session-level alert for the PM (permission prompt, idle, stall, crash). */ +export async function raiseSessionQuestion( + db: Db, + s: Session, + kind: QuestionKind, + text: string, + options?: string[], +): Promise { + const [row] = await db + .insert(questions) + .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options }) + .returning(); + await notify(db, { type: "question", questionId: row!.id }); + return row!; +} + +function sessionQuery(db: Db) { + return db + .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title }) + .from(sessions) + .innerJoin(projects, eq(sessions.projectId, projects.id)) + .leftJoin(tasks, eq(sessions.taskId, tasks.id)); +} + +function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null }): SessionView { + return { + ...r.session, + projectKey: r.projectKey, + taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, + taskTitle: r.taskTitle, + }; +} diff --git a/packages/runner/bin/peppa-hook b/packages/runner/bin/peppa-hook new file mode 100755 index 00000000..8f116528 --- /dev/null +++ b/packages/runner/bin/peppa-hook @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +# Not a Peppa session: nothing to do, skip node startup. +[ -z "${PEPPA_SESSION_ID:-}" ] && { cat >/dev/null; exit 0; } +[ -f "$PEPPA_ROOT/.env" ] && set -a && . "$PEPPA_ROOT/.env" && set +a +mkdir -p "$HOME/.peppa" +exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@" diff --git a/packages/runner/package.json b/packages/runner/package.json index 937a1115..614f44c0 100644 --- a/packages/runner/package.json +++ b/packages/runner/package.json @@ -3,6 +3,19 @@ "version": "0.0.0", "private": true, "type": "module", - "scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." }, - "dependencies": { "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*" } + "exports": { + ".": "./src/index.ts" + }, + "bin": { + "peppa-hook": "./bin/peppa-hook" + }, + "scripts": { + "typecheck": "tsc -p ." + }, + "dependencies": { + "@peppa/core": "workspace:*", + "@peppa/db": "workspace:*", + "@peppa/shared": "workspace:*", + "drizzle-orm": "0.45.4" + } } diff --git a/packages/runner/src/claude-config.ts b/packages/runner/src/claude-config.ts new file mode 100644 index 00000000..cf45c36f --- /dev/null +++ b/packages/runner/src/claude-config.ts @@ -0,0 +1,22 @@ +import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +const CONFIG = process.env.PEPPA_CLAUDE_CONFIG ?? join(homedir(), ".claude.json"); + +/** + * Marks a workspace as trusted in ~/.claude.json. Without it Claude Code ignores the + * project's .claude/settings.json (permissions, hooks) and .mcp.json servers. + */ +export function trustWorkspace(dir: string): void { + const cfg = existsSync(CONFIG) ? (JSON.parse(readFileSync(CONFIG, "utf8")) as Record) : {}; + cfg.projects ??= {}; + const p = (cfg.projects[dir] ??= {}); + if (p.hasTrustDialogAccepted && p.hasCompletedProjectOnboarding) return; + p.hasTrustDialogAccepted = true; + p.hasCompletedProjectOnboarding = true; + p.enabledMcpjsonServers = Array.from(new Set([...(p.enabledMcpjsonServers ?? []), "peppa"])); + const tmp = `${CONFIG}.peppa-${process.pid}`; + writeFileSync(tmp, JSON.stringify(cfg, null, 2)); + renameSync(tmp, CONFIG); +} diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts new file mode 100644 index 00000000..6eb0b7d6 --- /dev/null +++ b/packages/runner/src/hook.ts @@ -0,0 +1,124 @@ +// peppa-hook : called by Claude Code hooks (see template/.claude/settings.json). +// Reads the hook JSON from stdin and updates the Peppa session that PEPPA_SESSION_ID +// points to. Must never break the Claude session: always exits 0, errors go to a log. +import { appendFileSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { + answerQuestion, + getSession, + logSessionEvent, + pendingSessionQuestions, + raiseSessionQuestion, + updateSession, +} from "@peppa/core"; +import { createDb } from "@peppa/db"; + +interface HookInput { + session_id?: string; + transcript_path?: string; + hook_event_name?: string; + message?: string; + notification_type?: string; + prompt?: string; + reason?: string; + source?: string; + last_assistant_message?: string; +} + +const LOG = join(homedir(), ".peppa", "hook.log"); +const log = (msg: string) => { + try { + appendFileSync(LOG, `${new Date().toISOString()} ${msg}\n`); + } catch {} +}; + +/** Last assistant text from the transcript JSONL — what the PM needs to see. */ +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; +} + +const clip = (s: string, n = 1500) => (s.length > n ? `${s.slice(0, n)}…` : s); + +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); + const now = new Date(); + + switch (event) { + case "session-start": + await updateSession(db, s.id, { claudeSessionId: input.session_id ?? null, status: "running", lastActivityAt: now }); + break; + + case "prompt": { + // Someone typed into the terminal (or the bot pasted an answer): anything still + // pending for this session is now answered. + for (const q of await pendingSessionQuestions(db, s.id)) { + await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); + } + await updateSession(db, s.id, { status: "running", lastActivityAt: now }); + break; + } + + case "notification": { + const msg = input.message ?? "Claude Code ждёт внимания"; + const isPermission = input.notification_type === "permission_prompt" || /permission/i.test(msg); + // Idle notifications duplicate the Stop alert; only permissions need their own. + if (isPermission) { + await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now }); + await raiseSessionQuestion(db, s, "permission", msg, ["allow", "always", "deny"]); + } + break; + } + + case "stop": { + const text = input.last_assistant_message?.trim() || lastAssistantText(input.transcript_path); + await logSessionEvent(db, s, "turn_end", { text }); + // If the agent already asked via ask_pm/request_approval, the PM has the question. + if ((await pendingSessionQuestions(db, s.id)).length === 0) { + await raiseSessionQuestion(db, s, "attention", clip(text ?? "Сессия закончила ход и ждёт ввода.")); + } + await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now }); + break; + } + + case "session-end": + await updateSession(db, s.id, { status: "done", endedAt: now }); + await logSessionEvent(db, s, "session_end", { reason: input.reason }); + break; + + default: + log(`unknown event ${event}`); + } +} + +const event = process.argv[2] ?? ""; +let raw = ""; +try { + raw = readFileSync(0, "utf8"); +} catch {} +try { + await handle(event, raw ? (JSON.parse(raw) as HookInput) : {}); +} catch (e) { + log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`); +} +process.exit(0); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 354372b4..7b184e43 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -1,2 +1,4 @@ -// Runner + watchdog (stage 3): starts claude in tmux, ingests hook events, detects stalls. -console.log("@peppa/runner: not implemented yet"); +export * from "./claude-config.ts"; +export * from "./sessions.ts"; +export * as tmux from "./tmux.ts"; +export * from "./watchdog.ts"; diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts new file mode 100644 index 00000000..4dbc9b25 --- /dev/null +++ b/packages/runner/src/sessions.ts @@ -0,0 +1,130 @@ +import { existsSync, realpathSync } from "node:fs"; +import { + answerQuestion, + createSession, + getSession, + PeppaError, + resolveTask, + updateSession, + updateTask, + logSessionEvent, + type Question, + type SessionView, +} from "@peppa/core"; +import { projects, tasks, type Db } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import { trustWorkspace } from "./claude-config.ts"; +import * as tmux from "./tmux.ts"; + +export interface StartOptions { + /** Extra instructions appended to the default "work on " prompt. */ + prompt?: string; + permissionMode?: string; + model?: string; + /** Project for a bare task number ("42"). */ + defaultProjectKey?: string; +} + +const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`; + +/** Starts an interactive Claude Code session for a task in a detached tmux session. */ +export async function startSession(db: Db, taskInput: string, opts: StartOptions = {}): Promise { + const ref = await resolveTask(db, taskInput, opts.defaultProjectKey); + const dir = ref.project.workspacePath; + if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`); + const cwd = realpathSync(dir); + trustWorkspace(cwd); + + const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id }); + const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`; + await updateSession(db, session.id, { tmuxName }); + + const prompt = [`Работай над задачей ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n"); + const claude = process.env.PEPPA_CLAUDE_BIN ?? "claude"; + const args = [ + `--permission-mode ${shq(opts.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits")}`, + opts.model ? `--model ${shq(opts.model)}` : "", + shq(prompt), + ]; + try { + await tmux.newSession({ + name: tmuxName, + cwd, + command: `${claude} ${args.filter(Boolean).join(" ")}`, + env: { PEPPA_SESSION_ID: String(session.id), PEPPA_PROJECT_DIR: cwd }, + }); + } catch (e) { + await updateSession(db, session.id, { status: "failed", endedAt: new Date() }); + throw new PeppaError(`tmux failed to start: ${(e as Error).message}`); + } + await updateSession(db, session.id, { status: "running", lastActivityAt: new Date() }); + await logSessionEvent(db, session, "started", { tmuxName, prompt }); + return getSession(db, session.id); +} + +export async function sendToSession(db: Db, sessionId: number, text: string): Promise { + const s = await getSession(db, sessionId); + if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`); + await tmux.sendText(s.tmuxName, text); + await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() }); +} + +export async function stopSession(db: Db, sessionId: number): Promise { + const s = await getSession(db, sessionId); + if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName); + await updateSession(db, s.id, { status: "done", endedAt: new Date() }); + await logSessionEvent(db, s, "stopped"); +} + +const APPROVE_RE = /^\s*(ok|ок|да|yes|approve|approved|одобр|lgtm|go|погнали|делай)/i; +// Claude Code permission prompt: 1 = yes, 2 = yes and don't ask again, 3 = no. +const PERMISSION_KEYS: Record = { allow: "1", always: "2", deny: "3" }; + +/** + * Records the PM's answer and delivers it into the session's terminal: + * permission → menu choice; approval → status change + message; otherwise the text. + */ +export async function answerAndDeliver( + db: Db, + questionId: number, + answer: string, + via: NonNullable, +): Promise<{ delivered: boolean; question: Question }> { + const q = await answerQuestion(db, questionId, answer, via); + let message = answer; + + if (q.kind === "approval" && q.taskId) { + const approved = APPROVE_RE.test(answer); + const ref = await resolveTaskById(db, q.taskId); + await updateTask(db, ref, { status: approved ? "in_progress" : "proposing" }, q.sessionId ?? undefined); + message = approved + ? `PM одобрил proposal ${ref.key}. Статус in_progress — переходи к Apply.${answer.trim().length > 4 ? `\n\nКомментарий PM: ${answer}` : ""}` + : `PM не одобрил proposal ${ref.key}. Доработай proposal по комментарию и снова запроси одобрение.\n\nКомментарий PM: ${answer}`; + } else if (q.kind === "question") { + message = `Ответ PM на вопрос #${q.id}: ${answer}`; + } + + if (!q.sessionId) return { delivered: false, question: q }; + const s = await getSession(db, q.sessionId); + if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q }; + + if (q.kind === "permission") { + const key = PERMISSION_KEYS[answer.trim().toLowerCase()]; + if (key) await tmux.sendKeys(s.tmuxName, key); + else await tmux.sendText(s.tmuxName, answer); + } else { + await tmux.sendText(s.tmuxName, message); + } + await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() }); + return { delivered: true, question: q }; +} + +async function resolveTaskById(db: Db, taskId: number) { + const [row] = await db + .select({ key: projects.key, number: tasks.number }) + .from(tasks) + .innerJoin(projects, eq(tasks.projectId, projects.id)) + .where(eq(tasks.id, taskId)); + if (!row) throw new PeppaError(`Task #${taskId} not found`); + return resolveTask(db, `${row.key}-${row.number}`); +} diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts new file mode 100644 index 00000000..d186daa6 --- /dev/null +++ b/packages/runner/src/tmux.ts @@ -0,0 +1,81 @@ +import { execFile, spawn } from "node:child_process"; +import { promisify } from "node:util"; + +const run = promisify(execFile); +const TMUX = process.env.PEPPA_TMUX_BIN ?? "tmux"; + +async function tmux(...args: string[]): Promise { + const { stdout } = await run(TMUX, args); + return stdout; +} + +export interface NewTmuxSession { + name: string; + cwd: string; + command: string; + env: Record; +} + +export async function newSession(s: NewTmuxSession): Promise { + const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]); + await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", "220", "-y", "50", ...envArgs, s.command); + // Keep the pane after claude exits so the watchdog can read the exit status. + await tmux("set-option", "-t", s.name, "remain-on-exit", "on"); + await tmux("set-option", "-t", s.name, "history-limit", "20000"); +} + +export async function hasSession(name: string): Promise { + try { + await tmux("has-session", "-t", `=${name}`); + return true; + } catch { + return false; + } +} + +export interface PaneState { + dead: boolean; + exitStatus: number | null; +} + +export async function paneState(name: string): Promise { + const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status}")).trim(); + const [dead, status] = out.split(" "); + return { dead: dead === "1", exitStatus: status ? Number(status) : null }; +} + +/** Visible screen (plus `history` lines of scrollback) as plain text. */ +export async function capturePane(name: string, history = 0): Promise { + return tmux("capture-pane", "-p", "-J", "-t", `=${name}:`, "-S", String(-history)); +} + +/** + * Types text into the pane and submits it. Uses a bracketed paste so multi-line text + * lands as one prompt instead of being submitted line by line. + */ +export async function sendText(name: string, text: string, submit = true): Promise { + const buffer = `peppa-${process.pid}-${Date.now()}`; + await new Promise((resolve, reject) => { + const p = spawn(TMUX, ["load-buffer", "-b", buffer, "-"], { stdio: ["pipe", "ignore", "pipe"] }); + let err = ""; + p.stderr.on("data", (d) => (err += d)); + p.on("error", reject); + p.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`tmux load-buffer failed: ${err}`)))); + p.stdin.end(text); + }); + await tmux("paste-buffer", "-p", "-d", "-b", buffer, "-t", `=${name}:`); + if (submit) { + // Give the TUI a moment to finish handling the paste before Enter. + await new Promise((r) => setTimeout(r, 400)); + await tmux("send-keys", "-t", `=${name}:`, "Enter"); + } +} + +/** Sends tmux key names (e.g. "1", "Enter", "Escape", "C-c"). */ +export async function sendKeys(name: string, ...keys: string[]): Promise { + await tmux("send-keys", "-t", `=${name}:`, ...keys); +} + +export async function killSession(name: string): Promise { + await tmux("kill-session", "-t", `=${name}`); +} diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts new file mode 100644 index 00000000..046ec57a --- /dev/null +++ b/packages/runner/src/watchdog.ts @@ -0,0 +1,110 @@ +// Watchdog: polls Peppa's tmux sessions, tracks activity, and alerts the PM when a +// session dies, stalls, or hits a usage limit. Run under launchd with caffeinate. +import { createHash } from "node:crypto"; +import { + listSessions, + logSessionEvent, + pendingSessionQuestions, + raiseSessionQuestion, + updateSession, + type SessionView, +} from "@peppa/core"; +import type { Db } from "@peppa/db"; +import * as tmux from "./tmux.ts"; + +export interface WatchdogOptions { + intervalMs: number; + /** A running session with an unchanged screen for this long is "stalled". */ + stallMs: number; + log?: (msg: string) => void; +} + +// Claude Code's limit banners ("…usage limit reached… resets 3pm", "You've hit your limit"). +const LIMIT_RE = /(usage limit reached|limit reached.{0,40}reset|you've hit your (usage )?limit|out of extra usage)/i; + +// Screen hash per session, kept across ticks. +const lastScreen = new Map(); +const limitAlerted = new Set(); + +export async function tick(db: Db, opts: WatchdogOptions): Promise { + const log = opts.log ?? (() => {}); + for (const s of await listSessions(db, { active: true })) { + try { + await checkSession(db, s, opts, log); + } catch (e) { + log(`session #${s.id}: ${(e as Error).message}`); + } + } +} + +async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: (m: string) => void) { + if (s.tmuxName.startsWith("pending-")) return; + const label = `#${s.id} ${s.taskKey ?? ""} (${s.tmuxName})`; + + if (!(await tmux.hasSession(s.tmuxName))) { + log(`${label}: tmux session gone`); + await updateSession(db, s.id, { status: "failed", endedAt: new Date() }); + await logSessionEvent(db, s, "tmux_gone"); + await raiseSessionQuestion(db, s, "attention", `Сессия ${s.taskKey ?? s.id} пропала (tmux-сессии больше нет).`); + return; + } + + const pane = await tmux.paneState(s.tmuxName); + if (pane.dead) { + const ok = pane.exitStatus === 0; + log(`${label}: claude exited with ${pane.exitStatus}`); + const tail = (await tmux.capturePane(s.tmuxName, 30)).trimEnd().split("\n").slice(-15).join("\n"); + await updateSession(db, s.id, { status: ok ? "done" : "failed", endedAt: new Date() }); + await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail }); + if (!ok) { + await raiseSessionQuestion(db, s, "attention", `Claude в ${s.taskKey ?? `сессии ${s.id}`} упал (код ${pane.exitStatus}).\n\n${tail}`); + } + await tmux.killSession(s.tmuxName).catch(() => {}); + return; + } + + const screen = await tmux.capturePane(s.tmuxName); + const hash = createHash("sha1").update(screen).digest("hex"); + const now = Date.now(); + let last = s.lastActivityAt?.getTime() ?? now; + if (lastScreen.get(s.id) !== hash) { + last = now; + lastScreen.set(s.id, hash); + await updateSession(db, s.id, { + lastActivityAt: new Date(now), + ...(s.status === "stalled" ? { status: "running" as const } : {}), + }); + } + + if (LIMIT_RE.test(screen) && !limitAlerted.has(s.id)) { + limitAlerted.add(s.id); + const line = screen.split("\n").find((l) => LIMIT_RE.test(l))?.trim() ?? ""; + log(`${label}: usage limit`); + await logSessionEvent(db, s, "usage_limit", { line }); + await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Сессия ${s.id}`} упёрлась в лимит: ${line}`); + } + + if (s.status === "running" && now - last > opts.stallMs) { + log(`${label}: stalled`); + await updateSession(db, s.id, { status: "stalled" }); + await logSessionEvent(db, s, "stalled", { idleMinutes: Math.round((now - last) / 60000) }); + if ((await pendingSessionQuestions(db, s.id)).length === 0) { + const tail = screen.trimEnd().split("\n").slice(-12).join("\n"); + await raiseSessionQuestion( + db, + s, + "attention", + `${s.taskKey ?? `Сессия ${s.id}`}: экран не меняется ${Math.round((now - last) / 60000)} мин — похоже, зависла.\n\n${tail}`, + ); + } + } +} + +export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortSignal): Promise { + const log = opts.log ?? (() => {}); + log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`); + while (!signal?.aborted) { + await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`)); + await new Promise((r) => setTimeout(r, opts.intervalMs)); + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a74ff34c..c879959b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -218,6 +218,9 @@ importers: '@peppa/db': specifier: workspace:* version: link:../db + '@peppa/runner': + specifier: workspace:* + version: link:../runner '@peppa/shared': specifier: workspace:* version: link:../shared @@ -270,12 +273,18 @@ importers: packages/runner: dependencies: + '@peppa/core': + specifier: workspace:* + version: link:../core '@peppa/db': specifier: workspace:* version: link:../db '@peppa/shared': specifier: workspace:* version: link:../shared + drizzle-orm: + specifier: 0.45.4 + version: 0.45.4(postgres@4.1.1) packages/shared: dependencies: diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh new file mode 100755 index 00000000..4c6d5290 --- /dev/null +++ b/scripts/install-launchd.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Installs the Peppa watchdog as a launchd agent (starts at login, restarts on crash). +# caffeinate -i keeps the Mac from idle-sleeping while the watchdog runs. +# Remove: launchctl bootout gui/$(id -u)/quest.telecom.peppa.watchdog && rm the plist. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +LABEL=quest.telecom.peppa.watchdog +PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" +mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.peppa" +cat > "$PLIST" < + + + + Label$LABEL + ProgramArguments + + /usr/bin/caffeinate-i + $ROOT/packages/cli/bin/peppawatchdog + + EnvironmentVariables + PATH$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin + RunAtLoad + KeepAlive + StandardOutPath$HOME/.peppa/watchdog.log + StandardErrorPath$HOME/.peppa/watchdog.log + + +PLIST +launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true +launchctl bootstrap "gui/$(id -u)" "$PLIST" +echo "watchdog installed: $PLIST (log: ~/.peppa/watchdog.log)"