peppa/packages/testkit/test/helpers.ts
Асель 9cf0d53303 Add Telegram bot: pairing, durable outbox, answers from buttons and replies
- bot: own Bot API client, long polling with persisted offset, updates
  claimed before acting (no replay after restart), outbox with retries
  (429 retry_after, 5xx), /start pairing code (hashed, single use, 10 min),
  only the paired chat/user is served
- PM questions rendered per kind: approve button / reply to reject,
  option buttons, allow/always/deny, alerts with continue or resume/stop;
  messages are closed with who answered what, incl. terminal answers
- stopping/resuming a session expires its open questions
- CLI: peppa telegram pair|status|unpair; launchd agent for the bot
- testkit: mock-telegram + 11 bot journeys (32 e2e tests, all green)
- fix: keep the tmux server alive when empty (exit-empty off) — a new
  session could die with a server shutting down after the last kill
- fix: test env must load before runner modules (no leaks to real tmux)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:26:58 +05:00

126 lines
5.6 KiB
TypeScript

// Test harness for the CJM suite: isolated Postgres database, tmux server, state dir and
// workspaces; mock agents instead of the real CLIs.
// Import this before anything that pulls in @peppa/runner (statically or via @peppa/bot):
// runner modules read PEPPA_TMUX_SOCKET / PEPPA_HOME when they load.
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, settings, telegram_outbox, telegram_updates 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 });
}