233 lines
12 KiB
TypeScript
233 lines
12 KiB
TypeScript
// PEP-266: the launch smoke test. After every deploy (the service's commit changed) and once an hour
|
||
// the runner service starts each provider that has a usable subscription — Claude, Codex, OpenCode —
|
||
// the real way an agent starts (`startRunner`: tmux, container, subscription, folder trust) in its own
|
||
// worktree of the sandbox project with one short task: «create a file and commit it». A commit within
|
||
// the timeout = the launch works. Results are for the superadmin (Observability, `peppa smoke status`);
|
||
// a provider turning red — one message to the superadmins (`alertAdmins`), not the platform channel.
|
||
import { execFile } from "node:child_process";
|
||
import { existsSync } from "node:fs";
|
||
import { promisify } from "node:util";
|
||
import {
|
||
alertAdmins,
|
||
getProject,
|
||
getSession,
|
||
getSetting,
|
||
deleteSetting,
|
||
clearSmokeRequest,
|
||
isProjectPaused,
|
||
isUsable,
|
||
listSessions,
|
||
logEvent,
|
||
NoCapacityError,
|
||
peppaCommit,
|
||
platformProjectKey,
|
||
poolSubscriptions,
|
||
resolveRunnerSettings,
|
||
setSetting,
|
||
sharedPool,
|
||
type Project,
|
||
PROVIDER_LABEL,
|
||
SMOKE_HISTORY_KEY,
|
||
SMOKE_HISTORY_MAX,
|
||
SMOKE_RUN_KEY,
|
||
SMOKE_REQUEST_KEY,
|
||
smokeHistory,
|
||
smokeTimeoutMin,
|
||
type SmokeItem,
|
||
type SmokeRun,
|
||
type SmokeStatus,
|
||
type SmokeTrigger,
|
||
} from "@peppa/core";
|
||
import type { Db } from "@peppa/db";
|
||
import { loadEnv } from "@peppa/shared";
|
||
import { asIs, m } from "@peppa/shared/i18n";
|
||
import { PROVIDERS, type Provider } from "./providers.ts";
|
||
import { killRunner, startRunner, stopSession } from "./sessions.ts";
|
||
import * as tmux from "./tmux.ts";
|
||
|
||
const run = promisify(execFile);
|
||
|
||
export const SMOKE_FILE = "forge-smoke.txt";
|
||
export const SMOKE_PROMPT = `Проверка запуска агента FORGE. Создай в текущей папке файл ${SMOKE_FILE} с одной строкой ok и закоммить только его: git add ${SMOKE_FILE} && git commit -m "FORGE: проверка запуска". Больше ничего не делай и ни о чём не спрашивай.`;
|
||
|
||
const BOOT = Date.now();
|
||
const num = (v: string | undefined, d: number) => {
|
||
const n = v == null || v.trim() === "" ? NaN : Number(v);
|
||
return Number.isFinite(n) && n >= 0 ? n : d;
|
||
};
|
||
export const smokeEveryMin = () => num(process.env.PEPPA_SMOKE_EVERY_MIN, 60);
|
||
const settleMs = () => num(process.env.PEPPA_SMOKE_SETTLE_SEC, 60) * 1000;
|
||
const smokeProjectKey = () => process.env.PEPPA_SMOKE_PROJECT || platformProjectKey();
|
||
|
||
/** Why a run is due now, or null. */
|
||
async function dueTrigger(db: Db, now: Date): Promise<{ trigger: SmokeTrigger; by?: string | null } | null> {
|
||
const req = await getSetting<{ at: string; by: string | null }>(db, SMOKE_REQUEST_KEY);
|
||
if (req) return { trigger: "manual", by: req.by };
|
||
// Right after a (re)start the web and the agents' relay are still coming up.
|
||
if (Date.now() - BOOT < settleMs()) return null;
|
||
const last = (await smokeHistory(db))[0];
|
||
if (!last || last.commit !== peppaCommit()) return { trigger: "deploy" };
|
||
if (now.getTime() - Date.parse(last.at) >= smokeEveryMin() * 60_000) return { trigger: "hourly" };
|
||
return null;
|
||
}
|
||
|
||
const git = async (cwd: string, ...args: string[]) => (await run("git", args, { cwd, encoding: "utf8" })).stdout.trim();
|
||
|
||
/** The agent committed the file: it is in HEAD of its worktree. */
|
||
async function committed(cwd: string): Promise<boolean> {
|
||
if (!existsSync(cwd)) return false;
|
||
return !!(await git(cwd, "ls-tree", "--name-only", "HEAD", "--", SMOKE_FILE).catch(() => ""));
|
||
}
|
||
|
||
/** Starts one provider; never throws — a start that fails is the result. */
|
||
async function startOne(db: Db, project: Project, provider: Provider, poolId: number | null, now: Date): Promise<SmokeItem> {
|
||
const item: SmokeItem = { provider, status: "running", startedAt: now.toISOString() };
|
||
if (poolId == null) return { provider, status: "skipped", reason: m("нет подписки") };
|
||
const subs = (await poolSubscriptions(db, poolId)).filter((s) => s.provider === provider);
|
||
if (!subs.length) return { provider, status: "skipped", reason: m("нет подписки") };
|
||
if (!subs.some((s) => isUsable(s, now))) return { provider, status: "skipped", reason: m("подписка в лимите или без входа") };
|
||
const rs = await resolveRunnerSettings(db, project.id, null);
|
||
if (rs.maxRunners != null && (await listSessions(db, { active: true, projectId: project.id })).length >= rs.maxRunners) {
|
||
return { provider, status: "skipped", reason: m("у проекта нет места для ещё одного агента") };
|
||
}
|
||
try {
|
||
const s = await startRunner(db, project, null, {
|
||
provider,
|
||
poolId,
|
||
worktree: true,
|
||
name: m("Проверка запуска · {provider}", { provider: PROVIDER_LABEL[provider] }),
|
||
prompt: SMOKE_PROMPT,
|
||
});
|
||
return { ...item, sessionId: s.id, subscriptionId: s.subscriptionId, cwd: s.workspacePath };
|
||
} catch (e) {
|
||
if (e instanceof NoCapacityError) return { provider, status: "skipped", reason: m("на подписках нет места для ещё одного агента") };
|
||
return { provider, status: "failed", sec: 0, reason: m("агент не запустился: {error}", { error: asIs((e as Error).message.slice(0, 300)) }) };
|
||
}
|
||
}
|
||
|
||
async function startRun(db: Db, due: { trigger: SmokeTrigger; by?: string | null }, now: Date, log: (s: string) => void): Promise<SmokeRun | null> {
|
||
await clearSmokeRequest(db);
|
||
const project = await getProject(db, smokeProjectKey()).catch(() => null);
|
||
if (!project) {
|
||
log(`launch smoke: no sandbox project ${smokeProjectKey()}`);
|
||
return null;
|
||
}
|
||
const r: SmokeRun = { id: now.getTime(), at: now.toISOString(), commit: peppaCommit(), trigger: due.trigger, by: due.by ?? null, items: [] };
|
||
if (await isProjectPaused(db, project.id)) {
|
||
r.items = PROVIDERS.map((provider) => ({ provider, status: "skipped" as const, reason: m("проект проверки на паузе") }));
|
||
} else {
|
||
// The platform's shared pool (PEP-76); without one — the sandbox project's own.
|
||
const poolId = (await sharedPool(db))?.id ?? project.subscriptionPoolId ?? null;
|
||
for (const provider of PROVIDERS) r.items.push(await startOne(db, project, provider, poolId, now));
|
||
}
|
||
await setSetting(db, SMOKE_RUN_KEY, r);
|
||
log(`launch smoke (${r.trigger}): ${r.items.map((i) => `${i.provider} ${i.status}`).join(", ")}`);
|
||
return r;
|
||
}
|
||
|
||
/** The agent and its worktree go away; the screen is kept for a failure. */
|
||
async function cleanup(db: Db, project: Project | null, item: SmokeItem, keepScreen: boolean): Promise<void> {
|
||
if (item.sessionId == null) return;
|
||
const s = await getSession(db, item.sessionId).catch(() => null);
|
||
if (s && keepScreen) {
|
||
const screen = await tmux.capturePane(tmux.sessionPane(s)).catch(() => "");
|
||
item.screen = screen.split("\n").map((l) => l.trimEnd()).filter(Boolean).slice(-15).join("\n").slice(-2000);
|
||
}
|
||
if (s) {
|
||
await stopSession(db, s.id).catch(async () => {
|
||
await killRunner(s).catch(() => {});
|
||
});
|
||
}
|
||
if (project && item.cwd && item.cwd !== project.workspacePath && existsSync(item.cwd)) {
|
||
await git(project.workspacePath, "worktree", "remove", "--force", item.cwd).catch(() => {});
|
||
}
|
||
}
|
||
|
||
async function advance(db: Db, r: SmokeRun, now: Date, log: (s: string) => void): Promise<boolean> {
|
||
const project = await getProject(db, smokeProjectKey()).catch(() => null);
|
||
const timeoutMs = smokeTimeoutMin() * 60_000;
|
||
for (const item of r.items) {
|
||
if (item.status !== "running") continue;
|
||
const sec = Math.round((now.getTime() - Date.parse(item.startedAt ?? r.at)) / 1000);
|
||
if (item.cwd && (await committed(item.cwd))) {
|
||
Object.assign(item, { status: "ok", sec });
|
||
await cleanup(db, project, item, false);
|
||
continue;
|
||
}
|
||
const s = item.sessionId != null ? await getSession(db, item.sessionId).catch(() => null) : null;
|
||
if (!s || s.status === "failed" || s.status === "done") {
|
||
// glossary-ignore: итог проверки запуска читает только суперадмин
|
||
Object.assign(item, { status: "failed", sec, reason: m("процесс агента завершился без коммита") });
|
||
await cleanup(db, project, item, true);
|
||
} else if (sec * 1000 >= timeoutMs) {
|
||
// glossary-ignore: итог проверки запуска читает только суперадмин
|
||
Object.assign(item, { status: "failed", sec, reason: m("агент не сделал коммит за {n} мин", { n: smokeTimeoutMin() }) });
|
||
await cleanup(db, project, item, true);
|
||
}
|
||
}
|
||
if (r.items.some((i) => i.status === "running")) {
|
||
await setSetting(db, SMOKE_RUN_KEY, r);
|
||
return false;
|
||
}
|
||
r.finishedAt = now.toISOString();
|
||
const history = await smokeHistory(db);
|
||
await setSetting(db, SMOKE_HISTORY_KEY, [r, ...history].slice(0, SMOKE_HISTORY_MAX));
|
||
await deleteSetting(db, SMOKE_RUN_KEY);
|
||
if (project) {
|
||
await logEvent(db, { projectId: project.id, type: "launch_smoke", payload: { trigger: r.trigger, commit: r.commit, items: r.items.map(({ screen: _s, ...i }) => i) } }).catch(() => {});
|
||
}
|
||
log(`launch smoke done: ${r.items.map((i) => `${i.provider} ${i.status}${i.reason ? ` (${i.reason})` : ""}`).join(", ")}`);
|
||
await tell(db, r, history, log);
|
||
return true;
|
||
}
|
||
|
||
/** The last checked (ok/failed) result of the provider before this run. */
|
||
function previous(history: SmokeRun[], provider: Provider): { status: SmokeStatus; commit: string | null } | null {
|
||
for (const h of history) {
|
||
const i = h.items.find((x) => x.provider === provider && (x.status === "ok" || x.status === "failed"));
|
||
if (i) return { status: i.status, commit: h.commit };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** A provider turning red (or red on a new commit) — one message; back to green — one message. */
|
||
async function tell(db: Db, r: SmokeRun, history: SmokeRun[], log: (s: string) => void): Promise<void> {
|
||
const red: SmokeItem[] = [];
|
||
const green: SmokeItem[] = [];
|
||
for (const i of r.items) {
|
||
const prev = previous(history, i.provider);
|
||
if (i.status === "failed" && (prev?.status !== "failed" || prev.commit !== r.commit)) red.push(i);
|
||
if (i.status === "ok" && prev?.status === "failed") green.push(i);
|
||
}
|
||
const url = `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/observability`;
|
||
const commit = r.commit ? r.commit.slice(0, 7) : "?";
|
||
if (red.length) {
|
||
const list = red.map((i) => m("{provider} — {reason}", { provider: PROVIDER_LABEL[i.provider], reason: i.reason ?? "" })).join("; ");
|
||
await alertAdmins(db, `smoke:fail:${r.id}`, m("🚦 Агенты не запускаются (версия {commit}): {list}. Подробности: {url}", { commit, list, url }), log);
|
||
}
|
||
if (green.length) {
|
||
const list = green.map((i) => PROVIDER_LABEL[i.provider]).join(", ");
|
||
await alertAdmins(db, `smoke:ok:${r.id}`, m("✅ Агенты снова запускаются: {list} (версия {commit}).", { list, commit }), log);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Runner service tick: moves the run going on, or starts one when due (deploy, hourly, asked for).
|
||
* Never waits on the agents — it only looks into their worktrees. `PEPPA_SMOKE=off` turns it off.
|
||
*/
|
||
export async function smokeTick(db: Db, o: { now?: Date; log?: (s: string) => void } = {}): Promise<void> {
|
||
if (process.env.PEPPA_SMOKE === "off") return;
|
||
const now = o.now ?? new Date();
|
||
const log = o.log ?? (() => {});
|
||
const current = await getSetting<SmokeRun>(db, SMOKE_RUN_KEY);
|
||
if (current) {
|
||
await advance(db, current, now, log);
|
||
return;
|
||
}
|
||
const due = await dueTrigger(db, now);
|
||
if (!due) return;
|
||
const started = await startRun(db, due, now, log);
|
||
// Everything skipped or failed at the start: the run is over at once.
|
||
if (started && !started.items.some((i) => i.status === "running")) await advance(db, started, now, log);
|
||
}
|