peppa/packages/core/src/task-origin.ts

275 lines
14 KiB
TypeScript

// 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:<id>`, `product.version:<id>`,
// `product.rejected:<id>`, `product.digest:<id>`).
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";
export const TASK_ORIGINS = ["human", "acceptance", "incident", "analyst"] 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<TaskSeverity, string> = {
breakage: tr("Поломка"),
important: tr("Важно"),
minor: tr("Мелочь"),
};
export const ORIGIN_LABEL: Record<TaskOrigin, string> = {
human: tr("человек"),
acceptance: tr("агент приёмки"),
incident: tr("разбор ошибок"),
analyst: 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;
}
export const DEFAULT_AGENT_LIMITS: AgentLimits = { inWork: 3, perPass: 5, inRepo: 4 };
const limitsKey = (projectId: number) => `project.agent-limits:${projectId}`;
export async function getAgentLimits(db: Db, projectId: number): Promise<AgentLimits> {
const s = await getSetting<Partial<AgentLimits>>(db, limitsKey(projectId));
return { ...DEFAULT_AGENT_LIMITS, ...(s ?? {}) };
}
export async function setAgentLimits(db: Db, projectId: number, patch: Partial<AgentLimits> | "reset"): Promise<AgentLimits> {
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]] 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<number> {
const [r] = await db
.select({ n: sql<number>`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);
}
// ── «Предложено» ───────────────────────────────────────────────────────────────
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<number> {
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<string[]> {
return (await getSetting<string[]>(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<void> {
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<void> {
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<void> {
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<boolean> {
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<VersionState>(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<void> {
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<boolean> {
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<number[]> {
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<boolean> {
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<DigestState> => (await getSetting<DigestState>(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<AgentTaskRow[]> {
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<number>`sum(case when ${tasks.origin} = 'human' then 1 else 0 end)`,
agents: sql<number>`sum(case when ${tasks.origin} <> 'human' then 1 else 0 end)`,
proposed: sql<number>`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<number>`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<number> {
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");
}