peppa/packages/testkit/test/helpers.ts
2026-11-16 17:29:29 +05:00

136 lines
6.4 KiB
TypeScript

// Test harness for the CJM suite: isolated SQLite database file, 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, rmSync, 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-"));
// Every test file is its own process with its own temp dir, so its own database file:
// parallel suites (worktrees, CI jobs) never share state.
Object.assign(process.env, {
PEPPA_DB: join(TMP, "peppa.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_OPENCODE_BIN: join(ROOT, "packages/testkit/bin/mock-opencode"),
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: "",
// PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with
// accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on.
PEPPA_PRODUCT_LINK: "off",
// PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.
PEPPA_WEB_PROBE: "off",
});
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });
// 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");
export const db = dbmod.createDb();
dbmod.migrateDb(db);
export async function teardown() {
db.$client.close();
try {
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-server"], { stdio: "ignore" });
} catch {}
// Every run left its temp dir behind (~1 GB after a few hundred runs filled the disk);
// PEPPA_KEEP_TEST_TMP=1 keeps it for debugging.
// Processes of the tmux server just killed may still write a file for a moment (ENOTEMPTY on a
// busy CI runner, PEP-144) — retry instead of failing the whole test file.
if (!process.env.PEPPA_KEEP_TEST_TMP) rmSync(TMP, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
}
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" | "opencode"; subscriptionIds?: number[]; poolId?: number | null }): 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, opts);
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 });
}