// PEP-298, spec platform-delays «Конфликт с основной веткой — отдельный шаг»: Gitea re-checks // mergeability in the background after a push or a branch update and answers «conflict» meanwhile. // The first request to the agent goes only when the same head still conflicts CONFLICT_SETTLE_MIN // later; a story taken from review in vain goes back by itself. And the story card counts the checks // by the same list as the gate (that of the head commit). Mock Gitea, no agent turns. import assert from "node:assert/strict"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, before, describe, test } from "node:test"; import { core, db, project, runner, setDefaultOwner, teardown } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; import { events, sessions } from "@peppa/db"; import { and, eq } from "drizzle-orm"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-settle-")), "gitea")); const BOT = { id: 74, login: "peppa-bot", token: "mock-token-bot" }; const MIN = 60_000; before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; // The pause this story adds (helpers.ts turns it off for the other suites). process.env.PEPPA_CONFLICT_SETTLE_MIN = String(runner.CONFLICT_SETTLE_MIN); gitea.addUser(BOT); const owner = await core.upsertUserFromGitea(db, { id: 9401, login: "mock-owner-settle" }, { access_token: "x" }); setDefaultOwner(owner.id); runner.setConflictFilesLister(async () => ["a.txt"]); }); after(async () => { process.env.PEPPA_CONFLICT_SETTLE_MIN = "0"; runner.setConflictFilesLister(null); await gitea.stop(); await teardown(); }); /** A story in review, its agent finished, its green result in a PR; `checks` — the list of the head commit. */ async function inReview(checks: Record = { test: "pnpm test" }) { const tp = await project({ turns: [] }); const proj = await core.getProject(db, tp.key); const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks }); writeFileSync(join(tp.dir, ".peppa/project.json"), pj); gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } }); gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; const branch = `task/${tp.taskKey}`; let n = 0; const push = (files: Record = {}) => { const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${n++}.txt`]: String(n), ...files }); for (const c of Object.keys(checks)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, "success"); return sha; }; push(); const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch); const ref = await core.resolveTask(db, tp.taskKey); await core.updateTask(db, ref, { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }); const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id }); await db.update(sessions).set({ status: "done", endedAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s.id)); const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!; const requests = async () => (await db.select().from(events).where(and(eq(events.taskId, ref.task.id), eq(events.type, "conflict_rebase_requested")))).length; const status = async () => (await core.resolveTask(db, tp.taskKey)).task.status; const live = async () => (await core.listSessions(db, { active: true, taskId: ref.task.id })).length; const fresh = () => core.resolveTask(db, tp.taskKey); return { tp, proj, ref, pull, push, requests, status, live, fresh }; } /** A periodic path that sees the conflict (the held «готово», the accept, the auto-merge…), then the minute tick. */ async function sight(t: Awaited>, at: number) { const ref = await t.fresh(); const pull = (await core.prGate(ref)).pull!; if (pull.mergeable === false) await runner.conflictStep(db, ref, pull, { now: new Date(at) }); await runner.conflictStepTick(db, { now: new Date(at) }); } describe("Конфликт с основной веткой — ложный «конфликт» сразу после обновления (PEP-298)", () => { test("Scenario: Gitea две минуты после обновления ветки отвечает «конфликт» — агент не вызывается", async () => { const t = await inReview(); const T = Date.now(); // FORGE updated the branch: a new head, Gitea re-checks it and says «conflict» meanwhile. t.push(); t.pull().mergeable = false; await sight(t, T); assert.equal(await t.requests(), 0, "the first sight asks nobody"); assert.ok(await runner.getConflictSeen(db, t.ref.task.id), "the sight is remembered"); await sight(t, T + 1 * MIN); assert.equal(await t.requests(), 0, "a minute later — still waiting for the second look"); // Gitea finished re-checking: no conflict. t.pull().mergeable = true; await sight(t, T + 2 * MIN); await sight(t, T + 5 * MIN); assert.equal(await t.requests(), 0, "no request at all"); assert.equal(await t.status(), "review", "the story stays in review"); assert.equal(await t.live(), 0, "no agent started"); assert.equal(await runner.getConflictSeen(db, t.ref.task.id), null, "the sight is forgotten"); }); test("Scenario: Настоящий конфликт — просьба уходит через CONFLICT_SETTLE_MIN", async () => { const t = await inReview(); const T = Date.now(); t.pull().mergeable = false; // The agent cannot start right away (no room): the request waits in the queue. await core.waitForCapacity(db, t.ref.task.id, null, new Date(T)); await sight(t, T); await runner.conflictStepTick(db, { now: new Date(T + 1 * MIN) }); assert.equal(await t.requests(), 0); // Only the minute tick looks again — a periodic path that comes once an hour needs no second visit. await runner.conflictStepTick(db, { now: new Date(T + runner.CONFLICT_SETTLE_MIN * MIN) }); assert.equal(await t.requests(), 1, "the request goes after the settle time"); assert.equal(await t.status(), "in_progress"); assert.equal((await runner.getConflictStep(db, t.ref.task.id))?.from, "review"); await runner.conflictStepTick(db, { now: new Date(T + 10 * MIN) }); assert.equal(await t.requests(), 1, "one request per conflict"); await core.clearCapacityWait(db, t.ref.task.id); }); test("Scenario: Новая голова сбрасывает ожидание", async () => { const t = await inReview(); const T = Date.now(); t.pull().mergeable = false; await sight(t, T); t.push(); // the agent (or FORGE) pushed a minute later await sight(t, T + 1 * MIN); await sight(t, T + 2 * MIN); assert.equal(await t.requests(), 0, "the new head is judged from its own first sight"); assert.equal(await t.status(), "review"); t.pull().mergeable = true; await sight(t, T + 3 * MIN); }); test("Scenario: Зря переведённая в работу задача возвращается на проверку сама", async () => { const t = await inReview(); const T = Date.now(); t.pull().mergeable = false; await core.waitForCapacity(db, t.ref.task.id, null, new Date(T)); await sight(t, T); await sight(t, T + 3 * MIN); assert.equal(await t.requests(), 1); assert.equal(await t.status(), "in_progress"); // The conflict went by itself (Gitea re-checked longer than usual), the agent never started. t.pull().mergeable = true; await runner.conflictStepTick(db, { now: new Date(T + 4 * MIN) }); assert.equal(await t.status(), "review", "back to review"); assert.equal(await core.isWaitingForCapacity(db, t.ref.task.id), false, "the agent's place in the queue is given up"); assert.equal(await runner.getConflictStep(db, t.ref.task.id), null); const [e] = await db.select().from(events).where(and(eq(events.taskId, t.ref.task.id), eq(events.type, "conflict_false_back_to_review"))); assert.ok(e, "logged"); }); test("Агент уже обновил изменения — задача на проверку сама не возвращается", async () => { const t = await inReview(); const T = Date.now(); t.pull().mergeable = false; await core.waitForCapacity(db, t.ref.task.id, null, new Date(T)); await sight(t, T); await sight(t, T + 3 * MIN); assert.equal(await t.status(), "in_progress"); t.push(); t.pull().mergeable = true; await runner.conflictStepTick(db, { now: new Date(T + 10 * MIN) }); assert.equal(await t.status(), "in_progress", "the agent hands it off itself"); await core.clearCapacityWait(db, t.ref.task.id); }); }); describe("Карточка задачи и допуск считают проверки по одному списку (PEP-298)", () => { test("Scenario: В последней версии нужна проверка, которой нет в основной копии", async () => { // The head's list has four checks, the main working copy — three (PEP-217: «4 из 4» against «3 из 4»). const t = await inReview({ lint: "pnpm lint", build: "pnpm build", typecheck: "pnpm typecheck", test: "pnpm test" }); writeFileSync(join(t.tp.dir, ".peppa/project.json"), JSON.stringify({ slug: t.proj.slug, key: t.tp.key, checks: { lint: "x", build: "x", typecheck: "x" } })); const head = (await core.prGate(await t.fresh())).pull!.head.sha; const r = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo); // `test` never reported on this head. r.statuses.set(head, (r.statuses.get(head) ?? []).filter((s) => s.context !== "peppa/test")); for (const c of ["lint", "build", "typecheck"]) await runner.recordCheck(db, t.proj, { sha: head, branch: `task/${t.tp.taskKey}`, check: c, state: "success" }); const ref = await t.fresh(); const card = await core.taskCiSummary(db, ref); const gate = await core.prGate(ref); assert.equal(card.total, gate.summary?.total, "one list"); assert.equal(card.label, gate.summary?.label); assert.equal(card.state, "pending"); }); });