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/runner/src/accept-pending.ts b/packages/runner/src/accept-pending.ts index 5e322443..3e3e13d9 100644 --- a/packages/runner/src/accept-pending.ts +++ b/packages/runner/src/accept-pending.ts @@ -1,7 +1,7 @@ // PEP-127: «Принять» remembered over a conflict is carried through by the watchdog — the agent // rebases (flow.ts `deferAccept`), and once the story is back in review with green checks the PR // is merged and the story closed. The PM hears when it closed, or once if it could not be done. -import { alertAdmins, getReviewHold, platformDelay, setReviewHold, answerQuestion, askPm, clearPendingAccept, productLookLine, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef, isProjectPaused } from "@peppa/core"; +import { alertAdmins, foreignPrUrl, getReviewHold, platformDelay, setReviewHold, answerQuestion, askPm, clearPendingAccept, productLookLine, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef, isProjectPaused } from "@peppa/core"; import { questions, type Db } from "@peppa/db"; import { asIs, m } from "@peppa/shared/i18n"; import { and, eq, isNull } from "drizzle-orm"; @@ -45,6 +45,8 @@ async function carry(db: Db, taskId: number, state: PendingAccept, now: number, const hours = Math.round(waitMs() / 3_600_000); if (now - state.at > waitMs()) return fail(db, ref, m("агент не обновил изменения за {hours} ч", { hours }), true, log); if (!taskPrNumber(ref.project, ref.task.prUrl)) { + // PEP-296: a pull request of another repository is not «no PR» — nothing proves the result is merged. + if (foreignPrUrl(ref.project, ref.task.prUrl)) return fail(db, ref, m("ссылка на результат ведёт не в код проекта"), true, log); if (ref.task.status === "review") await finish(db, ref, log); return; } diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index d8662afa..25d15a7a 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -32,6 +32,7 @@ import { platformFailure, setSetting, taskPrNumber, + foreignPrUrl, type AutonomySettings, type GiteaClient, type Project, @@ -141,6 +142,8 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c // PEP-197: a story the factory made itself waits for the owner unless «Принимать сами» says otherwise. if (!(await mayAutoAcceptTask(db, task))) continue; const state = (await getSetting(db, mergeKey(task.id))) ?? {}; + // PEP-296: a pull request of another repository is not «no PR»: nothing is merged, nothing is closed on it. + if (foreignPrUrl(project, task.prUrl)) continue; if (!taskPrNumber(project, task.prUrl)) { await afterMerge(db, ref, a, state, log); continue; diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 06318aaa..802653d7 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -20,6 +20,7 @@ import { runLink, taskForCheck, taskPrNumber, + foreignPrUrl, upsertCheckRun, verifyHookSignature, type CheckReport, @@ -321,6 +322,8 @@ export async function pollChecks(db: Db, gitea: GiteaClient = giteaForBot()): Pr * Throws with the reason for the PM; a task without a PR has nothing to merge. */ export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<"merged" | "already" | "no_pr"> { + // PEP-296: a pull request of another repository is not «no PR» — accepting on it would close the story unmerged. + if (foreignPrUrl(ref.project, ref.task.prUrl)) throw new PeppaError(m("Принять не удалось: {reason}", { reason: m("ссылка на результат ведёт не в код проекта") })); if (!taskPrNumber(ref.project, ref.task.prUrl)) return "no_pr"; const gitea = client ?? giteaForBot(); const gate = await prGate(ref, gitea); 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..25c19e8a --- /dev/null +++ b/packages/testkit/test/foreign-pr-url.test.ts @@ -0,0 +1,125 @@ +// 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[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("Чужая ссылка уже записана: «Принять», запомненная приёмка и автомерж задачу не закрывают", 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); + }); +});