peppa/packages/core/src/autonomy.ts
Асель e9526c9329 PEP-79, PEP-80: new projects pick stories themselves; own subscription — Claude or ChatGPT
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 20:15:22 +05:00

169 lines
9.0 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.

// Project autonomy (PEP-23): who takes stories from the backlog, whether the PM approves
// proposals, how PRs are merged and how stories are closed, and idle pushes (PEP-24).
// Stored in `settings` (`project.autonomy:<id>`), no schema change; a project without a
// row is "manual" — exactly the behaviour before PEP-23.
import type { Db } from "@peppa/db";
import { PeppaError } from "./errors.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
export type PickMode = "pm" | "auto";
export type ProposalMode = "agent" | "pm";
export type MergeMode = "manual" | "auto";
export type CloseMode = "pm" | "after_merge" | "after_hours";
export interface AutonomySettings {
/** Who takes stories from the backlog: the PM (board) or the dispatcher (watchdog). */
pick: PickMode;
/** Stories the dispatcher keeps in work at once (agents share the project's working copy). */
wipLimit: number;
/** "pm": every proposal needs the PM's approval; "agent": only architectural stoppers. */
proposal: ProposalMode;
/** "auto": a green PR without conflicts and pipeline changes is merged by Peppa. */
merge: MergeMode;
/** When a story in review becomes Done. */
close: CloseMode;
closeAfterHours: number;
/** Push to the PM when no agent works and the backlog is not empty (PM picks). */
idlePush: boolean;
/** Not more often than this per project; also the "not now" snooze. */
idlePushHours: number;
/** Quiet hours (local time, 0–23): no idle pushes from `quietFrom` to `quietTo`. Null = none. */
quietFrom: number | null;
quietTo: number | null;
}
export type AutonomyLevel = "manual" | "assisted" | "self" | "auto";
const BASE: AutonomySettings = {
pick: "pm",
wipLimit: 1,
proposal: "agent",
merge: "manual",
close: "pm",
closeAfterHours: 24,
idlePush: false,
idlePushHours: 4,
quietFrom: 22,
quietTo: 9,
};
/** Presets shown as levels; any other combination is "custom". */
export const AUTONOMY_LEVELS: Record<AutonomyLevel, AutonomySettings> = {
// Before PEP-23: the PM moves cards and accepts; nothing starts by itself.
manual: BASE,
// The PM still decides, but Peppa pushes when agents idle with a non-empty backlog.
assisted: { ...BASE, idlePush: true },
// PEP-79: nobody drags cards — the dispatcher takes stories from the backlog; the PM still
// accepts the result. The default of a new project.
self: { ...BASE, pick: "auto" },
// Backlog → Done without a human: dispatcher, auto-merge, closing after the merge.
auto: { ...BASE, pick: "auto", merge: "auto", close: "after_merge", idlePush: true },
};
export const AUTONOMY_LEVEL_RU: Record<AutonomyLevel | "custom", string> = {
manual: "Ручной",
assisted: "С подсказками",
self: "Сам берёт",
auto: "Автомат",
custom: "Свой",
};
export const AUTONOMY_LEVEL_HINT: Record<AutonomyLevel, string> = {
manual: "PM двигает карточки и принимает стори; при простое Пеппа молчит.",
assisted: "PM решает сам, но если агенты простаивают, а в бэклоге есть стори, — пуш с кнопками «Взять / Следующую / Не сейчас».",
self: "Стори берутся из бэклога сами, по порядку на доске; результат принимаете вы («Принять» в ревью).",
auto: "Стори берутся из бэклога сами, зелёный PR мержится, стори закрывается после мержа. PM — только на стопперы и изменения конвейера.",
};
/** PEP-79: what a newly created project starts with (existing projects keep their settings). */
export const NEW_PROJECT_AUTONOMY: AutonomySettings = AUTONOMY_LEVELS.self;
const key = (projectId: number) => `project.autonomy:${projectId}`;
export function autonomyLevel(s: AutonomySettings): AutonomyLevel | "custom" {
for (const [name, preset] of Object.entries(AUTONOMY_LEVELS) as Array<[AutonomyLevel, AutonomySettings]>) {
if ((Object.keys(BASE) as Array<keyof AutonomySettings>).every((k) => preset[k] === s[k])) return name;
}
return "custom";
}
export async function getAutonomy(db: Db, projectId: number): Promise<AutonomySettings> {
const stored = await getSetting<Partial<AutonomySettings>>(db, key(projectId));
return normalize({ ...BASE, ...(stored ?? {}) });
}
export type AutonomyPatch = Partial<AutonomySettings> & { level?: AutonomyLevel };
const intIn = (v: unknown, min: number, max: number, name: string): number => {
const n = Number(v);
if (!Number.isInteger(n) || n < min || n > max) throw new PeppaError(`${name}: целое от ${min} до ${max}`);
return n;
};
function normalize(s: AutonomySettings): AutonomySettings {
const oneOf = <T extends string>(v: unknown, all: readonly T[], name: string): T => {
if (!all.includes(v as T)) throw new PeppaError(`${name}: одно из ${all.join(", ")}`);
return v as T;
};
const hour = (v: unknown, name: string) => (v === null || v === undefined || v === "" ? null : intIn(v, 0, 23, name));
const quietFrom = hour(s.quietFrom, "quietFrom");
const quietTo = hour(s.quietTo, "quietTo");
return {
pick: oneOf(s.pick, ["pm", "auto"], "pick"),
wipLimit: intIn(s.wipLimit, 1, 5, "wipLimit"),
proposal: oneOf(s.proposal, ["agent", "pm"], "proposal"),
merge: oneOf(s.merge, ["manual", "auto"], "merge"),
close: oneOf(s.close, ["pm", "after_merge", "after_hours"], "close"),
closeAfterHours: intIn(s.closeAfterHours, 1, 24 * 14, "closeAfterHours"),
idlePush: Boolean(s.idlePush),
idlePushHours: intIn(s.idlePushHours, 1, 24 * 7, "idlePushHours"),
// Both or none: half a range means nothing.
quietFrom: quietFrom != null && quietTo != null ? quietFrom : null,
quietTo: quietFrom != null && quietTo != null ? quietTo : null,
};
}
/**
* Changes a project's autonomy: a preset `level` first, then individual fields on top.
* Manual without overrides removes the row (back to "never configured").
*/
export async function setAutonomy(db: Db, projectId: number, patch: AutonomyPatch): Promise<AutonomySettings> {
const { level, ...fields } = patch;
if (level && !(level in AUTONOMY_LEVELS)) throw new PeppaError(`Уровень: одно из ${Object.keys(AUTONOMY_LEVELS).join(", ")}`);
const base = level ? AUTONOMY_LEVELS[level] : await getAutonomy(db, projectId);
const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined));
const next = normalize({ ...base, ...defined });
if (JSON.stringify(next) === JSON.stringify(BASE)) await deleteSetting(db, key(projectId));
else await setSetting(db, key(projectId), next);
return next;
}
/** True inside the quiet hours (local time of the machine Peppa runs on). */
export function inAutonomyQuietHours(s: Pick<AutonomySettings, "quietFrom" | "quietTo">, now: Date): boolean {
if (s.quietFrom == null || s.quietTo == null || s.quietFrom === s.quietTo) return false;
const h = now.getHours();
return s.quietFrom < s.quietTo ? h >= s.quietFrom && h < s.quietTo : h >= s.quietFrom || h < s.quietTo;
}
/** One-paragraph description for the PM (web, MCP, CLI). */
export function describeAutonomy(s: AutonomySettings): string {
const level = autonomyLevel(s);
const lines = [
`Уровень: ${AUTONOMY_LEVEL_RU[level]}`,
`Стори из бэклога берёт: ${s.pick === "auto" ? `Пеппа сама (одновременно до ${s.wipLimit})` : "PM"}`,
`Proposal: ${s.proposal === "pm" ? "каждый одобряет PM" : "без одобрения, кроме архитектурных стопперов"}`,
`Мерж PR: ${s.merge === "auto" ? "автоматически после зелёных проверок (кроме изменений конвейера)" : "по «Принять»"}`,
`Закрытие: ${s.close === "pm" ? "PM принимает" : s.close === "after_merge" ? "сразу после мержа" : `само через ${s.closeAfterHours} ч без замечаний`}`,
`Пуш при простое: ${s.idlePush ? `да, не чаще раза в ${s.idlePushHours} ч${s.quietFrom != null ? `, тихие часы ${s.quietFrom}:00–${s.quietTo}:00` : ""}` : "нет"}`,
];
return lines.join("\n");
}
/** The extra instruction for agents of a project (appended to the start prompt and get_task). */
export function agentAutonomyNote(s: AutonomySettings): string | null {
const notes: string[] = [];
if (s.proposal === "pm") notes.push("В этом проекте PM одобряет каждый proposal: после proposal — peppa.request_approval и конец хода, Apply только после одобрения.");
if (s.merge === "auto") notes.push("PR мержит Пеппа сама после зелёных проверок; не мержи его сам. Если Пеппа попросит ребейз — rebase на основную ветку и force-push в ту же ветку.");
return notes.length ? notes.join("\n") : null;
}