diff --git a/openspec/changes/pep-93-empty-pr-accept/proposal.md b/openspec/changes/pep-93-empty-pr-accept/proposal.md new file mode 100644 index 00000000..34e0149c --- /dev/null +++ b/openspec/changes/pep-93-empty-pr-accept/proposal.md @@ -0,0 +1,13 @@ +# Proposal: PEP-93 — «Принять» на пустом PR + +## Why +FRTVL-1: ветка FRTVL-2 выросла из ветки FRTVL-1, PR №2 смержили первым — он унёс в `main` все +коммиты FRTVL-1. PR №1 остался открытым и пустым; Gitea на merge отвечает +`405 Please try again later`, и «Принять» показывал PM эту ошибку, стори застревала в ревью. + +## What Changes +- `GiteaClient.commitsAhead` (compare base...head) и `closePullRequest`. +- `mergeOrCloseEmpty` (runner/ci-feedback.ts) в «Принять» (`mergeTaskPr`) и автомерже + (`autoMergeTask`): если в PR нечего мержить — комментарий «уже в main» и закрытие PR, + стори принимается; иначе обычный мерж. +- `mock-gitea`: compare, PATCH PR, 405 на пустой мерж (как настоящая Gitea). diff --git a/openspec/changes/pep-93-empty-pr-accept/specs/delivery-pipeline/spec.md b/openspec/changes/pep-93-empty-pr-accept/specs/delivery-pipeline/spec.md new file mode 100644 index 00000000..19ea1a47 --- /dev/null +++ b/openspec/changes/pep-93-empty-pr-accept/specs/delivery-pipeline/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: Приёмка PR, уже вошедшего в основную ветку +«Принять» и автомерж SHALL принимать стори, чьи коммиты уже в основной ветке (вошли с другим PR), закрывая её пустой PR с пояснением вместо мержа. + +#### Scenario: Ветка следующей стори унесла коммиты +- **WHEN** PM жмёт «Принять» у стори, в PR которой нет коммитов сверх основной ветки +- **THEN** PR закрывается с комментарием «уже в main», стори переходит в «Готово», ошибки Gitea PM не видит diff --git a/openspec/changes/pep-93-empty-pr-accept/tasks.md b/openspec/changes/pep-93-empty-pr-accept/tasks.md new file mode 100644 index 00000000..d7ec0457 --- /dev/null +++ b/openspec/changes/pep-93-empty-pr-accept/tasks.md @@ -0,0 +1,3 @@ +- [x] 1.1 `commitsAhead`, `closePullRequest` в GiteaClient +- [x] 1.2 `mergeOrCloseEmpty` в `mergeTaskPr` и `autoMergeTask` +- [x] 1.3 mock-gitea: compare, PATCH, 405 на пустой PR; тест в ci-feedback.test.ts diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index a362dff5..6afff4b7 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -264,6 +264,16 @@ export class GiteaClient { return this.request("POST", `${this.repoPath(owner, repo)}/pulls/${n}/merge`, { Do: "merge", head_commit_id: sha, delete_branch_after_merge: true }); } + /** Commits `head` has that `base` hasn't (0: nothing to merge — already in base). */ + async commitsAhead(owner: string, repo: string, base: string, head: string): Promise { + const r = await this.request<{ total_commits?: number; commits?: unknown[] }>("GET", `${this.repoPath(owner, repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`); + return r.total_commits ?? r.commits?.length ?? 0; + } + + closePullRequest(owner: string, repo: string, n: number) { + return this.request("PATCH", `${this.repoPath(owner, repo)}/pulls/${n}`, { state: "closed" }); + } + combinedStatus(owner: string, repo: string, ref: string) { return this.request("GET", `${this.repoPath(owner, repo)}/commits/${encodeURIComponent(ref)}/status`); } diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 1a02cb45..6abdff00 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -229,8 +229,23 @@ export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<" if (!gate.pull) return "no_pr"; if (gate.pull.merged) return "already"; if (!gate.ok) throw new PeppaError(`Мерж не выполнен: ${gate.reason}`); - await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); - return "merged"; + return (await mergeOrCloseEmpty(ref, gate.pull, gitea)) ? "merged" : "already"; +} + +/** + * PEP-93: a PR whose commits are all in the base already (a later story's branch grew from this + * one and was merged first) can't be merged — Gitea answers 405 «Please try again later». Then + * the work is in main: close the PR with a note instead. True when merged, false when closed. + */ +export async function mergeOrCloseEmpty(ref: TaskRef, pull: { number: number; head: { sha: string }; base: { ref: string } }, gitea: GiteaClient): Promise { + const { giteaOwner: owner, giteaRepo: repo } = ref.project; + if ((await gitea.commitsAhead(owner, repo, pull.base.ref, pull.head.sha)) === 0) { + await gitea.commentIssue(owner, repo, pull.number, `Все коммиты этого PR уже в \`${pull.base.ref}\` (вошли с другим PR) — закрываю без мержа. ${ref.key} принята.`).catch(() => {}); + await gitea.closePullRequest(owner, repo, pull.number); + return false; + } + await gitea.mergePullRequest(owner, repo, pull.number, pull.head.sha); + return true; } /** @@ -251,6 +266,6 @@ export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = g }); return { merged: false, reason: "изменение конвейера требует ревью PM" }; } - await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); + await mergeOrCloseEmpty(ref, gate.pull, gitea); return { merged: true }; } diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 50f5a427..5127db9a 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -257,6 +257,10 @@ export class MockGitea { return { state, sha, statuses }; } + private ahead(r: MockRepo, base: string, head: string): number { + return Number(execFileSync("git", ["--git-dir", r.path, "rev-list", "--count", `${base}..${head}`], { encoding: "utf8" }).trim()); + } + private merge(r: MockRepo, p: MockPull) { const g = (...a: string[]) => execFileSync("git", ["--git-dir", r.path, ...a], { encoding: "utf8" }).trim(); const head = g("rev-parse", p.head); @@ -436,6 +440,11 @@ export class MockGitea { const p = r.pulls.find((x) => x.number === Number(m![1])); if (!p) return { status: 404, body: { message: "pull not found" } }; if (method === "GET" && !m[2]) return { status: 200, body: this.pullJson(r, p) }; + if (method === "PATCH" && !m[2]) { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + if (body.state === "closed" || body.state === "open") p.state = body.state; + return { status: 201, body: this.pullJson(r, p) }; + } if (method === "GET" && m[2] === "/files") { const out = execFileSync("git", ["--git-dir", r.path, "diff", "--name-only", `${p.base}...${p.head}`], { encoding: "utf8" }).trim(); return { status: 200, body: out ? out.split("\n").map((filename) => ({ filename })) : [] }; @@ -445,6 +454,8 @@ export class MockGitea { if (p.merged) return { status: 405, body: { message: "already merged" } }; if (!p.mergeable) return { status: 405, body: { message: "Please try again later: merge conflict" } }; if (body.head_commit_id && body.head_commit_id !== this.sha(r.owner, r.name, p.head)) return { status: 409, body: { message: "head out of date" } }; + // Like Gitea: a PR with nothing to merge (head already in base) is refused. + if (this.ahead(r, p.base, p.head) === 0) return { status: 405, body: { message: "Please try again later" } }; this.merge(r, p); return { status: 200 }; } @@ -454,6 +465,10 @@ export class MockGitea { this.setStatus(r.owner, r.name, m[1]!, String(body.context), String(body.state), { target_url: body.target_url as string, description: body.description as string }); return { status: 201, body: {} }; } + if (method === "GET" && (m = sub.match(/^compare\/(.+)\.\.\.(.+)$/))) { + const n = this.ahead(r, decodeURIComponent(m[1]!), decodeURIComponent(m[2]!)); + return { status: 200, body: { total_commits: n, commits: [], files: [] } }; + } if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) }; if (method === "GET" && sub === "branches") { const out = execFileSync("git", ["--git-dir", r.path, "for-each-ref", "--format=%(refname:short)%09%(objectname)%09%(authorname)%09%(committerdate:iso-strict)%09%(contents:subject)", "refs/heads"], { encoding: "utf8" }).trim(); diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts index 398e189f..2163d923 100644 --- a/packages/testkit/test/ci-feedback.test.ts +++ b/packages/testkit/test/ci-feedback.test.ts @@ -2,7 +2,7 @@ // агенту», «Гейт ревью и мержа», «Изменение конвейера требует ревью» — one test per scenario, // against mock Gitea (commit statuses, PRs, webhooks) and mock-claude runners. import assert from "node:assert/strict"; -import { execFile } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { createHmac } from "node:crypto"; import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; @@ -222,6 +222,21 @@ describe("Гейт ревью и мержа", () => { assert.equal((await t.ref()).task.status, "done"); }); + test("PEP-93: PR already in main (a later story's branch grew from it and was merged) — closed with a note, story done", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success"); + const q = await toReview(t); + // The next story's PR carried this branch's commits into main first. + const r = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo); + execFileSync("git", ["--git-dir", r.path, "update-ref", "refs/heads/main", sha]); + await runner.acceptTask(db, q.id, "web"); + const pr = r.pulls[0]!; + assert.equal(pr.merged, false); + assert.equal(pr.state, "closed"); + assert.equal((await t.ref()).task.status, "done"); + }); + test("review gate: the agent can't move a task to review with red or running checks", async () => { const t = await ciTask({ checks: CHECKS }); const sha = t.push();