PEP-127: «Принять» при конфликте запоминается, вачдог доводит до мержа

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-15 18:01:27 +05:00
parent a5ba080fee
commit a3d784b812
12 changed files with 385 additions and 27 deletions

View File

@ -1,13 +1,13 @@
## 1. Ядро
- [ ] 1.1 `core/accept-pending.ts`: состояние `accept.pending:<taskId>` (get/set/clear/list), подпись статуса
- [ ] 1.2 `flow.ts`: `requestRebase` (из autonomy.ts), `acceptTask`/`acceptStory` откладывают «Принять» при конфликте, результат `pending`
- [ ] 1.3 `runner/accept-pending.ts`: `pendingAcceptTick` (мерж, повтор rebase, провал, сброс) + вызов в `tick` вачдога
- [ ] 1.4 Stop-хук, ревьюер и автомерж не трогают стори с запомненным «Принять»
- [x] 1.1 `core/accept-pending.ts`: состояние `accept.pending:<taskId>` (get/set/clear/list), подпись статуса
- [x] 1.2 `flow.ts`: `requestRebase` (из autonomy.ts), `acceptTask`/`acceptStory` откладывают «Принять» при конфликте, результат `pending`
- [x] 1.3 `runner/accept-pending.ts`: `pendingAcceptTick` (мерж, повтор rebase, провал, сброс) + вызов в `tick` вачдога
- [x] 1.4 Stop-хук, ревьюер и автомерж не трогают стори с запомненным «Принять»
## 2. Каналы
- [ ] 2.1 Раннер-сервис, бот, MCP PM, веб-экшены: ответ «принято, довожу»
- [ ] 2.2 Веб: статус на странице стори и карточке доски, кнопка «Принять» при конфликте
## 3. Проверка
- [ ] 3.1 e2e `accept-pending.test.ts` по сценариям спеки
- [x] 3.1 e2e `accept-pending.test.ts` по сценариям спеки
- [ ] 3.2 AGENTS.md, память, typecheck + e2e зелёные

View File

@ -0,0 +1,32 @@
// PEP-127: «Принять» pressed while the story's PR conflicts with the main branch is remembered —
// the agent rebases, Peppa merges and closes the story by itself (runner/accept-pending.ts).
import { settings, type Db } from "@peppa/db";
import { like } from "drizzle-orm";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
export interface PendingAccept {
/** When the PM accepted (ms). */
at: number;
/** Where «Принять» was pressed. */
via: string;
/** Rebase requests sent to the agent so far. */
rebases: number;
}
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 = "Принято — агент обновляет изменения, закроется само";
/** Answer that closes the ready-for-review message of a deferred accept. */
export const PENDING_ACCEPT_ANSWER = `✅ ${PENDING_ACCEPT_LABEL}`;
export const getPendingAccept = (db: Db, taskId: number) => getSetting<PendingAccept>(db, key(taskId));
export const setPendingAccept = (db: Db, taskId: number, s: PendingAccept) => setSetting(db, key(taskId), s);
export const clearPendingAccept = (db: Db, taskId: number) => deleteSetting(db, key(taskId));
/** All remembered accepts: task id → state. */
export async function listPendingAccepts(db: Db): Promise<Map<number, PendingAccept>> {
const rows = await db.select().from(settings).where(like(settings.key, `${PREFIX}%`));
return new Map(rows.map((r) => [Number(r.key.slice(PREFIX.length)), r.value as PendingAccept]));
}

View File

@ -40,6 +40,7 @@ export * from "./notifications.ts";
export * from "./digest.ts";
export * from "./platform-channel.ts";
export * from "./autonomy.ts";
export * from "./accept-pending.ts";
export * from "./openspec.ts";
export * from "./steps.ts";
export * from "./preview.ts";

View File

