peppa/packages/core/src/ci.ts
peppa-bot 3d35bbf2b6
All checks were successful
peppa/lint lint: success за 4с
peppa/typecheck typecheck: success за 54с
peppa/build build: success за 40с
peppa/test test: success за 1720с
peppa-ci / ci (pull_request) Successful in 31m31s
PEP-308: проверка, которая не отчиталась, не держит задачу — «проверки ещё идут» только пока статусы меняются
PEP-217 стояла шесть дней: ветка в конфликте с main, три проверки из четырёх зелёные, статуса
peppa/test нет — задание пропало. Гейт отвечал «проверки ещё идут (3 из 4)»: просьба обновить
ветку была придержана «до конца проверок» навсегда, агент на update_task(status: review) получал
«подожди проверок».

- core/ci.ts: `lostChecks` — нужные проверки без результата на голове, чьи статусы peppa/* молчат
  дольше PEPPA_CHECKS_LOST_HOURS (3 ч); `prGate` для такой головы не говорит «ещё идут», а идёт
  дальше: конфликт, отставание (обновление ветки запустит проверки), иначе «проверки не завершились».
- runner/flow.ts: `requestRebase` потерянных проверок не ждёт.
- mcp/agent.ts: отказ агенту называет конфликт и молчащую проверку и что сделать; такую передачу
  на ревью не запоминаем (`review.wanted`).
- runner/review-wanted.ts, stuck-tasks.ts: отметка снимается; сторож застрявших задач просит агента
  запустить проверки новым коммитом.
- Мок Gitea: у статуса время (`updated_at`). Спека platform-delays, переводы en/kk.
- Тесты lost-checks.test.ts: 5 из 6 падали до исправления.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 00:55:50 +05:00

289 lines
16 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 { m as tr } from "@peppa/shared/i18n";
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, GiteaCommitStatus, GiteaPull } from "./gitea.ts";
import { giteaForBot } from "./users.ts";
import { getSetting } from "./settings.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: tr("проверки не настроены") };
// `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: tr("Проверки: {passed} из {total} пройдены, упало: {failed}", { passed, total, failed: failed.map((f) => f.check).join(", ") }) };
if (passed === total) return { ...base, state: "success", passed, failed, label: tr("Проверки: {passed} из {total} пройдены", { passed, total }) };
if (!runs.length) return { ...base, state: "none", passed, failed, label: tr("Проверки ещё не запускались") };
return { ...base, state: "pending", passed, failed, label: tr("Проверки идут: {passed} из {total}", { 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]);
}
/**
* PEP-296: the story's link looks like a pull request, but not one of the project's repository
* (an agent wrote the address of an old Git from the docs). Not «no PR»: nothing proves the
* result is merged.
*/
export function foreignPrUrl(project: Project, prUrl: string | null | undefined): boolean {
return /\/pulls\/\d+/.test(prUrl ?? "") && taskPrNumber(project, prUrl) == null;
}
/** 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;
}
/** PEP-205: the project has checks configured (its stories wait for them). */
export function projectHasChecks(project: Project): boolean {
return configuredChecks(workspaceProjectJson(project)).length > 0;
}
/**
* PEP-255: the executor registration that runs a project's checks — one shared runner for the
* repos in the bot's namespace, its own registration for every other repo (runner/ci.ts `setupCi`).
*/
export function ciLane(project: Pick<Project, "giteaOwner" | "giteaRepo">): string {
return project.giteaOwner === (process.env.GITEA_BOT_USER ?? "peppa-bot") ? "bot" : `repo:${project.giteaOwner}/${project.giteaRepo}`;
}
/** PEP-205/255: `checks.queue` — the episode of a stuck queue and who waits for it. */
export interface ChecksQueueState {
since: number;
win?: number;
/** Lanes (`ciLane`) standing as a whole: every head on them stands, heads of at least two projects. */
lanes?: string[];
/** Projects with a stuck head of their own. Missing — a record from before PEP-255: everybody waits. */
projects?: number[];
}
/**
* PEP-205: the checks queue stands. PEP-255: for a project only when a head of its own is stuck or
* its whole lane stands — another project's stuck job on the same executor holds nobody else.
* Without a project: whether anything is stuck at all.
*/
export async function checksQueueStanding(db: Db, project?: Pick<Project, "id" | "giteaOwner" | "giteaRepo">): Promise<boolean> {
const q = await getSetting<ChecksQueueState>(db, "checks.queue");
if (!q) return false;
if (!project || !Array.isArray(q.projects)) return true;
return q.projects.includes(project.id) || (q.lanes ?? []).includes(ciLane(project));
}
/** PEP-255: what is stuck right now (superadmin's status). Null — nothing. */
export async function standingChecksLanes(db: Db): Promise<string[] | null> {
const q = await getSetting<ChecksQueueState>(db, "checks.queue");
if (!q) return null;
if (!Array.isArray(q.projects)) return ["all"];
return [...(q.lanes ?? []).map((l) => `lane ${l}`), ...q.projects.map((id) => `project #${id}`)];
}
/** 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;
/** PEP-127: the only obstacle — the PR branch lacks the current head of the base branch (Peppa updates it itself). */
behind?: boolean;
/** PEP-308: checks of the head that never reported and no longer will (see `lostChecks`): nothing is running. */
lost?: string[];
}
/** PEP-308: statuses of a head silent for longer than this — a check without a result is lost, not running. 0 — never. */
export const checksLostMs = () => Math.max(0, Number(process.env.PEPPA_CHECKS_LOST_HOURS ?? 3)) * 3600_000;
/**
* PEP-308: the configured checks that have no result on a head whose `peppa/*` statuses have all been
* silent for `checksLostMs()` — their job is gone (cut by a restart, never taken by a runner). PEP-217
* stood for six days on «проверки ещё идут (3 из 4)». Empty when a status is fresh, when Gitea gives
* no times, or when there are no statuses at all (that head is the checks queue's business, PEP-205).
*/
export function lostChecks(configured: string[], statuses: GiteaCommitStatus[], now: number = Date.now()): string[] {
const limit = checksLostMs();
const own = statuses.filter((s) => s.context.startsWith("peppa/"));
if (!limit || !own.length) return [];
const times = own.map((s) => Date.parse(s.updated_at ?? ""));
if (times.some((t) => !Number.isFinite(t)) || now - Math.max(...times) < limit) return [];
const done = new Set(own.filter((s) => s.status === "success" || s.status === "failure" || s.status === "error").map((s) => s.context.slice(6)));
return configured.filter((c) => !done.has(c));
}
/** True when the PR branch does not contain the current head of its base branch. */
export function pullBehind(pull: GiteaPull): boolean {
return pull.state === "open" && !pull.merged && !!pull.merge_base && !!pull.base.sha && pull.merge_base !== pull.base.sha;
}
/**
* 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);
// PEP-296: a pull request of another repository — the gate is closed (PEP-255 and PEP-257 were
// accepted as «Готово» with unmerged results on such a link).
if (!n && foreignPrUrl(ref.project, ref.task.prUrl)) return { ok: false, reason: tr("ссылка на результат ведёт не в код проекта"), summary: null, pull: null };
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 configured = configuredChecks(projectJson);
const summary = summarizeChecks(configured, runs, pull.head.sha);
if (summary.state === "failure") return { ok: false, reason: tr("проверки не пройдены ({list})", { list: summary.failed.map((f) => f.check).join(", ") }), summary, pull };
// PEP-308: a check that has been silent for hours is not «still running» — waiting for it holds a
// conflict's rebase and the agent's hand-off for ever. Such a head goes on to the reasons below.
const lostList = summary.state === "pending" ? lostChecks(configured, status.statuses ?? []) : [];
const lost = lostList.length ? { lost: lostList } : {};
if ((summary.state === "pending" && !lostList.length) || summary.state === "none") return { ok: false, reason: tr("проверки ещё идут ({passed} из {total})", { passed: summary.passed, total: summary.total }), summary, pull };
if (pull.state === "open" && pull.mergeable === false) return { ok: false, ...lost, reason: tr("изменения конфликтуют с основной версией кода"), summary, pull };
// PEP-127: green checks of a head that lacks the fresh base prove nothing about the merge result.
// (A head with lost checks that is only behind: Peppa's update of the branch makes a new head, the checks run again.)
if (pullBehind(pull)) return { ok: false, behind: true, ...lost, reason: tr("изменения отстают от основной версии кода — FORGE обновляет их и ждёт проверок"), summary, pull };
if (lostList.length) {
const hours = Math.round(checksLostMs() / 3600_000);
return { ok: false, ...lost, reason: tr("проверки не завершились: {list} — отчёта нет больше {hours} ч, нужна новая версия изменений", { list: lostList.join(", "), hours }), 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;
}