peppa/packages/runner/src/conflict-step.ts
peppa-bot ec1d042b0a
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/test test: success за 1546с
peppa-ci / ci (pull_request) Successful in 29m2s
PEP-297: время в очереди на агента — не молчание агента в шаге конфликта
После выкатки PEP-269 задача с конфликтом, которая стояла в очереди на агента
(предел задач на код), через 90 минут эскалировалась суперадмину как «агент не
обновил изменения», хотя агент ещё не стартовал: 15 ложных сообщений за полтора
часа. Пока задача ждёт места (isWaitingForCapacity), шаг — «ждём», а время
агента отсчитывается с момента, когда он получил место.

Тест в conflict-step.test.ts падал до исправления.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 20:53:41 +05:00

209 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-269: a conflict of the story's result with the main branch is one step, not a loop of
// relaunches. PEP-217 stood in work for over a day: five places (the accept, the held
// «готово», the revoked card, the auto-merge, the stuck healing) each asked the agent to rebase
// with their own counters. Now they all call `conflictStep`:
// - first sight of the conflict → one request to the agent (rebase, resolve, force-push);
// - the agent pushed and the main branch moved on meanwhile → a second and last request;
// - the agent pushed and the conflict stays, or it did not push for CONFLICT_WAIT_MIN and does not
// work → a person: one delay card to the superadmin (PEP-150) with the conflicting files.
// The state lives in `conflict.step:<taskId>`; `conflictStepTick` clears it once the conflict is
// gone and escalates a silent agent.
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
clearPlatformDelay,
deleteSetting,
getSetting,
giteaForBot,
isProjectPaused,
isWaitingForCapacity,
listSessions,
logEvent,
platformDelay,
prGate,
setSetting,
type GiteaClient,
type GiteaPull,
type TaskRef,
} from "@peppa/core";
import { settings, keyPrefix, type Db } from "@peppa/db";
import { asIs, m } from "@peppa/shared/i18n";
import { requestRebase } from "./flow.ts";
import { credentialHelper, run } from "./git.ts";
import { resolveTaskById } from "./sessions.ts";
type Log = (m: string) => void;
/** Requests to the agent per conflict: the second one only when the main branch moved on after its push. */
export const CONFLICT_MAX_ATTEMPTS = 2;
/** The agent has this long (min) to update its result while it does not work. */
export const CONFLICT_WAIT_MIN = 90;
/** A new head is judged only after Gitea had this long (min) to re-check it. */
export const CONFLICT_SETTLE_MIN = 2;
export interface ConflictStep {
/** Head of the result and of the main branch when the agent was last asked. */
headSha: string;
baseSha: string | null;
/** When the agent was asked; while the story waits for a place among the agents — the last minute of that wait (PEP-297). */
at: number;
attempts: number;
/** A new head of the result first seen (Gitea re-checks mergeability in the background after a push). */
seen?: { sha: string; at: number };
/** A person decides: why and which files. */
escalated?: { at: number; why: string; files: string[] };
}
export type ConflictOutcome = "requested" | "waiting" | "held" | "escalated";
const PREFIX = "conflict.step:";
const stepKey = (taskId: number) => `${PREFIX}${taskId}`;
export const getConflictStep = (db: Db, taskId: number) => getSetting<ConflictStep>(db, stepKey(taskId));
/** The conflict is gone (or the story left work): the step and its delay card go. */
export async function clearConflictStep(db: Db, ref: Pick<TaskRef, "project" | "task">, log?: Log): Promise<void> {
const step = await getConflictStep(db, ref.task.id);
if (!step) return;
await deleteSetting(db, stepKey(ref.task.id));
await clearPlatformDelay(db, { projectId: ref.project.id, taskId: ref.task.id }, "conflict");
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_resolved", payload: { attempts: step.attempts, escalated: !!step.escalated } });
log?.(`#${ref.task.id}: conflict step over`);
}
type FilesLister = (ref: TaskRef, pull: GiteaPull) => Promise<string[] | null>;
let filesLister: FilesLister = gitConflictFiles;
/** Tests: the conflicting files without a real merge. */
export function setConflictFilesLister(f: FilesLister | null): void {
filesLister = f ?? gitConflictFiles;
}
/** A git call bounded in time: the list of files must never hold the escalation (CI, a slow Gitea). */
const GIT_TIMEOUT_MS = 20_000;
const git = (cwd: string, ...args: string[]) =>
run("git", ["-c", "credential.helper=", "-c", `credential.helper=${credentialHelper()}`, ...args], {
cwd,
timeout: GIT_TIMEOUT_MS,
killSignal: "SIGKILL",
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
});
/**
* The files that conflict: fetch both heads into the project's working copy (objects and
* FETCH_HEAD only, the working tree is untouched) and `git merge-tree` them. Null — unknown.
*/
async function gitConflictFiles(ref: TaskRef, pull: GiteaPull): Promise<string[] | null> {
const dir = ref.project.workspacePath;
if (!dir || !existsSync(join(dir, ".git"))) return null;
try {
await git(dir, "fetch", "--no-tags", "origin", pull.base.ref, pull.head.ref);
const base = (await git(dir, "rev-parse", `origin/${pull.base.ref}`).catch(() => null))?.stdout.trim() || pull.base.sha;
if (!base) return null;
const out = await git(dir, "merge-tree", "--write-tree", "--name-only", "--no-messages", base, pull.head.sha).then(
(r) => r.stdout,
(e: { code?: number; stdout?: string }) => (e.code === 1 ? (e.stdout ?? "") : null),
);
if (out == null) return null;
// The first line is the tree; the rest — the conflicted files.
return [...new Set(out.split("\n").slice(1).map((l) => l.trim()).filter(Boolean))];
} catch {
return null;
}
}
const working = async (db: Db, taskId: number) => (await listSessions(db, { active: true, taskId })).some((s) => ["starting", "running"].includes(s.status));
/** Asks the agent (returns false when the checks queue or the running checks hold the request). */
async function ask(db: Db, ref: TaskRef, pull: GiteaPull, attempts: number, now: number, log: Log, force?: boolean): Promise<boolean> {
if (!(await requestRebase(db, ref, { force }))) return false;
await setSetting(db, stepKey(ref.task.id), { headSha: pull.head.sha, baseSha: pull.base.sha ?? null, at: now, attempts } satisfies ConflictStep);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_rebase_requested", payload: { attempt: attempts, head: pull.head.sha } });
log(`${ref.key}: conflict with the main branch — rebase requested (${attempts}/${CONFLICT_MAX_ATTEMPTS})`);
return true;
}
async function escalate(db: Db, ref: TaskRef, pull: GiteaPull, step: ConflictStep, why: string, now: number, log: Log): Promise<ConflictOutcome> {
const files = (await filesLister(ref, pull).catch(() => null)) ?? [];
await setSetting(db, stepKey(ref.task.id), { ...step, escalated: { at: now, why, files } } satisfies ConflictStep);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_escalated", payload: { why, files, attempts: step.attempts, pr: pull.html_url } });
const list = files.length ? files.slice(0, 20).join(", ") + (files.length > 20 ? ` (+${files.length - 20})` : "") : m("список файлов не получен");
// glossary-ignore: сообщение суперадмину
const details = m("⚠️ {key} «{title}»: изменения конфликтуют с основной версией, агент не справился ({why}, просьб: {n}). Разрешите конфликт или перезапустите агента. Файлы: {files}. Результат: {url}", {
key: ref.key,
title: asIs(ref.task.title),
why,
n: step.attempts,
files: asIs(list),
url: pull.html_url,
});
await platformDelay(db, { projectId: ref.project.id, taskId: ref.task.id }, { reason: "conflict", state: "admin", exhausted: true, attempts: step.attempts, buttons: true, details, action: why, now: new Date(now), log });
log(`${ref.key}: conflict not resolved by the agent (${why}) — the superadmin decides; files: ${files.join(", ") || "?"}`);
return "escalated";
}
/**
* The result `pull` conflicts with the main branch (`mergeable === false`): one step of the
* conflict. Idempotent — call it on every sight of the conflict.
*/
export async function conflictStep(db: Db, ref: TaskRef, pull: GiteaPull, o: { now?: Date; log?: Log; force?: boolean } = {}): Promise<ConflictOutcome> {
const log = o.log ?? (() => {});
const now = (o.now ?? new Date()).getTime();
const step = await getConflictStep(db, ref.task.id);
if (!step) return (await ask(db, ref, pull, 1, now, log, o.force)) ? "requested" : "held";
if (step.escalated) return "escalated";
if (pull.head.sha === step.headSha) {
// PEP-297: the story waits for a place among the agents (the repository limit, the subscriptions) —
// its agent has not started, so it is not silent. The agent's time counts from the moment it gets the place.
if (await isWaitingForCapacity(db, ref.task.id)) {
if (now - step.at >= 60_000) await setSetting(db, stepKey(ref.task.id), { ...step, at: now } satisfies ConflictStep);
return "waiting";
}
// The agent has not pushed yet.
if ((await working(db, ref.task.id)) || now - step.at < CONFLICT_WAIT_MIN * 60_000) return "waiting";
return escalate(db, ref, pull, step, m("агент не обновил изменения"), now, log);
}
// The agent pushed: Gitea re-checks the conflict in the background — judge the new head a bit later.
if (step.seen?.sha !== pull.head.sha) {
await setSetting(db, stepKey(ref.task.id), { ...step, seen: { sha: pull.head.sha, at: now } } satisfies ConflictStep);
return "waiting";
}
if (now - step.seen.at < CONFLICT_SETTLE_MIN * 60_000) return "waiting";
// The conflict stays. A new one — the main branch moved on after the request.
const moved = !!pull.base.sha && !!step.baseSha && pull.base.sha !== step.baseSha;
if (moved && step.attempts < CONFLICT_MAX_ATTEMPTS) {
if (await working(db, ref.task.id)) return "waiting"; // its turn is not over yet
return (await ask(db, ref, pull, step.attempts + 1, now, log)) ? "requested" : "held";
}
if (await working(db, ref.task.id)) return "waiting";
return escalate(db, ref, pull, step, m("агент не смог разрешить конфликт"), now, log);
}
/** Watchdog, once a minute: a resolved conflict clears its step, a silent agent is escalated. */
export async function conflictStepTick(db: Db, o: { now?: Date; gitea?: GiteaClient; log?: Log } = {}): Promise<void> {
const log = o.log ?? (() => {});
const rows = await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, PREFIX));
for (const row of rows) {
const taskId = Number(row.key.slice(PREFIX.length));
try {
const ref = await resolveTaskById(db, taskId).catch(() => null);
if (!ref) {
await deleteSetting(db, row.key);
continue;
}
if (ref.task.archivedAt || ["done", "backlog"].includes(ref.task.status)) {
await clearConflictStep(db, ref, log);
continue;
}
if (await isProjectPaused(db, ref.project.id)) continue;
const gate = await prGate(ref, o.gitea ?? giteaForBot()).catch(() => null);
if (!gate) continue; // Gitea unreachable: the next minute
const pull = gate.pull;
if (!pull || pull.merged || pull.state !== "open" || pull.mergeable !== false) {
await clearConflictStep(db, ref, log);
continue;
}
await conflictStep(db, ref, pull, { now: o.now, log });
} catch (e) {
log(`conflict step #${taskId}: ${(e as Error).message}`);
}
}
}