@ -0,0 +1,89 @@
// 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 { answerQuestion, askPm, clearPendingAccept, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef } from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { and, eq, isNull } from "drizzle-orm";
import { notifyPm } from "./autonomy.ts";
import { mergeOrCloseEmpty } from "./ci-feedback.ts";
import { moveTask, requestRebase } from "./flow.ts";
import { cleanupWorktree } from "./runners.ts";
import { resolveTaskById } from "./sessions.ts";
import { syncWorkspace } from "./workspace-sync.ts";
/** Rebase requests per accept before the PM is told it did not work out. */
export const ACCEPT_MAX_REBASES = 3;
const waitMs = () => (Number(process.env.PEPPA_ACCEPT_WAIT_HOURS) || 24) * 3_600_000;
export interface PendingAcceptTickOptions {
now?: Date;
gitea?: GiteaClient;
log?: (m: string) => void;
}
export async function pendingAcceptTick(db: Db, opts: PendingAcceptTickOptions = {}): Promise<void> {
const log = opts.log ?? (() => {});
const now = (opts.now ?? new Date()).getTime();
for (const [taskId, state] of await listPendingAccepts(db)) {
try {
await carry(db, taskId, state, now, opts.gitea, log);
} catch (e) {
log(`pending accept #${taskId}: ${(e as Error).message}`);
}
}
}
async function carry(db: Db, taskId: number, state: PendingAccept, now: number, client: GiteaClient | undefined, log: (m: string) => void) {
const ref = await resolveTaskById(db, taskId).catch(() => null);
// The PM took the story away (backlog, archive) or it is done already: nothing to carry.
if (!ref || ref.task.archivedAt || !["review", "in_progress", "proposing"].includes(ref.task.status)) {
await clearPendingAccept(db, taskId);
return;
}
const hours = Math.round(waitMs() / 3_600_000);
if (now - state.at > waitMs()) return fail(db, ref, `агент не обновил изменения за ${hours} ч`, "Откройте задачу: нажмите «Принять» ещё раз или напишите агенту, что сделать.", log);
if (!taskPrNumber(ref.project, ref.task.prUrl)) {
if (ref.task.status === "review") await finish(db, ref, log);
return;
}
const gitea = client ?? giteaForBot();
const gate = await prGate(ref, gitea); // Gitea down → the next tick tries again
const pull = gate.pull;
if (!pull) return;
if (pull.merged) return finish(db, ref, log);
if (pull.state !== "open") return fail(db, ref, "результат был закрыт и не попал в продукт", "Откройте задачу и напишите агенту, что сделать.", log);
// Merged only from review: the agent says itself that the rebase is finished.
if (ref.task.status !== "review") return;
if (gate.ok) {
await mergeOrCloseEmpty(ref, pull, gitea);
return finish(db, ref, log);
}
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);
}
await setPendingAccept(db, taskId, { ...state, rebases: state.rebases + 1 });
await requestRebase(db, ref);
log(`${ref.key}: accepted, conflicts again — rebase ${state.rebases + 1}/${ACCEPT_MAX_REBASES}`);
}
/** Merged: the story is closed like on «Принять», the PM is told. */
async function finish(db: Db, ref: TaskRef, log: (m: string) => void) {
await clearPendingAccept(db, ref.task.id);
const open = await db.select().from(questions).where(and(eq(questions.taskId, ref.task.id), isNull(questions.answeredAt)));
for (const q of open) await answerQuestion(db, q.id, "✅ Принято", "system").catch(() => {});
await moveTask(db, ref, "done");
for (const s of await listSessions(db, { taskId: ref.task.id })) if (s.workspacePath && ["done", "failed"].includes(s.status)) await cleanupWorktree(db, s).catch(() => {});
await syncWorkspace(db, ref).catch(() => {});
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_completed", payload: { pr: ref.task.prUrl } });
await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `✅ ${ref.key} «${ref.task.title}» принята и закрыта: агент обновил изменения, проверки пройдены.`);
log(`${ref.key}: accepted story merged and closed`);
}
/** Could not be carried through: forgotten, one message — what happened and what to do. */
async function fail(db: Db, ref: TaskRef, why: string, todo: string, log: (m: string) => void) {
await clearPendingAccept(db, ref.task.id);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_failed", payload: { why } });
await askPm(db, ref, { kind: "attention", text: `⚠️ ${ref.key} «${ref.task.title}»: не получилось довести приёмку до конца — ${why}. ${todo}` });
log(`${ref.key}: accepted story not merged — ${why}`);
}

View File

