// PEP-197: who made a story, «Предложено», limits for stories of agents, the product's version // with a finish line, and what the acceptance agent may not do alone. State lives in `tasks` // (origin, proposed, severity) and `settings` (`project.agent-limits:`, `product.version:`, // `product.rejected:`, `product.digest:`). import { m as tr } from "@peppa/shared/i18n"; import { projects, sessions, tasks, type Db } from "@peppa/db"; import { and, eq, gte, inArray, isNull, ne, sql } from "drizzle-orm"; import { getAutonomy, type AcceptOwnMode } from "./autonomy.ts"; import { logEvent } from "./audit.ts"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { usageTotals } from "./usage.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; // PEP-270: `agent` — a story the developing agent filed itself (MCP `create_task` of its session). export const TASK_ORIGINS = ["human", "acceptance", "incident", "analyst", "agent"] as const; export type TaskOrigin = (typeof TASK_ORIGINS)[number]; export const TASK_SEVERITIES = ["breakage", "important", "minor"] as const; export type TaskSeverity = (typeof TASK_SEVERITIES)[number]; export const isAgentOrigin = (origin: string): boolean => origin !== "human"; export const SEVERITY_LABEL: Record = { breakage: tr("Поломка"), important: tr("Важно"), minor: tr("Мелочь"), }; export const ORIGIN_LABEL: Record = { human: tr("человек"), acceptance: tr("агент приёмки"), incident: tr("разбор ошибок"), analyst: tr("аналитик"), agent: tr("агент разработки"), }; // ── limits ───────────────────────────────────────────────────────────────────── export interface AgentLimits { /** Stories made by agents that may be in work at once, per project. */ inWork: number; /** Proposals the acceptance agent may make in one pass. */ perPass: number; /** PEP-205: stories of one repository in work at once, whoever made them (0 — no limit); the rest wait «В очереди». */ inRepo: number; /** PEP-270: proposals of agents (developing and acceptance) per project in the last 24 hours. */ perDay: number; } export const DEFAULT_AGENT_LIMITS: AgentLimits = { inWork: 3, perPass: 5, inRepo: 4, perDay: 5 }; const limitsKey = (projectId: number) => `project.agent-limits:${projectId}`; export async function getAgentLimits(db: Db, projectId: number): Promise { const s = await getSetting>(db, limitsKey(projectId)); return { ...DEFAULT_AGENT_LIMITS, ...(s ?? {}) }; } export async function setAgentLimits(db: Db, projectId: number, patch: Partial | "reset"): Promise { if (patch === "reset") { await deleteSetting(db, limitsKey(projectId)); return DEFAULT_AGENT_LIMITS; } const next = { ...(await getAgentLimits(db, projectId)), ...patch }; for (const [k, max] of [["inWork", 20], ["perPass", 20], ["inRepo", 50], ["perDay", 50]] as const) { if (!Number.isInteger(next[k]) || next[k] < 0 || next[k] > max) throw new PeppaError(tr("{name}: целое от 0 до {max}", { name: k, max })); } await setSetting(db, limitsKey(projectId), next); return next; } /** Stories of agents in work (not in review), of one project. */ export async function agentTasksInWork(db: Db, projectId: number): Promise { const [r] = await db .select({ n: sql`count(*)` }) .from(tasks) .where(and(eq(tasks.projectId, projectId), eq(tasks.status, "in_progress"), ne(tasks.origin, "human"), isNull(tasks.archivedAt))); return Number(r?.n ?? 0); } // ── PEP-270: proposals per day ───────────────────────────────────────────────── /** Origins that spend the daily limit: what agents thought up themselves (not bugs of users, not parts of a person's story). */ export const PROPOSAL_ORIGINS = ["agent", "acceptance"] as const; export const PROPOSAL_WINDOW_MS = 86_400_000; /** Stories agents filed in the project during the last 24 hours (archived — declined — ones count too). */ export async function proposalsToday(db: Db, projectId: number, now = new Date()): Promise { const [r] = await db .select({ n: sql`count(*)` }) .from(tasks) .where(and(eq(tasks.projectId, projectId), inArray(tasks.origin, [...PROPOSAL_ORIGINS]), gte(tasks.createdAt, new Date(now.getTime() - PROPOSAL_WINDOW_MS)))); return Number(r?.n ?? 0); } /** How many more proposals the project may get from agents right now. */ export async function proposalRoom(db: Db, projectId: number, now = new Date()): Promise<{ room: number; limit: number; used: number }> { const limit = (await getAgentLimits(db, projectId)).perDay; const used = await proposalsToday(db, projectId, now); return { room: Math.max(0, limit - used), limit, used }; } // ── «Предложено» ─────────────────────────────────────────────────────────────── export async function proposedTasks(db: Db, projectId: number) { return db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.proposed, true), isNull(tasks.archivedAt))); } export async function proposedCount(db: Db, projectId: number): Promise { return (await proposedTasks(db, projectId)).length; } const rejectedKey = (projectId: number) => `product.rejected:${projectId}`; export const normTitle = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim(); export async function rejectedTitles(db: Db, projectId: number): Promise { return (await getSetting(db, rejectedKey(projectId))) ?? []; } /** «Делать»: the story goes to the backlog (the dispatcher may take it). */ export async function approveProposal(db: Db, taskId: number, by?: string): Promise { const [t] = await db.update(tasks).set({ proposed: false }).where(and(eq(tasks.id, taskId), eq(tasks.proposed, true))).returning(); if (!t) return; await logEvent(db, { projectId: t.projectId, taskId: t.id, type: "proposal_approved", payload: { by: by ?? null } }); await notify(db, { type: "task_updated", taskId: t.id }); } /** «Не надо»: archived with a mark; the acceptance agent will not suggest it again. */ export async function rejectProposal(db: Db, taskId: number, by?: string): Promise { const [t] = await db.update(tasks).set({ proposed: false, archivedAt: new Date() }).where(and(eq(tasks.id, taskId), eq(tasks.proposed, true))).returning(); if (!t) return; const list = await rejectedTitles(db, t.projectId); const n = normTitle(t.title); if (!list.includes(n)) await setSetting(db, rejectedKey(t.projectId), [...list, n].slice(-200)); await logEvent(db, { projectId: t.projectId, taskId: t.id, type: "proposal_rejected", payload: { by: by ?? null } }); await notify(db, { type: "task_updated", taskId: t.id }); } /** Bulk: `important` — «Делать важные» (breakage and important), `none` — «Отклонить всё». */ export async function resolveProposals(db: Db, ids: number[], mode: "important" | "none", by?: string): Promise { if (!ids.length) return; const rows = await db.select().from(tasks).where(and(inArray(tasks.id, ids), eq(tasks.proposed, true))); for (const t of rows) { if (mode === "none") await rejectProposal(db, t.id, by); else if (t.severity === "breakage" || t.severity === "important") await approveProposal(db, t.id, by); } } // ── who may be accepted automatically ────────────────────────────────────────── /** May Peppa merge and close this story without the owner (autonomy «Принимать сами», PEP-197)? */ export function mayAutoAccept(task: { origin: string; severity: string | null }, mode: AcceptOwnMode): boolean { if (!isAgentOrigin(task.origin)) return true; if (mode === "all") return true; if (mode === "mine_breakage") return task.severity === "breakage"; return false; } export async function mayAutoAcceptTask(db: Db, task: { projectId: number; origin: string; severity: string | null }): Promise { if (!isAgentOrigin(task.origin)) return true; return mayAutoAccept(task, (await getAutonomy(db, task.projectId)).acceptOwn); } // ── version with a finish line ───────────────────────────────────────────────── export interface VersionState { /** Stories of the human that make this version. */ ids: number[]; startedAt: string; /** Set when the owner was told «Версия готова» (or the project had nothing open). */ doneAt: string | null; } const versionKey = (projectId: number) => `product.version:${projectId}`; export const getVersion = (db: Db, projectId: number) => getSetting(db, versionKey(projectId)); /** A person made a story: it joins the open version, or starts a new one after a finished one. */ export async function touchVersion(db: Db, projectId: number, taskId: number): Promise { const v = await getVersion(db, projectId); if (!v || v.doneAt) await setSetting(db, versionKey(projectId), { ids: [taskId], startedAt: new Date().toISOString(), doneAt: null } satisfies VersionState); else if (!v.ids.includes(taskId)) await setSetting(db, versionKey(projectId), { ...v, ids: [...v.ids, taskId] }); } /** The project's version is finished: nothing a person asked for is open. */ export async function versionFinished(db: Db, projectId: number): Promise { const v = await getVersion(db, projectId); if (v) return v.doneAt != null; // Never tracked (an old project): finished when no story of a person is open. const open = await openHumanTasks(db, projectId); if (open.length === 0) { await setSetting(db, versionKey(projectId), { ids: [], startedAt: new Date().toISOString(), doneAt: new Date().toISOString() } satisfies VersionState); return true; } await setSetting(db, versionKey(projectId), { ids: open, startedAt: new Date().toISOString(), doneAt: null } satisfies VersionState); return false; } async function openHumanTasks(db: Db, projectId: number): Promise { const rows = await db .select({ id: tasks.id }) .from(tasks) .where(and(eq(tasks.projectId, projectId), eq(tasks.origin, "human"), ne(tasks.status, "done"), isNull(tasks.archivedAt))); return rows.map((r) => r.id); } /** * After a pass of the acceptance agent: every story of the version is done (or archived) and * no breakage was found → the version is finished. True once, when it just finished. */ export async function finishVersionIfReady(db: Db, projectId: number, foundBreakage: boolean): Promise { if (foundBreakage) return false; if (!(await getVersion(db, projectId))) await versionFinished(db, projectId); // starts tracking const v = await getVersion(db, projectId); if (!v || v.doneAt) return false; const rows = await db.select({ status: tasks.status, archivedAt: tasks.archivedAt }).from(tasks).where(inArray(tasks.id, v.ids)); if (rows.some((r) => r.status !== "done" && !r.archivedAt)) return false; await setSetting(db, versionKey(projectId), { ...v, doneAt: new Date().toISOString() }); await logEvent(db, { projectId, type: "version_done", payload: { stories: v.ids.length } }); return true; } // ── improvements saved for the weekly message after the finish ───────────────── export interface DigestItem { title: string; description: string; severity: TaskSeverity; } export interface DigestState { items: DigestItem[]; sentAt: string | null; } const digestKey = (projectId: number) => `product.digest:${projectId}`; export const getDigest = async (db: Db, projectId: number): Promise => (await getSetting(db, digestKey(projectId))) ?? { items: [], sentAt: null }; export const setDigest = (db: Db, projectId: number, d: DigestState) => setSetting(db, digestKey(projectId), d); // ── summary for the superadmin (and the table of the review) ─────────────────── export interface AgentTaskRow { projectId: number; key: string; name: string; human: number; agents: number; proposed: number; agentsLastWeek: number; /** Money spent on sessions of stories made by agents over 7 days, USD. */ agentCostWeek: number; agentsMoreThanHuman: boolean; } export async function agentTaskSummary(db: Db, now = new Date()): Promise { const since = new Date(now.getTime() - 7 * 86_400_000); const rows = await db .select({ projectId: projects.id, key: projects.key, name: projects.name, human: sql`sum(case when ${tasks.origin} = 'human' then 1 else 0 end)`, agents: sql`sum(case when ${tasks.origin} <> 'human' then 1 else 0 end)`, proposed: sql`sum(case when ${tasks.proposed} = 1 and ${tasks.archivedAt} is null then 1 else 0 end)`, }) .from(projects) .innerJoin(tasks, eq(tasks.projectId, projects.id)) .where(isNull(projects.deletedAt)) .groupBy(projects.id); const out: AgentTaskRow[] = []; for (const r of rows) { const [last] = await db .select({ n: sql`count(*)` }) .from(tasks) .where(and(eq(tasks.projectId, r.projectId), ne(tasks.origin, "human"), gte(tasks.createdAt, since))); out.push({ projectId: r.projectId, key: r.key, name: r.name, human: Number(r.human), agents: Number(r.agents), proposed: Number(r.proposed), agentsLastWeek: Number(last?.n ?? 0), agentCostWeek: await agentCostWeek(db, r.projectId, since), agentsMoreThanHuman: Number(r.agents) > Number(r.human), }); } return out.sort((a, b) => b.agentCostWeek - a.agentCostWeek || b.agents - a.agents); } /** Sum of the cost of sessions of agent-made stories (sessions.usage keeps cost by generation). */ async function agentCostWeek(db: Db, projectId: number, since: Date): Promise { const rows = await db .select({ usage: sessions.usage }) .from(sessions) .innerJoin(tasks, eq(tasks.id, sessions.taskId)) .where(and(eq(sessions.projectId, projectId), ne(tasks.origin, "human"), gte(sessions.lastActivityAt, since))); const total = rows.reduce((sum, r) => sum + (usageTotals(r.usage).costUsd ?? 0), 0); return Math.round(total * 100) / 100; } export function agentTaskTable(rows: AgentTaskRow[]): string { const head = "проект | человек | агенты | предложено | агенты за 7 дн. | траты агентов за 7 дн., $ | агентов больше"; return [head, ...rows.map((r) => `${r.key} | ${r.human} | ${r.agents} | ${r.proposed} | ${r.agentsLastWeek} | ${r.agentCostWeek.toFixed(2)} | ${r.agentsMoreThanHuman ? "да" : "нет"}`)].join("\n"); }