195 lines
11 KiB
TypeScript
195 lines
11 KiB
TypeScript
// 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 { m as tr } from "@peppa/shared/i18n";
|
||
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";
|
||
/** PEP-197: whose stories Peppa accepts herself: only the person's / and breakages / all. */
|
||
export type AcceptOwnMode = "mine" | "mine_breakage" | "all";
|
||
export const ACCEPT_OWN_MODES: readonly AcceptOwnMode[] = ["mine", "mine_breakage", "all"];
|
||
|
||
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;
|
||
/** PEP-197: «Принимать сами» — which stories (by who made them) merge and close without the owner. */
|
||
acceptOwn: AcceptOwnMode;
|
||
/** 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,
|
||
acceptOwn: "mine_breakage",
|
||
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: tr("Ручной"),
|
||
assisted: tr("С подсказками"),
|
||
self: tr("Сам берёт"),
|
||
auto: tr("Автомат"),
|
||
custom: tr("Свой"),
|
||
};
|
||
|
||
export const AUTONOMY_LEVEL_HINT: Record<AutonomyLevel, string> = {
|
||
manual: tr("Вы сами двигаете карточки и принимаете задачи; когда агенты простаивают, Peppa FACTORY молчит."),
|
||
assisted: tr("Вы решаете сами, но если агенты простаивают, а в бэклоге есть задачи, придёт сообщение с кнопками «Взять / Следующую / Не сейчас»."),
|
||
self: tr("Задачи берутся из бэклога сами, по порядку на доске; результат принимаете вы («Принять» в ревью)."),
|
||
auto: tr("Задачи берутся из бэклога сами и закрываются после проверок без вашего участия. Вас зовут, только когда без вас не обойтись."),
|
||
};
|
||
|
||
/**
|
||
* PEP-79/94: what a newly created project starts with (existing projects keep their settings):
|
||
* «Автомат» — the PM is a product person and approves nothing technical; a green PR is merged
|
||
* and the story closed without waiting for «Принять».
|
||
*/
|
||
export const NEW_PROJECT_AUTONOMY: AutonomySettings = AUTONOMY_LEVELS.auto;
|
||
|
||
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(tr("{name}: целое от {min} до {max}", { 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(tr("{name}: одно из {list}", { name, list: 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"),
|
||
acceptOwn: oneOf(s.acceptOwn ?? "mine_breakage", ACCEPT_OWN_MODES, "acceptOwn"),
|
||
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(tr("Уровень: одно из {list}", { list: Object.keys(AUTONOMY_LEVELS).join(", ") }));
|
||
const current = await getAutonomy(db, projectId);
|
||
// PEP-197: a level changes how work goes, not whose stories are accepted without the owner.
|
||
const base = level ? { ...AUTONOMY_LEVELS[level], acceptOwn: current.acceptOwn } : current;
|
||
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 = [
|
||
tr("Уровень: {v}", { v: AUTONOMY_LEVEL_RU[level] }),
|
||
// glossary-ignore: подробное описание автономности — для MCP и командной строки, на экране «Продакта» его нет
|
||
tr("Стори из бэклога берёт: {v}", { v: s.pick === "auto" ? tr("Peppa FACTORY сама (одновременно до {n})", { n: s.wipLimit }) : "PM" }),
|
||
tr("Proposal: {v}", { v: s.proposal === "pm" ? tr("каждый одобряет PM") : tr("без одобрения, кроме архитектурных стопперов") }),
|
||
// glossary-ignore: подробное описание автономности — для MCP и командной строки, на экране «Продакта» его нет
|
||
tr("Мерж PR: {v}", { v: s.merge === "auto" ? tr("автоматически после зелёных проверок (кроме изменений конвейера)") : tr("по «Принять»") }),
|
||
tr("Закрытие: {v}", {
|
||
// glossary-ignore: подробное описание автономности — для MCP и командной строки, на экране «Продакта» его нет
|
||
v: s.close === "pm" ? tr("PM принимает") : s.close === "after_merge" ? tr("сразу после мержа") : tr("само через {n} ч без замечаний", { n: s.closeAfterHours }),
|
||
}),
|
||
tr("Принимать сами: {v}", { v: s.acceptOwn === "mine" ? tr("только мои задачи") : s.acceptOwn === "all" ? tr("всё") : tr("мои и поломки") }),
|
||
tr("Пуш при простое: {v}", {
|
||
v: !s.idlePush
|
||
? tr("нет")
|
||
: s.quietFrom != null
|
||
? tr("да, не чаще раза в {n} ч, тихие часы {from}:00–{to}:00", { n: s.idlePushHours, from: s.quietFrom, to: s.quietTo })
|
||
: tr("да, не чаще раза в {n} ч", { n: s.idlePushHours }),
|
||
}),
|
||
];
|
||
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;
|
||
}
|