// 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 { answerQuestion, askPm, askPmProject, blockedTaskIds, enqueueTelegram, getAutonomy, getSetting, giteaForBot, inAutonomyQuietHours, listProjects, listSessions, queuedItems, listTasks, pipelineChanges, prGate, projectPoolExhausted, questionRecipients, raiseSessionQuestion, setSetting, taskPrNumber, type AutonomySettings, type GiteaClient, type Project, type Question, type SessionView, type Task, type TaskRef, projectAgentWarning, intakePendingTasks, } 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 } from "./flow.ts"; import { autoMergeTask } from "./ci-feedback.ts"; import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts"; import { syncWorkspace } from "./workspace-sync.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 = "▶️ Взять"; export const IDLE_NEXT = "⏭ Следующую"; export const IDLE_SNOOZE = "💤 Не сейчас"; 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(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; /** 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 { const log = opts.log ?? (() => {}); const now = opts.now ?? new Date(); for (const project of await listProjects(db)) { 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); const state = (await getSetting(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`); } 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}`); } } } async function requestRebase(db: Db, ref: TaskRef) { const text = `Пеппа не может смержить PR ${ref.key}: конфликты с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок снова update_task(status: review).`; const session = (await listSessions(db, { active: true, taskId: ref.task.id }))[0]; if (session) { await sendToSession(db, session.id, text).catch(() => {}); await moveTask(db, ref, "in_progress"); } else { await moveTask(db, ref, "in_progress", { prompt: text }); } } /** 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, "✅ Закрыто автоматически: PR смержен"); await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `🤖 ${ref.key} «${ref.task.title}»: PR смержен, стори закрыта автоматически.`); 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 = `✅ Стори ${ref.key} готова к ревью${ref.task.prUrl ? ` · PR смержен автоматически: ${ref.task.prUrl}` : ""}${ a.close === "after_hours" ? `\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(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); if (gate?.pull && !gate.pull.merged && (await pipelineChanges(ref, gate.pull, gitea)).length) { await setSetting(db, mergeKey(task.id), { ...state, pipelineSha: gate.pull.head.sha }); await askPm(db, ref, { kind: "question", text: `⚠️ ${ref.key}: PR меняет конвейер (.gitea/, checks/deploy) — сам не закрою, нужно ваше «Принять».` }); continue; } } try { await acceptTask(db, q.id, "system", `✅ Принято автоматически: ${a.closeAfterHours} ч без замечаний`); await notifyPm(db, project.id, `auto:accepted:${q.id}`, `🤖 ${ref.key} «${task.title}» закрыта автоматически: ${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); await askPm(db, ref, { kind: "question", text: `⚠️ ${ref.key}: не получилось закрыть автоматически — ${(e as Error).message}` }); } log(`${ref.key}: auto-close failed — ${(e as Error).message}`); } } } /** A plain Telegram message (no question, nothing to answer) to the project's people. */ async function notifyPm(db: Db, projectId: number, dedupeKey: string, text: string) { 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 ───────────────────────────────────────────────────────── 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, "(неактуально: агент уже работает или бэклог пуст)", "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); try { const r = await moveTask(db, ref, "in_progress", { prompt: "Стори взята из бэклога автоматически (автономность проекта). Работай по правилам до PR и review." }); 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(() => {}); await setIdle(db, project.id, { ...state, failUntil: now.getTime() + DISPATCH_RETRY_MS }); await askPmProject(db, project, { kind: "attention", text: `⚠️ ${project.name}: диспетчер не смог запустить агента на ${ref.key} — ${(e as Error).message}\nПовторю через ${DISPATCH_RETRY_MS / 60_000} мин.`, }); log(`${ref.key}: dispatch failed — ${(e as Error).message}`); return; } } if (!backlog.length && working.length === 0 && a.idlePush && !state.emptyNotified) { await setIdle(db, project.id, { ...state, emptyNotified: true }); await askPmProject(db, project, { kind: "attention", text: `📭 ${project.name}: бэклог пуст — агентам нечего делать. Добавьте стори, и Пеппа возьмёт их сама.` }); } 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(db: Db, projectId: number, backlog?: T[]): Promise { 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); const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id)); // PEP-103: fixing errors comes first — bug stories, then the rest, each in board order. const bugs = await bugTaskIds(db, projectId); return [...ready.filter((t) => bugs.has(t.id)), ...ready.filter((t) => !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> { 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 { 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: `😴 ${project.name}: агенты простаивают, в бэклоге ${left}. Взять в работу ${ref.key} «${task.title}»?`, options: [`${IDLE_TAKE} ${ref.key}`, IDLE_NEXT, `${IDLE_SNOOZE} (${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 { 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) { await askPmProject(db, ref.project, { kind: "attention", text: `⚠️ ${ref.key} не запущена: ${(e as Error).message}` }); } 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);