peppa/packages/runner/src/autonomy.ts

422 lines
23 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.

// Autonomous factory (PEP-23/24/25), run from the watchdog tick:
// - auto-merge of green review PRs and closing by the project's settings (PEP-25);
// - closing a story N hours after "ready for review" without comments (PEP-23);
// - the backlog dispatcher: either an agent works, or the PM got a push (PEP-24).
// Everything here is driven by core/autonomy.ts settings; "manual" (default) does nothing.
import { asIs, m } from "@peppa/shared/i18n";
import {
answerQuestion,
askPm,
getPendingAccept,
askPmProject,
blockedTaskIds,
enqueueTelegram,
getAutonomy,
getSetting,
giteaForBot,
inAutonomyQuietHours,
listProjects,
listSessions,
queuedItems,
listTasks,
pipelineChanges,
prGate,
projectPoolExhausted,
questionRecipients,
raiseSessionQuestion,
alertAdmins,
clearPlatformDelay,
getPlatformDelay,
platformFailure,
setSetting,
taskPrNumber,
type AutonomySettings,
type GiteaClient,
type Project,
type Question,
type SessionView,
type Task,
type TaskRef,
projectAgentWarning,
intakePendingTasks,
productUrls,
productLookLine,
getProductLinkState,
pendingRefinements,
pausedProjectIds,
isProjectPaused,
} from "@peppa/core";
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, requestRebase } from "./flow.ts";
import { autoMergeTask } from "./ci-feedback.ts";
import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts";
import { syncWorkspace } from "./workspace-sync.ts";
import { startDelay } from "./platform-delays.ts";
import { pipelineGuard } from "./pipeline-guard.ts";
export interface AutonomyTickOptions {
now?: Date;
log?: (m: string) => void;
gitea?: GiteaClient;
}
/** Statuses in which a session counts as an agent at work (WIP) for the dispatcher. */
const WORKING: Task["status"][] = ["proposing", "awaiting_approval", "in_progress", "blocked"];
/** After a failed automatic start, the dispatcher waits this long before trying again. */
export const DISPATCH_RETRY_MS = 30 * 60_000;
export const IDLE_TAKE = m("▶️ Взять");
export const IDLE_NEXT = m("⏭ Следующую");
export const IDLE_SNOOZE = m("💤 Не сейчас");
interface IdleState {
/** The open "agents are idle" question. */
questionId?: number | null;
/** When the last idle push went out (ms). */
at?: number;
snoozeUntil?: number;
/** Auto mode: the PM was told the backlog is empty (until a story appears). */
emptyNotified?: boolean;
/** Auto mode: no new start attempts before this (ms) after a failed one. */
failUntil?: number;
}
const idleKey = (projectId: number) => `autonomy.idle:${projectId}`;
const getIdle = async (db: Db, projectId: number) => (await getSetting<IdleState>(db, idleKey(projectId))) ?? {};
const setIdle = (db: Db, projectId: number, s: IdleState) => setSetting(db, idleKey(projectId), s);
/** Per story: what the auto-merge already did for its PR (no repeated questions/rebase requests). */
interface MergeState {
/** Head SHA whose pipeline change the PM was asked about. */
pipelineSha?: string;
/** Head SHA the agent was asked to rebase. */
rebaseSha?: string;
/** Head SHA for which Peppa asked Gitea to bring the main branch into the PR branch (PEP-127). */
updateSha?: string;
/** PR (or "no-pr") for which the "merged, accept?" message was raised. */
reviewFor?: string;
}
const mergeKey = (taskId: number) => `autonomy.merge:${taskId}`;
const refOf = (project: Project, task: Task): TaskRef => ({ project, task, key: formatTaskKey(project.key, task.number) });
export async function autonomyTick(db: Db, opts: AutonomyTickOptions = {}): Promise<void> {
const log = opts.log ?? (() => {});
const now = opts.now ?? new Date();
const paused = await pausedProjectIds(db);
for (const project of await listProjects(db)) {
// PEP-174: a project on pause — no auto-merge, no auto-close, no dispatcher, no idle pushes.
if (paused.has(project.id)) continue;
const a = await getAutonomy(db, project.id);
if (a.pick === "pm" && a.merge === "manual" && a.close === "pm" && !a.idlePush) continue; // manual
try {
if (a.merge === "auto") await autoMergeReviews(db, project, a, opts.gitea, log);
if (a.close === "after_hours") await autoCloseReviews(db, project, a, now, opts.gitea, log);
await dispatch(db, project, a, now, log);
} catch (e) {
log(`autonomy ${project.key}: ${(e as Error).message}`);
}
}
}
// ── PEP-25: auto-merge and closing ─────────────────────────────────────────────
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);
continue;
}
const gitea = client ?? giteaForBot();
const gate = await prGate(ref, gitea);
if (!gate.pull || gate.pull.merged) {
await afterMerge(db, ref, a, state, log);
continue;
}
const sha = gate.pull.head.sha;
if (!gate.ok) {
// Conflicts: the agent rebases itself (once per head commit). Red/pending: CI feedback.
if (gate.pull.mergeable === false && state.rebaseSha !== sha) {
await setSetting(db, mergeKey(task.id), { ...state, rebaseSha: sha });
await requestRebase(db, ref);
log(`${ref.key}: conflicts — rebase requested`);
} else if (gate.behind && state.updateSha !== sha) {
// PEP-127: merged only with the current main inside — update the branch, wait for its checks.
await setSetting(db, mergeKey(task.id), { ...state, updateSha: sha });
await gitea.updatePullBranch(project.giteaOwner, project.giteaRepo, gate.pull.number).catch((e) => log(`${ref.key}: branch update failed — ${(e as Error).message}`));
log(`${ref.key}: behind the main branch — PR branch updated`);
}
continue;
}
if (state.pipelineSha === sha) continue; // the PM reviews this pipeline change
const r = await autoMergeTask(db, ref, gitea);
if (r.merged) {
log(`${ref.key}: PR auto-merged`);
await afterMerge(db, ref, a, state, log);
} else if (r.reason) {
await setSetting(db, mergeKey(task.id), { ...state, pipelineSha: sha });
log(`${ref.key}: not auto-merged — ${r.reason}`);
}
}
}
/** 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") {
await closeStory(db, ref, m("✅ Закрыто автоматически: изменения приняты"));
await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("🤖 {key} «{title}»: изменения приняты, задача закрыта автоматически.", { key: ref.key, title: asIs(ref.task.title) })}${await productLookLine(db, ref.project.id)}`);
log(`${ref.key}: closed after merge`);
return;
}
const pr = ref.task.prUrl ?? "no-pr";
if (state.reviewFor === pr) return;
await setSetting(db, mergeKey(ref.task.id), { ...state, reviewFor: pr });
const text = `${m("✅ Задача {key} готова к ревью", { key: ref.key })}${ref.task.prUrl ? ` · ${m("Изменения приняты автоматически: {url}", { url: ref.task.prUrl })}` : ""}${
a.close === "after_hours" ? `\n${m("Закроется сама через {n} ч, если не будет замечаний.", { n: a.closeAfterHours })}` : ""
}`;
const session = (await listSessions(db, { active: true, taskId: ref.task.id }))[0];
if (session) await raiseSessionQuestion(db, session, "attention", text);
else await askPm(db, ref, { kind: "attention", text });
}
/** Done: pending questions of the story are closed, its agent stopped, the working copy updated. */
async function closeStory(db: Db, ref: TaskRef, answer: string) {
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, answer, "system").catch(() => {});
await moveTask(db, ref, "done");
await syncWorkspace(db, ref).catch(() => "failed");
}
/** close = after_hours: "ready for review" unanswered for N hours → accepted (merged if needed). */
async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, now: Date, client: GiteaClient | undefined, log: (m: string) => void) {
const cutoff = now.getTime() - a.closeAfterHours * 3_600_000;
for (const task of await listTasks(db, { projectId: project.id, statuses: ["review"] })) {
const [q] = await db
.select()
.from(questions)
.where(and(eq(questions.taskId, task.id), eq(questions.kind, "attention"), isNull(questions.answeredAt)));
if (!q || q.createdAt.getTime() > cutoff) continue;
const ref = refOf(project, task);
// A pipeline change is never accepted without the PM, however long it waits.
const state = (await getSetting<MergeState>(db, mergeKey(task.id))) ?? {};
if (state.pipelineSha) continue;
if (taskPrNumber(project, task.prUrl)) {
const gitea = client ?? giteaForBot();
const gate = await prGate(ref, gitea).catch(() => null);
const changes = gate?.pull && !gate.pull.merged ? await pipelineChanges(ref, gate.pull, gitea) : [];
if (gate?.pull && changes.length) {
await setSetting(db, mergeKey(task.id), { ...state, pipelineSha: gate.pull.head.sha });
// PEP-150: the superadmin decides (the owner still has «Принять» on the story).
await pipelineGuard(db, ref, gate.pull, changes, log);
continue;
}
}
try {
const r = await acceptTask(db, q.id, "system", m("✅ Принято автоматически: {n} ч без замечаний", { n: a.closeAfterHours }));
// PEP-127: not mergeable yet — remembered, `pendingAcceptTick` closes the story and tells the PM.
if (r.pending) continue;
await notifyPm(db, project.id, `auto:accepted:${q.id}`, m("🤖 {key} «{title}» закрыта автоматически: {n} ч без замечаний.", { key: ref.key, title: asIs(task.title), n: a.closeAfterHours }));
log(`${ref.key}: closed after ${a.closeAfterHours}h`);
} catch (e) {
const key = `auto:closefail:${q.id}`;
if (!(await getSetting(db, key))) {
await setSetting(db, key, true);
// PEP-150: the owner still has «Принять» on the story; why it did not close by itself is the superadmin's to see.
await alertAdmins(db, `delay:t${task.id}:autoclose:${q.id}`, m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: (e as Error).message }), log);
}
log(`${ref.key}: auto-close failed — ${(e as Error).message}`);
}
}
}
/** A plain Telegram message (no question, nothing to answer) to the project's people. */
export async function notifyPm(db: Db, projectId: number, dedupeKey: string, text: string) {
if (await isProjectPaused(db, projectId)) return;
for (const u of await questionRecipients(db, projectId)) {
await enqueueTelegram(db, { dedupeKey: `${dedupeKey}:${u.id}`, method: "sendMessage", params: { chat_id: u.telegramChatId, text } });
}
}
// ── PEP-24: dispatcher ─────────────────────────────────────────────────────────
/** PEP-185: how many ready stories the «auto» dispatcher takes right now (0 while it can't start any:
* no subscription, limits, a recent failure, the WIP limit reached). The rest wait for a person. */
export async function autoPickSlots(db: Db, project: Project, a: AutonomySettings, now = new Date()): Promise<number> {
if (a.pick !== "auto") return 0;
const sessions = (await listSessions(db, { active: true })).filter((s) => s.projectId === project.id);
if (await projectAgentWarning(db, project.id, now)) return 0;
if (sessions.some((s) => s.status === "rate_limited") || (await projectPoolExhausted(db, project.id, now))) return 0;
if (((await getIdle(db, project.id)).failUntil ?? 0) > now.getTime()) return 0;
const working = await workingSessions(db, sessions);
const queued = (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length;
return Math.max(0, a.wipLimit - working.length - queued);
}
async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date, log: (m: string) => void) {
const sessions = (await listSessions(db, { active: true })).filter((s) => s.projectId === project.id);
const working = await workingSessions(db, sessions);
const backlog = await listTasks(db, { projectId: project.id, statuses: ["backlog"] });
// PEP-42: only stories whose predecessors are in review/done; PEP-34: in board order.
const ready = await readyBacklog(db, project.id, backlog);
const state = await getIdle(db, project.id);
// Someone works or nothing is left: an open "agents are idle" question is moot.
if ((working.length > 0 || !backlog.length) && state.questionId) {
await answerQuestion(db, state.questionId, m("(неактуально: агент уже работает или бэклог пуст)"), "system").catch(() => {});
state.questionId = null;
await setIdle(db, project.id, state);
}
if (backlog.length && state.emptyNotified) {
state.emptyNotified = false;
await setIdle(db, project.id, state);
}
// Limits: never start or offer while the project's agents can't run.
const limited = sessions.some((s) => s.status === "rate_limited") || (await projectPoolExhausted(db, project.id, now));
if (a.pick === "auto") {
// PEP-79: no subscription chosen (or none works) — the project page says so; no retries, no pings.
if (await projectAgentWarning(db, project.id, now)) return;
if (limited || (state.failUntil ?? 0) > now.getTime()) return;
// PEP-10: stories waiting in runner queues count as taken.
let slots = a.wipLimit - working.length - (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length;
for (const task of ready) {
if (slots <= 0) break;
const ref = refOf(project, task);
// PEP-150: a story whose start attempts ran out waits for the superadmin; the next one goes.
if ((await getPlatformDelay(db, { projectId: project.id, taskId: task.id }, "start"))?.exhausted) continue;
try {
const r = await moveTask(db, ref, "in_progress", { prompt: "Стори взята из бэклога автоматически (автономность проекта). Работай по правилам до PR и review." });
await clearPlatformDelay(db, { projectId: project.id, taskId: task.id }, "start");
log(`${ref.key}: dispatched (session #${r.started})`);
slots--;
} catch (e) {
// Back to the backlog: the card must not hang in "in progress" without an agent.
const fresh = await resolveTaskById(db, task.id).catch(() => null);
if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {});
// PEP-150: not the owner's to fix — the story shows the delay line, the dispatcher
// retries with a growing pause, the superadmin is told once (and when it gives up).
const d = await startDelay(db, { projectId: project.id, taskId: task.id }, m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: asIs(project.name), key: ref.key, error: (e as Error).message }), e, { now, log });
await setIdle(db, project.id, { ...state, failUntil: d?.retryAt ?? now.getTime() + DISPATCH_RETRY_MS });
log(`${ref.key}: dispatch failed — ${(e as Error).message}`);
return;
}
}
// «Все задачи сделаны» only when nothing is left on the board but review/done — a story
// stuck in work while its start is retried (PEP-150) is not «nothing to do».
const unfinished = !backlog.length && working.length === 0 ? (await listTasks(db, { projectId: project.id, statuses: ["proposing", "awaiting_approval", "in_progress"] })).length : 1;
if (!backlog.length && working.length === 0 && !unfinished && a.idlePush && !state.emptyNotified) {
await setIdle(db, project.id, { ...state, emptyNotified: true });
// PEP-111: everything asked for is done — say where the result is and what to do next.
const product = (await productUrls(db, [project.id])).get(project.id);
const web = process.env.PEPPA_WEB_URL ?? "";
await askPmProject(db, project, {
kind: "attention",
text: [
m("📭 {project}: все задачи сделаны, бэклог пуст — агентам нечего делать.", { project: asIs(project.name) }),
...(product ? [product.live ? m("Ваш продукт: {url}", { url: product.url }) : m("Версия для проверки: {url}", { url: product.url })] : []),
m("Что дальше: опишите следующую задачу аналитику в чате проекта ({url}) или добавьте задачу на доске — агенты возьмут её сами.", { url: `${web}/chats/${project.key}` }),
].join("\n"),
});
}
return;
}
if (!a.idlePush || working.length > 0 || !ready.length || limited || state.questionId) return;
if (inAutonomyQuietHours(a, now)) return;
if ((state.snoozeUntil ?? 0) > now.getTime()) return;
if (state.at && now.getTime() - state.at < a.idlePushHours * 3_600_000) return;
await offerStory(db, project, ready[0]!, now);
log(`${project.key}: idle push (${formatTaskKey(project.key, ready[0]!.number)})`);
}
/** Backlog stories that can start now: not blocked by a predecessor (PEP-42), in board order (PEP-34). */
export async function readyBacklog<T extends Task = Task & { key: string }>(db: Db, projectId: number, backlog?: T[]): Promise<T[]> {
const list = backlog ?? ((await listTasks(db, { projectId, statuses: ["backlog"] })) as unknown as T[]);
const blocked = await blockedTaskIds(db, projectId);
// PEP-84: stories «продакт» and «аналитик» have not finished with stay out of the dispatcher's reach.
const refining = await intakePendingTasks(db, projectId);
// PEP-115: nor does a story whose fresh comment the analyst is still working into the description.
const commented = await pendingRefinements(db, { projectId });
const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id));
// PEP-103: fixing errors comes first — bug stories, then the rest, each in board order.
const bugs = await bugTaskIds(db, projectId);
// PEP-145: before everything — the system story that makes the product open by a link.
const link = (await getProductLinkState(db, projectId))?.taskId;
return [...ready.filter((t) => t.id === link), ...ready.filter((t) => t.id !== link && bugs.has(t.id)), ...ready.filter((t) => t.id !== link && !bugs.has(t.id))];
}
/** Bug stories of a project: made from a production error (PEP-58) or in the «Стабильность» epic. */
export async function bugTaskIds(db: Db, projectId: number): Promise<Set<number>> {
const fromIncidents = await db.select({ id: incidents.taskId }).from(incidents).where(and(eq(incidents.projectId, projectId), isNotNull(incidents.taskId)));
const inStability = await db
.select({ id: tasks.id })
.from(tasks)
.innerJoin(goals, eq(goals.id, tasks.goalId))
.where(and(eq(tasks.projectId, projectId), eq(goals.title, "Стабильность")));
return new Set([...fromIncidents.map((r) => r.id!), ...inStability.map((r) => r.id)]);
}
/** Sessions that hold a WIP slot: their story is being worked on (not in review). */
async function workingSessions(db: Db, sessions: SessionView[]): Promise<SessionView[]> {
const out: SessionView[] = [];
for (const s of sessions) {
if (!s.taskId) continue;
const ref = await resolveTaskById(db, s.taskId).catch(() => null);
if (ref && WORKING.includes(ref.task.status)) out.push(s);
}
return out;
}
async function offerStory(db: Db, project: Project, task: Task, now: Date) {
const a = await getAutonomy(db, project.id);
const ref = refOf(project, task);
const left = (await listTasks(db, { projectId: project.id, statuses: ["backlog"] })).length;
const q = await askPm(db, ref, {
kind: "question",
text: m("😴 {project}: агенты простаивают, в бэклоге {n}. Взять в работу {key} «{title}»?", { project: asIs(project.name), n: left, key: ref.key, title: asIs(task.title) }),
options: [`${IDLE_TAKE} ${ref.key}`, IDLE_NEXT, m("💤 Не сейчас ({n} ч)", { n: a.idlePushHours })],
});
const state = await getIdle(db, project.id);
await setIdle(db, project.id, { ...state, questionId: q.id, at: now.getTime() });
}
/** The PM's answer to an "agents are idle" push (Telegram buttons, web, MCP). */
export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise<boolean> {
const state = await getIdle(db, q.projectId);
if (!state.questionId || state.questionId !== q.id || !q.taskId) return false;
const ref = await resolveTaskById(db, q.taskId);
const a = await getAutonomy(db, q.projectId);
const now = Date.now();
const text = answer.trim();
if (text.startsWith(IDLE_NEXT)) {
const backlog = await readyBacklog(db, q.projectId);
const at = backlog.findIndex((t) => t.id === ref.task.id);
const next = (at >= 0 ? backlog[at + 1] : backlog.find((t) => t.position > ref.task.position)) ?? backlog.find((t) => t.id !== ref.task.id);
await setIdle(db, q.projectId, { ...state, questionId: null });
if (next) await offerStory(db, ref.project, next, new Date(now));
return true;
}
if (text.startsWith(IDLE_TAKE)) {
await setIdle(db, q.projectId, { ...state, questionId: null });
if (ref.task.status !== "backlog") return true; // already moved by someone
try {
await moveTask(db, ref, "in_progress");
} catch (e) {
// PEP-150: the platform tries again by itself; the owner sees the delay line on the story.
const fresh = await resolveTaskById(db, ref.task.id).catch(() => null);
if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {});
await startDelay(db, { projectId: ref.project.id, taskId: ref.task.id }, m("⚠️ {key} не запущена: {error}", { key: ref.key, error: (e as Error).message }), e);
}
return true;
}
// "Not now" (or any other text): quiet for idlePushHours.
await setIdle(db, q.projectId, { ...state, questionId: null, snoozeUntil: now + a.idlePushHours * 3_600_000 });
return true;
}
onAnswer(onIdleAnswer);