From 23fc8e063afd334a43eb16981ca618807ce165e9 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Wed, 25 Nov 2026 18:38:54 +0500 Subject: [PATCH] =?UTF-8?q?PEP-296:=20=D1=81=D1=81=D1=8B=D0=BB=D0=BA=D0=B0?= =?UTF-8?q?=20=D0=BD=D0=B0=20PR=20=D0=BD=D0=B5=20=D0=B8=D0=B7=20=D1=80?= =?UTF-8?q?=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8=D1=82=D0=BE=D1=80=D0=B8=D1=8F=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0=20=D0=BD=D0=B5=20?= =?UTF-8?q?=D0=BE=D1=82=D0=BA=D1=80=D1=8B=D0=B2=D0=B0=D0=B5=D1=82=20=D0=B3?= =?UTF-8?q?=D0=B5=D0=B9=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 25.11 PEP-255 и PEP-257 стали «Готово» с несмерженными PR: агент после rebase записал pr_url на старый Git, taskPrNumber не узнал репозиторий, prGate вернул «PR нет», запомненное «Принять» закрыло задачу без мержа. - core/ci.ts: foreignPrUrl; prGate закрыт для ссылки вида /pulls/ не из репозитория проекта. - mcp/agent.ts: update_task приводит такую ссылку к настоящему PR проекта (тот же номер, ветка задачи) или отказывает агенту. - тест foreign-pr-url.test.ts (падал до исправления). Co-Authored-By: Claude Fable 5.2 --- packages/core/src/ci.ts | 12 +++ packages/mcp/src/agent.ts | 23 ++++- packages/shared/src/i18n/en/bot.ts | 1 + packages/shared/src/i18n/kk/bot.ts | 1 + packages/testkit/test/foreign-pr-url.test.ts | 99 ++++++++++++++++++++ 5 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 packages/testkit/test/foreign-pr-url.test.ts diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts index 5040bd39..bd458737 100644 --- a/packages/core/src/ci.ts +++ b/packages/core/src/ci.ts @@ -100,6 +100,15 @@ export function taskPrNumber(project: Project, prUrl: string | null | undefined) 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/-…`, or the task whose PR it is. */ export async function taskForCheck(db: Db, project: Project, branch: string | null | undefined, prNumber: number | null | undefined): Promise { const m = branch?.match(new RegExp(`^task/${project.key}-(\\d+)`, "i")); @@ -158,6 +167,9 @@ export function pullBehind(pull: GiteaPull): boolean { */ export async function prGate(ref: TaskRef, client?: GiteaClient): Promise { 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; diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts index e22ce19c..2f8a7cd3 100644 --- a/packages/mcp/src/agent.ts +++ b/packages/mcp/src/agent.ts @@ -7,6 +7,7 @@ import { askPm, admitAgentMessage, prGate, + foreignPrUrl, renderDetails, renderMain, setTaskResult, @@ -192,8 +193,10 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer summary: z.string().optional().describe("With status: review — what the owner gets, ONE plain sentence for a non-engineer («Добавил вход по почте: письмо с кодом приходит за минуту»). It becomes the second line of the «готово» message. Same rules as any message to the owner: no file names, branches, commands, PR numbers, statuses"), details: z.string().optional().describe("With status: review — technical details of the result (what changed, how it was checked); shown to the owner only under «Подробнее», not checked"), }, - async ({ task, status, openspec_change, pr_url, title, description, summary, details }) => { + async ({ task, status, openspec_change, pr_url: givenPrUrl, title, description, summary, details }) => { const ref = await resolve(task); + // PEP-296: a link to a pull request of another repository is never stored. + const pr_url = givenPrUrl ? await ownPrUrl(ref, givenPrUrl) : undefined; // PEP-152: the agent's words about the result are a message for the owner — the same format. if (status === "review" && (summary?.trim() || details?.trim())) { const r = await admit(ref, "done", { summary: summary?.trim() || "", details }, summary?.trim() ? {} : { skip: true }); @@ -260,6 +263,24 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer }, ); + /** + * PEP-296: the PR link an agent passes. One of the project's repository — as it is. One of another + * repository (an old Git address from the docs): the project's own pull request with that number + * and the story's branch gets its real address; anything else is refused — a foreign link read as + * «no PR», and the story was accepted as done with an unmerged result. + */ + async function ownPrUrl(ref: TaskRef, url: string): Promise { + if (!foreignPrUrl(ref.project, url)) return url; + const { giteaOwner: o, giteaRepo: r } = ref.project; + const n = Number(/\/pulls\/(\d+)/.exec(url)![1]); + const pull = await giteaForBot().getPullRequest(o, r, n).catch(() => null); + const own = pull?.head.ref.match(new RegExp(`^task/${ref.project.key}-(\\d+)`, "i")); + if (pull && own && Number(own[1]) === ref.task.number) return pull.html_url; + throw new PeppaError( + `pr_url ${url} is not a pull request of this project's repository (${o}/${r}). Pass the URL that open_pull_request returned (or the one the push printed), or leave pr_url out: the story keeps the pull request it already has.`, + ); + } + // PEP-149: four kinds of messages to the owner — question (here), done (Peppa sends it itself // after green checks), progress (report_progress), blocker (report_blocker). /** PEP-152: takes a message for the owner or refuses it with the list of violations. */ diff --git a/packages/shared/src/i18n/en/bot.ts b/packages/shared/src/i18n/en/bot.ts index b497f549..0d65ea4e 100644 --- a/packages/shared/src/i18n/en/bot.ts +++ b/packages/shared/src/i18n/en/bot.ts @@ -264,6 +264,7 @@ export const bot: Dict = { "проверки не пройдены ({list})": "checks failed ({list})", "проверки ещё идут ({passed} из {total})": "checks still running ({passed} of {total})", "изменения конфликтуют с основной версией кода": "the changes conflict with the main version of the code", + "ссылка на результат ведёт не в код проекта": "the link to the result does not lead to the project's code", "Лимит итераций ревьюера — от 1 до {max}": "Reviewer iteration limit is from 1 to {max}", "Ревьюер проверяет PR…": "Reviewer is checking the PR…", "Ревьюер не отработал: {error}": "Reviewer failed: {error}", diff --git a/packages/shared/src/i18n/kk/bot.ts b/packages/shared/src/i18n/kk/bot.ts index eb484f9b..7aa12ea2 100644 --- a/packages/shared/src/i18n/kk/bot.ts +++ b/packages/shared/src/i18n/kk/bot.ts @@ -263,6 +263,7 @@ export const bot: Dict = { "проверки не пройдены ({list})": "тексерістерден өтпеді ({list})", "проверки ещё идут ({passed} из {total})": "тексерістер әлі жүріп жатыр ({passed} / {total})", "изменения конфликтуют с основной версией кода": "өзгерістер кодтың негізгі нұсқасымен қайшы келеді", + "ссылка на результат ведёт не в код проекта": "нәтижеге сілтеме жоба кодына апармайды", "Лимит итераций ревьюера — от 1 до {max}": "Ревьюер итерацияларының лимиті — 1 мен {max} аралығында", "Ревьюер проверяет PR…": "Ревьюер PR-ды тексеріп жатыр…", "Ревьюер не отработал: {error}": "Ревьюер орындалмады: {error}", diff --git a/packages/testkit/test/foreign-pr-url.test.ts b/packages/testkit/test/foreign-pr-url.test.ts new file mode 100644 index 00000000..da1a154f --- /dev/null +++ b/packages/testkit/test/foreign-pr-url.test.ts @@ -0,0 +1,99 @@ +// 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"; + +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[0]["turns"]; + +/** A story in review with an open green PR (task/-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("Чужая ссылка на 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); + }); +});