peppa/packages/core/src/ci.ts
peppa-bot 23fc8e063a
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 38с
peppa/test test: success за 1461с
peppa-ci / ci (pull_request) Successful in 26m56s
PEP-296: ссылка на PR не из репозитория проекта не открывает гейт
25.11 PEP-255 и PEP-257 стали «Готово» с несмерженными PR: агент после rebase
записал pr_url на старый Git, taskPrNumber не узнал репозиторий, prGate вернул
«PR нет», запомненное «Принять» закрыло задачу без мержа.

- core/ci.ts: foreignPrUrl; prGate закрыт для ссылки вида /pulls/<n> не из
  репозитория проекта.
- mcp/agent.ts: update_task приводит такую ссылку к настоящему PR проекта
  (тот же номер, ветка задачи) или отказывает агенту.
- тест foreign-pr-url.test.ts (падал до исправления).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 18:38:54 +05:00

225 lines
12 KiB
TypeScript
Raw Permalink 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, 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-205: the checks queue stands (`checks.queue` is set while a head waits longer than the threshold). */
export async function checksQueueStanding(db: Db): Promise<boolean> {
return (await getSetting(db, "checks.queue")) != 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;
/** PEP-127: the only obstacle — the PR branch lacks the current head of the base branch (Peppa updates it itself). */
behind?: boolean;
}
/** 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 summary = summarizeChecks(configuredChecks(projectJson), runs, pull.head.sha);
if (summary.state === "failure") return { ok: false, reason: tr("проверки не пройдены ({list})", { list: summary.failed.map((f) => f.check).join(", ") }), summary, pull };
if (summary.state === "pending" || 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, reason: tr("изменения конфликтуют с основной версией кода"), summary, pull };
// PEP-127: green checks of a head that lacks the fresh base prove nothing about the merge result.
if (pullBehind(pull)) return { ok: false, behind: true, reason: tr("изменения отстают от основной версии кода — FORGE обновляет их и ждёт проверок"), 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;
}