peppa/packages/runner/src/ci.ts
Асель 358fb5c0e9 PEP-66: «стори» and «эпики» in web, bot, notifications, MCP texts, help; tab tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:28:42 +05:00

137 lines
7.3 KiB
TypeScript

// CI for factory projects (PEP-57): Gitea Actions on Peppa's act_runner (label
// `peppa-trusted`, docker.sock of the host). The runner is registered only for project repos:
// once for peppa-bot's own repos (scripts/ci-runner-register.sh) and per repo for projects in
// someone else's namespace. Workflow files come from the shared template.
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { giteaForBot, PeppaError, projectHookSecret, type GiteaClient, type Project } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { repoAdmins } from "./share.ts";
import { git, run, templateRepoUrl } from "./git.ts";
/** Files of the CI contract, copied from the template into project repos. */
export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh", ".gitea/workflows/deploy.yml", ".gitea/peppa-deploy.sh"];
/** Starting points copied only when the project has none yet (the project owns them after). */
export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "deploy/Dockerfile.python"];
export const CI_BRANCH = "peppa/ci";
export const CI_SECRET_NAME = "PEPPA_CI_SECRET";
/** Where Gitea webhooks and CI reports reach Peppa. */
export const giteaHookUrl = () => `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/api/hooks/gitea`;
const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot";
/**
* Registers an act_runner for one scope. Default: `docker exec` into the peppa-act-runner
* container (infra/act-runner); PEPPA_CI_REGISTER_BIN replaces it (tests: a mock script).
* The token goes through the environment, never the command line.
*/
export async function registerCiRunner(name: string, token: string): Promise<void> {
const env = { ...process.env, PEPPA_RUNNER_TOKEN: token };
const bin = process.env.PEPPA_CI_REGISTER_BIN;
if (bin) await run(bin, [name], { env });
else await run("docker", ["exec", "-e", "PEPPA_RUNNER_TOKEN", process.env.PEPPA_CI_RUNNER_CONTAINER ?? "peppa-act-runner", "peppa-runner-register", name], { env });
}
/** Runs `fn` with the first repo admin client that succeeds. */
async function asAdmin<T>(clients: GiteaClient[], what: string, fn: (c: GiteaClient) => Promise<T>): Promise<T> {
let last: unknown;
for (const c of clients) {
try {
return await fn(c);
} catch (e) {
last = e;
}
}
throw new PeppaError(`${what}: ${(last as Error | undefined)?.message ?? "нет доступа к репозиторию"}`);
}
export interface CiSetup {
/** "bot" — covered by the runner of peppa-bot's repos; "repo" — registered for this repo. */
runner: "bot" | "repo";
}
/** Runner coverage, the Actions secret for CI reports and the webhook. Idempotent. */
export async function setupCi(db: Db, project: Project): Promise<CiSetup> {
const clients = await repoAdmins(db, project);
if (!clients.length) throw new PeppaError("Нет доступа к Gitea");
let runner: CiSetup["runner"] = "bot";
if (project.giteaOwner !== botLogin()) {
const token = await asAdmin(clients, "Токен регистрации раннера", (c) => c.runnerRegistrationToken(project.giteaOwner, project.giteaRepo));
await registerCiRunner(`repo-${project.giteaOwner}--${project.giteaRepo}`, token);
runner = "repo";
}
const secret = projectHookSecret(project.id);
await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, secret));
// PR and push events (preview stands, merges) — signed with the same secret.
await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, ["pull_request", "push"]));
return { runner };
}
export interface ConnectCiResult extends CiSetup {
/** PR with the workflow files; null when the default branch already has them. */
prUrl: string | null;
}
/**
* "Connect CI" for an existing project: runner + secret, then a PR from Peppa that adds the
* workflow files from the template and an empty `checks` in .peppa/project.json.
*/
export async function connectCi(db: Db, project: Project, o: { templateUrl?: string; log?: (s: string) => void } = {}): Promise<ConnectCiResult> {
const log = o.log ?? (() => {});
log("runner + secret");
const setup = await setupCi(db, project);
const bot = giteaForBot();
const repo = await bot.getRepo(project.giteaOwner, project.giteaRepo);
if (!repo) throw new PeppaError(`Репозиторий ${project.giteaOwner}/${project.giteaRepo} не найден`);
const base = project.defaultBranch;
const work = mkdtempSync(join(tmpdir(), "peppa-ci-"));
try {
log("clone");
const dest = join(work, "repo");
const tpl = join(work, "tpl");
await git(work, "clone", "-q", repo.clone_url, dest);
await git(work, "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl);
await git(dest, "checkout", "-q", "-B", CI_BRANCH, `origin/${base}`);
for (const f of [...CI_FILES, ...CD_SCAFFOLD.filter((f) => !existsSync(join(dest, f)))]) {
mkdirSync(dirname(join(dest, f)), { recursive: true });
cpSync(join(tpl, f), join(dest, f));
}
const pf = join(dest, ".peppa/project.json");
const data = existsSync(pf) ? (JSON.parse(readFileSync(pf, "utf8")) as Record<string, unknown>) : { slug: project.slug, key: project.key, name: project.name, peppaUrl: loadEnv().PEPPA_WEB_URL };
if (!data.checks) {
data.checks = {};
mkdirSync(dirname(pf), { recursive: true });
writeFileSync(pf, `${JSON.stringify(data, null, 2)}\n`);
}
await git(dest, "add", "-A");
const { stdout: staged } = await git(dest, "diff", "--cached", "--name-only");
if (!staged.trim()) return { ...setup, prUrl: null };
log("push");
await git(dest, "-c", "user.name=Peppa", "-c", `user.email=${botLogin()}@telecom.quest`, "commit", "-qm", "Подключить CI Пеппы (Gitea Actions)");
await git(dest, "push", "-q", "-f", "origin", `HEAD:refs/heads/${CI_BRANCH}`);
const open = await bot.openPullForBranch(project.giteaOwner, project.giteaRepo, CI_BRANCH);
const pr =
open ??
(await bot.createPullRequest(project.giteaOwner, project.giteaRepo, {
head: CI_BRANCH,
base,
title: "Подключить CI Пеппы",
body: [
"PR от Пеппы (PEP-57): проверки на каждый PR через Gitea Actions.",
"",
`- ${CI_FILES.map((f) => `\`${f}\``).join(", ")} — из шаблона, под стек не меняются;`,
"- команды проверок — в `.peppa/project.json` → `checks` (`install`, `lint`, `typecheck`, `test`, `build`); пустая команда = шаг пропущен.",
"- деплой (preview на PR, staging на мерж, прод по кнопке PM) — `.peppa/project.json` → `deploy` + `Dockerfile` (заготовки в `deploy/`); без `deploy` шаг пропускается.",
"",
"Заполнить `checks` — первая стори агента в проекте. Изменение конвейера требует ревью PM.",
].join("\n"),
}));
return { ...setup, prUrl: pr.html_url };
} finally {
rmSync(work, { recursive: true, force: true });
}
}