// 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:`; `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, 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; 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(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, log?: Log): Promise { 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; 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 { 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 { 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 { 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 { 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) { // 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 { 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}`); } } }