// PEP-269, spec platform-delays «Конфликт с основной веткой — отдельный шаг»: the PEP-217 scenario — // a result conflicting with the main branch ends in at most 2 requests to the agent, then a person // (the superadmin) gets the conflicting files. 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, telegramOutbox, users } from "@peppa/db"; import { and, eq, sql } from "drizzle-orm"; import { stripAsIs } from "@peppa/shared/i18n"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-conflict-")), "gitea")); const BOT = { id: 73, login: "peppa-bot", token: "mock-token-bot" }; const CHECKS = { test: "pnpm test" }; const MIN = 60_000; const ADMIN_CHAT = 9302; const FILES = ["apps/web/app/layout.tsx", "docs/bundle-baseline.json"]; before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; process.env.PEPPA_STUCK_TASKS = "on"; gitea.addUser(BOT); const owner = await core.upsertUserFromGitea(db, { id: 9301, login: "mock-owner-conflict" }, { access_token: "x" }); const admin = await core.upsertUserFromGitea(db, { id: ADMIN_CHAT, login: "mock-admin-conflict" }, { access_token: "x" }); await db.update(users).set({ telegramChatId: ADMIN_CHAT, telegramUserId: ADMIN_CHAT }).where(eq(users.id, admin.id)); await core.setPlatformAdmins(db, ["mock-admin-conflict"]); setDefaultOwner(owner.id); runner.setConflictFilesLister(async () => FILES); }); after(async () => { delete process.env.PEPPA_STUCK_TASKS; runner.setConflictFilesLister(null); await gitea.stop(); await teardown(); }); const toAdmin = async (key: string) => (await db.select().from(telegramOutbox).where(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, ADMIN_CHAT))).map((r) => stripAsIs(String(r.params.text))).filter((t) => t.includes(key)); /** PEP-217: a story in work, its agent idle for 40 min, its green result conflicts with main. */ async function conflicted() { 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: 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 = () => { const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${n++}.txt`]: String(n) }); gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, "peppa/test", "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: "in_progress", 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: "idle", lastActivityAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s.id)); const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!; pull().mergeable = false; const mainMoves = () => gitea.commit(proj.giteaOwner, proj.giteaRepo, "main", { [`main${n++}.txt`]: "m" }); const requests = async () => (await db.select().from(events).where(and(eq(events.taskId, ref.task.id), eq(events.type, "conflict_rebase_requested")))).length; const relaunches = async () => (await db.select().from(events).where(and(eq(events.sessionId, s.id), eq(events.type, "resumed")))).length; const scope = { projectId: proj.id, taskId: ref.task.id }; const step = () => runner.getConflictStep(db, ref.task.id); return { tp, proj, ref, pull, push, mainMoves, requests, relaunches, scope, step }; } /** Everything the watchdog runs once a minute that may touch a conflict. */ async function minute(at: number) { await runner.stuckTaskTick(db, { now: new Date(at) }); await runner.conflictStepTick(db, { now: new Date(at) }); } describe("Конфликт с основной веткой — отдельный шаг", () => { test("Scenario: Агент не справился — человек со списком файлов (сценарий PEP-217)", async () => { const t = await conflicted(); const T = Date.now(); await minute(T); assert.equal(await t.requests(), 1, "one request to the agent"); assert.equal(await t.relaunches(), 0, "no relaunch for a conflict"); assert.equal(await runner.getStuckHeal(db, t.ref.task.id), null, "the stuck healing leaves the conflict to its step"); // A day of watchdog minutes before the agent pushes: nothing more is asked. for (const at of [5, 20, 60, 80]) await minute(T + at * MIN); assert.equal(await t.requests(), 1); // The agent pushes, the conflict stays; the main branch did not move. t.push(); await minute(T + 85 * MIN); await minute(T + 88 * MIN); assert.equal(await t.requests(), 1, "no second request: the main branch did not move"); const d = await core.getPlatformDelay(db, t.scope, "conflict"); assert.equal(d?.exhausted, true, "a person decides"); const msgs = await toAdmin(t.tp.taskKey); assert.equal(msgs.length, 1, "one message to the superadmin"); for (const f of FILES) assert.ok(msgs[0]!.includes(f), `the message lists ${f}`); assert.match(msgs[0]!, /не смог разрешить конфликт/); assert.equal(await core.taskDelayed(db, t.ref.task.id), true, "the owner sees the delay line"); // Later minutes: no more requests, no relaunches, still one message. for (const at of [120, 300, 600]) await minute(T + at * MIN); assert.equal(await t.requests(), 1); assert.equal(await t.relaunches(), 0); assert.equal((await toAdmin(t.tp.taskKey)).length, 1); // A person resolved it: the step and the card go. t.pull().mergeable = true; await runner.conflictStepTick(db, { now: new Date(T + 610 * MIN) }); assert.equal(await t.step(), null); assert.equal(await core.getPlatformDelay(db, t.scope, "conflict"), null); const [e] = await db.select().from(events).where(and(eq(events.taskId, t.ref.task.id), eq(events.type, "conflict_resolved"))); assert.ok(e, "conflict_resolved logged"); }); test("Scenario: Основная ветка ушла вперёд — вторая и последняя попытка", async () => { const t = await conflicted(); const T = Date.now(); await minute(T); assert.equal(await t.requests(), 1); // The agent pushed, but someone's story landed in main meanwhile — a new conflict. t.mainMoves(); t.push(); await minute(T + 30 * MIN); await minute(T + 33 * MIN); assert.equal(await t.requests(), 2, "the second request"); assert.equal((await t.step())?.attempts, 2); // Main moves again, the agent pushes again: no third request — a person. t.mainMoves(); t.push(); await minute(T + 60 * MIN); await minute(T + 63 * MIN); assert.equal(await t.requests(), 2, "never more than 2"); assert.equal((await core.getPlatformDelay(db, t.scope, "conflict"))?.exhausted, true); assert.equal((await toAdmin(t.tp.taskKey)).length, 1); }); test("Scenario: Агент молчит — через 90 минут человек", async () => { const t = await conflicted(); const T = Date.now(); await minute(T); await minute(T + 80 * MIN); assert.equal(await core.getPlatformDelay(db, t.scope, "conflict"), null, "still the agent's time"); await minute(T + 91 * MIN); assert.equal((await core.getPlatformDelay(db, t.scope, "conflict"))?.exhausted, true); assert.match((await toAdmin(t.tp.taskKey))[0]!, /агент не обновил изменения/); assert.equal(await t.requests(), 1); }); test("Scenario: Агент разрешил конфликт — шаг снят", async () => { const t = await conflicted(); const T = Date.now(); await minute(T); t.push(); t.pull().mergeable = true; await runner.conflictStepTick(db, { now: new Date(T + 10 * MIN) }); assert.equal(await t.step(), null); assert.equal((await toAdmin(t.tp.taskKey)).length, 0, "nobody bothered"); }); test("Кнопка «Перезапустить» начинает шаг заново", async () => { const t = await conflicted(); const T = Date.now(); await minute(T); await minute(T + 91 * MIN); assert.equal((await t.step())?.escalated != null, true); await runner.delayAction(db, { projectId: t.proj.id, taskId: t.ref.task.id }, "conflict", "restart").catch(() => {}); assert.equal(await t.step(), null, "the step starts afresh"); for (const s of await core.listSessions(db, { active: true, taskId: t.ref.task.id })) await runner.stopSession(db, s.id).catch(() => {}); }); });