peppa/packages/testkit/test/helpers.ts
Асель 8fee68f8eb PEP-22: Gitea Actions workflow for Peppa on the PEP-57 runner; testkit creates its DB over SQL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 15:00:28 +05:00

139 lines
6.3 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 postgres from "postgres";
import type { Scenario, MockLogEntry } from "../src/scenario.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-cjm-"));
// PEPPA_TEST_DB lets parallel sessions (one per worktree) run the suite without sharing a database;
// PEPPA_TEST_PG points at another Postgres server (CI job: a service container).
const TEST_DB = process.env.PEPPA_TEST_DB ?? "peppa_test";
const TEST_PG = process.env.PEPPA_TEST_PG ?? "postgres://peppa:peppa@127.0.0.1:5433";
if (!/^[a-z0-9_]+$/.test(TEST_DB)) throw new Error(`bad PEPPA_TEST_DB: ${TEST_DB}`);
Object.assign(process.env, {
DATABASE_URL: `${TEST_PG}/${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",
PEPPA_CI_REGISTER_BIN: join(ROOT, "packages/testkit/bin/mock-ci-register"),
// 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 });
{
const admin = postgres(`${TEST_PG}/postgres`, { max: 1, onnotice: () => {} });
const [exists] = await admin`select 1 from pg_database where datname = ${TEST_DB}`;
if (!exists) await admin.unsafe(`create database ${TEST_DB}`);
await admin.end();
}
// 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, users, settings, telegram_outbox, telegram_updates, oauth_clients 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;
let defaultOwnerId: number | null = null;
/** Projects created by `project()` from now on belong to this user. */
export function setDefaultOwner(userId: number | null) {
defaultOwnerId = userId;
}
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, ownerId: defaultOwnerId });
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 });
}