peppa/packages/testkit/test/helpers.ts
peppa-bot 546027bb4e
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1471с
peppa-ci / ci (pull_request) Successful in 29m20s
PEP-277: сторож «прод отстаёт от main» — сообщение суперадминам
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:40:49 +00:00

185 lines
9.2 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",
PEPPA_BRANCH_PROTECT: "off",
PEPPA_TEMPLATE_SYNC: "off",
PEPPA_AGENT_VERSIONS: "off",
PEPPA_DEPLOY_LAG: "off",
// PEP-185: no «Взять в работу?» questions in other suites; pick-question.test.ts turns it on.
PEPPA_PICK_QUESTION: "off",
// PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.
PEPPA_WEB_PROBE: "off",
// PEP-189: the guard runs `docker stop` — never against the real docker of the machine running tests;
// domain-guard.test.ts turns it on with mock-docker.
PEPPA_DOMAIN_GUARD: "off",
PEPPA_ORPHAN_CONTAINERS: "off",
// PEP-222: agents run in containers by default; suites run mock agents directly in tmux unless they ask for a container.
PEPPA_DEFAULT_ISOLATION: "none",
// PEP-153: the message classifier never reaches a real CLI from a test.
PEPPA_INTENT_BIN: join(ROOT, "packages/testkit/bin/mock-intake"),
// PEP-198: agents' questions go straight to the owner in other suites; one-analyst.test.ts turns
// the analyst's relay on. The evening digest and the stuck-story check — only there too.
PEPPA_AGENT_RELAY: "off",
PEPPA_READY_DIGEST: "off",
PEPPA_STUCK_TASKS: "off",
// PEP-266: the launch smoke test starts agents on its own — launch-smoke.test.ts turns it on.
PEPPA_SMOKE: "off",
PEPPA_CONNECTION_CHECK: "off",
// PEP-208: the night silence would hold every message of a suite run at night; night-quiet.test.ts
// turns it on with its own clock.
PEPPA_NIGHT_QUIET: "off",
// PEP-209: a bin started from a worktree reads the main checkout's .env — never in a test.
PEPPA_ENV_FALLBACK: "off",
// PEP-209: «готово» cards go one by one in other suites; accept-screen.test.ts turns the summary on.
PEPPA_ACCEPT_DIGEST: "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})` : ""}`);
}
/**
* PEP-150: failures go to the superadmin, not to the project's owner. Makes one more superadmin
* with Telegram and returns a reader of the «delay» messages queued for them.
*/
let adminSeq = 0;
export async function superadmin(): Promise<() => Promise<string[]>> {
const { telegramOutbox, users } = dbmod;
const { and, eq, like, sql } = await import("drizzle-orm");
const { stripAsIs } = await import("@peppa/shared/i18n");
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
const chat = 990_000 + ++adminSeq;
const login = `mock-superadmin-${process.pid}-${adminSeq}`;
const u = await core.upsertUserFromGitea(db, { id: chat, login }, { access_token: "x" });
await db.update(users).set({ telegramChatId: chat, telegramUserId: chat }).where(eq(users.id, u.id));
// Added to the admins there are: suites that made their own superadmin keep it.
await core.setPlatformAdmins(db, [...(await core.platformAdmins(db)), login]);
return async () =>
(await db.select().from(telegramOutbox).where(and(like(telegramOutbox.dedupeKey, "delay:%"), eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, chat)))).map((r) => stripAsIs(String(r.params.text)));
}
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 });
}