@ -6,6 +6,7 @@
import {
answerQuestion,
askPm,
getPendingAccept,
askPmProject,
blockedTaskIds,
enqueueTelegram,
@ -39,7 +40,7 @@ import {
import { goals, incidents, questions, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, eq, isNotNull, isNull } from "drizzle-orm";
import { acceptTask, moveTask } from "./flow.ts";
import { acceptTask, moveTask, requestRebase } from "./flow.ts";
import { autoMergeTask } from "./ci-feedback.ts";
import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts";
import { syncWorkspace } from "./workspace-sync.ts";
@ -108,6 +109,8 @@ export async function autonomyTick(db: Db, opts: AutonomyTickOptions = {}): Prom
async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, client: GiteaClient | undefined, log: (m: string) => void) {
for (const task of await listTasks(db, { projectId: project.id, statuses: ["review"] })) {
const ref = refOf(project, task);
// PEP-127: the PM accepted this story already — `pendingAcceptTick` merges and closes it.
if (await getPendingAccept(db, task.id)) continue;
const state = (await getSetting<MergeState>(db, mergeKey(task.id))) ?? {};
if (!taskPrNumber(project, task.prUrl)) {
await afterMerge(db, ref, a, state, log);
@ -141,17 +144,6 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c
}
}
async function requestRebase(db: Db, ref: TaskRef) {
const text = `Пеппа не может смержить PR ${ref.key}: конфликты с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок снова update_task(status: review).`;
const session = (await listSessions(db, { active: true, taskId: ref.task.id }))[0];
if (session) {
await sendToSession(db, session.id, text).catch(() => {});
await moveTask(db, ref, "in_progress");
} else {
await moveTask(db, ref, "in_progress", { prompt: text });
}
}
/** The PR is merged (or there is none): close the story or ask the PM, by `close`. */
async function afterMerge(db: Db, ref: TaskRef, a: AutonomySettings, state: MergeState, log: (m: string) => void) {
if (a.close === "after_merge") {
@ -217,7 +209,7 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n
}
/** A plain Telegram message (no question, nothing to answer) to the project's people. */
async function notifyPm(db: Db, projectId: number, dedupeKey: string, text: string) {
export async function notifyPm(db: Db, projectId: number, dedupeKey: string, text: string) {
for (const u of await questionRecipients(db, projectId)) {
await enqueueTelegram(db, { dedupeKey: `${dedupeKey}:${u.id}`, method: "sendMessage", params: { chat_id: u.telegramChatId, text } });
}

View File

@ -1,10 +1,10 @@
// PM-side moves on the task board and review acceptance (web and Telegram use these).
import { releaseIntake } from "./intake.ts";
import { answerQuestion, dropQueuedTask, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
import { answerQuestion, 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";
import { assertBudgetOpen, stopSession, type StartOptions } from "./sessions.ts";
import { assertBudgetOpen, sendToSession, stopSession, type StartOptions } from "./sessions.ts";
import { cleanupWorktree, releaseRunner, runnerFollowsQueue, startTaskOnRunner } from "./runners.ts";
import { mergeTaskPr } from "./ci-feedback.ts";
import { syncWorkspace } from "./workspace-sync.ts";
@ -107,16 +107,53 @@ export async function reorderBoardTask(db: Db, ref: TaskRef, r: ReorderTo) {
return reorderTask(db, ref, r, columnOf);
}
/** The agent of the story rebases its PR onto the fresh main branch (live runner or a new one); the story goes back to work. */
export async function requestRebase(db: Db, ref: TaskRef) {
const text = `Пеппа не может смержить PR ${ref.key}: конфликты с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок снова update_task(status: review).`;
const session = (await activeSessions(db, ref.task.id))[0];
if (session) {
await sendToSession(db, session.id, text).catch(() => {});
await moveTask(db, ref, "in_progress");
} else {
await moveTask(db, ref, "in_progress", { prompt: text });
}
}
/** A story reference from «Принять»; `pending` — accepted, Peppa carries it to the merge itself (PEP-127). */
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.
*/
async function deferAccept(db: Db, ref: TaskRef, via: string): Promise<boolean> {
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 });
try {
await requestRebase(db, ref);
} catch (e) {
// No agent could start (budget, subscription): nothing is remembered, the story stays in review.
await clearPendingAccept(db, ref.task.id);
const fresh = await resolveTask(db, ref.key);
if (fresh.task.status !== "review") await updateTask(db, fresh, { status: "review" }).catch(() => {});
throw new PeppaError(`Изменения нужно обновить перед приёмкой, но агент не запустился: ${(e as Error).message}`);
}
return true;
}
/**
* "Accept" on a ready-for-review message: the task's PR is merged (green checks, no
* conflicts — otherwise nothing changes and the PM sees why; Gitea deletes the branch),
* task done, session stopped, the working copy fast-forwarded to main.
*/
export async function acceptTask(db: Db, questionId: number, via: NonNullable<Question["answeredVia"]>, answer = "✅ Принято"): Promise<TaskRef> {
export async function acceptTask(db: Db, questionId: number, via: NonNullable<Question["answeredVia"]>, answer = "✅ Принято"): Promise<AcceptResult> {
const q = await getQuestion(db, questionId);
if (isRunnerClient()) {
const r = await runnerCall<{ key: string }>(db, "accept", { questionId, via, answer }, { key: q.taskId ? `task:${q.taskId}` : null });
return resolveTask(db, r.key);
const r = await runnerCall<{ key: string; pending?: boolean }>(db, "accept", { questionId, via, answer }, { key: q.taskId ? `task:${q.taskId}` : null });
return { ...(await resolveTask(db, r.key)), pending: !!r.pending };
}
if (!q.taskId) throw new PeppaError("Вопрос не привязан к задаче");
if (q.answeredAt) throw new PeppaError(`Уже отвечено (${q.answeredVia}): ${q.answer}`);
@ -127,6 +164,10 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable<Qu
.where(eq(tasks.id, q.taskId));
const ref = await resolveTask(db, formatTaskKey(t!.key, t!.number));
if (ref.task.status !== "review") throw new PeppaError(`${ref.key} не в ревью (сейчас ${ref.task.status})`);
if (await deferAccept(db, ref, via)) {
await answerQuestion(db, q.id, PENDING_ACCEPT_ANSWER, via).catch(() => {});
return { ...ref, pending: true };
}
await mergeTaskPr(ref);
// The merge webhook (PEP-46) may have closed the question and the story already.
await answerQuestion(db, q.id, answer, via).catch(() => {});
@ -142,11 +183,15 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable<Qu
* «Принять и смержить» on the story page (PEP-32): the open ready-for-review message is
* accepted like in the bot; without one the same steps run by hand (gate, merge, done, sync).
*/
export async function acceptStory(db: Db, ref: TaskRef, via: NonNullable<Question["answeredVia"]> = "web"): Promise<TaskRef> {
if (isRunnerClient()) return resolveTask(db, (await runnerCall<{ key: string }>(db, "acceptStory", { task: ref.key, via }, { key: `task:${ref.task.id}` })).key);
export async function acceptStory(db: Db, ref: TaskRef, via: NonNullable<Question["answeredVia"]> = "web"): Promise<AcceptResult> {
if (isRunnerClient()) {
const r = await runnerCall<{ key: string; pending?: boolean }>(db, "acceptStory", { task: ref.key, via }, { key: `task:${ref.task.id}` });
return { ...(await resolveTask(db, r.key)), pending: !!r.pending };
}
if (ref.task.status !== "review") throw new PeppaError(`${ref.key} не в ревью (сейчас ${ref.task.status})`);
const [open] = (await pendingQuestions(db, ref.project.id)).filter((q) => q.taskId === ref.task.id && q.kind === "attention").slice(-1);
if (open) return acceptTask(db, open.id, via);
if (await deferAccept(db, ref, via)) return { ...ref, pending: true };
await mergeTaskPr(ref);
await moveTask(db, ref, "done");
await syncWorkspace(db, ref).catch(() => {});

View File

@ -22,6 +22,7 @@ import {
getReviewSettings,
latestReview,
pendingReview,
getPendingAccept,
reviewNote,
reviewPreview,
reviewPreviewNote,
@ -221,6 +222,12 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
return null;
}
if (task?.status === "review" && (await getPendingAccept(db, task.id))) {
// PEP-127: the PM accepted already — the watchdog merges after green checks, no new review message.
await logSessionEvent(db, s, "awaiting_accept_merge", { pr: task.prUrl });
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
if (task?.status === "review" && (await getAutonomy(db, task.projectId)).merge === "auto") {
// PEP-25: Peppa merges this PR itself (watchdog); the PM hears only if it can't.
await logSessionEvent(db, s, "awaiting_automerge", { pr: task.prUrl });

View File

@ -30,6 +30,7 @@ export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
export * from "./autonomy.ts";
export * from "./accept-pending.ts";
export * from "./workspace-sync.ts";
export * from "./rotation.ts";
export * from "./live.ts";

View File

@ -12,6 +12,7 @@ import {
latestReview,
listSessions,
pendingReview,
getPendingAccept,
queueReview,
raiseSessionQuestion,
resolveTask,
@ -126,6 +127,8 @@ export type ReviewRequest =
export async function requestReview(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<ReviewRequest> {
const settings = await getReviewSettings(db, ref.project.id);
if (!settings.enabled) return { action: "review" };
// PEP-127: the PM accepted this story already; the rebase is not reviewed again.
if (await getPendingAccept(db, ref.task.id)) return { action: "review" };
const n = taskPrNumber(ref.project, ref.task.prUrl);
if (!n) return { action: "review" };
let sha: string;

View File

@ -29,8 +29,14 @@ export const RUNNER_COMMANDS: Record<string, Handler> = {
sendEscalated: async (db, p) => ({ result: await sendWithEscalation(db, p.sessionId, p.text) }),
move: async (db, p) => moveTask(db, await resolveTask(db, p.task), p.to as BoardColumn, p.start as StartOptions),
archive: async (db, p) => archiveTask(db, await resolveTask(db, p.task), !!p.archived),
accept: async (db, p) => ({ key: (await acceptTask(db, p.questionId, p.via as Via, p.answer)).key }),
acceptStory: async (db, p) => ({ key: (await acceptStory(db, await resolveTask(db, p.task), p.via as Via)).key }),
accept: async (db, p) => {
const r = await acceptTask(db, p.questionId, p.via as Via, p.answer);
return { key: r.key, pending: !!r.pending };
},
acceptStory: async (db, p) => {
const r = await acceptStory(db, await resolveTask(db, p.task), p.via as Via);
return { key: r.key, pending: !!r.pending };
},
answer: async (db, p) => {
const r = await answerAndDeliver(db, p.questionId, p.answer, p.via as Via);
return { delivered: r.delivered, questionId: r.question.id };

View File

@ -35,6 +35,7 @@ import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
import { autonomyTick } from "./autonomy.ts";
import { pendingAcceptTick } from "./accept-pending.ts";
import { intakeTick } from "./intake.ts";
import { storyRefineTick } from "./story-refine.ts";
import { analystChatTick } from "./analyst-chat.ts";
@ -98,6 +99,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake"));
// PEP-115: a comment on a backlog story — the analyst reworks the story.
await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine"));
// PEP-127: accepts remembered over a conflict — merge and close once the agent has rebased.
await pendingAcceptTick(db, { now: opts.now, log }).catch(failed(db, log, "pending accepts"));
await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy"));
// PEP-110: the analyst answers people in the projects' discussions.
await analystChatTick(db, { log }).catch(failed(db, log, "analyst chat"));

View File

@ -0,0 +1,179 @@
// PEP-127, spec task-autonomy «"Принять" при конфликте доводится до конца без PM»:
// 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-accept-")), "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" };
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<typeof project>[0]["turns"];
/** A story with an open green PR (task/<KEY>-1) in mock Gitea; `review` puts it in review right away. */
async function prTask(turns: Turns, review = true) {
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";
let n = 0;
const push = () => gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { [`f${n++}.txt`]: String(n) });
const green = (s: string) => {
for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, s, `peppa/${c}`, "success");
};
green(push());
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);
if (review) await core.updateTask(db, await ref(), { status: "review", prUrl });
const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!;
const status = async () => (await ref()).task.status;
const toReview = async () => core.updateTask(db, await ref(), { status: "review" });
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);
};
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 };
}
const tick = (now = new Date()) => runner.pendingAcceptTick(db, { now });
const failures = async (projectId: number) => (await core.pendingQuestions(db, projectId)).filter((q) => q.text.includes("не получилось довести приёмку"));
describe("accept over a conflict", () => {
test("Конфликт при «Принять» — закрывается само", async () => {
const t = await prTask(
[
[{ mcp: "update_task", args: { task: "1", status: "review" } }, { say: "PR открыт." }],
[{ mcp: "update_task", args: { task: "1", status: "review" } }, { say: "Rebase сделан." }],
],
false,
);
// The agent's first turn hands the story to review with the PR.
await core.updateTask(db, await t.ref(), { prUrl: t.prUrl });
const sid = await t.tp.start();
const review = await t.tp.waitQuestion(sid, "attention");
assert.match(review.text, /готова к ревью/);
t.pull().mergeable = false;
const r = await runner.acceptTask(db, review.id, "telegram");
t.pull().mergeable = true; // the agent "rebases" before its turn reaches update_task
assert.equal(r.pending, true, "accepted, carried through by Peppa");
assert.equal((await core.getQuestion(db, review.id)).answer, core.PENDING_ACCEPT_ANSWER);
assert.ok(await core.getPendingAccept(db, (await t.ref()).task.id));
const ev = await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase"));
assert.match(String(ev.prompt), /force-with-lease/);
// Back in review: no new «готова к ревью» for the PM.
await waitFor("stop hook saw the accept", async () => (await t.taskEvents("awaiting_accept_merge")).length || undefined);
assert.equal(await t.status(), "review");
assert.equal((await core.pendingQuestions(db, t.proj.id)).length, 0, "nothing new to answer");
assert.equal(t.pull().merged, false);
await tick();
assert.equal(t.pull().merged, true);
assert.equal(await t.status(), "done");
assert.equal(await core.getPendingAccept(db, (await t.ref()).task.id), null);
assert.equal((await t.taskEvents("accept_completed")).length, 1);
await t.tp.waitStatus(sid, "done");
});
test("Проверки после rebase ещё идут", async () => {
const t = await prTask([]);
t.pull().mergeable = false;
const r = await runner.acceptStory(db, await t.ref(), "web");
assert.equal(r.pending, true);
assert.equal(await t.status(), "in_progress", "the agent is rebasing");
await tick();
assert.equal(t.pull().merged, false, "not merged while the agent works");
const sha = t.push(); // the rebased head, checks not reported yet
t.pull().mergeable = true;
await t.toReview();
await tick();
assert.equal(t.pull().merged, false);
assert.equal(await t.status(), "review");
assert.equal((await failures(t.proj.id)).length, 0);
t.green(sha);
await tick();
assert.equal(t.pull().merged, true);
assert.equal(await t.status(), "done");
});
test("Три конфликта подряд", async () => {
const t = await prTask([]);
t.pull().mergeable = false;
await runner.acceptStory(db, await t.ref(), "web");
for (let i = 2; i <= runner.ACCEPT_MAX_REBASES; i++) {
await t.toReview();
await tick();
assert.equal(await t.status(), "in_progress", `rebase ${i} requested`);
assert.equal((await core.getPendingAccept(db, (await t.ref()).task.id))?.rebases, i);
}
await t.toReview();
await tick();
await tick();
const qs = await failures(t.proj.id);
assert.equal(qs.length, 1, "one message");
assert.match(qs[0]!.text, /Нажмите «Принять» ещё раз/);
assert.equal(await core.getPendingAccept(db, (await t.ref()).task.id), null);
assert.equal(await t.status(), "review");
// Nothing merges by itself any more, even when the conflict is gone.
t.pull().mergeable = true;
await tick();
assert.equal(t.pull().merged, false);
await t.stopAll();
});
test("Срок вышел: одно сообщение PM", async () => {
const t = await prTask([]);
t.pull().mergeable = false;
await runner.acceptStory(db, await t.ref(), "web");
await tick(new Date(Date.now() + 25 * 3_600_000));
const qs = await failures(t.proj.id);
assert.equal(qs.length, 1);
assert.match(qs[0]!.text, /за 24 ч/);
await t.stopAll();
});
test("PM забрал стори", async () => {
const t = await prTask([]);
t.pull().mergeable = false;
await runner.acceptStory(db, await t.ref(), "web");
await runner.moveTask(db, await t.ref(), "backlog");
await tick();
assert.equal(await core.getPendingAccept(db, (await t.ref()).task.id), null);
t.pull().mergeable = true;
await tick();
assert.equal(t.pull().merged, false);
assert.equal(await t.status(), "backlog");
});
test("без конфликта «Принять» работает как раньше", async () => {
const t = await prTask([]);
const r = await runner.acceptStory(db, await t.ref(), "web");
assert.ok(!r.pending);
assert.equal(t.pull().merged, true);
assert.equal(await t.status(), "done");
});
});