peppa/packages/testkit/test/helpers.ts
Асель 3ab408eb70 PEP-57: CI for factory projects — act_runner, template workflow, connect CI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:19:11 +05:00

133 lines
6.0 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-"));
// PEPPA_TEST_DB lets parallel sessions (one per worktree) run the suite without sharing a database.
const TEST_DB = process.env.PEPPA_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",
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 });
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, 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 });
}