diff --git a/AGENTS.md b/AGENTS.md index ce892198..77320aea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ - **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` +- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) diff --git a/infra/act-runner/config.yaml b/infra/act-runner/config.yaml new file mode 100644 index 00000000..03fe7506 --- /dev/null +++ b/infra/act-runner/config.yaml @@ -0,0 +1,23 @@ +# Общий конфиг всех регистраций act_runner Пеппы (каждая — в /data/runners/<имя>/). +log: + level: info +runner: + file: .runner + # Mac — и сборка, и стенды: не больше 2 job одновременно на регистрацию. + capacity: 2 + timeout: 1h + fetch_timeout: 5s + fetch_interval: 2s + labels: + - "peppa-trusted:docker://gitea/runner-images:ubuntu-latest" +cache: + enabled: true +container: + # Сеть Traefik: job видит gitea и стенды проектов по именам контейнеров. + network: traefik_default + privileged: false + # Пусто = docker.sock монтируется в контейнеры job'ов (docker build / compose в деплое). + docker_host: "" + force_pull: false +host: + workdir_parent: /data/host diff --git a/infra/act-runner/docker-compose.yml b/infra/act-runner/docker-compose.yml new file mode 100644 index 00000000..00395d56 --- /dev/null +++ b/infra/act-runner/docker-compose.yml @@ -0,0 +1,30 @@ +# act_runner для Gitea Actions проектов Пеппы (PEP-57). +# Метка `peppa-trusted`: job'ы идут в контейнерах с docker.sock хоста (сборка образов и +# деплой). Поэтому раннер регистрируется ТОЛЬКО на репозитории проектов Пеппы: на +# пользователя peppa-bot (его репо) и по одному на репо проекта другого владельца +# (`peppa ci connect`). Глобальной (инстанс) регистрации нет и быть не должно. +# docker compose -f infra/act-runner/docker-compose.yml up -d +# scripts/ci-runner-register.sh peppa-bot — регистрация на репо peppa-bot +name: peppa-ci +services: + act-runner: + image: gitea/act_runner:0.2.11 + container_name: peppa-act-runner + restart: unless-stopped + entrypoint: ["/sbin/tini", "--", "/peppa/supervise.sh"] + environment: + # Gitea в той же docker-сети Traefik — раннер ходит к ней напрямую, мимо Cloudflare. + GITEA_INSTANCE_URL: http://gitea:3000 + volumes: + - ./config.yaml:/etc/act_runner/config.yaml:ro + - ./supervise.sh:/peppa/supervise.sh:ro + - ./register.sh:/usr/local/bin/peppa-runner-register:ro + - peppa-act-runner:/data + - /var/run/docker.sock:/var/run/docker.sock + networks: + - traefik_default +volumes: + peppa-act-runner: +networks: + traefik_default: + external: true diff --git a/infra/act-runner/register.sh b/infra/act-runner/register.sh new file mode 100755 index 00000000..59ae2841 --- /dev/null +++ b/infra/act-runner/register.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# peppa-runner-register <имя> (токен регистрации — в переменной PEPPA_RUNNER_TOKEN) +# Регистрирует раннер в /data/runners/<имя>/; supervise.sh запустит его демона. +set -eu +name="$1" +case "$name" in *[!a-zA-Z0-9._-]*|"") echo "bad name: $name" >&2; exit 2;; esac +: "${PEPPA_RUNNER_TOKEN:?PEPPA_RUNNER_TOKEN is required}" +d="/data/runners/$name" +mkdir -p "$d" +cd "$d" +rm -f .runner .pid +act_runner register --no-interactive --config /etc/act_runner/config.yaml \ + --instance "$GITEA_INSTANCE_URL" --token "$PEPPA_RUNNER_TOKEN" --name "peppa-$name" \ + --labels "peppa-trusted:docker://gitea/runner-images:ubuntu-latest" +echo "registered peppa-$name" diff --git a/infra/act-runner/supervise.sh b/infra/act-runner/supervise.sh new file mode 100755 index 00000000..55fc1090 --- /dev/null +++ b/infra/act-runner/supervise.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# Держит по одному `act_runner daemon` на каждую регистрацию /data/runners/<имя>/.runner; +# новые регистрации (peppa-runner-register) и упавшие демоны подхватываются за 10 секунд. +mkdir -p /data/runners +while :; do + for d in /data/runners/*/; do + [ -f "$d.runner" ] || continue + name=$(basename "$d") + if [ -f "$d.pid" ] && kill -0 "$(cat "$d.pid")" 2>/dev/null; then continue; fi + echo "[supervise] start $name" + (cd "$d" && exec act_runner daemon --config /etc/act_runner/config.yaml 2>&1) | sed "s/^/[$name] /" & + echo $! > "$d.pid" + done + sleep 10 +done diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/pep-57-ci-cd/design.md index d7b83f18..e7334f63 100644 --- a/openspec/changes/pep-57-ci-cd/design.md +++ b/openspec/changes/pep-57-ci-cd/design.md @@ -48,3 +48,21 @@ Gitea 1.22 на `git.telecom.quest`, Actions в конфиге явно не н 1. act_runner + включение Actions; 2. шаблон и проект-образец (SBX) проходят CI; 3. вебхуки и гейты; 4. staging/preview; 5. прод и откат; 6. перевод самой Пеппы. Существующие проекты получают workflow отдельным PR от Пеппы («подключить CI»). + +## Уточнения при реализации + +- **Actions в Gitea 1.22 включены по умолчанию** (`has_actions` у репозиториев) — app.ini не + правили, Gitea не перезапускали. Экшены (`actions/checkout`) берутся с github.com. +- **Регистрация раннера — не глобальная.** Глобальный раннер выполнял бы workflow любого из + ~11 тыс. аккаунтов с docker.sock хоста. Поэтому один контейнер `peppa-act-runner` держит + несколько регистраций (`/data/runners/<имя>/.runner`, `supervise.sh`): на пользователя + `peppa-bot` (все его репо) и по одной на репо проекта в чужом пространстве (токен + регистрации — клиентом владельца репо). Job'ы — в сети `traefik_default`, Gitea для раннера + — `http://gitea:3000`. +- **Логи job недоступны через API Gitea 1.22** (ни REST, ни web-маршрут по токену). Поэтому + шаг `.gitea/peppa-check.sh` сам пишет статус коммита `peppa/<проверка>` и отправляет в + Пеппу отчёт с хвостом лога (200 строк), подписанный HMAC секретом Actions + `PEPPA_CI_SECRET` = `projectHookSecret(project.id)` (производный от `PEPPA_SECRET`, в БД не + хранится). Тот же секрет — у вебхука Gitea проекта. +- **Статусы**: `install` сообщает только о провале; «N из N» считается по статусам + `peppa/*` головного SHA. diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md index 43f59de1..768d3037 100644 --- a/openspec/changes/pep-57-ci-cd/tasks.md +++ b/openspec/changes/pep-57-ci-cd/tasks.md @@ -4,12 +4,12 @@ ## 0. Перед стартом -- [ ] 0.1 Получить ответы PM на «Решения PM» в proposal (request_approval — это архитектурные решения); убедиться, что PEP-16 (закрытый вход) сделан — без него этап 1 не начинать +- [x] 0.1 Получить ответы PM на «Решения PM» в proposal (request_approval — это архитектурные решения); убедиться, что PEP-16 (закрытый вход) сделан — без него этап 1 не начинать ## 1. CI -- [ ] 1.1 `infra/`: act_runner в docker (метка `peppa-trusted`), включить Actions в Gitea; проверка: тестовый workflow в `peppa-bot/sandbox` зелёный -- [ ] 1.2 Шаблон: `.gitea/workflows/ci.yml` (читает `checks` из `.peppa/project.json`), поля `checks`/`deploy` в project.json, раздел в RULES.md «перед PR запусти checks локально»; залить шаблон +- [x] 1.1 `infra/`: act_runner в docker (метка `peppa-trusted`), включить Actions в Gitea; проверка: тестовый workflow в `peppa-bot/sandbox` зелёный +- [x] 1.2 Шаблон: `.gitea/workflows/ci.yml` (читает `checks` из `.peppa/project.json`), поля `checks`/`deploy` в project.json, раздел в RULES.md «перед PR запусти checks локально»; залить шаблон - [ ] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX ## 2. Обратная связь и гейты diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index cf2b4576..0714401e 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -39,7 +39,7 @@ import { type TaskStatus, } from "@peppa/core"; import { createDb } from "@peppa/db"; -import { answerAndDeliver, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { answerAndDeliver, connectCi, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { loadEnv } from "@peppa/shared"; @@ -49,6 +49,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa project add [--owner peppa] [--repo ] [--path ] (register only) peppa project owner peppa project list + peppa ci connect [KEY] (runner + secret + PR with the CI workflow from the template) peppa goal add [KEY] [-d <description>] peppa goal list [KEY] peppa task add [KEY] <title> [-g <goal-id>] [-d <description>] @@ -168,6 +169,13 @@ async function main(): Promise<void> { case "project list": for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`); break; + case "ci connect": { + const [key] = withKey(args, 0); + const p = await getProject(db, key); + const r = await connectCi(db, p, { log: (step) => console.log(`… ${step}`) }); + console.log(`${p.key}: runner=${r.runner}, ${r.prUrl ? `PR ${r.prUrl}` : "workflow already on the default branch"}`); + break; + } case "goal add": { const [key, [title]] = withKey(args, 1); if (!title) throw new PeppaError("usage: peppa goal add [KEY] <title>"); diff --git a/packages/core/src/crypto.ts b/packages/core/src/crypto.ts index e970226a..bcb3a7e5 100644 --- a/packages/core/src/crypto.ts +++ b/packages/core/src/crypto.ts @@ -45,3 +45,14 @@ export function verify<T>(token: string | undefined): T | null { } export const hashToken = (s: string) => createHmac("sha256", key("hash")).update(s).digest("hex"); + +/** Per-project secret for Gitea webhooks and CI reports (Actions secret PEPPA_CI_SECRET). */ +export const projectHookSecret = (projectId: number) => createHmac("sha256", key("ci")).update(String(projectId)).digest("hex"); + +/** Checks `X-Gitea-Signature` (hex HMAC-SHA256 of the raw body) against the project's secret. */ +export function verifyHookSignature(projectId: number, body: string, signature: string | null | undefined): boolean { + if (!signature) return false; + const expected = createHmac("sha256", projectHookSecret(projectId)).update(body).digest(); + const given = Buffer.from(signature.trim().toLowerCase(), "hex"); + return given.length === expected.length && timingSafeEqual(given, expected); +} diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index 5bb1e099..8ea94ac3 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -25,6 +25,36 @@ export interface GiteaRepo { html_url: string; permissions?: { admin: boolean; push: boolean; pull: boolean }; } +export interface GiteaPull { + number: number; + state: "open" | "closed"; + title: string; + body?: string; + html_url: string; + merged: boolean; + mergeable: boolean; + head: { ref: string; sha: string; repo?: { full_name: string } | null }; + base: { ref: string }; +} +export interface GiteaCommitStatus { + context: string; + status: "pending" | "success" | "error" | "failure" | "warning"; + target_url?: string; + description?: string; + updated_at?: string; +} +export interface GiteaCombinedStatus { + state: "" | "pending" | "success" | "error" | "failure" | "warning"; + sha: string; + statuses: GiteaCommitStatus[] | null; +} +export interface GiteaHook { + id: number; + type: string; + active: boolean; + events: string[]; + config: { url: string; content_type: string }; +} export interface OAuthTokens { access_token: string; refresh_token?: string; @@ -128,6 +158,75 @@ export class GiteaClient { } } + private repoPath(owner: string, repo: string) { + return `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`; + } + + createPullRequest(owner: string, repo: string, pr: { head: string; base: string; title: string; body?: string }) { + return this.request<GiteaPull>("POST", `${this.repoPath(owner, repo)}/pulls`, pr); + } + + getPullRequest(owner: string, repo: string, n: number) { + return this.request<GiteaPull>("GET", `${this.repoPath(owner, repo)}/pulls/${n}`); + } + + async openPullForBranch(owner: string, repo: string, branch: string): Promise<GiteaPull | null> { + const pulls = await this.request<GiteaPull[]>("GET", `${this.repoPath(owner, repo)}/pulls?state=open&limit=50`); + return pulls.find((p) => p.head.ref === branch) ?? null; + } + + /** Paths changed by a pull request. */ + async pullFiles(owner: string, repo: string, n: number): Promise<string[]> { + const files = await this.request<Array<{ filename: string }>>("GET", `${this.repoPath(owner, repo)}/pulls/${n}/files?limit=100`); + return files.map((f) => f.filename); + } + + /** Merges a PR; `sha` guards against merging a head that changed since the checks. */ + mergePullRequest(owner: string, repo: string, n: number, sha?: string) { + return this.request<void>("POST", `${this.repoPath(owner, repo)}/pulls/${n}/merge`, { Do: "merge", head_commit_id: sha, delete_branch_after_merge: true }); + } + + combinedStatus(owner: string, repo: string, ref: string) { + return this.request<GiteaCombinedStatus>("GET", `${this.repoPath(owner, repo)}/commits/${encodeURIComponent(ref)}/status`); + } + + /** A file at `ref` as text (null if absent). */ + async fileText(owner: string, repo: string, path: string, ref: string): Promise<string | null> { + try { + const f = await this.request<{ content: string }>("GET", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`); + return Buffer.from(f.content, "base64").toString("utf8"); + } catch (e) { + if (e instanceof GiteaError && e.status === 404) return null; + throw e; + } + } + + setActionsSecret(owner: string, repo: string, name: string, data: string) { + return this.request<void>("PUT", `${this.repoPath(owner, repo)}/actions/secrets/${encodeURIComponent(name)}`, { data }); + } + + /** act_runner registration token: for one repo, or (no args) for the token owner's repos. */ + async runnerRegistrationToken(owner?: string, repo?: string): Promise<string> { + const path = owner && repo ? `${this.repoPath(owner, repo)}/actions/runners/registration-token` : "/user/actions/runners/registration-token"; + return (await this.request<{ token: string }>("GET", path)).token; + } + + listHooks(owner: string, repo: string) { + return this.request<GiteaHook[]>("GET", `${this.repoPath(owner, repo)}/hooks`); + } + + /** Creates the webhook for `url`, or updates the existing one (secret, events). */ + async upsertHook(owner: string, repo: string, url: string, secret: string, events: string[]): Promise<GiteaHook> { + const body = { type: "gitea", active: true, events, branch_filter: "*", config: { url, content_type: "json", secret } }; + const existing = (await this.listHooks(owner, repo)).find((h) => h.config.url === url); + if (existing) return this.request<GiteaHook>("PATCH", `${this.repoPath(owner, repo)}/hooks/${existing.id}`, body); + return this.request<GiteaHook>("POST", `${this.repoPath(owner, repo)}/hooks`, body); + } + + createTag(owner: string, repo: string, tag: string, target: string, message?: string) { + return this.request<{ name: string }>("POST", `${this.repoPath(owner, repo)}/tags`, { tag_name: tag, target, message }); + } + deleteRepo(owner: string, repo: string) { return this.request<void>("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`); } diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts new file mode 100644 index 00000000..c1bfc310 --- /dev/null +++ b/packages/runner/src/ci.ts @@ -0,0 +1,127 @@ +// 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"]; +export const CI_BRANCH = "peppa/ci"; +export const CI_SECRET_NAME = "PEPPA_CI_SECRET"; + +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 and the Actions secret for CI reports. 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"; + } + await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, projectHookSecret(project.id))); + 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) { + 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`); пустая команда = шаг пропущен.", + "", + "Заполнить `checks` — первая задача агента в проекте. Изменение конвейера требует ревью PM.", + ].join("\n"), + })); + return { ...setup, prUrl: pr.html_url }; + } finally { + rmSync(work, { recursive: true, force: true }); + } +} diff --git a/packages/runner/src/git.ts b/packages/runner/src/git.ts new file mode 100644 index 00000000..c84ad563 --- /dev/null +++ b/packages/runner/src/git.ts @@ -0,0 +1,26 @@ +// git as peppa-bot: the per-repo `peppa` credential helper answers for the Gitea host. +import { execFile } from "node:child_process"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { loadEnv, peppaRoot } from "@peppa/shared"; + +export const run = promisify(execFile); + +export function credentialHelper(): string { + return `!${peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../.."))}/packages/cli/bin/git-credential-peppa`; +} + +export function git(cwd: string, ...args: string[]) { + // The peppa helper answers for the Gitea host with the bot token; nothing else is consulted. + return run("git", ["-c", "credential.helper=", "-c", `credential.helper=${credentialHelper()}`, ...args], { + cwd, + env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, + }); +} + +/** Clone URL of the shared project template (override for tests). */ +export function templateRepoUrl(override?: string): string { + const env = loadEnv(); + return override ?? process.env.PEPPA_TEMPLATE_URL ?? `${env.GITEA_URL}/${env.GITEA_TEMPLATE_REPO}.git`; +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 0d4c1e1d..4517fa98 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -10,3 +10,4 @@ export * from "./claude-auth.ts"; export * from "./share.ts"; export * from "./limits.ts"; export * from "./monitor.ts"; +export * from "./ci.ts"; diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts index 7bc6cf4e..67a46894 100644 --- a/packages/runner/src/provision.ts +++ b/packages/runner/src/provision.ts @@ -1,18 +1,15 @@ // Creates or connects a project: Gitea repo with peppa-bot as collaborator, files from the // shared template, OpenSpec, a working copy for agent sessions, and the Peppa record. // Used by the web (acting as the logged-in user) and the CLI (acting as peppa-bot). -import { execFile } from "node:child_process"; import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { promisify } from "node:util"; +import { join } from "node:path"; import { createProject, PeppaError, type GiteaClient, type Project } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; -import { loadEnv, peppaRoot } from "@peppa/shared"; +import { loadEnv } from "@peppa/shared"; import { eq, or } from "drizzle-orm"; - -const run = promisify(execFile); +import { setupCi } from "./ci.ts"; +import { credentialHelper, git, run, templateRepoUrl } from "./git.ts"; export interface ProvisionOptions { /** Acts in Gitea: the user's OAuth client, or the bot's. */ @@ -80,7 +77,7 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Pro log("template"); const tpl = mkdtempSync(join(tmpdir(), "peppa-tpl-")); try { - await git(tmpdir(), "clone", "-q", "--depth", "1", o.templateUrl ?? process.env.PEPPA_TEMPLATE_URL ?? `${env.GITEA_URL}/${env.GITEA_TEMPLATE_REPO}.git`, tpl); + await git(tmpdir(), "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl); for (const entry of readdirSync(tpl)) { if (TEMPLATE_SKIP.has(entry) || existsSync(join(dest, entry))) continue; cpSync(join(tpl, entry), join(dest, entry), { recursive: true }); @@ -113,7 +110,7 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Pro } // 6. Peppa record — last, so a failure above leaves nothing in Peppa - return await createProject(db, { + const project = await createProject(db, { slug: o.slug, key, name: o.name, @@ -122,6 +119,10 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Pro workspacePath: dest, ownerId: o.ownerId ?? null, }); + // 7. CI (PEP-57): runner, Actions secret, webhook. Best effort — `peppa ci connect` redoes it. + log("ci"); + await setupCi(db, project).catch((e) => log(`ci: ${(e as Error).message}`)); + return project; } catch (e) { rmSync(dest, { recursive: true, force: true }); if (e instanceof PeppaError) throw e; @@ -131,15 +132,3 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Pro ); } } - -function credentialHelper(): string { - return `!${peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../.."))}/packages/cli/bin/git-credential-peppa`; -} - -function git(cwd: string, ...args: string[]) { - // The peppa helper answers for the Gitea host with the bot token; nothing else is consulted. - return run("git", ["-c", "credential.helper=", "-c", `credential.helper=${credentialHelper()}`, ...args], { - cwd, - env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, - }); -} diff --git a/packages/runner/src/share.ts b/packages/runner/src/share.ts index da860f1f..b4e667d1 100644 --- a/packages/runner/src/share.ts +++ b/packages/runner/src/share.ts @@ -17,7 +17,7 @@ import type { Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; /** Gitea clients that may administer the project's repo: its owner, then peppa-bot. */ -async function repoAdmins(db: Db, project: Project): Promise<GiteaClient[]> { +export async function repoAdmins(db: Db, project: Project): Promise<GiteaClient[]> { const out: GiteaClient[] = []; const owner = project.ownerId ? await getUser(db, project.ownerId) : null; if (owner) { diff --git a/packages/shared/src/task-key.ts b/packages/shared/src/task-key.ts index 7c582dea..f05bd6de 100644 --- a/packages/shared/src/task-key.ts +++ b/packages/shared/src/task-key.ts @@ -25,4 +25,19 @@ export interface PeppaProjectFile { key: string; name: string; peppaUrl: string; + /** CI commands (PEP-57); a missing command = the step is skipped. `install` runs first. */ + checks?: Partial<Record<CheckName | "install", string>>; + /** Deployment (PEP-57): compose file with Traefik labels, service, port, health path. */ + deploy?: { + compose?: string; + service?: string; + port?: number; + health?: string; + migrate?: string; + hosts?: Partial<Record<"preview" | "staging" | "prod", string>>; + }; } + +/** CI checks of a project, in the order the workflow runs them. */ +export const CHECK_NAMES = ["lint", "typecheck", "test", "build"] as const; +export type CheckName = (typeof CHECK_NAMES)[number]; diff --git a/packages/testkit/bin/mock-ci-register b/packages/testkit/bin/mock-ci-register new file mode 100755 index 00000000..fcd10f83 --- /dev/null +++ b/packages/testkit/bin/mock-ci-register @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# mock-ci-register <name> — stands in for `docker exec peppa-act-runner peppa-runner-register` +# (PEPPA_CI_REGISTER_BIN). Same contract: token in PEPPA_RUNNER_TOKEN, name as the argument. +set -euo pipefail +: "${PEPPA_RUNNER_TOKEN:?PEPPA_RUNNER_TOKEN is required}" +printf '{"name":"%s","token":"%s"}\n' "$1" "$PEPPA_RUNNER_TOKEN" >> "${PEPPA_HOME:?}/mock-ci-register.jsonl" +echo "registered peppa-$1" diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 2c3605b3..e587790d 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -1,6 +1,9 @@ // Mock Gitea for tests: the API endpoints Peppa uses plus OAuth token exchange. Repos are // local bare git repositories, so clone/push against `clone_url` really works. +// CI (PEP-57): pull requests, commit statuses, Actions secrets, runner tokens, webhooks +// (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags. import { execFileSync } from "node:child_process"; +import { createHmac } from "node:crypto"; import { mkdirSync } from "node:fs"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; @@ -14,6 +17,22 @@ interface MockRepo { collaborators: Record<string, string>; admins: Set<string>; private: boolean; + pulls: MockPull[]; + statuses: Map<string, Array<{ context: string; status: string; target_url?: string; description?: string }>>; + secrets: Record<string, string>; + hooks: Array<{ id: number; url: string; secret: string; events: string[] }>; + tags: Array<{ name: string; target: string }>; +} + +export interface MockPull { + number: number; + head: string; + base: string; + title: string; + body: string; + state: "open" | "closed"; + merged: boolean; + mergeable: boolean; } export interface MockGiteaUser { @@ -27,6 +46,7 @@ export class MockGitea { readonly repos = new Map<string, MockRepo>(); readonly users = new Map<string, MockGiteaUser>(); readonly oauthCodes = new Map<string, string>(); // code → token + readonly runnerTokens: Array<{ scope: string; token: string }> = []; private seq = 1; private server: Server | null = null; url = ""; @@ -72,7 +92,20 @@ export class MockGitea { } execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git add -A && git -c user.name=t -c user.email=t@t commit -qm init && git push -q ${JSON.stringify(path)} main`]); } - const repo: MockRepo = { id: this.seq++, owner, name, path, collaborators: {}, admins: new Set(opts.admins ?? [owner]), private: opts.private ?? true }; + const repo: MockRepo = { + id: this.seq++, + owner, + name, + path, + collaborators: {}, + admins: new Set(opts.admins ?? [owner]), + pulls: [], + statuses: new Map(), + secrets: {}, + hooks: [], + tags: [], + private: opts.private ?? true, + }; this.repos.set(`${owner}/${name}`, repo); return repo; } @@ -89,6 +122,114 @@ export class MockGitea { return execFileSync("git", ["--git-dir", r.path, "show", `main:${file}`], { encoding: "utf8" }); } + repo(owner: string, name: string): MockRepo { + const r = this.repos.get(`${owner}/${name}`); + if (!r) throw new Error(`mock-gitea: no repo ${owner}/${name}`); + return r; + } + + /** SHA of a branch (or any rev) in the repo. */ + sha(owner: string, name: string, rev: string): string { + return execFileSync("git", ["--git-dir", this.repo(owner, name).path, "rev-parse", rev], { encoding: "utf8" }).trim(); + } + + /** Files on any rev. */ + filesAt(owner: string, name: string, rev: string): string[] { + return execFileSync("git", ["--git-dir", this.repo(owner, name).path, "ls-tree", "-r", "--name-only", rev], { encoding: "utf8" }).trim().split("\n"); + } + + /** Pushes `files` as a new commit on `branch` (created from main if missing); returns its SHA. */ + commit(owner: string, name: string, branch: string, files: Record<string, string>, message = "change"): string { + const r = this.repo(owner, name); + const work = `${r.path}-c${this.seq++}`; + execFileSync("git", ["clone", "-q", r.path, work]); + const has = execFileSync("git", ["-C", work, "ls-remote", "--heads", "origin", branch], { encoding: "utf8" }).trim(); + execFileSync("git", ["-C", work, "checkout", "-q", "-B", branch, ...(has ? [`origin/${branch}`] : [])]); + for (const [f, text] of Object.entries(files)) { + mkdirSync(join(work, f, ".."), { recursive: true }); + execFileSync("bash", ["-c", `cat > ${JSON.stringify(join(work, f))}`], { input: text }); + } + execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git add -A && git -c user.name=t -c user.email=t@t commit -qm ${JSON.stringify(message)} && git push -q origin ${branch}`]); + return this.sha(owner, name, branch); + } + + /** A PR from `head` into main, as an agent would open it. */ + openPull(owner: string, name: string, head: string, title = head, body = ""): MockPull { + const r = this.repo(owner, name); + const pr: MockPull = { number: r.pulls.length + 1, head, base: "main", title, body, state: "open", merged: false, mergeable: true }; + r.pulls.push(pr); + return pr; + } + + /** Records a commit status, like a CI job does. */ + setStatus(owner: string, name: string, sha: string, context: string, status: string, extra: { target_url?: string; description?: string } = {}) { + const r = this.repo(owner, name); + const list = (r.statuses.get(sha) ?? []).filter((s) => s.context !== context); + list.push({ context, status, ...extra }); + r.statuses.set(sha, list); + } + + /** Sends a webhook event to every hook of the repo subscribed to it; returns HTTP statuses. */ + async deliver(owner: string, name: string, event: string, payload: object): Promise<number[]> { + const r = this.repo(owner, name); + const out: number[] = []; + for (const h of r.hooks.filter((h) => h.events.includes(event) || h.events.includes(event.split("_")[0]!))) { + const body = JSON.stringify(payload); + const res = await fetch(h.url, { + method: "POST", + headers: { "Content-Type": "application/json", "X-Gitea-Event": event, "X-Gitea-Signature": createHmac("sha256", h.secret).update(body).digest("hex") }, + body, + }); + out.push(res.status); + } + return out; + } + + pullJson(r: MockRepo, p: MockPull) { + let sha = ""; + try { + sha = this.sha(r.owner, r.name, p.head); + } catch {} + return { + number: p.number, + state: p.state, + title: p.title, + body: p.body, + html_url: `${this.url}/${r.owner}/${r.name}/pulls/${p.number}`, + merged: p.merged, + mergeable: p.mergeable, + head: { ref: p.head, sha, repo: { full_name: `${r.owner}/${r.name}` } }, + base: { ref: p.base }, + }; + } + + private combined(r: MockRepo, ref: string) { + let sha = ref; + try { + sha = this.sha(r.owner, r.name, ref); + } catch {} + const statuses = r.statuses.get(sha) ?? []; + const st = statuses.map((s) => s.status); + const state = !st.length ? "" : st.some((s) => s === "failure" || s === "error") ? "failure" : st.some((s) => s === "pending") ? "pending" : "success"; + return { state, sha, statuses }; + } + + private merge(r: MockRepo, p: MockPull) { + const g = (...a: string[]) => execFileSync("git", ["--git-dir", r.path, ...a], { encoding: "utf8" }).trim(); + const head = g("rev-parse", p.head); + const base = g("rev-parse", p.base); + let isAncestor = true; + try { + g("merge-base", "--is-ancestor", base, head); + } catch { + isAncestor = false; + } + const target = isAncestor ? head : g("-c", "user.name=t", "-c", "user.email=t@t", "commit-tree", `${head}^{tree}`, "-p", base, "-p", head, "-m", `Merge pull request #${p.number}`); + g("update-ref", `refs/heads/${p.base}`, target); + p.merged = true; + p.state = "closed"; + } + private isEmpty(r: MockRepo) { return execFileSync("git", ["--git-dir", r.path, "for-each-ref"], { encoding: "utf8" }).trim() === ""; } @@ -139,6 +280,17 @@ export class MockGitea { const u = [...this.users.values()].find((x) => x.login.toLowerCase() === want); return u ? { status: 200, body: { id: u.id, login: u.login, full_name: u.login } } : { status: 404, body: { message: "user does not exist" } }; } + if (method === "GET" && path === "/api/v1/user/actions/runners/registration-token") { + const token = `mock-runner-token-${me.login}-${this.seq++}`; + this.runnerTokens.push({ scope: `user:${me.login}`, token }); + return { status: 200, body: { token } }; + } + if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/(.+)$/))) { + const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); + if (!r) return { status: 404, body: { message: "not found" } }; + const res = this.handleRepo(r, me, method, m[3]!, url, body); + if (res) return res; + } if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; @@ -166,4 +318,79 @@ export class MockGitea { } return { status: 404, body: { message: `mock-gitea: ${method} ${path}` } }; } + + private handleRepo(r: MockRepo, me: MockGiteaUser, method: string, sub: string, url: string, body: Record<string, unknown>): { status: number; body?: unknown } | null { + const isAdmin = r.admins.has(me.login); + const canWrite = isAdmin || r.owner === me.login || r.collaborators[me.login] === "write" || r.collaborators[me.login] === "admin"; + const q = new URLSearchParams(url.split("?")[1] ?? ""); + let m: RegExpMatchArray | null = null; + if (method === "GET" && sub === "actions/runners/registration-token") { + if (!isAdmin) return { status: 403, body: { message: "forbidden" } }; + const token = `mock-runner-token-${r.owner}-${r.name}-${this.seq++}`; + this.runnerTokens.push({ scope: `repo:${r.owner}/${r.name}`, token }); + return { status: 200, body: { token } }; + } + if (method === "PUT" && (m = sub.match(/^actions\/secrets\/([^/]+)$/))) { + if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } }; + r.secrets[decodeURIComponent(m[1]!)] = String(body.data); + return { status: 201 }; + } + if (method === "GET" && sub === "hooks") return { status: 200, body: r.hooks.map((h) => ({ id: h.id, type: "gitea", active: true, events: h.events, config: { url: h.url, content_type: "json" } })) }; + if ((method === "POST" && sub === "hooks") || (method === "PATCH" && (m = sub.match(/^hooks\/(\d+)$/)))) { + if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } }; + const cfg = body.config as { url: string; secret: string }; + const events = body.events as string[]; + let h = m ? r.hooks.find((x) => x.id === Number(m![1])) : undefined; + if (h) Object.assign(h, { url: cfg.url, secret: cfg.secret, events }); + else r.hooks.push((h = { id: this.seq++, url: cfg.url, secret: cfg.secret, events })); + return { status: m ? 200 : 201, body: { id: h.id, type: "gitea", active: true, events, config: { url: h.url, content_type: "json" } } }; + } + if (method === "POST" && sub === "pulls") { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + return { status: 201, body: this.pullJson(r, this.openPull(r.owner, r.name, String(body.head), String(body.title), String(body.body ?? ""))) }; + } + if (method === "GET" && sub === "pulls") { + const state = q.get("state") ?? "open"; + return { status: 200, body: r.pulls.filter((p) => state === "all" || p.state === state).map((p) => this.pullJson(r, p)) }; + } + if ((m = sub.match(/^pulls\/(\d+)(\/files|\/merge)?$/))) { + const p = r.pulls.find((x) => x.number === Number(m![1])); + if (!p) return { status: 404, body: { message: "pull not found" } }; + if (method === "GET" && !m[2]) return { status: 200, body: this.pullJson(r, p) }; + if (method === "GET" && m[2] === "/files") { + const out = execFileSync("git", ["--git-dir", r.path, "diff", "--name-only", `${p.base}...${p.head}`], { encoding: "utf8" }).trim(); + return { status: 200, body: out ? out.split("\n").map((filename) => ({ filename })) : [] }; + } + if (method === "POST" && m[2] === "/merge") { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + if (p.merged) return { status: 405, body: { message: "already merged" } }; + if (!p.mergeable) return { status: 405, body: { message: "Please try again later: merge conflict" } }; + if (body.head_commit_id && body.head_commit_id !== this.sha(r.owner, r.name, p.head)) return { status: 409, body: { message: "head out of date" } }; + this.merge(r, p); + return { status: 200 }; + } + } + if (method === "POST" && (m = sub.match(/^statuses\/([0-9a-f]+)$/))) { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + this.setStatus(r.owner, r.name, m[1]!, String(body.context), String(body.state), { target_url: body.target_url as string, description: body.description as string }); + return { status: 201, body: {} }; + } + if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) }; + if (method === "GET" && (m = sub.match(/^contents\/(.+)$/))) { + try { + const text = execFileSync("git", ["--git-dir", r.path, "show", `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + return { status: 200, body: { content: Buffer.from(text).toString("base64"), encoding: "base64" } }; + } catch { + return { status: 404, body: { message: "not found" } }; + } + } + if (method === "POST" && sub === "tags") { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + const target = this.sha(r.owner, r.name, String(body.target)); + execFileSync("git", ["--git-dir", r.path, "tag", String(body.tag_name), target]); + r.tags.push({ name: String(body.tag_name), target }); + return { status: 201, body: { name: body.tag_name, commit: { sha: target } } }; + } + return null; + } } diff --git a/packages/testkit/test/ci.test.ts b/packages/testkit/test/ci.test.ts new file mode 100644 index 00000000..9143d755 --- /dev/null +++ b/packages/testkit/test/ci.test.ts @@ -0,0 +1,142 @@ +// PEP-57: CI for factory projects — runner registration, Actions secret, "connect CI" PR, +// and the template's check step (.gitea/peppa-check.sh) against mock Gitea. +import assert from "node:assert/strict"; +import { execFile, execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import { core, db, runner, teardown } from "./helpers.ts"; +import { CHECK_NAMES } from "@peppa/shared"; +import { MockGitea } from "../src/mock-gitea.ts"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const TMP = mkdtempSync(join(tmpdir(), "peppa-ci-")); +process.env.PEPPA_SECRET = "mock-secret-for-tests"; + +const gitea = new MockGitea(join(TMP, "gitea")); +const BOT = { id: 61, login: "peppa-bot", token: "mock-token-bot" }; +const OWNER = { id: 62, login: "mock-dana", token: "mock-token-dana" }; +let templateUrl = ""; +let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>; +let seq = 0; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); + gitea.addUser(OWNER); + const tpl = gitea.addRepo("peppa-bot", "template"); + execFileSync("bash", ["-c", `cd ${JSON.stringify(join(ROOT, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]); + templateUrl = tpl.path; + owner = await core.upsertUserFromGitea(db, OWNER, { access_token: OWNER.token }); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +const registrations = () => { + const f = join(process.env.PEPPA_HOME!, "mock-ci-register.jsonl"); + return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { name: string; token: string }) : []; +}; + +/** A project whose repo (with an initial commit) lives in mock Gitea under `ns`. */ +async function ciProject(ns: string, files: Record<string, string> = {}) { + const key = `CI${String.fromCharCode(65 + seq++)}`; + const slug = key.toLowerCase(); + gitea.addRepo(ns, slug, { + admins: [ns], + files: { "README.md": "# x\n", ".peppa/project.json": JSON.stringify({ slug, key, name: key, peppaUrl: "http://peppa.test" }), ...files }, + }); + if (ns !== BOT.login) gitea.repo(ns, slug).collaborators[BOT.login] = "write"; + const p = await core.createProject(db, { slug, key, name: key, giteaOwner: ns, workspacePath: join(TMP, "ws", slug), ownerId: ns === BOT.login ? null : owner.id }); + return p; +} + +describe("CI: connect a project", () => { + test("peppa-bot's repo: covered by the bot runner, secret set, PR with the workflow and empty checks", async () => { + const p = await ciProject(BOT.login); + const before = registrations().length; + const r = await runner.connectCi(db, p, { templateUrl }); + assert.equal(r.runner, "bot"); + assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos"); + const repo = gitea.repo(BOT.login, p.giteaRepo); + assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id)); + assert.ok(r.prUrl?.endsWith("/pulls/1")); + const pr = repo.pulls[0]!; + assert.equal(pr.head, runner.CI_BRANCH); + const files = gitea.filesAt(BOT.login, p.giteaRepo, pr.head); + for (const f of runner.CI_FILES) assert.ok(files.includes(f), f); + const pj = JSON.parse(execFileSync("git", ["--git-dir", repo.path, "show", `${pr.head}:.peppa/project.json`], { encoding: "utf8" })); + assert.deepEqual(pj.checks, {}); + assert.equal(pj.key, p.key, "the project's own fields are kept"); + + // Running again re-uses the open PR; after the merge there is nothing to connect. + assert.equal((await runner.connectCi(db, p, { templateUrl })).prUrl, r.prUrl); + await core.giteaForBot().mergePullRequest(BOT.login, p.giteaRepo, 1); + assert.equal((await runner.connectCi(db, p, { templateUrl })).prUrl, null); + }); + + test("repo in the owner's namespace: per-repo runner registered with the owner's token", async () => { + const p = await ciProject(OWNER.login); + const r = await runner.connectCi(db, p, { templateUrl }); + assert.equal(r.runner, "repo"); + const reg = registrations().at(-1)!; + assert.equal(reg.name, `repo-${OWNER.login}--${p.giteaRepo}`); + assert.ok(gitea.runnerTokens.some((t) => t.token === reg.token && t.scope === `repo:${OWNER.login}/${p.giteaRepo}`)); + assert.equal(gitea.repo(OWNER.login, p.giteaRepo).secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id)); + }); + + test("template workflow: trusted runner, no fork PRs, every check as its own step", () => { + const wf = readFileSync(join(ROOT, "template/.gitea/workflows/ci.yml"), "utf8"); + assert.match(wf, /runs-on: peppa-trusted/); + assert.match(wf, /head\.repo\.full_name == github\.repository/); + for (const c of ["install", ...CHECK_NAMES]) assert.match(wf, new RegExp(`peppa-check\\.sh ${c}\\b`)); + }); +}); + +describe("CI: check step (.gitea/peppa-check.sh)", () => { + const script = join(ROOT, "template/.gitea/peppa-check.sh"); + function workdir(checks: Record<string, string>) { + const d = mkdtempSync(join(TMP, "job-")); + mkdirSync(join(d, ".peppa")); + writeFileSync(join(d, ".peppa/project.json"), JSON.stringify({ slug: "x", key: "X", name: "x", peppaUrl: "", checks })); + return d; + } + // Async: the script talks to mock Gitea, which runs in this process. + const step = (cwd: string, check: string, env: Record<string, string> = {}) => + new Promise<{ status: number; stdout: string }>((done) => { + execFile("bash", [script, check], { cwd, encoding: "utf8", env: { ...process.env, GITHUB_ACTIONS: "", ...env } }, (err, stdout) => + done({ status: err ? Number((err as { code?: number }).code ?? 1) : 0, stdout }), + ); + }); + + test("locally: runs the command, keeps its exit code; a missing command is skipped", async () => { + const d = workdir({ test: "echo testing; exit 3", lint: "echo fine" }); + const t = await step(d, "test"); + assert.equal(t.status, 3); + assert.match(t.stdout, /testing/); + assert.equal((await step(d, "lint")).status, 0); + const b = await step(d, "build"); + assert.equal(b.status, 0); + assert.match(b.stdout, /не настроена/); + }); + + test("in CI: writes the commit status peppa/<check> to Gitea", async () => { + const p = await ciProject(BOT.login); + const sha = gitea.sha(BOT.login, p.giteaRepo, "main"); + const d = workdir({ test: "exit 1", build: "true" }); + const env = { GITHUB_ACTIONS: "true", GITHUB_SERVER_URL: gitea.url, GITHUB_REPOSITORY: `${BOT.login}/${p.giteaRepo}`, GITHUB_RUN_NUMBER: "7", PEPPA_SHA: sha, GITEA_TOKEN: BOT.token }; + assert.equal((await step(d, "test", env)).status, 1); + assert.equal((await step(d, "build", env)).status, 0); + const st = await core.giteaForBot().combinedStatus(BOT.login, p.giteaRepo, sha); + assert.equal(st.state, "failure"); + const byCtx = Object.fromEntries(st.statuses!.map((s) => [s.context, s])); + assert.equal(byCtx["peppa/test"]?.status, "failure"); + assert.equal(byCtx["peppa/build"]?.status, "success"); + assert.equal(byCtx["peppa/test"]?.target_url, `/${BOT.login}/${p.giteaRepo}/actions/runs/7`); + }); +}); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index a4be3443..87ff6cd4 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -23,6 +23,7 @@ Object.assign(process.env, { 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: "", diff --git a/scripts/ci-runner-register.sh b/scripts/ci-runner-register.sh new file mode 100755 index 00000000..c3296e95 --- /dev/null +++ b/scripts/ci-runner-register.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Регистрирует act_runner Пеппы на репозитории peppa-bot (уровень пользователя) или на +# один репозиторий: scripts/ci-runner-register.sh [owner/repo] +# Токен регистрации берётся токеном peppa-bot из .env и в вывод не попадает. +set -euo pipefail +cd "$(dirname "$0")/.." +set -a; . "${PEPPA_ENV_FILE:-./.env}"; set +a +if [[ $# -ge 1 ]]; then + path="repos/$1/actions/runners/registration-token"; name="repo-${1//\//--}" +else + path="user/actions/runners/registration-token"; name="peppa-bot" +fi +PEPPA_RUNNER_TOKEN=$(curl -fsS -H "Authorization: token $GITEA_TOKEN" "$GITEA_URL/api/v1/$path" | python3 -c 'import json,sys;print(json.load(sys.stdin)["token"])') +export PEPPA_RUNNER_TOKEN +docker exec -e PEPPA_RUNNER_TOKEN peppa-act-runner peppa-runner-register "$name" diff --git a/template/.gitea/peppa-check.sh b/template/.gitea/peppa-check.sh new file mode 100644 index 00000000..3a87f0ed --- /dev/null +++ b/template/.gitea/peppa-check.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Шаг CI Пеппы: bash .gitea/peppa-check.sh <проверка> +# Команда — .peppa/project.json → checks.<проверка>; нет команды — шаг пропущен. +# Результат: статус коммита «peppa/<проверка>» в Gitea и отчёт в Пеппу с хвостом лога +# (подпись HMAC-SHA256 секретом PEPPA_CI_SECRET). Шаг «install» сообщает только о провале. +# Локально (без CI): bash .gitea/peppa-check.sh test — просто выполнит команду. +set -uo pipefail +check="$1" +cfg=.peppa/project.json +cmd=$(jq -r --arg c "$check" '.checks[$c] // empty' "$cfg" 2>/dev/null) +if [[ -z "$cmd" ]]; then + echo "peppa: проверка «$check» не настроена — пропуск" + exit 0 +fi +log=$(mktemp) +started=$(date +%s) +bash -o pipefail -c "$cmd" 2>&1 | tee "$log" +code=${PIPESTATUS[0]} +took=$(($(date +%s) - started)) +[[ -n "${GITHUB_ACTIONS:-}" ]] || exit "$code" + +state=success +[[ $code -eq 0 ]] || state=failure +[[ $check == install && $state == success ]] && exit 0 +sha="${PEPPA_SHA:-$GITHUB_SHA}" +# Относительная ссылка, как у статусов самой Gitea (GITHUB_SERVER_URL здесь внутренний). +run_url="/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_NUMBER" + +if [[ -n "${GITEA_TOKEN:-}" ]]; then + jq -n --arg s "$state" --arg c "peppa/$check" --arg u "$run_url" --arg d "$check: $state за ${took}с" \ + '{state:$s, context:$c, target_url:$u, description:$d}' | + curl -fsS -o /dev/null -X POST -H "Authorization: token $GITEA_TOKEN" -H "Content-Type: application/json" \ + --data-binary @- "$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/statuses/$sha" || + echo "peppa: не удалось записать статус коммита" +fi + +peppa_url=$(jq -r '.peppaUrl // empty' "$cfg") +if [[ -n "$peppa_url" && -n "${PEPPA_CI_SECRET:-}" ]]; then + body=$(tail -n 200 "$log" | jq -Rs --arg repo "$GITHUB_REPOSITORY" --arg sha "$sha" --arg branch "${PEPPA_BRANCH:-}" \ + --arg pr "${PEPPA_PR:-}" --arg check "$check" --arg state "$state" --arg url "$run_url" --argjson took "$took" \ + '{repository:$repo, sha:$sha, branch:$branch, pr:($pr|tonumber? // null), check:$check, state:$state, run_url:$url, duration_sec:$took, log_tail:.}') + sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}') + curl -fsS -o /dev/null -m 20 -X POST "$peppa_url/api/hooks/gitea" -H "Content-Type: application/json" \ + -H "X-Peppa-Event: check" -H "X-Gitea-Signature: $sig" --data-binary "$body" || + echo "peppa: Пеппа недоступна — статус заберёт опрос" +fi +exit "$code" diff --git a/template/.gitea/workflows/ci.yml b/template/.gitea/workflows/ci.yml new file mode 100644 index 00000000..216563f4 --- /dev/null +++ b/template/.gitea/workflows/ci.yml @@ -0,0 +1,38 @@ +# CI проекта Пеппы (PEP-57). Команды проверок — в .peppa/project.json → "checks"; +# под стек проекта этот файл менять не нужно. Изменение этого файла или "checks" +# PM видит отдельно, и такой PR не мержится автоматически. +name: ci +on: + pull_request: + push: + branches: [main] +env: + PEPPA_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + PEPPA_BRANCH: ${{ github.head_ref || github.ref_name }} + PEPPA_PR: ${{ github.event.pull_request.number }} + PEPPA_CI_SECRET: ${{ secrets.PEPPA_CI_SECRET }} + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} +jobs: + checks: + # Раннер с docker.sock хоста: только ветки этого репозитория, PR из форков не запускаются. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: peppa-trusted + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.PEPPA_SHA }} + - id: install + name: install + run: bash .gitea/peppa-check.sh install + - name: lint + if: (success() || failure()) && steps.install.outcome == 'success' + run: bash .gitea/peppa-check.sh lint + - name: typecheck + if: (success() || failure()) && steps.install.outcome == 'success' + run: bash .gitea/peppa-check.sh typecheck + - name: test + if: (success() || failure()) && steps.install.outcome == 'success' + run: bash .gitea/peppa-check.sh test + - name: build + if: (success() || failure()) && steps.install.outcome == 'success' + run: bash .gitea/peppa-check.sh build diff --git a/template/RULES.md b/template/RULES.md index 702a02fd..12cdd5f1 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -66,6 +66,26 @@ PM отвечает только на **архитектурные стоппе к ревью»: кнопка «Принять» закрывает задачу, текстом — замечания, их доделываешь. - Статус `done` ставит только PM. +## CI: проверки перед PR + +Каждый PR проверяет Gitea Actions (`.gitea/workflows/ci.yml` из шаблона): `install`, затем +`lint`, `typecheck`, `test`, `build`. Команды — в `.peppa/project.json` → `checks`: + +```json +{ "checks": { "install": "pnpm install --frozen-lockfile", "lint": "pnpm lint", + "typecheck": "pnpm typecheck", "test": "pnpm test", "build": "pnpm build" } } +``` + +- `checks` пустой — заполни его на первой задаче проекта под его стек. Нет команды — + шаг пропущен; проект без команд в Пеппе виден как «проверки не настроены». +- **Перед PR запусти проверки локально** тем же скриптом, что и CI: + `bash .gitea/peppa-check.sh <проверка>` для каждой из них. Красное не пушь. +- Красная проверка в PR вернётся к тебе сообщением с именем шага и хвостом лога — почини + и запушь в ту же ветку. После 3 красных прогонов подряд Пеппа зовёт PM. +- Не «чини» CI, ослабляя проверки. Изменения `checks`, `deploy` и `.gitea/` PM видит + отдельно, такой PR не мержится автоматически — опиши в PR, зачем это нужно. +- Задача попадает в ревью и мержится только с зелёными проверками последнего коммита. + ## Спецификации — сценарии в формате Gherkin Требования в `specs/**/spec.md` пиши как раньше (`### Requirement:` + текст с SHALL), а