peppa/packages/testkit/test/foreign-pr-url.test.ts
peppa-bot d20bfe496e
Some checks failed
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 35с
peppa/test test: failure за 1638с
peppa-ci / ci (pull_request) Failing after 29m35s
PEP-296: чужая ссылка не закрывает задачу и в запомненной приёмке, «Принять», автомерже
pendingAcceptTick завершал приёмку, когда taskPrNumber не узнавал ссылку
(так закрылись PEP-255 и PEP-257); mergeTaskPr возвращал «PR нет», автомерж
шёл в afterMerge. Теперь ссылка вида /pulls/<n> не из репозитория проекта —
отказ с причиной, задача остаётся на проверке. Тест на все три пути.

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

126 lines
7.3 KiB
TypeScript

// PEP-296: a pull request link of another repository is not «no PR».
// 25.11.2026: PEP-255 and PEP-257 became «Готово» with unmerged results. The agent, asked to
// rebase over a remembered «Принять», set `pr_url` to the PR address of an old Git; the gate read
// the foreign link as «nothing to check» and the accept closed the story without a merge.
// mock-claude runners, mock Gitea.
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, waitFor, type TestProject } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { events } 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-foreign-pr-")), "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" };
/** The address an agent took from old docs: another host, another owner, the right number. */
const oldGit = (n: number) => `https://old-git.example/peppa/peppa/pulls/${n}`;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
});
after(async () => {
await gitea.stop();
await teardown();
});
type Turns = Parameters<typeof project>[0]["turns"];
/** A story in review with an open green PR (task/<KEY>-1) in mock Gitea. */
async function prTask(turns: Turns) {
const tp: TestProject = 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 sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" });
for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, "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 pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!;
return { tp, proj, pr, prUrl, ref, pull };
}
const tick = () => runner.pendingAcceptTick(db, { now: new Date() });
describe("PEP-296: ссылка на PR не из репозитория проекта", () => {
test("Гейт закрыт: чужая ссылка — не «PR нет»", async () => {
const t = await prTask([]);
const ref = await t.ref();
assert.equal(core.foreignPrUrl(ref.project, oldGit(t.pr.number)), true);
assert.equal(core.foreignPrUrl(ref.project, t.prUrl), false, "the project's own PR");
assert.equal(core.foreignPrUrl(ref.project, null), false, "no link at all is still «no PR»");
assert.equal(core.foreignPrUrl(ref.project, "https://example.com/preview"), false, "not a PR link");
const gate = await core.prGate({ ...ref, task: { ...ref.task, prUrl: oldGit(t.pr.number) } });
assert.equal(gate.ok, false, "nothing proves the result is merged");
assert.match(String(gate.reason), /не в код проекта/);
assert.equal((await core.prGate({ ...ref, task: { ...ref.task, prUrl: null } })).ok, true, "a story without a PR passes as before");
});
test("«Принять» запомнено, агент записал адрес старого Git — задача закрывается только настоящим мержем", async () => {
const t = await prTask([[{ mcp: "update_task", args: { task: "1", status: "review", pr_url: oldGit(1) } }, { say: "Обновил изменения." }]]);
assert.equal(t.pr.number, 1);
// The owner accepts over a conflict: FORGE remembers it and asks the agent to rebase.
t.pull().mergeable = false;
const r = await runner.acceptStory(db, await t.ref(), "web");
assert.equal(r.pending, true);
t.pull().mergeable = true; // the agent "rebases" before its turn reaches update_task
const call = await t.tp.waitLog("the agent hands the story back", (e) => e.ev === "mcp" && e.tool === "update_task");
assert.equal(call.isError, false, String(call.text));
await waitFor("back in review", async () => ((await t.ref()).task.status === "review" ? true : undefined));
assert.equal((await t.ref()).task.prUrl, t.prUrl, "the project's own PR is stored, not the foreign address");
await tick();
assert.equal(t.pull().merged, true, "accepted means merged");
assert.equal((await t.ref()).task.status, "done");
});
test("Чужая ссылка уже записана: «Принять», запомненная приёмка и автомерж задачу не закрывают", async () => {
const t = await prTask([]);
await core.updateTask(db, await t.ref(), { prUrl: oldGit(t.pr.number) });
const taskId = (await t.ref()).task.id;
const status = async () => (await t.ref()).task.status;
// «Принять» by a person: refused with the reason.
await assert.rejects(runner.acceptStory(db, await t.ref(), "web"), /не в код проекта/);
assert.equal(await status(), "review");
// The accept remembered earlier (the way PEP-255 was closed): forgotten, the story stays.
await core.setPendingAccept(db, taskId, { at: Date.now(), via: "web", rebases: 1 });
await tick();
assert.equal(await status(), "review", "not «Готово» without a merge");
assert.equal(await core.getPendingAccept(db, taskId), null);
assert.equal((await db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, "accept_failed")))).length, 1);
// «Сам мержит и закрывает»: the auto-merge leaves it alone as well.
await core.setAutonomy(db, t.proj.id, { level: "auto", merge: "auto", close: "after_merge" });
await runner.autonomyTick(db, { now: new Date() });
assert.equal(await status(), "review");
assert.equal(t.pull().merged, false);
});
test("Чужая ссылка на PR другой задачи — отказ, прежняя ссылка остаётся", async () => {
const t = await prTask([[{ mcp: "update_task", args: { task: "1", status: "review", pr_url: oldGit(99) } }, { say: "Готово." }]]);
await core.updateTask(db, await t.ref(), { status: "in_progress" });
await t.tp.start();
const call = await t.tp.waitLog("refused", (e) => e.ev === "mcp" && e.tool === "update_task");
assert.equal(call.isError, true);
assert.match(String(call.text), /not a pull request of this project's repository/);
const now = (await t.ref()).task;
assert.equal(now.prUrl, t.prUrl);
assert.equal(now.status, "in_progress", "not handed to review on a foreign link");
assert.equal(t.pull().merged, false);
});
});