Merge pull request 'PEP-93: «Принять» на пустом PR' (#87) from task/pep-93 into main
This commit is contained in:
commit
51847e1ac1
13
openspec/changes/pep-93-empty-pr-accept/proposal.md
Normal file
13
openspec/changes/pep-93-empty-pr-accept/proposal.md
Normal file
@ -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).
|
||||
@ -0,0 +1,8 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Приёмка PR, уже вошедшего в основную ветку
|
||||
«Принять» и автомерж SHALL принимать стори, чьи коммиты уже в основной ветке (вошли с другим PR), закрывая её пустой PR с пояснением вместо мержа.
|
||||
|
||||
#### Scenario: Ветка следующей стори унесла коммиты
|
||||
- **WHEN** PM жмёт «Принять» у стори, в PR которой нет коммитов сверх основной ветки
|
||||
- **THEN** PR закрывается с комментарием «уже в main», стори переходит в «Готово», ошибки Gitea PM не видит
|
||||
3
openspec/changes/pep-93-empty-pr-accept/tasks.md
Normal file
3
openspec/changes/pep-93-empty-pr-accept/tasks.md
Normal file
@ -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
|
||||
@ -264,6 +264,16 @@ export class GiteaClient {
|
||||
return this.request<void>("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<number> {
|
||||
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<void>("PATCH", `${this.repoPath(owner, repo)}/pulls/${n}`, { state: "closed" });
|
||||
}
|
||||
|
||||
combinedStatus(owner: string, repo: string, ref: string) {
|
||||
return this.request<GiteaCombinedStatus>("GET", `${this.repoPath(owner, repo)}/commits/${encodeURIComponent(ref)}/status`);
|
||||
}
|
||||
|
||||
@ -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<boolean> {
|
||||
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 };
|
||||
}
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -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();
|
||||
|
||||
Loading…
Reference in New Issue
Block a user