From f246813e358ad6bd3f099835bcbef8f23167f833 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 21:54:50 +0500 Subject: [PATCH] =?UTF-8?q?PEP-127:=20=D0=BC=D0=B5=D1=80=D0=B6=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D1=81=D0=BE=20=D1=81=D0=B2?= =?UTF-8?q?=D0=B5=D0=B6=D0=B8=D0=BC=20main=20=D0=B2=D0=BD=D1=83=D1=82?= =?UTF-8?q?=D1=80=D0=B8=20=E2=80=94=20Peppa=20=D1=81=D0=B0=D0=BC=D0=B0=20?= =?UTF-8?q?=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D1=8F=D0=B5=D1=82=20=D0=BE?= =?UTF-8?q?=D1=82=D1=81=D1=82=D0=B0=D0=B2=D1=88=D1=83=D1=8E=20=D0=B2=D0=B5?= =?UTF-8?q?=D1=82=D0=BA=D1=83=20=D0=B8=20=D0=B6=D0=B4=D1=91=D1=82=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BE=D0=BA;=20=C2=AB=D0=9F?= =?UTF-8?q?=D1=80=D0=B8=D0=BD=D1=8F=D1=82=D1=8C=C2=BB=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D0=BE=D0=BC=D0=B8=D0=BD=D0=B0=D0=B5=D1=82=D1=81=D1=8F=20=D0=B8?= =?UTF-8?q?=20=D0=BF=D1=80=D0=B8=20=D0=B8=D0=B4=D1=83=D1=89=D0=B8=D1=85=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 1 + apps/bot/src/bot.ts | 2 +- apps/web/app/(app)/t/[key]/tabs.tsx | 6 +- .../design.md | 12 +++ .../proposal.md | 17 ++++ .../specs/task-autonomy/spec.md | 29 ++++++ .../tasks.md | 7 ++ openspec/specs/task-autonomy/spec.md | 28 ++++++ packages/core/src/accept-pending.ts | 4 +- packages/core/src/ci.ts | 9 ++ packages/core/src/gitea.ts | 9 +- packages/core/src/review-card.ts | 2 + packages/mcp/src/manager.ts | 4 +- packages/runner/src/accept-pending.ts | 8 ++ packages/runner/src/autonomy.ts | 11 ++- packages/runner/src/flow.ts | 22 +++-- packages/runner/src/review-card.ts | 8 ++ packages/testkit/src/mock-gitea.ts | 32 ++++++- packages/testkit/test/accept-pending.test.ts | 89 ++++++++++++++++++- 19 files changed, 280 insertions(+), 20 deletions(-) create mode 100644 openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/design.md create mode 100644 openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/proposal.md create mode 100644 openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/specs/task-autonomy/spec.md create mode 100644 openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/tasks.md diff --git a/AGENTS.md b/AGENTS.md index 4e14f298..20aecaa8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,6 +46,7 @@ - **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок) - **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx` - **«Принять» при конфликте (PEP-127)**: PR стори конфликтует с основной веткой → `acceptTask`/`acceptStory` (runner/flow.ts `deferAccept`) не падают, а запоминают решение — `settings` `accept.pending:` (`core/accept-pending.ts`: `{at, via, rebases}`), вопрос «готово к ревью» закрывается ответом `PENDING_ACCEPT_ANSWER`, агент получает `requestRebase` (flow.ts; общий с автомержем), результат `pending: true` (бот/MCP/веб отвечают «принято, закроется само»). `pendingAcceptTick` (runner/accept-pending.ts, тик вачдога перед `autonomyTick`): стори в `review` и гейт зелёный → мерж, `done`, событие `accept_completed`, сообщение PM; снова конфликт → ещё rebase (до `ACCEPT_MAX_REBASES` = 3); провал (3 конфликта, PR закрыт, `PEPPA_ACCEPT_WAIT_HOURS` = 24) → состояние стирается, одно `attention` PM; стори ушла в бэклог/архив — стирается молча. Пока ждёт: Stop-хук не шлёт «готово к ревью» (`awaiting_accept_merge`), ревьюер и автомерж стори не трогают. Веб: плашка `PENDING_ACCEPT_LABEL` на странице стори и карточке доски, кнопка «Принять» на вкладке результата активна при конфликте. Красные/идущие проверки по-прежнему отказ с причиной. Тест `accept-pending.test.ts` +- **Мерж только со свежим main внутри (PEP-127)**: `prGate` закрыт с `behind: true`, если ветка открытого PR не содержит голову основной (`pullBehind`: `merge_base` ≠ `base.sha` из ответа Gitea); `reviewGate` агента `behind` пропускает. Обновляет Пеппа — `GiteaClient.updatePullBranch` (`POST /pulls/{n}/update`, merge), раз на head SHA (`updateSha` в `review.hold` / `accept.pending` / `autonomy.merge`), потом ждёт проверок нового коммита: `reviewCardTick`, `pendingAcceptTick`, `autoMergeReviews`. `deferAccept` запоминает «Принять» при конфликте, отставшей ветке и идущих проверках; красные — отказ с причиной - **«Готова к ревью» только когда можно смержить (PEP-127)**: `reviewGate` (flow.ts) при ошибке Gitea закрыт (`GATE_UNKNOWN_REASON`). Сообщение «готова к ревью» из Stop-хука и ревьюера идёт только через `sendReviewCard` (core/review-card.ts): `prGate` ok в момент отправки → вопрос `attention`; иначе придерживается в `settings` `review.hold:` (`{text, at, rebaseSha}`), событие `awaiting_checks`. `reviewCardTick` (runner/review-card.ts, вачдог раз в минуту рядом с `reviewTick`): придержанное → отправить при зелёном гейте; конфликт → `requestRebase` один раз на head SHA; открытое сообщение у PM и PR стал в конфликте → ответ system `REVIEW_REVOKED_ANSWER`, rebase, после возврата в ревью — новое сообщение. Новый путь, который шлёт PM «Принять», — только через `sendReviewCard`. `mock-gitea.down = true` — 500 на всё - **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning` - **Продакту — без технических вопросов (PEP-94)**: правила `template/RULES.md` — технику агент решает сам (`design.md`, `remember`), `ask_pm` — только продуктовое, простыми словами, рекомендация первой, ответа не ждёт; MCP `request_approval` отклоняется, если `proposal !== "pm"`; аналитик не спрашивает (вопросы → «Допущения» сразу); `NEW_PROJECT_AUTONOMY` = `auto`; в вебе Proposal → «План», вкладки стори по-русски (id прежние) diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index f80429d7..d07bbdb0 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -690,7 +690,7 @@ export function createBot(o: BotOptions) { try { const ref = await acceptTask(db, id, "telegram"); // PEP-127: over a conflict the accept is remembered and carried through. - toast = ref.pending ? `${ref.key}: принято ✅ Агент обновляет изменения, задача закроется сама` : `${ref.key} принята ✅`; + toast = ref.pending ? `${ref.key}: принято ✅ Изменения обновляются, задача закроется сама` : `${ref.key} принята ✅`; } catch (e) { toast = (e as Error).message; } diff --git a/apps/web/app/(app)/t/[key]/tabs.tsx b/apps/web/app/(app)/t/[key]/tabs.tsx index 494574e2..013fcc5b 100644 --- a/apps/web/app/(app)/t/[key]/tabs.tsx +++ b/apps/web/app/(app)/t/[key]/tabs.tsx @@ -305,8 +305,8 @@ export function MergeTab({ /** PEP-127: «Принять» is remembered — the agent updates the changes, Peppa closes the story itself. */ accepted?: boolean; }) { - // PEP-127: a conflict does not block «Принять» — it is remembered and carried through. - const conflict = pull?.state === "open" && pull.mergeable === false; + // PEP-127: an open PR that can't be merged yet does not block «Принять» — it is remembered and carried through. + const carried = pull?.state === "open" && !!gate && !gate.ok; if (!prUrl) return PR ещё нет — агент откроет его, когда закончит работу.; return (
@@ -352,7 +352,7 @@ export function MergeTab({ {taskStatus === "review" && !pull?.merged && !accepted && (
- diff --git a/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/design.md b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/design.md new file mode 100644 index 00000000..8012493c --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/design.md @@ -0,0 +1,12 @@ +# Design + +- **Признак отставания — из ответа Gitea о PR** (`merge_base` против `base.sha`), без лишнего + запроса compare; нет полей — считаем «не отстаёт» (как раньше). +- **Обновление — merge основной ветки в ветку PR через API Gitea**, а не rebase агентом: агент + не нужен, конфликтов нет (иначе `mergeable: false` и обычный путь rebase). Сбой обновления + (409) — следующая минута увидит конфликт. +- **Открытые сообщения у PM не отзываются при каждом движении main**: при 10+ стори в ревью + каждый мерж перезапускал бы проверки всех. Вместо этого «Принять» на отставшей ветке + запоминается («Принято — изменения обновляются, закроется само»): PM не видит отказа и не + нажимает дважды, мерж — только после проверок коммита со свежим main. +- Подпись статуса стала нейтральной («изменения обновляются»): обновляет не всегда агент. diff --git a/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/proposal.md b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/proposal.md new file mode 100644 index 00000000..f56eda0b --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/proposal.md @@ -0,0 +1,17 @@ +# Proposal: PEP-127 (дополнение координатора) — мерж только со свежим main внутри + +## Why +2026-11-15: PEP-124 и PEP-123 приняты подряд, у каждого PR проверки головы были зелёные, но после +второго мержа main стал красным (`pnpm lint`), и «Принять» перестал работать у всех задач. Зелёные +проверки ветки без текущего main ничего не говорят о результате мержа. + +## What Changes +- `prGate`: открытый PR, чья ветка не содержит текущую голову основной ветки (`merge_base` ≠ + `base.sha`), — гейт закрыт, `behind: true`. +- Ветку обновляет сама Пеппа: `GiteaClient.updatePullBranch` (`POST /pulls/{n}/update`), один раз + на головной коммит, дальше ждёт проверок нового коммита: перед отправкой «готова к ревью» + (`reviewCardTick`), после «Принять» (`pendingAcceptTick`), в автомерже (`autoMergeReviews`). +- «Принять» запоминается не только при конфликте, но и когда ветка отстала или проверки ещё идут; + красные проверки — по-прежнему отказ с причиной (спека delivery-pipeline). +- Агенту отставшая ветка не мешает отдать стори в ревью (`reviewGate` пропускает `behind`). +- `mock-gitea`: `base.sha`, `merge_base`, `POST /pulls/{n}/update`. diff --git a/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/specs/task-autonomy/spec.md b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/specs/task-autonomy/spec.md new file mode 100644 index 00000000..1327eb77 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/specs/task-autonomy/spec.md @@ -0,0 +1,29 @@ +## ADDED Requirements + +### Requirement: Мерж только со свежей основной веткой внутри +PR стори SHALL мержиться («Принять», автомерж), только если его ветка содержит текущую голову основной ветки и проверки этого головного коммита зелёные. Отставшую ветку Пеппа SHALL обновлять сама через Gitea и ждать проверок нового коммита; сообщение «готова к ревью» в это время MUST NOT уходить PM, а нажатое «Принять» SHALL запоминаться без отказа. + +#### Scenario: Основная ветка ушла вперёд перед «Принять» +- **GIVEN** стори «AUTO-1» в ревью с зелёными проверками +- **AND** в основную ветку смержена другая стори, конфликта нет +- **WHEN** PM нажимает «Принять» +- **THEN** ошибки нет, PR не смержен, ветка PR обновлена и содержит голову основной ветки +- **AND** после зелёных проверок нового коммита PR смержен и стори «Готово» + +#### Scenario: Вместе со свежей основной веткой проверки красные +- **GIVEN** «Принять» по «AUTO-1» запомнено, ветка обновлена +- **AND** проверка «test» нового коммита провалена +- **WHEN** проходит тик вачдога +- **THEN** PR не смержен, основная ветка остаётся зелёной + +#### Scenario: Сообщение PM ждёт обновления ветки +- **GIVEN** стори «AUTO-1» в ревью, её ветка отстаёт от основной +- **WHEN** проходит проверка вачдога +- **THEN** ветка обновлена, PM ничего не получает +- **AND** после зелёных проверок нового коммита PM получает «готова к ревью» + +#### Scenario: Автомерж отставшей ветки +- **GIVEN** проект с автомержем, стори «AUTO-1» в ревью, ветка отстаёт от основной +- **WHEN** проходит тик автономности +- **THEN** PR не смержен, ветка обновлена +- **AND** после зелёных проверок нового коммита PR смержен diff --git a/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/tasks.md b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/tasks.md new file mode 100644 index 00000000..43913805 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-127-merge-with-current-main/tasks.md @@ -0,0 +1,7 @@ +## 1. Код +- [x] 1.1 `prGate`: `behind`; `GiteaClient.updatePullBranch` +- [x] 1.2 «Принять» запоминается при отставшей ветке и идущих проверках; `pendingAcceptTick` обновляет ветку +- [x] 1.3 `reviewCardTick` и автомерж обновляют отставшую ветку +## 2. Проверка +- [x] 2.1 mock-gitea (`base.sha`, `merge_base`, update), тесты сценариев +- [x] 2.2 AGENTS.md, полный прогон diff --git a/openspec/specs/task-autonomy/spec.md b/openspec/specs/task-autonomy/spec.md index 21dfe548..409f6125 100644 --- a/openspec/specs/task-autonomy/spec.md +++ b/openspec/specs/task-autonomy/spec.md @@ -103,3 +103,31 @@ - **WHEN** проходит проверка вачдога - **THEN** сообщение закрыто ответом «Агент обновляет изменения — пришлём задачу снова, когда её можно будет принять» - **AND** агент получает задание на rebase, а после зелёных проверок PM получает новое сообщение + +### Requirement: Мерж только со свежей основной веткой внутри +PR стори SHALL мержиться («Принять», автомерж), только если его ветка содержит текущую голову основной ветки и проверки этого головного коммита зелёные. Отставшую ветку Пеппа SHALL обновлять сама через Gitea и ждать проверок нового коммита; сообщение «готова к ревью» в это время MUST NOT уходить PM, а нажатое «Принять» SHALL запоминаться без отказа. + +#### Scenario: Основная ветка ушла вперёд перед «Принять» +- **GIVEN** стори «AUTO-1» в ревью с зелёными проверками +- **AND** в основную ветку смержена другая стори, конфликта нет +- **WHEN** PM нажимает «Принять» +- **THEN** ошибки нет, PR не смержен, ветка PR обновлена и содержит голову основной ветки +- **AND** после зелёных проверок нового коммита PR смержен и стори «Готово» + +#### Scenario: Вместе со свежей основной веткой проверки красные +- **GIVEN** «Принять» по «AUTO-1» запомнено, ветка обновлена +- **AND** проверка «test» нового коммита провалена +- **WHEN** проходит тик вачдога +- **THEN** PR не смержен, основная ветка остаётся зелёной + +#### Scenario: Сообщение PM ждёт обновления ветки +- **GIVEN** стори «AUTO-1» в ревью, её ветка отстаёт от основной +- **WHEN** проходит проверка вачдога +- **THEN** ветка обновлена, PM ничего не получает +- **AND** после зелёных проверок нового коммита PM получает «готова к ревью» + +#### Scenario: Автомерж отставшей ветки +- **GIVEN** проект с автомержем, стори «AUTO-1» в ревью, ветка отстаёт от основной +- **WHEN** проходит тик автономности +- **THEN** PR не смержен, ветка обновлена +- **AND** после зелёных проверок нового коммита PR смержен diff --git a/packages/core/src/accept-pending.ts b/packages/core/src/accept-pending.ts index 09bc36a7..092e0a04 100644 --- a/packages/core/src/accept-pending.ts +++ b/packages/core/src/accept-pending.ts @@ -11,13 +11,15 @@ export interface PendingAccept { via: string; /** Rebase requests sent to the agent so far. */ rebases: number; + /** Head SHA for which Peppa asked Gitea to bring the base branch into the PR branch. */ + updateSha?: string; } const PREFIX = "accept.pending:"; const key = (taskId: number) => `${PREFIX}${taskId}`; /** What the PM sees on the story while the accept is being carried through. */ -export const PENDING_ACCEPT_LABEL = "Принято — агент обновляет изменения, закроется само"; +export const PENDING_ACCEPT_LABEL = "Принято — изменения обновляются, закроется само"; /** Answer that closes the ready-for-review message of a deferred accept. */ export const PENDING_ACCEPT_ANSWER = `✅ ${PENDING_ACCEPT_LABEL}`; diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts index 06a5a5cb..89698d43 100644 --- a/packages/core/src/ci.ts +++ b/packages/core/src/ci.ts @@ -131,6 +131,13 @@ export interface GateResult { reason?: string; summary: CiSummary | null; pull: GiteaPull | null; + /** PEP-127: the only obstacle — the PR branch lacks the current head of the base branch (Peppa updates it itself). */ + behind?: boolean; +} + +/** True when the PR branch does not contain the current head of its base branch. */ +export function pullBehind(pull: GiteaPull): boolean { + return pull.state === "open" && !pull.merged && !!pull.merge_base && !!pull.base.sha && pull.merge_base !== pull.base.sha; } /** @@ -152,6 +159,8 @@ export async function prGate(ref: TaskRef, client?: GiteaClient): Promise f.check).join(", ")})`, summary, pull }; if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: `проверки ещё идут (${summary.passed} из ${summary.total})`, summary, pull }; if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: "есть конфликты с основной веткой", summary, pull }; + // PEP-127: green checks of a head that lacks the fresh base prove nothing about the merge result. + if (pullBehind(pull)) return { ok: false, behind: true, reason: "ветка отстаёт от основной — Пеппа обновляет её и ждёт проверок", summary, pull }; return { ok: true, summary, pull }; } diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index 6afff4b7..249256ce 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -35,7 +35,9 @@ export interface GiteaPull { merged: boolean; mergeable: boolean; head: { ref: string; sha: string; repo?: { full_name: string } | null }; - base: { ref: string }; + base: { ref: string; sha?: string }; + /** Common ancestor of the head and the base branch; ≠ base.sha — the branch is behind the base. */ + merge_base?: string; } export interface GiteaBranch { name: string; @@ -270,6 +272,11 @@ export class GiteaClient { return r.total_commits ?? r.commits?.length ?? 0; } + /** PEP-127: brings the base branch into the PR branch (a merge commit by the token's user); fails on a conflict. */ + updatePullBranch(owner: string, repo: string, n: number) { + return this.request("POST", `${this.repoPath(owner, repo)}/pulls/${n}/update?style=merge`); + } + closePullRequest(owner: string, repo: string, n: number) { return this.request("PATCH", `${this.repoPath(owner, repo)}/pulls/${n}`, { state: "closed" }); } diff --git a/packages/core/src/review-card.ts b/packages/core/src/review-card.ts index 8ffa7e5d..e1425849 100644 --- a/packages/core/src/review-card.ts +++ b/packages/core/src/review-card.ts @@ -18,6 +18,8 @@ export interface ReviewHold { at: number; /** Head SHA the agent was asked to rebase (once per head commit). */ rebaseSha?: string; + /** Head SHA for which Peppa asked Gitea to bring the base branch into the PR branch. */ + updateSha?: string; } const PREFIX = "review.hold:"; diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index ffad236a..368b5e01 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -522,7 +522,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ tool( "answer_question", - "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the story's PR (only with green CI checks, otherwise the reason is returned; on a conflict the accept is remembered — the agent rebases and Peppa merges and closes the story by itself) and closes the story, any other text goes back to the agent.", + "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the story's PR (when it can't be merged yet — conflict, behind the main branch, checks not green — the accept is remembered and Peppa merges and closes the story by itself after green checks) and closes the story, any other text goes back to the agent.", { question_id: z.number().int(), answer: z.string().min(1) }, false, async ({ question_id, answer }) => { @@ -531,7 +531,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ if (q.answeredAt) return `Already answered (${q.answeredVia}): ${q.answer}`; if (answer.trim().toLowerCase() === "accept" && (await isReviewQuestion(db, q))) { const ref = await acceptTask(db, q.id, "web"); - return ref.pending ? `${ref.key} accepted. Its changes conflict with the main branch: the agent is rebasing, Peppa will merge and close the story by itself after green checks — nothing more to press.` : `${ref.key} accepted → Done`; + return ref.pending ? `${ref.key} accepted. Its PR can't be merged right now (conflict, behind the main branch, or checks not green yet): Peppa brings it up to date, merges and closes the story by itself after green checks — nothing more to press.` : `${ref.key} accepted → Done`; } const { delivered } = await answerAndDeliver(db, q.id, answer, "web"); return delivered ? "Delivered to the agent session." : "Saved; the session is not running right now."; diff --git a/packages/runner/src/accept-pending.ts b/packages/runner/src/accept-pending.ts index 0163fe9c..9bac52db 100644 --- a/packages/runner/src/accept-pending.ts +++ b/packages/runner/src/accept-pending.ts @@ -58,6 +58,14 @@ async function carry(db: Db, taskId: number, state: PendingAccept, now: number, await mergeOrCloseEmpty(ref, pull, gitea); return finish(db, ref, log); } + if (gate.behind) { + // The main branch moved on: Peppa updates the PR branch itself (once per head) and waits for its checks. + if (state.updateSha === pull.head.sha) return; + await setPendingAccept(db, taskId, { ...state, updateSha: pull.head.sha }); + await gitea.updatePullBranch(ref.project.giteaOwner, ref.project.giteaRepo, pull.number); + log(`${ref.key}: accepted, behind the main branch — PR branch updated`); + return; + } if (pull.mergeable !== false) return; // checks are running or red — CI feedback handles red if (state.rebases >= ACCEPT_MAX_REBASES) { return fail(db, ref, "изменения несколько раз подряд разошлись с основной версией", "Нажмите «Принять» ещё раз чуть позже или напишите агенту, что поправить.", log); diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index 0647fa2b..24d1b669 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -81,6 +81,8 @@ interface MergeState { pipelineSha?: string; /** Head SHA the agent was asked to rebase. */ rebaseSha?: string; + /** Head SHA for which Peppa asked Gitea to bring the main branch into the PR branch (PEP-127). */ + updateSha?: string; /** PR (or "no-pr") for which the "merged, accept?" message was raised. */ reviewFor?: string; } @@ -129,6 +131,11 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c await setSetting(db, mergeKey(task.id), { ...state, rebaseSha: sha }); await requestRebase(db, ref); log(`${ref.key}: conflicts — rebase requested`); + } else if (gate.behind && state.updateSha !== sha) { + // PEP-127: merged only with the current main inside — update the branch, wait for its checks. + await setSetting(db, mergeKey(task.id), { ...state, updateSha: sha }); + await gitea.updatePullBranch(project.giteaOwner, project.giteaRepo, gate.pull.number).catch((e) => log(`${ref.key}: branch update failed — ${(e as Error).message}`)); + log(`${ref.key}: behind the main branch — PR branch updated`); } continue; } @@ -194,7 +201,9 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n } } try { - await acceptTask(db, q.id, "system", `✅ Принято автоматически: ${a.closeAfterHours} ч без замечаний`); + const r = await acceptTask(db, q.id, "system", `✅ Принято автоматически: ${a.closeAfterHours} ч без замечаний`); + // PEP-127: not mergeable yet — remembered, `pendingAcceptTick` closes the story and tells the PM. + if (r.pending) continue; await notifyPm(db, project.id, `auto:accepted:${q.id}`, `🤖 ${ref.key} «${task.title}» закрыта автоматически: ${a.closeAfterHours} ч без замечаний.`); log(`${ref.key}: closed after ${a.closeAfterHours}h`); } catch (e) { diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index 43cd277e..ea45f2e7 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -1,6 +1,6 @@ // PM-side moves on the task board and review acceptance (web and Telegram use these). import { releaseIntake } from "./intake.ts"; -import { answerQuestion, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core"; +import { answerQuestion, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core"; import { tasks, projects, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { eq } from "drizzle-orm"; @@ -33,7 +33,8 @@ async function activeSessions(db: Db, taskId: number) { export async function reviewGate(ref: TaskRef): Promise { const gate = await prGate(ref).catch(() => null); if (!gate) return GATE_UNKNOWN_REASON; - return gate.ok ? null : gate.reason ?? "проверки не пройдены"; + // A branch that is only behind the base is updated by Peppa itself before the PM hears (PEP-127). + return gate.ok || gate.behind ? null : gate.reason ?? "проверки не пройдены"; } /** @@ -124,15 +125,22 @@ export async function requestRebase(db: Db, ref: TaskRef) { export type AcceptResult = TaskRef & { pending?: boolean }; /** - * PEP-127: the PR conflicts with the main branch → the accept is remembered instead of failing: - * the agent gets the rebase, `pendingAcceptTick` merges and closes the story once it is back in - * review with green checks. False — no conflict, accept the usual way. + * PEP-127: the PR can't be merged right now → the accept is remembered instead of failing, and + * `pendingAcceptTick` merges and closes the story once it is in review, up to date and green. + * A conflict: the agent rebases. Behind the base: Peppa updates the branch (Gitea) and waits for + * the checks of the new head. Checks still running: wait. Red checks are not deferred. + * False — mergeable now (or no PR, or Gitea can't be asked): accept the usual way. */ async function deferAccept(db: Db, ref: TaskRef, via: string): Promise { const gate = await prGate(ref).catch(() => null); const pull = gate?.pull; - if (!pull || pull.merged || pull.state !== "open" || pull.mergeable !== false) return false; - await setPendingAccept(db, ref.task.id, { at: Date.now(), via, rebases: 1 }); + if (!gate || gate.ok || !pull || pull.merged || pull.state !== "open") return false; + // Red checks are refused with the reason, as before (spec delivery-pipeline): the agent fixes them first. + if (gate.summary?.state === "failure") return false; + const conflict = pull.mergeable === false; + await setPendingAccept(db, ref.task.id, { at: Date.now(), via, rebases: conflict ? 1 : 0, ...(gate.behind ? { updateSha: pull.head.sha } : {}) }); + if (gate.behind) await giteaForBot().updatePullBranch(ref.project.giteaOwner, ref.project.giteaRepo, pull.number).catch(() => {}); + if (!conflict) return true; try { await requestRebase(db, ref); } catch (e) { diff --git a/packages/runner/src/review-card.ts b/packages/runner/src/review-card.ts index 0ebbc4ac..b9041667 100644 --- a/packages/runner/src/review-card.ts +++ b/packages/runner/src/review-card.ts @@ -45,6 +45,14 @@ async function releaseHeld(db: Db, taskId: number, hold: ReviewHold, client: Git return; } const pull = gate.pull; + if (pull && gate.behind) { + // The main branch moved on: Peppa updates the PR branch itself (once per head); the PM hears after its checks. + if (hold.updateSha === pull.head.sha) return; + await setReviewHold(db, taskId, { ...hold, updateSha: pull.head.sha }); + await gitea.updatePullBranch(ref.project.giteaOwner, ref.project.giteaRepo, pull.number); + log(`${ref.key}: in review, behind the main branch — PR branch updated`); + return; + } if (pull && pull.state === "open" && pull.mergeable === false && hold.rebaseSha !== pull.head.sha) { await setReviewHold(db, taskId, { ...hold, rebaseSha: pull.head.sha }); await requestRebase(db, ref); diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 29fcf29c..4dce78b2 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -230,6 +230,26 @@ export class MockGitea { return out; } + private tryGit(r: MockRepo, args: string[]): string { + try { + return execFileSync("git", ["--git-dir", r.path, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); + } catch { + return ""; + } + } + + /** `POST /pulls/{n}/update`: the base branch merged into the PR branch; false on a conflict. */ + updateBranch(r: MockRepo, p: MockPull): boolean { + const work = `${r.path}-u${this.seq++}`; + execFileSync("git", ["clone", "-q", r.path, work]); + try { + execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git checkout -q ${p.head} && git -c user.name=t -c user.email=t@t merge -q --no-edit origin/${p.base} && git push -q origin ${p.head}`], { stdio: "ignore" }); + return true; + } catch { + return false; + } + } + pullJson(r: MockRepo, p: MockPull) { let sha = ""; try { @@ -244,7 +264,8 @@ export class MockGitea { merged: p.merged, mergeable: p.mergeable, head: { ref: p.head, sha, repo: { full_name: `${r.owner}/${r.name}` } }, - base: { ref: p.base }, + base: { ref: p.base, sha: this.tryGit(r, ["rev-parse", p.base]) }, + merge_base: this.tryGit(r, ["merge-base", p.base, p.head]), }; } @@ -259,7 +280,7 @@ export class MockGitea { return { state, sha, statuses }; } - private ahead(r: MockRepo, base: string, head: string): number { + ahead(r: MockRepo, base: string, head: string): number { return Number(execFileSync("git", ["--git-dir", r.path, "rev-list", "--count", `${base}..${head}`], { encoding: "utf8" }).trim()); } @@ -438,7 +459,7 @@ export class MockGitea { if (!p) return { status: 404, body: { message: "pull not found" } }; return { status: 200, text: execFileSync("git", ["--git-dir", r.path, "diff", `${p.base}...${p.head}`], { encoding: "utf8" }) }; } - if ((m = sub.match(/^pulls\/(\d+)(\/files|\/merge)?$/))) { + if ((m = sub.match(/^pulls\/(\d+)(\/files|\/merge|\/update)?$/))) { 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) }; @@ -451,6 +472,11 @@ export class MockGitea { 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 })) : [] }; } + if (method === "POST" && m[2] === "/update") { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + if (!p.mergeable || !this.updateBranch(r, p)) return { status: 409, body: { message: "merge conflict" } }; + return { status: 200 }; + } if (method === "POST" && m[2] === "/merge") { if (!canWrite) return { status: 403, body: { message: "forbidden" } }; if (p.merged) return { status: 405, body: { message: "already merged" } }; diff --git a/packages/testkit/test/accept-pending.test.ts b/packages/testkit/test/accept-pending.test.ts index 29b14c8a..770e99ca 100644 --- a/packages/testkit/test/accept-pending.test.ts +++ b/packages/testkit/test/accept-pending.test.ts @@ -52,8 +52,12 @@ async function prTask(turns: Turns, review = true) { const stopAll = async () => { for (const s of (await core.listSessions(db, { active: true })).filter((s) => s.projectId === proj.id)) await runner.stopSession(db, s.id); }; + /** Someone else's story lands in main: the PR branch is behind now (no conflict). */ + const mainMoves = () => gitea.commit(proj.giteaOwner, proj.giteaRepo, "main", { [`main${n++}.txt`]: "m" }); + const head = () => gitea.sha(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); + const contains = (sha: string) => gitea.ahead(gitea.repo(proj.giteaOwner, proj.giteaRepo), `task/${tp.taskKey}`, sha) === 0; const taskEvents = async (type: string) => db.select().from(events).where(and(eq(events.taskId, (await ref()).task.id), eq(events.type, type))); - return { tp, proj, prUrl, push, green, ref, pull, status, toReview, stopAll, taskEvents }; + return { tp, proj, prUrl, push, green, ref, pull, status, toReview, stopAll, taskEvents, mainMoves, head, contains }; } const tick = (now = new Date()) => runner.pendingAcceptTick(db, { now }); @@ -277,3 +281,86 @@ describe("ready-for-review only when mergeable", () => { await t.stopAll(); }); }); + +// PEP-127 (дополнение координатора): зелёные проверки головы PR без свежего main ничего не +// гарантируют — перед «Принять» и автомержем ветка должна содержать текущую голову main. +describe("merge only with the current main inside", () => { + test("Main ушёл вперёд — «Принять» запоминается, ветка обновляется, мерж после проверок нового коммита", async () => { + const t = await prTask([]); + const before = t.head(); + const main = t.mainMoves(); + const r = await runner.acceptStory(db, await t.ref(), "web"); + assert.equal(r.pending, true, "not merged on stale checks"); + assert.equal(t.pull().merged, false); + assert.notEqual(t.head(), before, "Peppa updated the PR branch itself"); + assert.ok(t.contains(main), "the branch has the current main"); + assert.equal(await t.status(), "review", "no agent needed"); + await tick(); + assert.equal(t.pull().merged, false, "checks of the new head are not there yet"); + t.green(t.head()); + await tick(); + assert.equal(t.pull().merged, true); + assert.equal(await t.status(), "done"); + }); + + test("Два зелёных PR подряд: второй не мержится, если вместе с main проверки красные", async () => { + const t = await prTask([]); + t.mainMoves(); + await runner.acceptStory(db, await t.ref(), "web"); + gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, t.head(), "peppa/typecheck", "success"); + gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, t.head(), "peppa/test", "failure"); + await tick(); + assert.equal(t.pull().merged, false, "main stays green"); + assert.notEqual(await t.status(), "done"); + await t.stopAll(); + }); + + test("Проверки ещё идут при «Принять» — запоминается и закрывается само", async () => { + const t = await prTask([]); + const sha = t.push(); + const r = await runner.acceptStory(db, await t.ref(), "web"); + assert.equal(r.pending, true); + await tick(); + assert.equal(t.pull().merged, false); + t.green(sha); + await tick(); + assert.equal(t.pull().merged, true); + assert.equal(await t.status(), "done"); + }); + + test("Сообщение PM не уходит, пока ветка отстаёт от main", async () => { + const t = await prTask([]); + const main = t.mainMoves(); + assert.equal(await core.sendReviewCard(db, await t.ref(), CARD), null, "held"); + await cardTick(); + assert.ok(t.contains(main), "branch updated by Peppa"); + await cardTick(); + assert.equal((await cards(t.proj.id)).length, 0, "waiting for the checks of the new head"); + t.green(t.head()); + await cardTick(); + assert.equal((await cards(t.proj.id)).length, 1); + }); + + test("Агент отдаёт в ревью отставшую ветку — можно: обновит Peppa", async () => { + const t = await prTask([], false); + await core.updateTask(db, await t.ref(), { status: "in_progress", prUrl: t.prUrl }); + t.mainMoves(); + await runner.moveTask(db, await t.ref(), "review"); + assert.equal(await t.status(), "review"); + }); + + test("Автомерж: отставшая ветка сначала обновляется", async () => { + const t = await prTask([]); + await core.setAutonomy(db, t.proj.id, { merge: "auto", close: "after_merge", quietFrom: null, quietTo: null }); + const main = t.mainMoves(); + await runner.autonomyTick(db, {}); + assert.equal(t.pull().merged, false); + assert.ok(t.contains(main)); + await runner.autonomyTick(db, {}); + assert.equal(t.pull().merged, false, "checks of the new head pending"); + t.green(t.head()); + await runner.autonomyTick(db, {}); + assert.equal(t.pull().merged, true); + assert.equal(await t.status(), "done"); + }); +});