// PEP-278, spec delivery-pipeline «"Готово" — когда изменения работают»: an accepted story is // «Принято, ждёт обновления» until its merge commit runs (platform: the live web's commit; // a project: a healthy staging/prod version). Mock Gitea, no agents. 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, teardown } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; import { chatMessages, events, releases } from "@peppa/db"; import { stripAsIs } from "@peppa/shared/i18n"; import { and, eq } from "drizzle-orm"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-rollout-")), "gitea")); const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; const CHECKS = { test: "pnpm test" }; before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; gitea.addUser(BOT); }); after(async () => { delete process.env.PEPPA_PLATFORM_KEY; await gitea.stop(); await teardown(); }); /** A story in review with a green PR in mock Gitea; `platform` — the project is the platform's. */ async function storyInReview(o: { platform?: boolean } = {}) { const tp = await project({ turns: [] }); if (o.platform) process.env.PEPPA_PLATFORM_KEY = tp.key; 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 head = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" }, `${tp.taskKey}: change`); gitea.setStatus(proj.giteaOwner, proj.giteaRepo, head, "peppa/test", "success"); const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`; const ref = () => core.resolveTask(db, tp.taskKey); await core.updateTask(db, await ref(), { status: "review", prUrl }); const oldMain = gitea.sha(proj.giteaOwner, proj.giteaRepo, "main"); const repoPath = gitea.repo(proj.giteaOwner, proj.giteaRepo).path; const waiting = async () => (await core.awaitingRollout(db)).has((await ref()).task.id); const taskEvents = async (type: string) => db.select().from(events).where(and(eq(events.taskId, (await ref()).task.id), eq(events.type, type))); const thread = async () => { await core.syncChats(db); const rows = await db.select().from(chatMessages).where(eq(chatMessages.threadKey, `task:${(await ref()).task.id}`)); return rows.map((r) => stripAsIs(r.text)); }; const release = (env: "staging" | "prod", status: "healthy" | "rolled_back", tasks: string[], sha = "f".repeat(40)) => db.insert(releases).values({ projectId: proj.id, env, sha, tasks, status }); return { tp, proj, ref, oldMain, repoPath, waiting, taskEvents, thread, release, main: () => gitea.sha(proj.giteaOwner, proj.giteaRepo, "main") }; } const liveWeb = (commit: string) => core.setSetting(db, "heartbeat:web", { at: new Date().toISOString(), commit }); describe("«Готово» только когда изменения работают", () => { test("Платформа: принята, но не выкачена", async () => { const s = await storyInReview({ platform: true }); await liveWeb(s.oldMain); await runner.acceptStory(db, await s.ref()); assert.equal((await s.ref()).task.status, "done", "the status machine is unchanged"); assert.equal(await s.waiting(), true); await runner.rolloutTick(db, { root: s.repoPath }); assert.equal(await s.waiting(), true, "the live web runs a commit without the merge"); assert.ok((await s.thread()).some((t) => t.includes("Задача принята — изменения заработают после обновления версии"))); // Платформа: выкачена — the web restarts on the merge commit. await liveWeb(s.main()); await runner.rolloutTick(db, { root: s.repoPath }); assert.equal(await s.waiting(), false); assert.equal((await s.taskEvents("task_rolled_out")).length, 1); await runner.rolloutTick(db, { root: s.repoPath }); assert.equal((await s.taskEvents("task_rolled_out")).length, 1, "said once"); assert.equal((await s.thread()).filter((t) => t.includes("Изменения задачи уже работают — задача готова")).length, 1); delete process.env.PEPPA_PLATFORM_KEY; }); // PEP-305: 26.11.2026 one version (1dc99c5b) carried two accepted stories. The image of the platform // has no git checkout, `git merge-base` failed, and only the story whose merge commit WAS the live // commit became «Готово» — PEP-301, merged one commit earlier, waited for ever. test("Платформа в контейнере (нет git): одна версия несёт две задачи — обе «Готово»", async () => { const noGit = mkdtempSync(join(tmpdir(), "peppa-nogit-")); const s = await storyInReview({ platform: true }); await liveWeb(s.oldMain); await runner.acceptStory(db, await s.ref()); const m1 = s.main(); // The next story is merged right after: m2 is a descendant of m1, and the web restarts on m2. const m2 = gitea.commit(s.proj.giteaOwner, s.proj.giteaRepo, "main", { "g.txt": "2" }, "Merge pull request 'вторая задача' (#2)"); assert.notEqual(m1, m2); const g = core.giteaForBot(); let asked = 0; const list = g.listCommits.bind(g); g.listCommits = (...a: Parameters) => { asked++; return list(...a); }; const tick = () => runner.rolloutTick(db, { root: noGit, gitea: g }); await tick(); assert.equal(await s.waiting(), true, "the live web runs a commit made before the merge"); assert.ok(asked > 0, "git could not tell — Gitea was asked"); const first = asked; await tick(); assert.equal(asked, first, "the commits of one live commit are read once, not every minute"); await liveWeb(m2); await tick(); assert.equal(await s.waiting(), false, "m2 carries m1"); const out = await s.taskEvents("task_rolled_out"); assert.equal(out.length, 1); assert.equal((out[0]!.payload as { env: string }).env, "live"); delete process.env.PEPPA_PLATFORM_KEY; }); test("git: «не предок» — нет; нет хранилища или коммита — неизвестно", async () => { const s = await storyInReview(); const older = s.oldMain; const newer = gitea.commit(s.proj.giteaOwner, s.proj.giteaRepo, "main", { "h.txt": "3" }, "next"); assert.equal(core.commitIn(s.repoPath, older, newer), true); assert.equal(core.commitIn(s.repoPath, newer, older), false, "git answered: not an ancestor"); assert.equal(core.commitIn(s.repoPath, "a".repeat(40), newer), null, "a commit git has never seen"); assert.equal(core.commitIn(mkdtempSync(join(tmpdir(), "peppa-nogit-")), older, newer), null, "not a git checkout"); }); test("Проект: здоровая версия для проверки; сломанная версия не считается", async () => { const s = await storyInReview(); await s.release("staging", "healthy", []); await runner.acceptStory(db, await s.ref()); assert.equal(await s.waiting(), true); await s.release("staging", "rolled_back", [s.tp.taskKey]); await runner.rolloutTick(db); assert.equal(await s.waiting(), true, "a rolled back version does not count"); await s.release("staging", "healthy", [s.tp.taskKey]); await runner.rolloutTick(db); assert.equal(await s.waiting(), false); assert.equal((await s.taskEvents("task_rolled_out"))[0]?.payload && ((await s.taskEvents("task_rolled_out"))[0]!.payload as { env: string }).env, "staging"); }); test("Проект без выкладки — сразу «Готово»", async () => { const s = await storyInReview(); await runner.acceptStory(db, await s.ref()); assert.equal((await s.ref()).task.status, "done"); assert.equal(await s.waiting(), false); assert.ok((await s.thread()).some((t) => t.includes("Задача принята и закрыта"))); }); test("Задача ушла из «Готово» — ожидание снято", async () => { const s = await storyInReview(); await s.release("prod", "healthy", []); await runner.acceptStory(db, await s.ref()); assert.equal(await s.waiting(), true); await core.updateTask(db, await s.ref(), { status: "in_progress" }); assert.equal(await s.waiting(), false); }); test("Карточка «Продакта» говорит, что изменения скоро заработают", () => { const v = core.storyProductView({ status: "done", rollout: true, agentWorking: false, openQuestions: 0 }); assert.equal(v.now, core.STORY_PRODUCT_TEXT.rollout.now); assert.equal(core.storyProductView({ status: "done", agentWorking: false, openQuestions: 0 }).now, core.STORY_PRODUCT_TEXT.done.now); }); });