453 lines
24 KiB
TypeScript
453 lines
24 KiB
TypeScript
// 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 {
|
||
askPmProject,
|
||
clearCapacityWait,
|
||
clearPlatformDelay,
|
||
dropQueuedTask,
|
||
deleteSetting,
|
||
getSetting,
|
||
giteaForBot,
|
||
isProjectPaused,
|
||
isWaitingForCapacity,
|
||
listSessions,
|
||
listTasks,
|
||
logEvent,
|
||
platformDelay,
|
||
prGate,
|
||
queuedItems,
|
||
setSetting,
|
||
taskPrNumber,
|
||
type GateResult,
|
||
type GiteaClient,
|
||
type GiteaPull,
|
||
type Question,
|
||
type TaskRef,
|
||
} from "@peppa/core";
|
||
import { checkRuns, settings, keyPrefix, type Db } from "@peppa/db";
|
||
import { and, eq, min } from "drizzle-orm";
|
||
import { asIs, m } from "@peppa/shared/i18n";
|
||
import { archiveTask, requestRebase } from "./flow.ts";
|
||
import { credentialHelper, run } from "./git.ts";
|
||
import { platformToReview } from "./review-wanted.ts";
|
||
import { onAnswer, 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;
|
||
/** PEP-298: the first request about a conflict waits this long (min) for a second sight; `PEPPA_CONFLICT_SETTLE_MIN` (tests: 0). */
|
||
export const conflictSettleMs = () => {
|
||
const v = Number(process.env.PEPPA_CONFLICT_SETTLE_MIN ?? CONFLICT_SETTLE_MIN);
|
||
return (Number.isFinite(v) && v >= 0 ? v : CONFLICT_SETTLE_MIN) * 60_000;
|
||
};
|
||
|
||
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[] };
|
||
/** PEP-298: the story's status when the agent was first asked (a story taken from review in vain goes back). */
|
||
from?: string;
|
||
}
|
||
/** `settling` (PEP-298): the conflict was first seen less than CONFLICT_SETTLE_MIN ago — Gitea may still be re-checking. */
|
||
export type ConflictOutcome = "requested" | "waiting" | "held" | "escalated" | "settling";
|
||
|
||
const PREFIX = "conflict.step:";
|
||
const stepKey = (taskId: number) => `${PREFIX}${taskId}`;
|
||
export const getConflictStep = (db: Db, taskId: number) => getSetting<ConflictStep>(db, stepKey(taskId));
|
||
|
||
/**
|
||
* PEP-301: the first request the checks queue (or the running checks) held. It is not done: the
|
||
* minute tick repeats the step while the conflict stays. Kept apart from the step: the step's
|
||
* readers (the accept, the stuck healing) take its presence for «the agent was asked».
|
||
*/
|
||
export interface ConflictHeld {
|
||
at: number;
|
||
headSha: string;
|
||
}
|
||
const HELD = "conflict.held:";
|
||
const heldKey = (taskId: number) => `${HELD}${taskId}`;
|
||
export const getConflictHeld = (db: Db, taskId: number) => getSetting<ConflictHeld>(db, heldKey(taskId));
|
||
|
||
/**
|
||
* PEP-298: the first sight of a conflict on this head. Gitea re-checks mergeability in the background
|
||
* after a push and after FORGE updates the branch, and answers «conflict» meanwhile: 15 of 40 requests
|
||
* on 25.11 were false. The first request goes only when the same head still conflicts
|
||
* CONFLICT_SETTLE_MIN later; the minute tick looks again, so a periodic caller needs no second visit.
|
||
*/
|
||
export interface ConflictSeen {
|
||
sha: string;
|
||
at: number;
|
||
}
|
||
const SEEN = "conflict.seen:";
|
||
const seenKey = (taskId: number) => `${SEEN}${taskId}`;
|
||
export const getConflictSeen = (db: Db, taskId: number) => getSetting<ConflictSeen>(db, seenKey(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> {
|
||
await deleteSetting(db, heldKey(ref.task.id));
|
||
await deleteSetting(db, seenKey(ref.task.id));
|
||
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 deleteSetting(db, heldKey(ref.task.id));
|
||
await deleteSetting(db, seenKey(ref.task.id));
|
||
const from = attempts === 1 ? ref.task.status : (await getConflictStep(db, ref.task.id))?.from;
|
||
await setSetting(db, stepKey(ref.task.id), { headSha: pull.head.sha, baseSha: pull.base.sha ?? null, at: now, attempts, ...(from ? { from } : {}) } 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) {
|
||
// PEP-298: two sights of the same head CONFLICT_SETTLE_MIN apart — Gitea's answer right after a push is not a conflict yet.
|
||
const settle = conflictSettleMs();
|
||
const seen = settle ? await getConflictSeen(db, ref.task.id) : null;
|
||
if (settle && seen?.sha !== pull.head.sha) {
|
||
await setSetting(db, seenKey(ref.task.id), { sha: pull.head.sha, at: now } satisfies ConflictSeen);
|
||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_seen", payload: { head: pull.head.sha } });
|
||
log(`${ref.key}: Gitea says conflict — looking again in ${settle / 60_000} min`);
|
||
return "settling";
|
||
}
|
||
if (seen && now - seen.at < settle) return "settling";
|
||
if (await ask(db, ref, pull, 1, now, log, o.force)) return "requested";
|
||
// PEP-301: the request was held (the checks queue, running checks) — not done, the tick repeats it.
|
||
const held = await getConflictHeld(db, ref.task.id);
|
||
if (!held) {
|
||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_rebase_held", payload: { head: pull.head.sha } });
|
||
log(`${ref.key}: conflict with the main branch — the request waits for the checks`);
|
||
}
|
||
await setSetting(db, heldKey(ref.task.id), { at: held?.at ?? now, headSha: pull.head.sha } satisfies ConflictHeld);
|
||
return "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, a held
|
||
* request (PEP-301) goes once its reason passed.
|
||
*/
|
||
export async function conflictStepTick(db: Db, o: { now?: Date; gitea?: GiteaClient; log?: Log } = {}): Promise<void> {
|
||
const log = o.log ?? (() => {});
|
||
const ids = new Set<number>();
|
||
for (const prefix of [PREFIX, HELD, SEEN]) {
|
||
for (const row of await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, prefix))) ids.add(Number(row.key.slice(prefix.length)));
|
||
}
|
||
for (const taskId of ids) {
|
||
try {
|
||
const ref = await resolveTaskById(db, taskId).catch(() => null);
|
||
if (!ref) {
|
||
await deleteSetting(db, stepKey(taskId));
|
||
await deleteSetting(db, heldKey(taskId));
|
||
await deleteSetting(db, seenKey(taskId));
|
||
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) {
|
||
if (pull && !pull.merged && pull.state === "open" && (await backToReview(db, ref, gate, log)) === "later") continue;
|
||
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}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* PEP-298: the conflict is gone, but the story was taken from review for it and its agent never
|
||
* started (it waits for a place among the agents or in the runner queue), and nothing was pushed —
|
||
* the request was in vain: the story goes back to review by itself. `later` — its checks still run.
|
||
*/
|
||
async function backToReview(db: Db, ref: TaskRef, gate: GateResult, log: Log): Promise<"back" | "later" | "no"> {
|
||
const step = await getConflictStep(db, ref.task.id);
|
||
const pull = gate.pull;
|
||
if (!step || step.escalated || step.from !== "review" || ref.task.status !== "in_progress" || !pull) return "no";
|
||
if (pull.head.sha !== step.headSha) return "no"; // the agent pushed: its own hand-off
|
||
if ((await listSessions(db, { active: true, taskId: ref.task.id })).length) return "no";
|
||
if (gate.summary?.state === "pending" && !gate.lost?.length) return "later";
|
||
if (!(gate.ok || gate.behind)) return "no";
|
||
await dropQueuedTask(db, ref.task.id);
|
||
await clearCapacityWait(db, ref.task.id);
|
||
await clearConflictStep(db, ref, log);
|
||
const withPr = ref.task.prUrl ? ref : { ...ref, task: { ...ref.task, prUrl: pull.html_url } };
|
||
await platformToReview(db, withPr, pull.head.sha, "conflict_false_back_to_review");
|
||
log(`${ref.key}: the conflict went by itself before the agent started — back to review`);
|
||
return "back";
|
||
}
|
||
|
||
// ── PEP-301: conflicts nobody works on ────────────────────────────────────────────────────────
|
||
|
||
/** The hourly sweep. */
|
||
export const ORPHAN_SWEEP_MS = 3600_000;
|
||
/** A conflicting result in review unchanged this long is the owner's call, not an agent's. */
|
||
export const STALE_REVIEW_DAYS = 7;
|
||
const SWEEP_AT = "conflict.sweep.at";
|
||
export const STALE_UPDATE_OPTION = m("Обновить и показать");
|
||
export const STALE_CLOSE_OPTION = m("Закрыть");
|
||
|
||
interface StaleState {
|
||
questionId: number;
|
||
taskIds: number[];
|
||
at: number;
|
||
}
|
||
const staleKey = (projectId: number) => `stale.review:${projectId}`;
|
||
const staleQuestionKey = (questionId: number) => `stale.review.q:${questionId}`;
|
||
|
||
/** The open result of the story: its `pr_url`, else the open PR of `task/<key>`. */
|
||
async function storyPull(ref: TaskRef, gitea: GiteaClient): Promise<GiteaPull | null> {
|
||
const { giteaOwner: o, giteaRepo: r } = ref.project;
|
||
const n = taskPrNumber(ref.project, ref.task.prUrl);
|
||
const pull = n
|
||
? await gitea.getPullRequest(o, r, n)
|
||
: ((await gitea.openPullForBranch(o, r, `task/${ref.key.toLowerCase()}`)) ?? (await gitea.openPullForBranch(o, r, `task/${ref.key}`)));
|
||
return pull && pull.state === "open" && !pull.merged ? pull : null;
|
||
}
|
||
|
||
/** When the result got its current head: the first check FORGE saw for it, else the story's last change. */
|
||
async function resultSince(db: Db, ref: TaskRef, sha: string): Promise<number> {
|
||
const [row] = await db.select({ at: min(checkRuns.createdAt) }).from(checkRuns).where(and(eq(checkRuns.projectId, ref.project.id), eq(checkRuns.sha, sha)));
|
||
const at = row?.at as Date | number | null | undefined;
|
||
return at == null ? ref.task.updatedAt.getTime() : at instanceof Date ? at.getTime() : Number(at);
|
||
}
|
||
|
||
/**
|
||
* PEP-301, once an hour (the watchdog calls it every minute): a story in work or in review whose
|
||
* open result conflicts with the main branch, whose agent does not work, which does not wait for a
|
||
* place among the agents and has no conflict step — gets the step (one request, then a person).
|
||
* Results in review unchanged for STALE_REVIEW_DAYS go to the owner instead: one message per project.
|
||
*/
|
||
export async function orphanConflictTick(db: Db, o: { now?: Date; gitea?: GiteaClient; log?: Log; force?: boolean } = {}): Promise<{ stepped: string[]; stale: string[] }> {
|
||
const log = o.log ?? (() => {});
|
||
const now = (o.now ?? new Date()).getTime();
|
||
const out = { stepped: [] as string[], stale: [] as string[] };
|
||
if (process.env.PEPPA_ORPHAN_CONFLICTS === "off") return out;
|
||
if (!o.force) {
|
||
const last = await getSetting<number>(db, SWEEP_AT);
|
||
if (last != null && now - last < ORPHAN_SWEEP_MS) return out;
|
||
}
|
||
await setSetting(db, SWEEP_AT, now);
|
||
const gitea = o.gitea ?? giteaForBot();
|
||
const stale = new Map<number, TaskRef[]>();
|
||
for (const t of await listTasks(db, { statuses: ["in_progress", "review"] })) {
|
||
try {
|
||
if ((await getConflictStep(db, t.id)) || (await getConflictHeld(db, t.id))) continue;
|
||
if (await isWaitingForCapacity(db, t.id)) continue;
|
||
if ((await queuedItems(db, { taskId: t.id })).length) continue;
|
||
if (await working(db, t.id)) continue;
|
||
const ref = await resolveTaskById(db, t.id).catch(() => null);
|
||
if (!ref || (await isProjectPaused(db, ref.project.id))) continue;
|
||
const pull = await storyPull(ref, gitea).catch(() => null);
|
||
if (!pull || pull.mergeable !== false) continue;
|
||
if (ref.task.status === "review" && now - (await resultSince(db, ref, pull.head.sha)) > STALE_REVIEW_DAYS * 86_400_000) {
|
||
stale.set(ref.project.id, [...(stale.get(ref.project.id) ?? []), ref]);
|
||
continue;
|
||
}
|
||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_orphan_found", payload: { status: ref.task.status, pr: pull.html_url, head: pull.head.sha } });
|
||
const fresh = ref.task.prUrl ? ref : { ...ref, task: { ...ref.task, prUrl: pull.html_url } };
|
||
const r = await conflictStep(db, fresh, pull, { now: new Date(now), log });
|
||
log(`${ref.key}: a conflict nobody worked on — step ${r}`);
|
||
out.stepped.push(ref.key);
|
||
} catch (e) {
|
||
log(`orphan conflict #${t.id}: ${(e as Error).message}`);
|
||
}
|
||
}
|
||
for (const [projectId, refs] of stale) {
|
||
if (await askAboutStale(db, projectId, refs, now, log).catch((e) => (log(`stale review #${projectId}: ${(e as Error).message}`), false))) out.stale.push(...refs.map((r) => r.key));
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** One message per project; while it is open nothing more, after the answer — only about new stories. */
|
||
async function askAboutStale(db: Db, projectId: number, refs: TaskRef[], now: number, log: Log): Promise<boolean> {
|
||
const prev = await getSetting<StaleState>(db, staleKey(projectId));
|
||
if (prev) {
|
||
const q = await getSetting<StaleState>(db, staleQuestionKey(prev.questionId));
|
||
if (q) return false; // still open
|
||
}
|
||
const fresh = refs.filter((r) => !prev?.taskIds.includes(r.task.id));
|
||
if (!fresh.length) return false;
|
||
const project = refs[0]!.project;
|
||
const list = refs.map((r) => `• ${r.key} «${asIs(r.task.title)}»`).join("\n");
|
||
const q = await askPmProject(db, project, {
|
||
kind: "question",
|
||
msgType: "question",
|
||
options: [STALE_UPDATE_OPTION, STALE_CLOSE_OPTION],
|
||
defaultOption: STALE_UPDATE_OPTION,
|
||
text: [
|
||
m("🗂 {project}: задач ждут вашей проверки больше недели — {n}. Их изменения расходятся с основной версией, принять их сейчас нельзя.", { project: asIs(project.name), n: refs.length }),
|
||
list,
|
||
m("«Обновить и показать» — агент обновит изменения, и задачи снова придут к вам на проверку. «Закрыть» — задачи уйдут в архив, их изменения не попадут в продукт."),
|
||
].join("\n"),
|
||
});
|
||
const state: StaleState = { questionId: q.id, taskIds: [...new Set([...(prev?.taskIds ?? []), ...refs.map((r) => r.task.id)])], at: now };
|
||
await setSetting(db, staleKey(projectId), state);
|
||
await setSetting(db, staleQuestionKey(q.id), { ...state, taskIds: refs.map((r) => r.task.id) });
|
||
await logEvent(db, { projectId, type: "stale_review_asked", payload: { questionId: q.id, tasks: refs.map((r) => r.key) } });
|
||
log(`stale review ${project.key}: asked about ${refs.map((r) => r.key).join(", ")}`);
|
||
return true;
|
||
}
|
||
|
||
/** The owner's answer to the message above (`onAnswer` registry). */
|
||
export async function onStaleReviewAnswer(db: Db, q: Question, answer: string, o: { gitea?: GiteaClient; log?: Log } = {}): Promise<boolean> {
|
||
if (q.taskId || q.sessionId) return false;
|
||
const state = await getSetting<StaleState>(db, staleQuestionKey(q.id));
|
||
if (!state) return false;
|
||
await deleteSetting(db, staleQuestionKey(q.id));
|
||
const log = o.log ?? (() => {});
|
||
const close = answer.trim() === STALE_CLOSE_OPTION;
|
||
const gitea = o.gitea ?? giteaForBot();
|
||
for (const taskId of state.taskIds) {
|
||
try {
|
||
const ref = await resolveTaskById(db, taskId).catch(() => null);
|
||
if (!ref || ref.task.archivedAt || ref.task.status !== "review") continue;
|
||
const pull = await storyPull(ref, gitea).catch(() => null);
|
||
if (close) {
|
||
await archiveTask(db, ref, true);
|
||
if (pull) await gitea.closePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, pull.number).catch(() => {});
|
||
await logEvent(db, { projectId: ref.project.id, taskId, type: "stale_review_closed", payload: { questionId: q.id } });
|
||
continue;
|
||
}
|
||
if (!pull || pull.mergeable !== false) continue;
|
||
const fresh = ref.task.prUrl ? ref : { ...ref, task: { ...ref.task, prUrl: pull.html_url } };
|
||
await conflictStep(db, fresh, pull, { log });
|
||
await logEvent(db, { projectId: ref.project.id, taskId, type: "stale_review_update", payload: { questionId: q.id } });
|
||
} catch (e) {
|
||
log(`stale review answer #${taskId}: ${(e as Error).message}`);
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
onAnswer((db, q, answer) => onStaleReviewAnswer(db, q, answer));
|