Add Codex provider, mock agents and end-to-end CJM suite
- runner: provider abstraction (claude | codex); per-run launch.sh keeps long argv out of tmux; Codex via notify callback + -c config for rules and the peppa MCP server; session env carries DATABASE_URL/PEPPA_HOME - testkit: mock-claude / mock-codex driven by scenarios — real hooks, notify, MCP calls, raw-mode TUI input with bracketed paste, permission dialog, usage limits, hangs, crashes, /clear - 21 CJM tests on an isolated DB, tmux server and state dir (all green) - fix: watchdog crash/stall alerts showed blank lines instead of the tail - bins load .env without overriding the caller's env; tmux socket option - AGENTS.md (was CLAUDE.md) and shared RULES.md: mock-first rule with a mock prefix for anything blocked on external dependencies Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e1384a4c6f
commit
1df550bb86
51
AGENTS.md
Normal file
51
AGENTS.md
Normal file
@ -0,0 +1,51 @@
|
||||
# Peppa
|
||||
|
||||
Софтвейр-фабрика: долгие Claude Code сессии в tmux + вачдог + Telegram-бот для PM,
|
||||
проекты ведутся по OpenSpec.
|
||||
|
||||
## Структура
|
||||
- `apps/web` — Next.js платформа (порт 3100): проекты, цели, задачи, сессии
|
||||
- `apps/bot` — Telegram-бот (grammY)
|
||||
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
|
||||
- `packages/shared` — env, ключи задач (`PEP-42`)
|
||||
- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё
|
||||
- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd
|
||||
- `packages/testkit` — `mock-claude` / `mock-codex` (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM
|
||||
- `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба
|
||||
- `packages/runner` — запуск claude в tmux (`peppa-<task>-s<id>`), вачдог, `peppa-hook`
|
||||
- хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s<id>-g<gen>/settings.json` (`claude --settings`)
|
||||
- `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется
|
||||
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
|
||||
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
|
||||
- StopFailure `rate_limit` → `rate_limited`; `peppa session resume <id>` → `claude --resume`
|
||||
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
||||
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
|
||||
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
|
||||
- `scripts/` — push-template.sh, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate)
|
||||
|
||||
## Внешние зависимости — через моки
|
||||
|
||||
Если упираешься во что-то, что от тебя не зависит (нет доступа или токена, сервис или CLI
|
||||
недоступен, нужна чужая авторизация, платный или боевой API, железо), не останавливайся
|
||||
и не жди: сделай мок и продолжай работу.
|
||||
|
||||
- Всё моковое помечай префиксом **`mock`** — в именах файлов, функций, переменных,
|
||||
env и фикстур: `mock-claude`, `mockGiteaClient`, `MOCK_TELEGRAM_TOKEN`,
|
||||
`mock-payload.json`. Так моки легко найти (`grep -ri mock`) и заменить настоящим.
|
||||
- Мок повторяет контракт настоящей зависимости (аргументы, форматы, ошибки), а не
|
||||
просто возвращает «ок», чтобы код поверх него был настоящим.
|
||||
- В отчёте/PR явно перечисли, что сделано на моках и что нужно для реальной
|
||||
интеграции (какой доступ, у кого).
|
||||
|
||||
## Команды
|
||||
- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate`
|
||||
- `pnpm typecheck`
|
||||
- `tsx packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера
|
||||
- `pnpm dev:web`
|
||||
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>`
|
||||
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
|
||||
- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (отдельная БД `peppa_test`, свой tmux `-L`, свой `PEPPA_HOME`)
|
||||
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
|
||||
|
||||
TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`.
|
||||
Сама Пеппа тоже ведётся по OpenSpec (`openspec/`).
|
||||
36
CLAUDE.md
36
CLAUDE.md
@ -1,35 +1 @@
|
||||
# Peppa
|
||||
|
||||
Софтвейр-фабрика: долгие Claude Code сессии в tmux + вачдог + Telegram-бот для PM,
|
||||
проекты ведутся по OpenSpec.
|
||||
|
||||
## Структура
|
||||
- `apps/web` — Next.js платформа (порт 3100): проекты, цели, задачи, сессии
|
||||
- `apps/bot` — Telegram-бот (grammY)
|
||||
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
|
||||
- `packages/shared` — env, ключи задач (`PEP-42`)
|
||||
- `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-<task>-s<id>`), вачдог, `peppa-hook`
|
||||
- хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s<id>-g<gen>/settings.json` (`claude --settings`)
|
||||
- `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется
|
||||
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
|
||||
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
|
||||
- StopFailure `rate_limit` → `rate_limited`; `peppa session resume <id>` → `claude --resume`
|
||||
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
||||
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
|
||||
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
|
||||
- `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 <project-dir> <task>` — смоук MCP-сервера
|
||||
- `pnpm dev:web`
|
||||
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>`
|
||||
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
|
||||
- Тест раннера без настоящего claude: `PEPPA_CLAUDE_BIN=<fake script>`, `PEPPA_CLAUDE_CONFIG=<tmp claude.json>`
|
||||
|
||||
TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`.
|
||||
Сама Пеппа тоже ведётся по OpenSpec (`openspec/`).
|
||||
@AGENTS.md
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
# Enabled per repo (never globally): git config credential.helper peppa
|
||||
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
[ "$1" = "get" ] || exit 0
|
||||
[ -f "$PEPPA_ROOT/.env" ] && set -a && . "$PEPPA_ROOT/.env" && set +a
|
||||
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
||||
want="${GITEA_URL#*://}"; host=""
|
||||
while IFS='=' read -r k v; do [ -z "$k" ] && break; [ "$k" = host ] && host="$v"; done
|
||||
[ "$host" = "$want" ] && [ -n "$GITEA_TOKEN" ] || exit 0
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
[ -f "$PEPPA_ROOT/.env" ] && set -a && . "$PEPPA_ROOT/.env" && set +a
|
||||
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
||||
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@"
|
||||
|
||||
@ -21,7 +21,7 @@ import {
|
||||
type TaskStatus,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { answerAndDeliver, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { answerAndDeliver, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
|
||||
@ -37,7 +37,7 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa task set <PEP-42|42> -s <status>
|
||||
peppa q list [KEY]
|
||||
peppa q answer <id> <answer> (delivered into the session's terminal)
|
||||
peppa session start <PEP-42|42> [-p <extra prompt>] [--mode <permission-mode>] [--model <m>]
|
||||
peppa session start <PEP-42|42> [--provider claude|codex] [-p <extra prompt>] [--mode <permission-mode>] [--model <m>]
|
||||
peppa session list [--all]
|
||||
peppa session send <id> <text>
|
||||
peppa session attach <id>
|
||||
@ -60,6 +60,7 @@ const { values: opts, positionals } = parseArgs({
|
||||
help: { type: "boolean", short: "h" },
|
||||
prompt: { type: "string", short: "p" },
|
||||
mode: { type: "string" },
|
||||
provider: { type: "string" },
|
||||
model: { type: "string" },
|
||||
all: { type: "boolean" },
|
||||
once: { type: "boolean" },
|
||||
@ -80,6 +81,12 @@ function withKey(rest: string[], required: number): [string, string[]] {
|
||||
return [here, rest];
|
||||
}
|
||||
|
||||
function provider(p: string | undefined): Provider | undefined {
|
||||
if (p === undefined) return undefined;
|
||||
if (!(PROVIDERS as string[]).includes(p)) throw new PeppaError(`Unknown provider "${p}" (${PROVIDERS.join(", ")})`);
|
||||
return p as Provider;
|
||||
}
|
||||
|
||||
function status(s: string | undefined): TaskStatus | undefined {
|
||||
if (s === undefined) return undefined;
|
||||
if (!(TASK_STATUSES as readonly string[]).includes(s)) throw new PeppaError(`Unknown status "${s}"`);
|
||||
@ -162,14 +169,14 @@ async function main(): Promise<void> {
|
||||
break;
|
||||
}
|
||||
case "session start": {
|
||||
const s = await startSession(db, args[0] ?? "", { prompt: opts.prompt, permissionMode: opts.mode, model: opts.model, defaultProjectKey: here });
|
||||
const s = await startSession(db, args[0] ?? "", { prompt: opts.prompt, permissionMode: opts.mode, model: opts.model, defaultProjectKey: here, provider: provider(opts.provider) });
|
||||
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}`);
|
||||
console.log(`#${String(s.id).padEnd(4)} ${(s.taskKey ?? "-").padEnd(10)} ${s.provider.padEnd(7)} ${s.status.padEnd(14)} ${ago.padEnd(9)} ${s.tmuxName}`);
|
||||
}
|
||||
break;
|
||||
case "session send":
|
||||
@ -178,7 +185,8 @@ async function main(): Promise<void> {
|
||||
break;
|
||||
case "session attach": {
|
||||
const s = await getSession(db, Number(args[0]));
|
||||
spawnSync("tmux", ["attach", "-t", s.tmuxName], { stdio: "inherit" });
|
||||
const socket = process.env.PEPPA_TMUX_SOCKET ? ["-L", process.env.PEPPA_TMUX_SOCKET] : [];
|
||||
spawnSync("tmux", [...socket, "attach", "-t", s.tmuxName], { stdio: "inherit" });
|
||||
break;
|
||||
}
|
||||
case "session resume": {
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { loadEnv, peppaHome } from "@peppa/shared";
|
||||
|
||||
const CACHE = join(homedir(), ".peppa", "rules.md");
|
||||
const CACHE = join(peppaHome(), "rules.md");
|
||||
const LOCAL = resolve(dirname(fileURLToPath(import.meta.url)), "../../../template/RULES.md");
|
||||
|
||||
export interface SharedRules {
|
||||
|
||||
@ -15,7 +15,10 @@ export interface SessionView extends Session {
|
||||
taskTitle: string | null;
|
||||
}
|
||||
|
||||
export async function createSession(db: Db, s: { projectId: number; taskId?: number }): Promise<Session> {
|
||||
export async function createSession(
|
||||
db: Db,
|
||||
s: { projectId: number; taskId?: number; provider?: Session["provider"] },
|
||||
): Promise<Session> {
|
||||
// tmux name needs the id, so insert with a unique placeholder first.
|
||||
const [row] = await db
|
||||
.insert(sessions)
|
||||
@ -45,7 +48,7 @@ export async function listSessions(db: Db, opts: { active?: boolean; taskId?: nu
|
||||
export async function updateSession(
|
||||
db: Db,
|
||||
id: number,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "claudeSessionId" | "generation" | "lastActivityAt" | "endedAt">>,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "lastActivityAt" | "endedAt">>,
|
||||
): Promise<Session> {
|
||||
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
|
||||
if (!row) throw new PeppaError(`Session #${id} not found`);
|
||||
|
||||
1
packages/db/migrations/0002_happy_preak.sql
Normal file
1
packages/db/migrations/0002_happy_preak.sql
Normal file
@ -0,0 +1 @@
|
||||
ALTER TABLE "sessions" ADD COLUMN "provider" text DEFAULT 'claude' NOT NULL;
|
||||
713
packages/db/migrations/meta/0002_snapshot.json
Normal file
713
packages/db/migrations/meta/0002_snapshot.json
Normal file
@ -0,0 +1,713 @@
|
||||
{
|
||||
"id": "93b4fb9b-40f7-4af5-9ff7-b89be76777ed",
|
||||
"prevId": "7e63ed2b-721c-4506-a2ab-21922112a126",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.events": {
|
||||
"name": "events",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"task_id": {
|
||||
"name": "task_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"session_id": {
|
||||
"name": "session_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"payload": {
|
||||
"name": "payload",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"events_project_id_projects_id_fk": {
|
||||
"name": "events_project_id_projects_id_fk",
|
||||
"tableFrom": "events",
|
||||
"tableTo": "projects",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"events_task_id_tasks_id_fk": {
|
||||
"name": "events_task_id_tasks_id_fk",
|
||||
"tableFrom": "events",
|
||||
"tableTo": "tasks",
|
||||
"columnsFrom": [
|
||||
"task_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"events_session_id_sessions_id_fk": {
|
||||
"name": "events_session_id_sessions_id_fk",
|
||||
"tableFrom": "events",
|
||||
"tableTo": "sessions",
|
||||
"columnsFrom": [
|
||||
"session_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.goals": {
|
||||
"name": "goals",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "goal_status",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'open'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"goals_project_id_projects_id_fk": {
|
||||
"name": "goals_project_id_projects_id_fk",
|
||||
"tableFrom": "goals",
|
||||
"tableTo": "projects",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.projects": {
|
||||
"name": "projects",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"slug": {
|
||||
"name": "slug",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"gitea_owner": {
|
||||
"name": "gitea_owner",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"gitea_repo": {
|
||||
"name": "gitea_repo",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"default_branch": {
|
||||
"name": "default_branch",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'main'"
|
||||
},
|
||||
"workspace_path": {
|
||||
"name": "workspace_path",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"next_task_number": {
|
||||
"name": "next_task_number",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 1
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"projects_slug_unique": {
|
||||
"name": "projects_slug_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"slug"
|
||||
]
|
||||
},
|
||||
"projects_key_unique": {
|
||||
"name": "projects_key_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"key"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.questions": {
|
||||
"name": "questions",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"task_id": {
|
||||
"name": "task_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"session_id": {
|
||||
"name": "session_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"kind": {
|
||||
"name": "kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"text": {
|
||||
"name": "text",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"options": {
|
||||
"name": "options",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"answer": {
|
||||
"name": "answer",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"answered_via": {
|
||||
"name": "answered_via",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"telegram_message_id": {
|
||||
"name": "telegram_message_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"awaiting_hook": {
|
||||
"name": "awaiting_hook",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"answered_at": {
|
||||
"name": "answered_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"questions_project_id_projects_id_fk": {
|
||||
"name": "questions_project_id_projects_id_fk",
|
||||
"tableFrom": "questions",
|
||||
"tableTo": "projects",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"questions_task_id_tasks_id_fk": {
|
||||
"name": "questions_task_id_tasks_id_fk",
|
||||
"tableFrom": "questions",
|
||||
"tableTo": "tasks",
|
||||
"columnsFrom": [
|
||||
"task_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"questions_session_id_sessions_id_fk": {
|
||||
"name": "questions_session_id_sessions_id_fk",
|
||||
"tableFrom": "questions",
|
||||
"tableTo": "sessions",
|
||||
"columnsFrom": [
|
||||
"session_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.sessions": {
|
||||
"name": "sessions",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"task_id": {
|
||||
"name": "task_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"tmux_name": {
|
||||
"name": "tmux_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"provider": {
|
||||
"name": "provider",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'claude'"
|
||||
},
|
||||
"claude_session_id": {
|
||||
"name": "claude_session_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"generation": {
|
||||
"name": "generation",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "session_status",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'starting'"
|
||||
},
|
||||
"last_activity_at": {
|
||||
"name": "last_activity_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"ended_at": {
|
||||
"name": "ended_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"sessions_project_id_projects_id_fk": {
|
||||
"name": "sessions_project_id_projects_id_fk",
|
||||
"tableFrom": "sessions",
|
||||
"tableTo": "projects",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"sessions_task_id_tasks_id_fk": {
|
||||
"name": "sessions_task_id_tasks_id_fk",
|
||||
"tableFrom": "sessions",
|
||||
"tableTo": "tasks",
|
||||
"columnsFrom": [
|
||||
"task_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"sessions_tmux_name_unique": {
|
||||
"name": "sessions_tmux_name_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"tmux_name"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.tasks": {
|
||||
"name": "tasks",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "serial",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"goal_id": {
|
||||
"name": "goal_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"number": {
|
||||
"name": "number",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"description": {
|
||||
"name": "description",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "task_status",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'backlog'"
|
||||
},
|
||||
"openspec_change": {
|
||||
"name": "openspec_change",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"pr_url": {
|
||||
"name": "pr_url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"tasks_project_number": {
|
||||
"name": "tasks_project_number",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "project_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "number",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"tasks_project_id_projects_id_fk": {
|
||||
"name": "tasks_project_id_projects_id_fk",
|
||||
"tableFrom": "tasks",
|
||||
"tableTo": "projects",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"tasks_goal_id_goals_id_fk": {
|
||||
"name": "tasks_goal_id_goals_id_fk",
|
||||
"tableFrom": "tasks",
|
||||
"tableTo": "goals",
|
||||
"columnsFrom": [
|
||||
"goal_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
"enums": {
|
||||
"public.goal_status": {
|
||||
"name": "goal_status",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"open",
|
||||
"done",
|
||||
"archived"
|
||||
]
|
||||
},
|
||||
"public.session_status": {
|
||||
"name": "session_status",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"starting",
|
||||
"running",
|
||||
"waiting_input",
|
||||
"idle",
|
||||
"stalled",
|
||||
"rate_limited",
|
||||
"done",
|
||||
"failed"
|
||||
]
|
||||
},
|
||||
"public.task_status": {
|
||||
"name": "task_status",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"backlog",
|
||||
"proposing",
|
||||
"awaiting_approval",
|
||||
"in_progress",
|
||||
"review",
|
||||
"done",
|
||||
"blocked"
|
||||
]
|
||||
}
|
||||
},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"roles": {},
|
||||
"policies": {},
|
||||
"views": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@ -15,6 +15,13 @@
|
||||
"when": 1794493804069,
|
||||
"tag": "0001_chunky_dreadnoughts",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1794495121487,
|
||||
"tag": "0002_happy_preak",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -75,13 +75,15 @@ export const sessionStatus = pgEnum("session_status", [
|
||||
"failed",
|
||||
]);
|
||||
|
||||
/** A Claude Code session running in tmux on this machine. */
|
||||
/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */
|
||||
export const sessions = pgTable("sessions", {
|
||||
id: serial("id").primaryKey(),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
|
||||
tmuxName: text("tmux_name").notNull().unique(),
|
||||
claudeSessionId: text("claude_session_id"),
|
||||
provider: text("provider", { enum: ["claude", "codex"] }).notNull().default("claude"),
|
||||
// Claude session id or Codex thread id — the resume target.
|
||||
conversationId: text("claude_session_id"),
|
||||
// Bumped on every launch/resume; hooks from an older generation are ignored.
|
||||
generation: integer("generation").notNull().default(0),
|
||||
status: sessionStatus("status").notNull().default("starting"),
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Launches the Peppa MCP server; keeps the caller's cwd so .peppa/project.json resolves.
|
||||
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
[ -f "$PEPPA_ROOT/.env" ] && set -a && . "$PEPPA_ROOT/.env" && set +a
|
||||
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
||||
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@"
|
||||
|
||||
@ -1,7 +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"
|
||||
[ -z "${PEPPA_SESSION_ID:-}" ] && { [ "${1:-}" = codex-notify ] || cat >/dev/null; exit 0; }
|
||||
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
||||
mkdir -p "${PEPPA_HOME:-$HOME/.peppa}"
|
||||
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@"
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
// peppa-hook <event>: called by the Claude Code hooks in the per-run settings file
|
||||
// (run-settings.ts). Reads the hook JSON from stdin and updates the Peppa session that
|
||||
// (run-settings.ts), and as Codex's notify program (`peppa-hook codex-notify <json>`). 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 { appendFileSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
@ -19,6 +18,7 @@ import {
|
||||
type SessionView,
|
||||
} from "@peppa/core";
|
||||
import { createDb, type Db } from "@peppa/db";
|
||||
import { peppaHome } from "@peppa/shared";
|
||||
import { HOOK_WAIT_SEC } from "./run-settings.ts";
|
||||
|
||||
interface HookInput {
|
||||
@ -45,7 +45,7 @@ interface AskQuestionItem {
|
||||
multiSelect?: boolean;
|
||||
}
|
||||
|
||||
const LOG = join(homedir(), ".peppa", "hook.log");
|
||||
const LOG = join(peppaHome(), "hook.log");
|
||||
const log = (msg: string) => {
|
||||
try {
|
||||
appendFileSync(LOG, `${new Date().toISOString()} ${msg}\n`);
|
||||
@ -159,6 +159,15 @@ async function askQuestion(db: Db, s: SessionView, input: HookInput) {
|
||||
});
|
||||
}
|
||||
|
||||
/** The agent finished a turn and waits for input: tell the PM unless it already asked. */
|
||||
async function turnEnd(db: Db, s: SessionView, text: string | null) {
|
||||
await logSessionEvent(db, s, "turn_end", { text });
|
||||
if ((await pendingSessionQuestions(db, s.id)).length === 0) {
|
||||
await raiseSessionQuestion(db, s, "attention", clip(text ?? "Сессия закончила ход и ждёт ввода."));
|
||||
}
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||||
}
|
||||
|
||||
async function handle(event: string, input: HookInput): Promise<void> {
|
||||
const sessionId = Number(process.env.PEPPA_SESSION_ID);
|
||||
if (!sessionId) return; // manual `claude`, not started by Peppa
|
||||
@ -173,8 +182,8 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
switch (event) {
|
||||
case "session-start":
|
||||
// Also fires after /clear and /resume, with a new Claude session id.
|
||||
await updateSession(db, s.id, { claudeSessionId: input.session_id ?? null, status: "running", lastActivityAt: now });
|
||||
await logSessionEvent(db, s, "claude_session", { source: input.source, claudeSessionId: input.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":
|
||||
@ -198,14 +207,17 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
await logSessionEvent(db, s, "notification", { type: input.notification_type, message: input.message });
|
||||
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 });
|
||||
case "stop":
|
||||
await turnEnd(db, s, input.last_assistant_message?.trim() || lastAssistantText(input.transcript_path));
|
||||
break;
|
||||
|
||||
case "codex-notify": {
|
||||
// Codex passes one JSON argument; only completed turns are reported.
|
||||
const n = JSON.parse(process.argv[3] ?? "{}") as Record<string, unknown>;
|
||||
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);
|
||||
break;
|
||||
}
|
||||
|
||||
@ -237,9 +249,12 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
|
||||
const event = process.argv[2] ?? "";
|
||||
let raw = "";
|
||||
try {
|
||||
raw = readFileSync(0, "utf8");
|
||||
} catch {}
|
||||
// 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 {}
|
||||
}
|
||||
try {
|
||||
await handle(event, raw ? (JSON.parse(raw) as HookInput) : {});
|
||||
} catch (e) {
|
||||
|
||||
@ -3,3 +3,4 @@ export * from "./sessions.ts";
|
||||
export * as tmux from "./tmux.ts";
|
||||
export * from "./watchdog.ts";
|
||||
export * from "./run-settings.ts";
|
||||
export * from "./providers.ts";
|
||||
|
||||
69
packages/runner/src/providers.ts
Normal file
69
packages/runner/src/providers.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Session } from "@peppa/core";
|
||||
import { writeRunRules, writeRunSettings } from "./run-settings.ts";
|
||||
|
||||
export type Provider = Session["provider"];
|
||||
export const PROVIDERS: Provider[] = ["claude", "codex"];
|
||||
|
||||
const BIN = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const HOOK_BIN = `${BIN}/packages/runner/bin/peppa-hook`;
|
||||
const MCP_BIN = `${BIN}/packages/mcp/bin/peppa-mcp`;
|
||||
|
||||
export interface LaunchContext {
|
||||
sessionId: number;
|
||||
generation: number;
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
rules: string;
|
||||
resume?: string;
|
||||
permissionMode?: string;
|
||||
model?: string;
|
||||
}
|
||||
|
||||
/** argv for one run of the agent CLI (executable first). */
|
||||
export function buildCommand(provider: Provider, c: LaunchContext): string[] {
|
||||
return provider === "codex" ? codexCommand(c) : claudeCommand(c);
|
||||
}
|
||||
|
||||
function claudeCommand(c: LaunchContext): string[] {
|
||||
return [
|
||||
process.env.PEPPA_CLAUDE_BIN ?? "claude",
|
||||
"--settings",
|
||||
writeRunSettings(c.sessionId, c.generation),
|
||||
"--append-system-prompt-file",
|
||||
writeRunRules(c.sessionId, c.generation, c.rules),
|
||||
"--permission-mode",
|
||||
c.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits",
|
||||
...(c.model ? ["--model", c.model] : []),
|
||||
...(c.resume ? ["--resume", c.resume] : []),
|
||||
"--",
|
||||
c.prompt,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Codex has no Claude-style hooks: Peppa only learns about completed turns through the
|
||||
* `notify` callback, and about crashes, stalls and limits through the watchdog.
|
||||
* Permission prompts can't be routed to the PM, so it runs in --full-auto by default.
|
||||
*/
|
||||
function codexCommand(c: LaunchContext): string[] {
|
||||
const toml = (v: unknown) => JSON.stringify(v);
|
||||
return [
|
||||
process.env.PEPPA_CODEX_BIN ?? "codex",
|
||||
"--no-alt-screen",
|
||||
"--cd",
|
||||
c.cwd,
|
||||
...(c.permissionMode ?? process.env.PEPPA_CODEX_MODE ?? "--full-auto").split(" ").filter(Boolean),
|
||||
...(c.model ? ["--model", c.model] : []),
|
||||
"-c",
|
||||
`notify=${toml([HOOK_BIN, "codex-notify"])}`,
|
||||
"-c",
|
||||
`developer_instructions=${toml(c.rules)}`,
|
||||
"-c",
|
||||
`mcp_servers.peppa.command=${toml(MCP_BIN)}`,
|
||||
...(c.resume ? ["resume", c.resume] : []),
|
||||
"--",
|
||||
c.prompt,
|
||||
];
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { peppaHome } from "@peppa/shared";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@ -7,7 +7,7 @@ const HOOK_BIN = resolve(dirname(fileURLToPath(import.meta.url)), "../bin/peppa-
|
||||
/** Blocking hooks wait for the PM this long before falling back to the terminal. */
|
||||
export const HOOK_WAIT_SEC = Number(process.env.PEPPA_HOOK_WAIT_SEC ?? 540);
|
||||
|
||||
export const RUNS_DIR = join(homedir(), ".peppa", "runs");
|
||||
export const RUNS_DIR = join(peppaHome(), "runs");
|
||||
|
||||
/**
|
||||
* Claude settings for one session run, passed with --settings. Hooks live here rather
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { existsSync, realpathSync } from "node:fs";
|
||||
import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
createSession,
|
||||
@ -14,8 +15,10 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { trustWorkspace } from "./claude-config.ts";
|
||||
import { writeRunRules, writeRunSettings } from "./run-settings.ts";
|
||||
import { buildCommand, type Provider } from "./providers.ts";
|
||||
import { runDir } from "./run-settings.ts";
|
||||
import * as tmux from "./tmux.ts";
|
||||
|
||||
export interface StartOptions {
|
||||
@ -25,19 +28,21 @@ export interface StartOptions {
|
||||
model?: string;
|
||||
/** Project for a bare task number ("42"). */
|
||||
defaultProjectKey?: string;
|
||||
provider?: Provider;
|
||||
}
|
||||
|
||||
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
|
||||
|
||||
/** Starts an interactive Claude Code session for a task in a detached tmux session. */
|
||||
/** Starts an interactive agent session (Claude Code or Codex) for a task in a detached tmux session. */
|
||||
export async function startSession(db: Db, taskInput: string, opts: StartOptions = {}): Promise<SessionView> {
|
||||
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 provider = opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
|
||||
if (provider === "claude") trustWorkspace(cwd);
|
||||
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider });
|
||||
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");
|
||||
@ -46,7 +51,7 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions
|
||||
|
||||
/**
|
||||
* Relaunches a finished/failed/rate-limited session in a new generation, continuing
|
||||
* the same Claude conversation (claude --resume) when its id is known.
|
||||
* the same conversation (claude --resume / codex resume) when its id is known.
|
||||
*/
|
||||
export async function resumeSession(db: Db, sessionId: number, opts: StartOptions = {}): Promise<SessionView> {
|
||||
const s = await getSession(db, sessionId);
|
||||
@ -56,14 +61,14 @@ export async function resumeSession(db: Db, sessionId: number, opts: StartOption
|
||||
}
|
||||
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
|
||||
const cwd = realpathSync(project!.workspacePath);
|
||||
trustWorkspace(cwd);
|
||||
if (s.provider === "claude") trustWorkspace(cwd);
|
||||
const prompt = [
|
||||
`Продолжай работу${s.taskKey ? ` над задачей ${s.taskKey}` : ""}: сессия была прервана. Сверься с peppa.get_task и tasks.md.`,
|
||||
opts.prompt,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
return launch(db, s, cwd, { ...opts, prompt, resume: s.claudeSessionId ?? undefined });
|
||||
return launch(db, s, cwd, { ...opts, prompt, resume: s.conversationId ?? undefined });
|
||||
}
|
||||
|
||||
async function launch(
|
||||
@ -73,32 +78,35 @@ async function launch(
|
||||
opts: StartOptions & { prompt: string; resume?: string },
|
||||
): Promise<SessionView> {
|
||||
const generation = s.generation + 1;
|
||||
const settings = writeRunSettings(s.id, generation);
|
||||
const rules = await loadSharedRules();
|
||||
const rulesFile = writeRunRules(s.id, generation, rules.text);
|
||||
const claude = process.env.PEPPA_CLAUDE_BIN ?? "claude";
|
||||
const args = [
|
||||
"--settings",
|
||||
settings,
|
||||
"--append-system-prompt-file",
|
||||
rulesFile,
|
||||
"--permission-mode",
|
||||
opts.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits",
|
||||
...(opts.model ? ["--model", opts.model] : []),
|
||||
...(opts.resume ? ["--resume", opts.resume] : []),
|
||||
"--",
|
||||
opts.prompt,
|
||||
];
|
||||
const argv = buildCommand(s.provider, {
|
||||
sessionId: s.id,
|
||||
generation,
|
||||
cwd,
|
||||
prompt: opts.prompt,
|
||||
rules: rules.text,
|
||||
resume: opts.resume,
|
||||
permissionMode: opts.permissionMode,
|
||||
model: opts.model,
|
||||
});
|
||||
// tmux runs a tiny launch script: keeps long argv (rules, prompts) out of the tmux
|
||||
// command line, and leaves a record of exactly what was started.
|
||||
const launchScript = join(runDir(s.id, generation), "launch.sh");
|
||||
writeFileSync(launchScript, `#!/bin/bash\nexec ${argv.map(shq).join(" ")}\n`);
|
||||
chmodSync(launchScript, 0o700);
|
||||
await updateSession(db, s.id, { generation, status: "starting", endedAt: null });
|
||||
try {
|
||||
await tmux.newSession({
|
||||
name: s.tmuxName,
|
||||
cwd,
|
||||
command: [claude, ...args].map(shq).join(" "),
|
||||
command: shq(launchScript),
|
||||
env: {
|
||||
PEPPA_SESSION_ID: String(s.id),
|
||||
PEPPA_GENERATION: String(generation),
|
||||
PEPPA_PROJECT_DIR: cwd,
|
||||
// Hooks and the MCP server must talk to the same DB / state dir as the runner.
|
||||
DATABASE_URL: loadEnv().DATABASE_URL,
|
||||
...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}),
|
||||
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
|
||||
},
|
||||
});
|
||||
@ -111,6 +119,7 @@ async function launch(
|
||||
generation,
|
||||
tmuxName: s.tmuxName,
|
||||
prompt: opts.prompt,
|
||||
provider: s.provider,
|
||||
rulesSource: rules.source,
|
||||
});
|
||||
return getSession(db, s.id);
|
||||
|
||||
@ -3,9 +3,11 @@ import { promisify } from "node:util";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const TMUX = process.env.PEPPA_TMUX_BIN ?? "tmux";
|
||||
// Separate tmux server (tmux -L) — tests use their own so they never touch real sessions.
|
||||
const SOCKET = process.env.PEPPA_TMUX_SOCKET ? ["-L", process.env.PEPPA_TMUX_SOCKET] : [];
|
||||
|
||||
async function tmux(...args: string[]): Promise<string> {
|
||||
const { stdout } = await run(TMUX, args);
|
||||
const { stdout } = await run(TMUX, [...SOCKET, ...args]);
|
||||
return stdout;
|
||||
}
|
||||
|
||||
@ -56,7 +58,7 @@ export async function capturePane(name: string, history = 0): Promise<string> {
|
||||
export async function sendText(name: string, text: string, submit = true): Promise<void> {
|
||||
const buffer = `peppa-${process.pid}-${Date.now()}`;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const p = spawn(TMUX, ["load-buffer", "-b", buffer, "-"], { stdio: ["pipe", "ignore", "pipe"] });
|
||||
const p = spawn(TMUX, [...SOCKET, "load-buffer", "-b", buffer, "-"], { stdio: ["pipe", "ignore", "pipe"] });
|
||||
let err = "";
|
||||
p.stderr.on("data", (d) => (err += d));
|
||||
p.on("error", reject);
|
||||
|
||||
@ -22,6 +22,11 @@ export interface WatchdogOptions {
|
||||
// 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;
|
||||
|
||||
/** Last non-empty screen lines — what the PM needs to see in an alert. */
|
||||
function screenTail(screen: string, lines: number): string {
|
||||
return screen.split("\n").map((l) => l.trimEnd()).filter(Boolean).slice(-lines).join("\n");
|
||||
}
|
||||
|
||||
// Screen hash per session, kept across ticks.
|
||||
const lastScreen = new Map<number, string>();
|
||||
const limitAlerted = new Set<number>();
|
||||
@ -53,7 +58,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log:
|
||||
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");
|
||||
const tail = screenTail(await tmux.capturePane(s.tmuxName, 200), 15);
|
||||
await updateSession(db, s.id, { status: ok ? "done" : "failed", endedAt: new Date() });
|
||||
await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail });
|
||||
if (!ok) {
|
||||
@ -91,7 +96,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log:
|
||||
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");
|
||||
const tail = screenTail(screen, 12);
|
||||
await raiseSessionQuestion(
|
||||
db,
|
||||
s,
|
||||
|
||||
@ -19,3 +19,8 @@ export function loadEnv(source: NodeJS.ProcessEnv = process.env): Env {
|
||||
env.PEPPA_WORKSPACES = env.PEPPA_WORKSPACES.replace(/^~(?=$|\/)/, homedir());
|
||||
return env;
|
||||
}
|
||||
|
||||
/** Peppa's local state dir (logs, run files, caches). Tests point it elsewhere. */
|
||||
export function peppaHome(): string {
|
||||
return process.env.PEPPA_HOME ?? `${homedir()}/.peppa`;
|
||||
}
|
||||
|
||||
4
packages/testkit/bin/mock-claude
Executable file
4
packages/testkit/bin/mock-claude
Executable file
@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Mock claude CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts).
|
||||
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" claude "$@"
|
||||
4
packages/testkit/bin/mock-codex
Executable file
4
packages/testkit/bin/mock-codex
Executable file
@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Mock codex CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts).
|
||||
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" codex "$@"
|
||||
18
packages/testkit/package.json
Normal file
18
packages/testkit/package.json
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@peppa/testkit",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"typecheck": "tsc -p .",
|
||||
"test": "tsx --test --test-concurrency=1 test/*.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "1.32.2",
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/runner": "workspace:*",
|
||||
"@peppa/shared": "workspace:*",
|
||||
"drizzle-orm": "0.45.4"
|
||||
}
|
||||
}
|
||||
341
packages/testkit/src/mock-agent.ts
Normal file
341
packages/testkit/src/mock-agent.ts
Normal file
@ -0,0 +1,341 @@
|
||||
// Mock Claude Code / Codex CLI. Accepts the same arguments Peppa's runner passes to the
|
||||
// real CLIs, fires the real hooks (Claude) or notify program (Codex), talks to the real
|
||||
// peppa MCP server, and reads terminal input the way a TUI does (raw mode, bracketed
|
||||
// paste, single-key permission dialog). Behaviour comes from a scenario file, so tests can
|
||||
// drive every customer journey: approvals, questions, permissions, limits, hangs, crashes.
|
||||
//
|
||||
// Usage: mock-agent.ts <claude|codex> [cli args...]
|
||||
// Typing "!{json action}" as a prompt runs that action — handy for manual runs.
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import type { Action, Scenario } from "./scenario.ts";
|
||||
|
||||
type Provider = "claude" | "codex";
|
||||
const provider = process.argv[2] as Provider;
|
||||
const argv = process.argv.slice(3);
|
||||
const cwd = process.cwd();
|
||||
const LOG = join(cwd, ".peppa", "mock-log.jsonl");
|
||||
const SCENARIO = join(cwd, ".peppa", "mock-scenario.json");
|
||||
|
||||
function log(ev: string, data: Record<string, unknown> = {}) {
|
||||
appendFileSync(LOG, `${JSON.stringify({ ev, provider, gen: process.env.PEPPA_GENERATION, t: Date.now(), ...data })}\n`);
|
||||
}
|
||||
const out = (s: string) => process.stdout.write(s.replace(/\n/g, "\r\n"));
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
// ── CLI arguments ────────────────────────────────────────────────────────────────
|
||||
interface Args {
|
||||
settings?: string;
|
||||
rulesFile?: string;
|
||||
resume?: string;
|
||||
prompt?: string;
|
||||
notify?: string[];
|
||||
developerInstructions?: string;
|
||||
mcpCommand?: string;
|
||||
}
|
||||
|
||||
function parseArgs(): Args {
|
||||
const a: Args = {};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const x = argv[i]!;
|
||||
if (x === "--") {
|
||||
a.prompt = argv.slice(i + 1).join(" ");
|
||||
break;
|
||||
}
|
||||
if (x === "--settings") a.settings = argv[++i];
|
||||
else if (x === "--append-system-prompt-file") a.rulesFile = argv[++i];
|
||||
else if (x === "--resume") a.resume = argv[++i];
|
||||
else if (x === "resume") a.resume = argv[++i];
|
||||
else if (x === "-c") {
|
||||
const [k, ...v] = argv[++i]!.split("=");
|
||||
const val = JSON.parse(v.join("="));
|
||||
if (k === "notify") a.notify = val;
|
||||
else if (k === "developer_instructions") a.developerInstructions = val;
|
||||
else if (k === "mcp_servers.peppa.command") a.mcpCommand = val;
|
||||
}
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
const args = parseArgs();
|
||||
const conversationId = args.resume ?? randomUUID();
|
||||
let lastMessage = "";
|
||||
|
||||
// ── hooks / notify ───────────────────────────────────────────────────────────────
|
||||
interface HookCmd {
|
||||
command: string;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
function hookFor(event: string, matchQuery?: string): HookCmd | null {
|
||||
if (!args.settings) return null;
|
||||
const groups = JSON.parse(readFileSync(args.settings, "utf8")).hooks?.[event] as
|
||||
| Array<{ matcher?: string; hooks: HookCmd[] }>
|
||||
| undefined;
|
||||
const g = groups?.find((g) => !g.matcher || (matchQuery && new RegExp(`^(${g.matcher})$`).test(matchQuery)));
|
||||
return g?.hooks[0] ?? null;
|
||||
}
|
||||
|
||||
/** Runs a Claude hook like Claude Code does: JSON on stdin, JSON (maybe) on stdout. */
|
||||
function fireHook(event: string, payload: Record<string, unknown>, matchQuery?: string): Promise<any> {
|
||||
const h = hookFor(event, matchQuery);
|
||||
if (!h) return Promise.resolve(null);
|
||||
const input = { session_id: conversationId, cwd, hook_event_name: event, ...payload };
|
||||
return new Promise((resolve) => {
|
||||
const p = spawn("sh", ["-c", h.command], { stdio: ["pipe", "pipe", "inherit"] });
|
||||
let stdout = "";
|
||||
const timer = setTimeout(() => p.kill(), (h.timeout ?? 60) * 1000);
|
||||
p.stdout.on("data", (d) => (stdout += d));
|
||||
p.on("close", () => {
|
||||
clearTimeout(timer);
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = stdout.trim() ? JSON.parse(stdout) : null;
|
||||
} catch {}
|
||||
log("hook", { event, output: parsed });
|
||||
resolve(parsed);
|
||||
});
|
||||
p.stdin.end(JSON.stringify(input));
|
||||
});
|
||||
}
|
||||
|
||||
function codexNotify(message: string): Promise<void> {
|
||||
if (!args.notify?.length) return Promise.resolve();
|
||||
const payload = { type: "agent-turn-complete", "thread-id": conversationId, "turn-id": randomUUID(), cwd, "last-assistant-message": message };
|
||||
return new Promise((resolve) => {
|
||||
const [cmd, ...rest] = args.notify!;
|
||||
const p = spawn(cmd!, [...rest, JSON.stringify(payload)], { stdio: "ignore" });
|
||||
p.on("close", () => {
|
||||
log("notify", { message });
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ── MCP ──────────────────────────────────────────────────────────────────────────
|
||||
let mcp: Client | null = null;
|
||||
|
||||
function mcpCommand(): string {
|
||||
if (args.mcpCommand) return args.mcpCommand;
|
||||
const cfgPath = join(cwd, ".mcp.json");
|
||||
const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf8")) : {};
|
||||
return process.env.PEPPA_MOCK_MCP_BIN ?? cfg.mcpServers?.peppa?.command ?? "peppa-mcp";
|
||||
}
|
||||
|
||||
async function callMcp(tool: string, toolArgs: Record<string, unknown>) {
|
||||
if (!mcp) {
|
||||
mcp = new Client({ name: `mock-${provider}`, version: "0" });
|
||||
await mcp.connect(new StdioClientTransport({ command: mcpCommand(), cwd, env: process.env as Record<string, string> }));
|
||||
}
|
||||
const r = await mcp.callTool({ name: tool, arguments: toolArgs });
|
||||
const text = (r.content as Array<{ text: string }>)[0]?.text ?? "";
|
||||
log("mcp", { tool, args: toolArgs, isError: !!r.isError, text });
|
||||
out(`⏺ peppa.${tool} → ${text.split("\n")[0]}\n`);
|
||||
}
|
||||
|
||||
// ── terminal input ───────────────────────────────────────────────────────────────
|
||||
type Mode = "prompt" | "dialog" | "frozen" | "busy";
|
||||
let mode: Mode = "busy";
|
||||
let buffer = "";
|
||||
let inPaste = false;
|
||||
let dialogResolve: ((key: string) => void) | null = null;
|
||||
const queue: string[] = [];
|
||||
let wake: (() => void) | null = null;
|
||||
|
||||
function onInput(chunk: string) {
|
||||
if (mode === "frozen") return;
|
||||
if (chunk.includes("\x03")) {
|
||||
log("exit", { code: 130, reason: "ctrl-c" });
|
||||
process.exit(130);
|
||||
}
|
||||
if (mode === "dialog" && dialogResolve) {
|
||||
const key = chunk.replace(/\x1b\[20[01]~/g, "").trim()[0];
|
||||
if (key && "123".includes(key)) {
|
||||
const r = dialogResolve;
|
||||
dialogResolve = null;
|
||||
r(key);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < chunk.length; i++) {
|
||||
if (chunk.startsWith("\x1b[200~", i)) {
|
||||
inPaste = true;
|
||||
i += 5;
|
||||
} else if (chunk.startsWith("\x1b[201~", i)) {
|
||||
inPaste = false;
|
||||
i += 5;
|
||||
} else if (chunk[i] === "\r" && !inPaste) {
|
||||
submit(buffer);
|
||||
buffer = "";
|
||||
} else if (chunk[i] === "\x7f") {
|
||||
buffer = buffer.slice(0, -1);
|
||||
} else {
|
||||
buffer += chunk[i] === "\r" ? "\n" : chunk[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function submit(text: string) {
|
||||
if (!text.trim()) return;
|
||||
queue.push(text);
|
||||
wake?.();
|
||||
}
|
||||
|
||||
async function nextPrompt(): Promise<string> {
|
||||
while (!queue.length) await new Promise<void>((r) => (wake = r));
|
||||
wake = null;
|
||||
return queue.shift()!;
|
||||
}
|
||||
|
||||
function dialog(): Promise<string> {
|
||||
mode = "dialog";
|
||||
return new Promise((r) => (dialogResolve = r));
|
||||
}
|
||||
|
||||
// ── actions ──────────────────────────────────────────────────────────────────────
|
||||
/** Returns false when the turn must end early (limit) without a normal Stop. */
|
||||
async function run(action: Action): Promise<boolean> {
|
||||
log("action", { action });
|
||||
if ("say" in action) {
|
||||
lastMessage = action.say;
|
||||
out(`⏺ ${action.say}\n`);
|
||||
} else if ("work" in action) {
|
||||
const frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
|
||||
const end = Date.now() + action.work;
|
||||
for (let i = 0; Date.now() < end; i++) {
|
||||
out(`\r${frames[i % frames.length]} Working… ${Math.round((end - Date.now()) / 100) / 10}s `);
|
||||
await sleep(100);
|
||||
}
|
||||
out("\n");
|
||||
} else if ("sleep" in action) {
|
||||
await sleep(action.sleep);
|
||||
} else if ("mcp" in action) {
|
||||
await callMcp(action.mcp, action.args ?? {});
|
||||
} else if ("permission" in action) {
|
||||
if (provider !== "claude") return true;
|
||||
const { tool, input } = action.permission;
|
||||
const res = await fireHook("PermissionRequest", { tool_name: tool, tool_input: input, permission_suggestions: [{ type: "addRules", rules: [{ toolName: tool }], behavior: "allow", destination: "localSettings" }] }, tool);
|
||||
const decision = res?.hookSpecificOutput?.decision;
|
||||
if (decision) {
|
||||
log("permission", { tool, via: "hook", behavior: decision.behavior, updatedPermissions: !!decision.updatedPermissions, message: decision.message });
|
||||
out(`⏺ ${tool} ${decision.behavior === "allow" ? "allowed" : "denied"} by hook\n`);
|
||||
} else {
|
||||
out(`\n Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and don't ask again for ${tool}\n 3. No, and tell Claude what to do differently (esc)\n`);
|
||||
await fireHook("Notification", { message: `Claude needs your permission to use ${tool}`, notification_type: "permission_prompt" }, "permission_prompt");
|
||||
const key = await dialog();
|
||||
mode = "busy";
|
||||
const behavior = key === "3" ? "deny" : "allow";
|
||||
log("permission", { tool, via: "terminal", key, behavior });
|
||||
out(`⏺ ${tool} ${behavior === "allow" ? "allowed" : "denied"} in terminal (${key})\n`);
|
||||
}
|
||||
} else if ("ask" in action) {
|
||||
if (provider !== "claude") return true;
|
||||
const questions = action.ask.map((q) => ({ question: q.question, header: "Q", options: (q.options ?? []).map((label) => ({ label })), multiSelect: false }));
|
||||
const res = await fireHook("PreToolUse", { tool_name: "AskUserQuestion", tool_input: { questions } }, "AskUserQuestion");
|
||||
const h = res?.hookSpecificOutput;
|
||||
if (h?.permissionDecision === "allow" && h.updatedInput?.answers) {
|
||||
log("ask", { via: "hook", answers: h.updatedInput.answers });
|
||||
out(`⏺ User answered: ${JSON.stringify(h.updatedInput.answers)}\n`);
|
||||
} else if (h?.permissionDecision === "deny") {
|
||||
log("ask", { via: "denied", reason: h.permissionDecisionReason });
|
||||
out(`⏺ AskUserQuestion denied: ${h.permissionDecisionReason}\n`);
|
||||
lastMessage = "Жду ответа PM на вопрос.";
|
||||
} else {
|
||||
log("ask", { via: "terminal" });
|
||||
}
|
||||
} else if ("limit" in action) {
|
||||
if (provider === "claude") {
|
||||
out("⎿ Claude usage limit reached. Your limit will reset at 5pm (Asia/Almaty).\n");
|
||||
await fireHook("StopFailure", { error: "rate_limit", error_details: "Usage limit reached, resets 5pm", last_assistant_message: lastMessage }, "rate_limit");
|
||||
} else {
|
||||
out("■ You've hit your usage limit. Upgrade or try again at 5:00 PM.\n");
|
||||
}
|
||||
log("limit");
|
||||
return false;
|
||||
} else if ("hang" in action) {
|
||||
log("hang");
|
||||
mode = "frozen";
|
||||
await new Promise(() => {});
|
||||
} else if ("crash" in action) {
|
||||
out(`Error: simulated crash (exit ${action.crash})\n`);
|
||||
log("exit", { code: action.crash, reason: "crash" });
|
||||
process.exit(action.crash);
|
||||
} else if ("clear" in action) {
|
||||
if (provider === "claude") {
|
||||
await fireHook("SessionEnd", { reason: "clear" }, "clear");
|
||||
const id = randomUUID();
|
||||
log("clear", { newConversationId: id });
|
||||
await fireHook("SessionStart", { source: "clear", session_id: id }, "clear");
|
||||
}
|
||||
} else if ("exit" in action) {
|
||||
log("exit", { code: 0, reason: "exit" });
|
||||
await fireHook("SessionEnd", { reason: "prompt_input_exit" });
|
||||
process.exit(0);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function turn(prompt: string, actions: Action[] | undefined) {
|
||||
mode = "busy";
|
||||
log("prompt", { prompt });
|
||||
out(`\n> ${prompt.replace(/\n/g, "\n ")}\n`);
|
||||
await fireHook("UserPromptSubmit", { prompt });
|
||||
lastMessage = "";
|
||||
let completed = true;
|
||||
if (prompt.startsWith("!")) {
|
||||
try {
|
||||
completed = await run(JSON.parse(prompt.slice(1)) as Action);
|
||||
} catch (e) {
|
||||
out(`bad action: ${(e as Error).message}\n`);
|
||||
}
|
||||
} else if (actions) {
|
||||
for (const a of actions) {
|
||||
if (!(await run(a))) {
|
||||
completed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lastMessage = `Получил: ${prompt.slice(0, 200)}`;
|
||||
out(`⏺ ${lastMessage}\n`);
|
||||
}
|
||||
if (completed) {
|
||||
if (provider === "claude") await fireHook("Stop", { last_assistant_message: lastMessage || "Готово." });
|
||||
else await codexNotify(lastMessage || "Готово.");
|
||||
}
|
||||
log("turn_end", { completed });
|
||||
mode = "prompt";
|
||||
out("\n> ");
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const scenario: Scenario = existsSync(SCENARIO) ? JSON.parse(readFileSync(SCENARIO, "utf8")) : { turns: [] };
|
||||
const turns = (args.resume && scenario.resumeTurns) || scenario.turns;
|
||||
const rules = args.rulesFile ? readFileSync(args.rulesFile, "utf8") : (args.developerInstructions ?? "");
|
||||
log("start", { argv, resume: args.resume ?? null, conversationId, rulesChars: rules.length, rulesHead: rules.split("\n")[0] });
|
||||
|
||||
if (process.stdin.isTTY) process.stdin.setRawMode(true);
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", onInput);
|
||||
process.stdout.write("\x1b[?2004h"); // ask the terminal for bracketed paste
|
||||
out(`${provider === "claude" ? "✻ Mock Claude Code" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`);
|
||||
|
||||
if (provider === "claude") await fireHook("SessionStart", { source: args.resume ? "resume" : "startup" }, args.resume ? "resume" : "startup");
|
||||
|
||||
let i = 0;
|
||||
if (args.prompt) await turn(args.prompt, turns[i++]);
|
||||
else mode = "prompt";
|
||||
for (;;) {
|
||||
const p = await nextPrompt();
|
||||
await turn(p, turns[i++]);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
log("fatal", { error: String(e?.stack ?? e) });
|
||||
process.exit(1);
|
||||
});
|
||||
27
packages/testkit/src/scenario.ts
Normal file
27
packages/testkit/src/scenario.ts
Normal file
@ -0,0 +1,27 @@
|
||||
// Scenario format for the mock agents. A scenario is a list of turns; the initial
|
||||
// prompt starts turn 0 and every prompt submitted afterwards starts the next turn.
|
||||
// It is read from <workspace>/.peppa/mock-scenario.json.
|
||||
|
||||
export type Action =
|
||||
| { say: string } // print an assistant message (the last one is the turn's final message)
|
||||
| { work: number } // animate a spinner for N ms (screen keeps changing)
|
||||
| { sleep: number }
|
||||
| { mcp: string; args?: Record<string, unknown> } // call a peppa MCP tool
|
||||
| { permission: { tool: string; input: Record<string, unknown> } } // claude: PermissionRequest
|
||||
| { ask: Array<{ question: string; options?: string[] }> } // claude: AskUserQuestion
|
||||
| { limit: true } // usage limit: StopFailure (claude) / banner only (codex)
|
||||
| { hang: true } // freeze: no output, no input handling
|
||||
| { crash: number } // exit with this code
|
||||
| { clear: true } // claude: /clear (SessionEnd + SessionStart with a new id)
|
||||
| { exit: true }; // clean exit (code 0)
|
||||
|
||||
export interface Scenario {
|
||||
turns: Action[][];
|
||||
/** Used instead of `turns` when the CLI is started with a resume target. */
|
||||
resumeTurns?: Action[][];
|
||||
}
|
||||
|
||||
export interface MockLogEntry {
|
||||
ev: string;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
320
packages/testkit/test/cjm.test.ts
Normal file
320
packages/testkit/test/cjm.test.ts
Normal file
@ -0,0 +1,320 @@
|
||||
// Customer journeys of Peppa, end to end: runner → tmux → mock agent CLI → real hooks /
|
||||
// notify → DB ← PM answers (as the Telegram bot will send them) → back into the session.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { core, db, project, runner, teardown, tick, waitFor } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
|
||||
const PM = "telegram" as const;
|
||||
const isPrompt = (needle: string) => (e: { ev: string; prompt?: unknown }) => e.ev === "prompt" && String(e.prompt).includes(needle);
|
||||
|
||||
describe("Claude: task lifecycle", () => {
|
||||
test("proposal → PM approval → apply → review; agent can't self-accept", async () => {
|
||||
const p = await project({
|
||||
turns: [
|
||||
[
|
||||
{ mcp: "get_task", args: { task: "1" } },
|
||||
{ mcp: "update_task", args: { task: "1", status: "proposing", openspec_change: "cjm-1-demo" } },
|
||||
{ work: 300 },
|
||||
{ mcp: "request_approval", args: { task: "1", summary: "Сделаем демо-фичу. Риски: нет." } },
|
||||
{ say: "Proposal готов, жду одобрения." },
|
||||
],
|
||||
[
|
||||
{ mcp: "report_progress", args: { task: "1", text: "реализовал 1/1" } },
|
||||
{ mcp: "update_task", args: { task: "1", status: "done" } },
|
||||
{ mcp: "update_task", args: { task: "1", status: "review", pr_url: "https://git.example/pr/1" } },
|
||||
{ say: "PR открыт." },
|
||||
],
|
||||
],
|
||||
});
|
||||
const sid = await p.start();
|
||||
|
||||
const approval = await p.waitQuestion(sid, "approval");
|
||||
await p.waitStatus(sid, "waiting_input");
|
||||
assert.equal((await p.task()).status, "awaiting_approval");
|
||||
assert.equal((await p.task()).openspecChange, "cjm-1-demo");
|
||||
// The agent already asked, so no extra "attention" ping for the same turn.
|
||||
assert.deepEqual((await p.pending(sid)).map((q) => q.kind), ["approval"]);
|
||||
|
||||
const { delivered } = await runner.answerAndDeliver(db, approval.id, "ок, погнали", PM);
|
||||
assert.ok(delivered);
|
||||
assert.equal((await p.task()).status, "in_progress");
|
||||
await p.waitLog("approval message reaches the agent", isPrompt("одобрил proposal"));
|
||||
|
||||
await p.waitLog("PR turn finished", (e) => e.ev === "turn_end" && e.gen === "1" && p.log().filter((x) => x.ev === "turn_end").length >= 2);
|
||||
const t = await p.task();
|
||||
assert.equal(t.status, "review");
|
||||
assert.equal(t.prUrl, "https://git.example/pr/1");
|
||||
const doneAttempt = p.log().find((e) => e.ev === "mcp" && e.tool === "update_task" && (e.args as { status?: string }).status === "done");
|
||||
assert.equal(doneAttempt?.isError, true, "agent must not be able to mark the task done");
|
||||
|
||||
const attention = await p.waitQuestion(sid, "attention");
|
||||
assert.match(attention.text, /PR открыт/);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("rejected proposal goes back to proposing with the PM's comment", async () => {
|
||||
const p = await project({
|
||||
turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План А для проверки отказа." } }, { say: "Жду." }], [{ say: "Переделал." }]],
|
||||
});
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "approval");
|
||||
await runner.answerAndDeliver(db, q.id, "нет, сделай через очередь", PM);
|
||||
assert.equal((await p.task()).status, "proposing");
|
||||
await p.waitLog("rejection reaches the agent", isPrompt("не одобрил"));
|
||||
assert.ok(p.log().some(isPrompt("сделай через очередь")));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Claude: questions to the PM", () => {
|
||||
test("ask_pm question answered from Telegram is typed into the session", async () => {
|
||||
const p = await project({
|
||||
turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]],
|
||||
});
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
assert.deepEqual(q.options, ["Postgres", "SQLite"]);
|
||||
await p.waitStatus(sid, "waiting_input");
|
||||
await runner.answerAndDeliver(db, q.id, "Postgres", PM);
|
||||
await p.waitLog("answer reaches the agent", isPrompt(`Ответ PM на вопрос #${q.id}: Postgres`));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("multi-line answer arrives as one prompt (bracketed paste)", async () => {
|
||||
const p = await project({ turns: [[{ say: "Что дальше?" }], [{ say: "Понял." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
await runner.answerAndDeliver(db, q.id, "строка один\nстрока два", PM);
|
||||
const e = await p.waitLog("pasted prompt", isPrompt("строка один"));
|
||||
assert.equal(e.prompt, "строка один\nстрока два");
|
||||
assert.equal(p.log().filter((x) => x.ev === "prompt").length, 2, "must not be split into two prompts");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("AskUserQuestion answered in time goes back through the hook", async () => {
|
||||
const p = await project({
|
||||
turns: [[{ ask: [{ question: "Какая БД?", options: ["Postgres", "SQLite"] }, { question: "Нужен Docker?", options: ["Да", "Нет"] }] }, { say: "Ок." }]],
|
||||
});
|
||||
const sid = await p.start();
|
||||
const qs = await waitFor("two hook questions", async () => {
|
||||
const list = (await p.pending(sid)).filter((q) => q.kind === "question");
|
||||
return list.length === 2 && list;
|
||||
});
|
||||
assert.ok(qs.every((q) => q.awaitingHook));
|
||||
await runner.answerAndDeliver(db, qs[0]!.id, "SQLite", PM);
|
||||
await runner.answerAndDeliver(db, qs[1]!.id, "Нет", PM);
|
||||
const e = await p.waitLog("answers via hook", (x) => x.ev === "ask" && x.via === "hook");
|
||||
assert.deepEqual(e.answers, { "Какая БД?": "SQLite", "Нужен Docker?": "Нет" });
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("AskUserQuestion timeout: tool denied, late answer typed into the terminal", async () => {
|
||||
const p = await project({ turns: [[{ ask: [{ question: "Деплоить сегодня?" }] }], [{ say: "Понял, деплою." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
await p.waitLog("hook gives up and denies", (x) => x.ev === "ask" && x.via === "denied", 15000);
|
||||
assert.equal((await core.getQuestion(db, q.id)).awaitingHook, false);
|
||||
await runner.answerAndDeliver(db, q.id, "да", PM);
|
||||
await p.waitLog("late answer typed in", isPrompt(`Ответ PM на вопрос #${q.id}: да`));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("typing in the terminal answers whatever the session was waiting for", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?" } }], [{ say: "Ок." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
await runner.sendToSession(db, sid, "назови peppa-api");
|
||||
await waitFor("answered via terminal", async () => (await core.getQuestion(db, q.id)).answeredVia === "terminal");
|
||||
assert.equal((await core.getQuestion(db, q.id)).answer, "назови peppa-api");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Claude: permissions", () => {
|
||||
for (const [answer, behavior] of [
|
||||
["allow", "allow"],
|
||||
["always", "allow"],
|
||||
["deny", "deny"],
|
||||
] as const) {
|
||||
test(`PM answers "${answer}" in time → hook returns ${behavior}`, async () => {
|
||||
const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "rm -rf build" } } }, { say: "Готово." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "permission");
|
||||
assert.match(q.text, /rm -rf build/);
|
||||
assert.equal((await p.session(sid)).status, "waiting_input");
|
||||
await runner.answerAndDeliver(db, q.id, answer, PM);
|
||||
const e = await p.waitLog("decision via hook", (x) => x.ev === "permission");
|
||||
assert.equal(e.via, "hook");
|
||||
assert.equal(e.behavior, behavior);
|
||||
assert.equal(e.updatedPermissions, answer === "always");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
}
|
||||
|
||||
test("no answer in time → Claude's own dialog; late answer presses the key", async () => {
|
||||
const p = await project({ turns: [[{ permission: { tool: "Write", input: { file_path: "/etc/hosts" } } }, { 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 new Promise((r) => setTimeout(r, 500)); // dialog drawn
|
||||
const { delivered } = await runner.answerAndDeliver(db, q.id, "allow", PM);
|
||||
assert.ok(delivered);
|
||||
const e = await p.waitLog("decision in terminal", (x) => x.ev === "permission");
|
||||
assert.equal(e.via, "terminal");
|
||||
assert.equal(e.key, "1");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Claude: failures and recovery", () => {
|
||||
test("usage limit → rate_limited; resume continues the same conversation in a new generation", async () => {
|
||||
const p = await project({ turns: [[{ work: 200 }, { limit: true }]], resumeTurns: [[{ say: "Продолжаю после лимита." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitStatus(sid, "rate_limited");
|
||||
const alert = await p.waitQuestion(sid, "attention");
|
||||
assert.match(alert.text, /лимит/);
|
||||
const conv = (await p.session(sid)).conversationId;
|
||||
assert.ok(conv);
|
||||
|
||||
await runner.answerAndDeliver(db, alert.id, "ok", PM).catch(() => {});
|
||||
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
|
||||
const resumed = await runner.resumeSession(db, sid);
|
||||
assert.equal(resumed.generation, 2);
|
||||
const start = await p.waitLog("gen 2 started", (e) => e.ev === "start" && e.gen === "2");
|
||||
assert.equal(start.resume, conv);
|
||||
await p.waitLog("resume prompt", (e) => e.ev === "prompt" && e.gen === "2" && String(e.prompt).includes("Продолжай работу"));
|
||||
|
||||
// A late hook from generation 1 must be ignored.
|
||||
execFileSync("bash", ["-c", `echo '{}' | PEPPA_SESSION_ID=${sid} PEPPA_GENERATION=1 ${process.env.PEPPA_MOCK_MCP_BIN!.replace("mcp/bin/peppa-mcp", "runner/bin/peppa-hook")} stop`]);
|
||||
await p.waitLog("gen 2 turn done", (e) => e.ev === "turn_end" && e.gen === "2");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("hang → watchdog marks stalled and alerts; still-running session can't be resumed", async () => {
|
||||
const p = await project({ turns: [[{ say: "Начинаю." }, { hang: true }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("frozen", (e) => e.ev === "hang");
|
||||
await tick(500);
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
await tick(500);
|
||||
await p.waitStatus(sid, "stalled", 3000);
|
||||
const alert = await p.waitQuestion(sid, "attention");
|
||||
assert.match(alert.text, /не меняется/);
|
||||
await assert.rejects(runner.resumeSession(db, sid), /still running/);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("busy agent with a changing screen is not reported as stalled", async () => {
|
||||
const p = await project({ turns: [[{ work: 5000 }, { say: "Долгая работа закончена." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("working", (e) => e.ev === "action" && "work" in (e.action as object));
|
||||
for (let i = 0; i < 4; i++) {
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
await tick(600);
|
||||
assert.notEqual((await p.session(sid)).status, "stalled");
|
||||
}
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("crash → failed with exit code and screen tail; resume relaunches", async () => {
|
||||
const p = await project({ turns: [[{ say: "Сейчас упаду." }, { crash: 3 }]], resumeTurns: [[{ say: "Поднялся." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("crashed", (e) => e.ev === "exit");
|
||||
await waitFor("pane dead", async () => {
|
||||
await tick();
|
||||
return (await p.session(sid)).status === "failed";
|
||||
});
|
||||
const alert = await p.waitQuestion(sid, "attention");
|
||||
assert.match(alert.text, /код 3/);
|
||||
assert.match(alert.text, /simulated crash/);
|
||||
await runner.resumeSession(db, sid);
|
||||
await p.waitLog("relaunched", (e) => e.ev === "turn_end" && e.gen === "2");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("tmux session killed from outside → failed, PM alerted", async () => {
|
||||
const p = await project({ turns: [[{ say: "Работаю." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitStatus(sid, "waiting_input");
|
||||
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
|
||||
await tick();
|
||||
assert.equal((await p.session(sid)).status, "failed");
|
||||
assert.ok((await p.pending(sid)).some((q) => /пропала/.test(q.text)));
|
||||
});
|
||||
|
||||
test("/clear ends the Claude conversation but not the process", async () => {
|
||||
const p = await project({ turns: [[{ clear: true }, { say: "Контекст очищен." }]] });
|
||||
const sid = await p.start();
|
||||
const before = await waitFor("conversation id", async () => (await p.session(sid)).conversationId);
|
||||
const cleared = await p.waitLog("cleared", (e) => e.ev === "clear");
|
||||
await waitFor("new conversation id stored", async () => (await p.session(sid)).conversationId === cleared.newConversationId);
|
||||
assert.notEqual(before, cleared.newConversationId);
|
||||
await p.waitStatus(sid, "waiting_input");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("shared rules are injected into the system prompt", async () => {
|
||||
const p = await project({ turns: [[{ say: "Ок." }]] });
|
||||
const sid = await p.start();
|
||||
const start = await p.waitLog("started", (e) => e.ev === "start");
|
||||
assert.equal(start.rulesHead, "# Правила Пеппы для агентов");
|
||||
assert.ok((start.argv as string[]).includes("--append-system-prompt-file"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Codex", () => {
|
||||
test("turn completion via notify; thread id stored; answer typed in; rules and MCP passed as config", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "get_task", args: { task: "1" } }, { say: "Codex: изучил задачу, вопрос — какой фреймворк?" }], [{ say: "Беру Fastify." }]] });
|
||||
const sid = await p.start({ provider: "codex" });
|
||||
const start = await p.waitLog("started", (e) => e.ev === "start");
|
||||
assert.equal(start.rulesHead, "# Правила Пеппы для агентов");
|
||||
assert.ok((start.argv as string[]).some((a) => a.startsWith("mcp_servers.peppa.command=")));
|
||||
const mcpCall = await p.waitLog("codex reaches peppa MCP", (e) => e.ev === "mcp" && e.tool === "get_task");
|
||||
assert.equal(mcpCall.isError, false);
|
||||
|
||||
const alert = await p.waitQuestion(sid, "attention");
|
||||
assert.match(alert.text, /какой фреймворк/);
|
||||
const s = await p.session(sid);
|
||||
assert.equal(s.provider, "codex");
|
||||
assert.equal(s.status, "waiting_input");
|
||||
assert.equal(s.conversationId, start.conversationId);
|
||||
|
||||
await runner.answerAndDeliver(db, alert.id, "Fastify", PM);
|
||||
await p.waitLog("answer typed in", isPrompt("Fastify"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("usage limit banner (no hook) → watchdog marks rate_limited", async () => {
|
||||
const p = await project({ turns: [[{ limit: true }]] });
|
||||
const sid = await p.start({ provider: "codex" });
|
||||
await p.waitLog("limit shown", (e) => e.ev === "limit");
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
await tick();
|
||||
assert.equal((await p.session(sid)).status, "rate_limited");
|
||||
assert.ok((await p.pending(sid)).some((q) => /лимит/.test(q.text)));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("crash → resume uses `codex resume <thread>`", async () => {
|
||||
const p = await project({ turns: [[{ say: "Первый ход." }], [{ crash: 2 }]], resumeTurns: [[{ say: "Вернулся." }]] });
|
||||
const sid = await p.start({ provider: "codex" });
|
||||
const alert = await p.waitQuestion(sid, "attention");
|
||||
const thread = (await p.session(sid)).conversationId;
|
||||
await runner.answerAndDeliver(db, alert.id, "продолжай", PM);
|
||||
await p.waitLog("crashed", (e) => e.ev === "exit");
|
||||
await waitFor("failed", async () => {
|
||||
await tick();
|
||||
return (await p.session(sid)).status === "failed";
|
||||
});
|
||||
await runner.resumeSession(db, sid);
|
||||
const start = await p.waitLog("gen 2", (e) => e.ev === "start" && e.gen === "2");
|
||||
assert.equal(start.resume, thread);
|
||||
const argv = start.argv as string[];
|
||||
assert.equal(argv[argv.indexOf("resume") + 1], thread);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
123
packages/testkit/test/helpers.ts
Normal file
123
packages/testkit/test/helpers.ts
Normal file
@ -0,0 +1,123 @@
|
||||
// Test harness for the CJM suite: isolated Postgres database, tmux server, state dir and
|
||||
// workspaces; mock agents instead of the real CLIs.
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, existsSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Scenario, MockLogEntry } from "../src/scenario.ts";
|
||||
|
||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||
const TMP = mkdtempSync(join(tmpdir(), "peppa-cjm-"));
|
||||
const TEST_DB = "peppa_test";
|
||||
|
||||
Object.assign(process.env, {
|
||||
DATABASE_URL: `postgres://peppa:peppa@127.0.0.1:5433/${TEST_DB}`,
|
||||
PEPPA_HOME: join(TMP, "home"),
|
||||
PEPPA_TMUX_SOCKET: `peppa-test-${process.pid}`,
|
||||
PEPPA_CLAUDE_BIN: join(ROOT, "packages/testkit/bin/mock-claude"),
|
||||
PEPPA_CODEX_BIN: join(ROOT, "packages/testkit/bin/mock-codex"),
|
||||
PEPPA_MOCK_MCP_BIN: join(ROOT, "packages/mcp/bin/peppa-mcp"),
|
||||
PEPPA_CLAUDE_CONFIG: join(TMP, "claude.json"),
|
||||
PEPPA_HOOK_WAIT_SEC: "4",
|
||||
// Unreachable on purpose: rules come from the cache/local template fallback.
|
||||
GITEA_URL: "http://127.0.0.1:9",
|
||||
GITEA_TOKEN: "",
|
||||
});
|
||||
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });
|
||||
|
||||
execFileSync("bash", [
|
||||
"-c",
|
||||
`docker exec peppa-postgres psql -U peppa -tAc "select 1 from pg_database where datname='${TEST_DB}'" | grep -q 1 || docker exec peppa-postgres createdb -U peppa ${TEST_DB}`,
|
||||
]);
|
||||
|
||||
// Import after the env is set: these modules read it at load time.
|
||||
export const core = await import("@peppa/core");
|
||||
export const runner = await import("@peppa/runner");
|
||||
const dbmod = await import("@peppa/db");
|
||||
const { migrate } = await import("drizzle-orm/postgres-js/migrator");
|
||||
const { sql } = await import("drizzle-orm");
|
||||
|
||||
export const db = dbmod.createDb();
|
||||
await migrate(db, { migrationsFolder: join(ROOT, "packages/db/migrations") });
|
||||
await db.execute(sql`truncate projects restart identity cascade`);
|
||||
|
||||
export async function teardown() {
|
||||
await db.$client.end();
|
||||
try {
|
||||
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-server"], { stdio: "ignore" });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export async function waitFor<T>(label: string, fn: () => Promise<T | null | undefined | false>, timeoutMs = 25000): Promise<T> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let last: unknown;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const v = await fn();
|
||||
if (v) return v as T;
|
||||
} catch (e) {
|
||||
last = e;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
throw new Error(`timed out waiting for: ${label}${last ? ` (last error: ${(last as Error).message})` : ""}`);
|
||||
}
|
||||
|
||||
let keySeq = 0;
|
||||
|
||||
export interface TestProject {
|
||||
key: string;
|
||||
dir: string;
|
||||
taskKey: string;
|
||||
start(opts?: { provider?: "claude" | "codex" }): Promise<number>;
|
||||
log(): MockLogEntry[];
|
||||
waitLog(label: string, pred: (e: MockLogEntry) => boolean, timeoutMs?: number): Promise<MockLogEntry>;
|
||||
session(id: number): ReturnType<typeof core.getSession>;
|
||||
pending(id: number): Promise<Awaited<ReturnType<typeof core.pendingSessionQuestions>>>;
|
||||
waitQuestion(id: number, kind: string, timeoutMs?: number): Promise<Awaited<ReturnType<typeof core.pendingSessionQuestions>>[number]>;
|
||||
waitStatus(id: number, status: string, timeoutMs?: number): Promise<void>;
|
||||
task(): Promise<Awaited<ReturnType<typeof core.resolveTask>>["task"]>;
|
||||
}
|
||||
|
||||
/** A fresh project + task with its own workspace and mock scenario. */
|
||||
export async function project(scenario: Scenario): Promise<TestProject> {
|
||||
const key = `T${String.fromCharCode(65 + Math.floor(keySeq / 26))}${String.fromCharCode(65 + (keySeq % 26))}`;
|
||||
keySeq++;
|
||||
const dir = join(TMP, "ws", key.toLowerCase());
|
||||
mkdirSync(join(dir, ".peppa"), { recursive: true });
|
||||
writeFileSync(join(dir, ".peppa/project.json"), JSON.stringify({ slug: key.toLowerCase(), key, name: key, peppaUrl: "http://test" }));
|
||||
writeFileSync(join(dir, ".mcp.json"), JSON.stringify({ mcpServers: { peppa: { command: process.env.PEPPA_MOCK_MCP_BIN } } }));
|
||||
writeFileSync(join(dir, ".peppa/mock-scenario.json"), JSON.stringify(scenario));
|
||||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: dir });
|
||||
const ref = await core.createTask(db, { projectId: p.id, title: `CJM ${key}`, description: "test task" });
|
||||
const logPath = join(dir, ".peppa/mock-log.jsonl");
|
||||
const log = () =>
|
||||
existsSync(logPath)
|
||||
? readFileSync(logPath, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as MockLogEntry)
|
||||
: [];
|
||||
const tp: TestProject = {
|
||||
key,
|
||||
dir,
|
||||
taskKey: ref.key,
|
||||
async start(opts = {}) {
|
||||
const s = await runner.startSession(db, ref.key, { provider: opts.provider });
|
||||
return s.id;
|
||||
},
|
||||
log,
|
||||
waitLog: (label, pred, t) => waitFor(label, async () => log().find(pred), t),
|
||||
session: (id) => core.getSession(db, id),
|
||||
pending: (id) => core.pendingSessionQuestions(db, id),
|
||||
waitQuestion: (id, kind, t) =>
|
||||
waitFor(`pending ${kind} question`, async () => (await core.pendingSessionQuestions(db, id)).find((q) => q.kind === kind), t),
|
||||
async waitStatus(id, status, t) {
|
||||
await waitFor(`session ${id} status ${status}`, async () => (await core.getSession(db, id)).status === status, t);
|
||||
},
|
||||
task: async () => (await core.resolveTask(db, ref.key)).task,
|
||||
};
|
||||
return tp;
|
||||
}
|
||||
|
||||
export function tick(stallMs = 60_000) {
|
||||
return runner.tick(db, { intervalMs: 0, stallMs });
|
||||
}
|
||||
1
packages/testkit/tsconfig.json
Normal file
1
packages/testkit/tsconfig.json
Normal file
@ -0,0 +1 @@
|
||||
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src", "test"] }
|
||||
21
pnpm-lock.yaml
generated
21
pnpm-lock.yaml
generated
@ -292,6 +292,27 @@ importers:
|
||||
specifier: 4.6.7
|
||||
version: 4.6.7
|
||||
|
||||
packages/testkit:
|
||||
dependencies:
|
||||
'@modelcontextprotocol/sdk':
|
||||
specifier: 1.32.2
|
||||
version: 1.32.2(zod@4.6.7)
|
||||
'@peppa/core':
|
||||
specifier: workspace:*
|
||||
version: link:../core
|
||||
'@peppa/db':
|
||||
specifier: workspace:*
|
||||
version: link:../db
|
||||
'@peppa/runner':
|
||||
specifier: workspace:*
|
||||
version: link:../runner
|
||||
'@peppa/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
drizzle-orm:
|
||||
specifier: 0.45.4
|
||||
version: 0.45.4(postgres@4.1.1)
|
||||
|
||||
packages:
|
||||
|
||||
'@drizzle-team/brocli@0.10.2':
|
||||
|
||||
11
scripts/lib/load-env.sh
Normal file
11
scripts/lib/load-env.sh
Normal file
@ -0,0 +1,11 @@
|
||||
# Sourced by Peppa's bin wrappers: exports .env values without overriding variables that
|
||||
# are already set, so tests (and the runner's per-session env) can point at another DB.
|
||||
_peppa_env="${PEPPA_ROOT:?}/.env"
|
||||
if [ -f "$_peppa_env" ]; then
|
||||
while IFS= read -r _line || [ -n "$_line" ]; do
|
||||
case "$_line" in ''|\#*) continue ;; esac
|
||||
_key="${_line%%=*}"
|
||||
[ -z "${!_key+x}" ] && export "$_line"
|
||||
done < "$_peppa_env"
|
||||
fi
|
||||
unset _peppa_env _line _key
|
||||
@ -72,6 +72,20 @@
|
||||
`openspec status --change <name>`). Статусы задач не меняй. В конце хода напиши, какие
|
||||
статусы нужно проставить.
|
||||
|
||||
## Внешние зависимости — через моки
|
||||
|
||||
Если упираешься во что-то, что от тебя не зависит (нет доступа или токена, сервис или CLI
|
||||
недоступен, нужна чужая авторизация, платный или боевой API, железо), не останавливайся
|
||||
и не жди: сделай мок и продолжай работу.
|
||||
|
||||
- Всё моковое помечай префиксом **`mock`** — в именах файлов, функций, переменных,
|
||||
env и фикстур: `mock-claude`, `mockGiteaClient`, `MOCK_TELEGRAM_TOKEN`,
|
||||
`mock-payload.json`. Так моки легко найти (`grep -ri mock`) и заменить настоящим.
|
||||
- Мок повторяет контракт настоящей зависимости (аргументы, форматы, ошибки), а не
|
||||
просто возвращает «ок», чтобы код поверх него был настоящим.
|
||||
- В отчёте, `report_progress` и PR явно перечисли, что сделано на моках и что нужно для реальной
|
||||
интеграции (какой доступ, у кого).
|
||||
|
||||
## Общие правила
|
||||
|
||||
- Не пушь в основную ветку напрямую, только через PR.
|
||||
|
||||
Loading…
Reference in New Issue
Block a user