platformDelay/sessionDelay вместо attention владельцу: падения и зависания агентов, лимиты, красные и зависшие проверки, запуск агента, обновление версии, приёмка; guard конвейера — вопрос суперадмину в платформенном проекте; строка задержки в задаче и на карточке; список задержек на Главной суперадмина. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
91 lines
5.2 KiB
TypeScript
91 lines
5.2 KiB
TypeScript
// PEP-150: a result that changes the checks or the way the product is updated is never accepted
|
||
// automatically — but whether to accept it is not the owner's question (they can't judge it).
|
||
// The superadmin is asked in the platform project («Принять» / «Вернуть агенту»), once per head
|
||
// commit; the owner gets nothing.
|
||
import { asIs, m } from "@peppa/shared/i18n";
|
||
import { alertAdmins, askPmProject, deleteSetting, getProject, getQuestion, getSetting, listSessions, logEvent, platformProjectKey, setSetting, type GiteaPull, type Question, type TaskRef } from "@peppa/core";
|
||
import type { Db } from "@peppa/db";
|
||
import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts";
|
||
|
||
export const GUARD_ACCEPT = m("✅ Принять");
|
||
export const GUARD_RETURN = m("↩️ Вернуть агенту");
|
||
|
||
interface Guard {
|
||
/** Head commit the superadmin was asked about. */
|
||
sha: string;
|
||
questionId: number | null;
|
||
}
|
||
const taskKey = (taskId: number) => `guard.task:${taskId}`;
|
||
const questionKey = (questionId: number) => `guard.question:${questionId}`;
|
||
|
||
/**
|
||
* Asks the superadmin about a result that changes the pipeline. Nothing new for a head commit
|
||
* already asked about, nor while the previous question of the story is still open.
|
||
*/
|
||
export async function pipelineGuard(db: Db, ref: TaskRef, pull: Pick<GiteaPull, "head" | "html_url">, changes: string[], log: (m: string) => void = () => {}): Promise<"asked" | "known"> {
|
||
const sha = pull.head.sha;
|
||
const prev = await getSetting<Guard>(db, taskKey(ref.task.id));
|
||
if (prev?.sha === sha) return "known";
|
||
if (prev?.questionId != null && !(await getQuestion(db, prev.questionId).catch(() => null))?.answeredAt) {
|
||
await setSetting(db, taskKey(ref.task.id), { ...prev, sha } satisfies Guard);
|
||
return "known";
|
||
}
|
||
const text = [
|
||
m("⚠️ {key} ({project}): изменения затрагивают проверки или обновление продукта — сами не принимаются, нужно ваше решение.", { key: ref.key, project: asIs(ref.project.name) }),
|
||
...changes.map((c) => `• ${c}`),
|
||
m("Результат: {url}", { url: pull.html_url }),
|
||
m("«Принять» примет изменения, «Вернуть агенту» — агент уберёт их из результата."),
|
||
].join("\n");
|
||
const platform = await getProject(db, platformProjectKey()).catch(() => null);
|
||
let questionId: number | null = null;
|
||
if (platform) {
|
||
const q = await askPmProject(db, platform, { kind: "question", options: [GUARD_ACCEPT, GUARD_RETURN], text });
|
||
questionId = q.id;
|
||
await setSetting(db, questionKey(q.id), ref.task.id);
|
||
} else {
|
||
// No platform project to ask in: the superadmin is at least told.
|
||
await alertAdmins(db, `delay:t${ref.task.id}:guard:${sha}`, text, log);
|
||
}
|
||
await setSetting(db, taskKey(ref.task.id), { sha, questionId } satisfies Guard);
|
||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "pipeline_guard", payload: { sha, changes, questionId } });
|
||
return "asked";
|
||
}
|
||
|
||
/** The superadmin's answer: «Принять» merges like any accept; anything else goes back to the agent. */
|
||
export async function onGuardAnswer(db: Db, q: Question, answer: string): Promise<boolean> {
|
||
if (q.taskId || q.sessionId || !(q.options ?? []).includes(GUARD_ACCEPT)) return false;
|
||
const taskId = await getSetting<number>(db, questionKey(q.id));
|
||
if (taskId == null) return false;
|
||
await deleteSetting(db, questionKey(q.id));
|
||
const ref = await resolveTaskById(db, taskId).catch(() => null);
|
||
if (!ref) return true;
|
||
const { acceptStory, moveTask } = await import("./flow.ts");
|
||
const said = answer.trim();
|
||
if (said === GUARD_ACCEPT) {
|
||
try {
|
||
await acceptStory(db, ref, "system");
|
||
await deleteSetting(db, taskKey(taskId));
|
||
} catch (e) {
|
||
await alertAdmins(db, `delay:t${taskId}:guard-accept:${q.id}`, m("⚠️ {key}: принять не получилось — {error}", { key: ref.key, error: (e as Error).message }), () => {});
|
||
}
|
||
return true;
|
||
}
|
||
// Back to the agent; a new head commit will be asked about again.
|
||
await deleteSetting(db, taskKey(taskId));
|
||
const note = said && said !== GUARD_RETURN ? `\nКомментарий администратора: ${said}` : "";
|
||
const text = `Администратор платформы не принял PR ${ref.key}: он меняет конвейер (.gitea/, checks или deploy в .peppa/project.json). Убери эти изменения из PR; если без них никак — объясни в описании PR, зачем они нужны. После зелёных проверок снова update_task(status: review).${note}`;
|
||
const session = (await listSessions(db, { active: true, taskId }))[0];
|
||
try {
|
||
if (session) {
|
||
await sendToSession(db, session.id, text).catch(() => {});
|
||
if (ref.task.status === "review") await moveTask(db, ref, "in_progress");
|
||
} else {
|
||
await moveTask(db, ref, "in_progress", { prompt: text });
|
||
}
|
||
} catch (e) {
|
||
await alertAdmins(db, `delay:t${taskId}:guard-return:${q.id}`, m("⚠️ {key} не запущена: {error}", { key: ref.key, error: (e as Error).message }), () => {});
|
||
}
|
||
return true;
|
||
}
|
||
onAnswer(onGuardAnswer);
|