peppa/packages/core/src/ci.ts
Асель daa612b0d8 PEP-57: gate — Gitea client only for tasks with a PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:37:10 +05:00

192 lines
9.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// CI results of factory projects (PEP-57): check runs per commit, the summary shown on the
// task card and the gate for review and merge (green checks of the PR head, no conflicts).
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { checkRuns, tasks, type Db } from "@peppa/db";
import { CHECK_NAMES, formatTaskKey, loadEnv, type CheckName, type PeppaProjectFile } from "@peppa/shared";
import { and, desc, eq } from "drizzle-orm";
import type { GiteaClient, GiteaPull } from "./gitea.ts";
import { giteaForBot } from "./users.ts";
import type { Project } from "./projects.ts";
import type { TaskRef } from "./tasks.ts";
export type CheckRun = typeof checkRuns.$inferSelect;
export type CheckState = CheckRun["state"];
export interface CheckReport {
sha: string;
branch?: string | null;
prNumber?: number | null;
check: string;
state: CheckState;
runUrl?: string | null;
logTail?: string | null;
durationSec?: number | null;
source?: CheckRun["source"];
}
/** Commands configured in a project file (JSON text); missing/empty ones are skipped by CI. */
export function configuredChecks(projectJson: string | null | undefined): CheckName[] {
if (!projectJson) return [];
try {
const checks = (JSON.parse(projectJson) as PeppaProjectFile).checks ?? {};
return CHECK_NAMES.filter((c) => typeof checks[c] === "string" && checks[c]!.trim() !== "");
} catch {
return [];
}
}
/** Full link to a run: CI reports relative `/owner/repo/actions/runs/N`. */
export function runLink(url: string | null | undefined): string | null {
if (!url) return null;
return url.startsWith("/") ? `${loadEnv().GITEA_URL}${url}` : url;
}
export interface CiSummary {
state: "not_configured" | "none" | "pending" | "success" | "failure";
passed: number;
total: number;
sha: string | null;
runUrl: string | null;
failed: Array<{ check: string; runUrl: string | null; logTail?: string | null }>;
/** One line for the task card, e.g. "Проверки: 4 из 4 пройдены". */
label: string;
}
type RunLike = { check: string; state: CheckState; runUrl?: string | null; logTail?: string | null };
export function summarizeChecks(configured: string[], runs: RunLike[], sha: string | null): CiSummary {
const total = configured.length;
const base = { sha, total, runUrl: runLink(runs.find((r) => r.runUrl)?.runUrl) };
if (!total) return { ...base, state: "not_configured", passed: 0, failed: [], label: "проверки не настроены" };
// `install` is not a check of its own, but when it fails nothing else ran.
const failed = runs.filter((r) => r.state === "failure" || r.state === "error").map((r) => ({ check: r.check, runUrl: runLink(r.runUrl), logTail: r.logTail }));
const passed = configured.filter((c) => runs.some((r) => r.check === c && r.state === "success")).length;
if (failed.length) return { ...base, state: "failure", passed, failed, label: `Проверки: ${passed} из ${total} пройдены, упало: ${failed.map((f) => f.check).join(", ")}` };
if (passed === total) return { ...base, state: "success", passed, failed, label: `Проверки: ${passed} из ${total} пройдены` };
if (!runs.length) return { ...base, state: "none", passed, failed, label: "Проверки ещё не запускались" };
return { ...base, state: "pending", passed, failed, label: `Проверки идут: ${passed} из ${total}` };
}
/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */
export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> {
const [prev] = await db
.select()
.from(checkRuns)
.where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), eq(checkRuns.check, r.check)));
const values = {
taskId: taskId ?? prev?.taskId ?? null,
branch: r.branch ?? prev?.branch ?? null,
prNumber: r.prNumber ?? prev?.prNumber ?? null,
state: r.state,
runUrl: r.runUrl ?? prev?.runUrl ?? null,
// A poll carries no log: keep the one the CI step sent.
logTail: r.logTail ?? prev?.logTail ?? null,
durationSec: r.durationSec ?? prev?.durationSec ?? null,
source: r.source ?? "report",
};
const [run] = prev
? await db.update(checkRuns).set(values).where(eq(checkRuns.id, prev.id)).returning()
: await db.insert(checkRuns).values({ projectId: project.id, sha: r.sha, check: r.check, ...values }).returning();
return { run: run!, changed: prev?.state !== r.state };
}
/** PR number of a task's pr_url when it points at the project's repo. */
export function taskPrNumber(project: Project, prUrl: string | null | undefined): number | null {
const m = prUrl?.match(/\/([^/]+)\/([^/]+)\/pulls\/(\d+)/);
if (!m || m[1]!.toLowerCase() !== project.giteaOwner.toLowerCase() || m[2]!.toLowerCase() !== project.giteaRepo.toLowerCase()) return null;
return Number(m[3]);
}
/** Task of a CI result: its branch `task/<KEY>-<n>…`, or the task whose PR it is. */
export async function taskForCheck(db: Db, project: Project, branch: string | null | undefined, prNumber: number | null | undefined): Promise<TaskRef | null> {
const m = branch?.match(new RegExp(`^task/${project.key}-(\\d+)`, "i"));
if (m) {
const [task] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.number, Number(m[1]))));
if (task) return { project, task, key: formatTaskKey(project.key, task.number) };
}
if (prNumber) {
for (const task of await db.select().from(tasks).where(eq(tasks.projectId, project.id))) {
if (taskPrNumber(project, task.prUrl) === prNumber) return { project, task, key: formatTaskKey(project.key, task.number) };
}
}
return null;
}
function workspaceProjectJson(project: Project): string | null {
const f = join(project.workspacePath, ".peppa/project.json");
return existsSync(f) ? readFileSync(f, "utf8") : null;
}
/** For the task card and MCP (no Gitea calls): checks of the task's latest commit. */
export async function taskCiSummary(db: Db, ref: TaskRef): Promise<CiSummary> {
const runs = await db.select().from(checkRuns).where(eq(checkRuns.taskId, ref.task.id)).orderBy(desc(checkRuns.updatedAt));
const sha = runs[0]?.sha ?? null;
return summarizeChecks(configuredChecks(workspaceProjectJson(ref.project)), runs.filter((r) => r.sha === sha), sha);
}
export interface GateResult {
ok: boolean;
/** Why not, for the PM: "проверки не пройдены", conflicts… */
reason?: string;
summary: CiSummary | null;
pull: GiteaPull | null;
}
/**
* Gate for review and merge: the task's PR head has green checks and no conflicts. A task
* without a PR or a project without checks passes (the card says "проверки не настроены").
*/
export async function prGate(ref: TaskRef, client?: GiteaClient): Promise<GateResult> {
const n = taskPrNumber(ref.project, ref.task.prUrl);
if (!n) return { ok: true, summary: null, pull: null };
const gitea = client ?? giteaForBot();
const { giteaOwner: o, giteaRepo: r } = ref.project;
const pull = await gitea.getPullRequest(o, r, n);
if (pull.merged) return { ok: true, summary: null, pull };
const [projectJson, status] = await Promise.all([gitea.fileText(o, r, ".peppa/project.json", pull.head.sha), gitea.combinedStatus(o, r, pull.head.sha)]);
const runs = (status.statuses ?? [])
.filter((s) => s.context.startsWith("peppa/"))
.map((s) => ({ check: s.context.slice(6), state: (s.status === "error" || s.status === "failure" ? "failure" : s.status === "success" ? "success" : "pending") as CheckState, runUrl: s.target_url }));
const summary = summarizeChecks(configuredChecks(projectJson), runs, pull.head.sha);
if (summary.state === "failure") return { ok: false, reason: `проверки не пройдены (${summary.failed.map((f) => f.check).join(", ")})`, summary, pull };
if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: `проверки ещё идут (${summary.passed} из ${summary.total})`, summary, pull };
if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: "есть конфликты с основной веткой", summary, pull };
return { ok: true, summary, pull };
}
/** Files that define the pipeline: changing them needs the PM's review even in auto mode. */
export function isPipelineFile(path: string): boolean {
return path.startsWith(".gitea/") || path === ".peppa/project.json";
}
/**
* Pipeline changes in a PR: workflow files, or `checks`/`deploy` in .peppa/project.json
* (other fields of the project file are not the pipeline). Empty = none.
*/
export async function pipelineChanges(ref: TaskRef, pull: GiteaPull, gitea: GiteaClient = giteaForBot()): Promise<string[]> {
const { giteaOwner: o, giteaRepo: r } = ref.project;
const out: string[] = [];
for (const f of (await gitea.pullFiles(o, r, pull.number)).filter(isPipelineFile)) {
if (f !== ".peppa/project.json") {
out.push(f);
continue;
}
const [before, after] = await Promise.all([gitea.fileText(o, r, f, pull.base.ref), gitea.fileText(o, r, f, pull.head.sha)]);
const pick = (t: string | null) => {
try {
const j = JSON.parse(t ?? "{}") as PeppaProjectFile;
return { checks: j.checks ?? {}, deploy: j.deploy ?? {} };
} catch {
return null;
}
};
const a = pick(before);
const b = pick(after);
for (const k of ["checks", "deploy"] as const) {
if (JSON.stringify(a?.[k]) !== JSON.stringify(b?.[k])) out.push(`${f} → ${k}: ${JSON.stringify(a?.[k] ?? null)} → ${JSON.stringify(b?.[k] ?? null)}`);
}
}
return out;
}