Merge pull request 'PEP-23/24/25: автономность проекта, диспетчер бэклога, приёмка = мерж' (#47) from task/pep-23 into main

This commit is contained in:
peppa-bot 2026-11-14 05:30:14 +05:00
commit 987ed91ed3
30 changed files with 1567 additions and 15 deletions

View File

@ -83,6 +83,21 @@ PM двигает карточки на доске (веб, `/p/<KEY>`): «В р
сбрасывается ответом человека), задача в `review` → сообщение «готово к ревью» с
«Принять» (`acceptTask` → `done`). Агенты мержат свои PR после зелёного e2e.
**Автономность проекта (PEP-23/24/25)**: настройки в `settings` (`project.autonomy:<id>`, без
колонок; нет строки = «ручной», как до PEP-23), `core/autonomy.ts` (`getAutonomy`/`setAutonomy`,
уровни manual/assisted/auto + поля pick/wipLimit/proposal/merge/close/closeAfterHours/idlePush/
idlePushHours/quietFrom/quietTo). `runner/autonomy.ts` `autonomyTick` из `tick` вачдога:
автомерж стори в ревью (`autoMergeTask`; конфликт → агенту rebase, один раз на head SHA;
конвейер → вопрос PM с «Принять»), закрытие (`after_merge` / `after_hours` через `acceptTask`),
диспетчер (WIP = сессии стори в работе, порядок — номер; при лимите/исчерпанном пуле —
ничего) и пуш «Агенты простаивают» (`onIdleAnswer`: Взять / Следующую / Не сейчас; состояние
`autonomy.idle:<projectId>`, тихие часы, не чаще `idlePushHours`). Хук в режиме merge=auto не шлёт
«готово к ревью». `acceptTask` после мержа — `syncWorkspace` (fetch, ff main, удаляет локальную
ветку стори; только чистая копия на main/ветке стори и без активных сессий;
`PEPPA_WORKSPACE_SYNC=off`). Веб «⋯ Настройки проекта» → «Автономность», MCP
`get_project_settings`/`update_project_settings`, CLI `peppa project autonomy`. MCP агента:
proposal=pm → `update_task in_progress` из backlog/proposing отклоняется.
## Пеппа ведётся через Пеппу
Пеппа — проект `PEP` в самой Пеппе (`.peppa/project.json`, MCP `peppa` из `.mcp.json`).

View File

@ -1,6 +1,9 @@
"use server";
import {
setAutonomy,
type AutonomyLevel,
type AutonomySettings,
linkEgovIin,
createEpic,
createTask,
@ -235,6 +238,33 @@ export async function setProjectVisibilityAction(f: FormData) {
});
}
/** PEP-23: project autonomy — a preset level, or the individual settings (owner or member). */
export async function setAutonomyAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const level = str(f, "level");
if (level) {
await setAutonomy(db, p.id, { level: level as AutonomyLevel });
return;
}
const hour = (k: string) => (str(f, k) === "" ? null : Number(str(f, k)));
const quiet = f.get("quiet") === "on";
await setAutonomy(db, p.id, {
pick: str(f, "pick") as AutonomySettings["pick"],
wipLimit: Number(str(f, "wipLimit")),
proposal: str(f, "proposal") as AutonomySettings["proposal"],
merge: str(f, "merge") as AutonomySettings["merge"],
close: str(f, "close") as AutonomySettings["close"],
closeAfterHours: Number(str(f, "closeAfterHours")),
idlePush: f.get("idlePush") === "on",
idlePushHours: Number(str(f, "idlePushHours")),
quietFrom: quiet ? hour("quietFrom") : null,
quietTo: quiet ? hour("quietTo") : null,
});
});
}
export async function removeProjectMember(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {

View File

@ -17,6 +17,7 @@ const TOOLS: Array<[string, string]> = [
["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"],
["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"],
["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"],
["get_project_settings / update_project_settings", "автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое"],
["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"],
];
@ -31,6 +32,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
{ title: "Автономность", say: "Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR", how: "update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»" },
{ title: "Видимость репозитория", say: "Сделай репозиторий PAY приватным", how: "set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»" },
{ title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»" },
{ title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" },
@ -96,6 +98,19 @@ export default async function Help() {
</div>
</Section>
<Section title="Автономность">
<p className="m-0 text-muted-foreground">
У каждого проекта — уровень автономности («⋯ Настройки проекта» → «Автономность», MCP <span className="font-mono">update_project_settings</span>,
CLI <span className="font-mono">peppa project autonomy KEY</span>). <b>Ручной</b> (по умолчанию): вы двигаете карточки и принимаете стори.{" "}
<b>С подсказками</b>: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками
«Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. <b>Автомат</b>: Пеппа сама берёт следующую стори из
бэклога (по номеру, одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент
сам делает rebase. Настройки можно комбинировать: одобрять каждый proposal, мержить сам, но закрывать вручную или «само через N
часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт
вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main.
</p>
</Section>
<Section title="CI/CD">
<p className="m-0 text-muted-foreground">
Каждый PR агента проверяет Gitea Actions: <span className="font-mono">install</span>, <span className="font-mono">lint</span>,{" "}

View File

@ -1,13 +1,14 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
import { getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
import { Hidden, SessionCard } from "@/components/cards";
import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
import { AutonomyPanel } from "@/components/Autonomy";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
@ -89,7 +90,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const isOwner = p.ownerId === user.id;
// PEP-67: default subscription pool; only a superadmin changes it.
const superadmin = await isSuperadmin(db, user);
const [pool, pools] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([])]);
const [pool, pools, autonomy] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id)]);
// Epic filter (PEP-66): only an open epic of this project filters; anything else shows all.
const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null;
const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
@ -148,6 +149,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
)}
</PanelSection>
<PanelSection title="Автономность">
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} />
</PanelSection>
<PanelSection title="Эпики" count={epics.length}>
<EpicsPanel projectId={p.id} epics={epics} back={back} />
</PanelSection>

View File

@ -0,0 +1,90 @@
// PEP-23: project autonomy in «⋯ Настройки проекта» — preset levels and the individual settings.
import { AUTONOMY_LEVEL_HINT, AUTONOMY_LEVEL_RU, AUTONOMY_LEVELS, autonomyLevel, type AutonomyLevel, type AutonomySettings } from "@peppa/core";
import { setAutonomyAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
import { Input, Label, NativeSelect } from "@/components/ui/input";
export function AutonomyPanel({ projectId, settings, back }: { projectId: number; settings: AutonomySettings; back: string }) {
const current = autonomyLevel(settings);
const s = settings;
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap gap-2" role="group" aria-label="Уровень автономности">
{(Object.keys(AUTONOMY_LEVELS) as AutonomyLevel[]).map((level) => (
<form key={level} action={setAutonomyAction}>
<Hidden fields={{ projectId, level, back }} />
<Button size="sm" variant={current === level ? "default" : "outline"} aria-pressed={current === level} title={AUTONOMY_LEVEL_HINT[level]}>
{AUTONOMY_LEVEL_RU[level]}
</Button>
</form>
))}
{current === "custom" && (
<Button size="sm" variant="default" disabled aria-pressed>
{AUTONOMY_LEVEL_RU.custom}
</Button>
)}
</div>
<p className="m-0 text-xs text-muted-foreground">{current === "custom" ? "Своя комбинация настроек ниже." : AUTONOMY_LEVEL_HINT[current]}</p>
<details>
<summary className="cursor-pointer text-sm text-primary">Настроить подробно</summary>
<form action={setAutonomyAction} className="mt-3 flex flex-col gap-3">
<Hidden fields={{ projectId, back }} />
<Label>
Кто берёт стори из бэклога
<NativeSelect name="pick" defaultValue={s.pick} className="h-8">
<option value="pm">PM — двигает карточки сам</option>
<option value="auto">Пеппа — сама, по номеру стори</option>
</NativeSelect>
</Label>
<Label>
Сколько стори в работе одновременно (для «Пеппа сама»)
<Input name="wipLimit" type="number" min={1} max={5} defaultValue={s.wipLimit} className="h-8" />
</Label>
<Label>
Proposal
<NativeSelect name="proposal" defaultValue={s.proposal} className="h-8">
<option value="agent">Без одобрения — PM только на архитектурные стопперы</option>
<option value="pm">Каждый proposal одобряет PM</option>
</NativeSelect>
</Label>
<Label>
Мерж PR
<NativeSelect name="merge" defaultValue={s.merge} className="h-8">
<option value="manual">По кнопке «Принять»</option>
<option value="auto">Сам после зелёных проверок и без конфликтов</option>
</NativeSelect>
</Label>
<Label>
Закрытие стори
<NativeSelect name="close" defaultValue={s.close} className="h-8">
<option value="pm">PM принимает</option>
<option value="after_merge">Сразу после мержа</option>
<option value="after_hours">Само через N часов без замечаний</option>
</NativeSelect>
</Label>
<Label>
N часов до автозакрытия
<Input name="closeAfterHours" type="number" min={1} max={336} defaultValue={s.closeAfterHours} className="h-8" />
</Label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="idlePush" defaultChecked={s.idlePush} /> Пуш, если агенты простаивают, а в бэклоге есть стори
</label>
<Label>
Не чаще раза в (часов); столько же длится «Не сейчас»
<Input name="idlePushHours" type="number" min={1} max={168} defaultValue={s.idlePushHours} className="h-8" />
</Label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="quiet" defaultChecked={s.quietFrom != null} /> Тихие часы
</label>
<div className="flex items-center gap-2 text-sm">
с <Input name="quietFrom" type="number" min={0} max={23} defaultValue={s.quietFrom ?? 22} className="h-8 w-20" aria-label="Тихие часы с" />
до <Input name="quietTo" type="number" min={0} max={23} defaultValue={s.quietTo ?? 9} className="h-8 w-20" aria-label="Тихие часы до" />
</div>
<Button size="sm" className="self-start">Сохранить</Button>
</form>
</details>
<p className="m-0 text-xs text-muted-foreground">PR, меняющий конвейер (.gitea/, checks, deploy), сам не мержится и не закрывается — его принимает PM.</p>
</div>
);
}

View File

@ -0,0 +1,90 @@
# Design: автономность проекта (PEP-23/24/25)
## Хранение — `settings`, без миграции
Настройки — JSON в `settings` под ключом `project.autonomy:<projectId>`. Нет строки =
«Ручной» (ровно поведение до PEP-23); сохранение «Ручного» без отличий удаляет строку.
Почему не колонки в `projects`: параллельно идут другие стори с миграциями (PEP-39 и др.),
а координатору не нужно применять миграцию до перезапуска сервисов — код со старой базой
работает сразу. Состояние диспетчера (`autonomy.idle:<projectId>`: открытый вопрос, время
пуша, «не сейчас до», «бэклог пуст сообщён», пауза после неудачного запуска) и автомержа
(`autonomy.merge:<taskId>`: head SHA, по которому уже спросили про конвейер / попросили
rebase, PR, по которому уже отправлено «смержено, принять?») — там же.
## Уровни и поля
| Поле | Ручной | С подсказками | Автомат |
|---|---|---|---|
| pick (кто берёт) | pm | pm | auto |
| wipLimit | 1 | 1 | 1 |
| proposal | agent | agent | agent |
| merge | manual | manual | auto |
| close | pm | pm | after_merge |
| idlePush | нет | да | да |
Остальное: `closeAfterHours` 24, `idlePushHours` 4, тихие часы 22–9 (локальное время машины).
Любая другая комбинация показывается как «Свой». WIP по умолчанию 1: агенты проекта
работают в одной рабочей копии, параллельные стори в ней мешают друг другу (лимит до 5 —
для проектов, где агенты работают в своих worktree).
## Порядок стори
В модели нет приоритета и позиции на доске — следующая стори = наименьший номер в бэклоге.
Появятся приоритеты — меняется одна сортировка в `dispatch`.
## Где работает
`autonomyTick` вызывается из `tick` вачдога (каждые 30 с) и пропускает проекты с «Ручным»
без запросов в Gitea. Для каждого проекта: автомерж стори в ревью → автозакрытие по
времени → диспетчер. Порядок важен: закрытая в этом же тике стори освобождает WIP, и
следующая берётся сразу.
«Работающий агент» (WIP) — активная сессия, чья стори в `proposing` / `awaiting_approval` /
`in_progress` / `blocked`. Сессия стори в ревью (ждёт «Принять») слот не занимает, иначе при
«PM принимает» диспетчер вставал бы до приёмки.
## Пуш при простое
Вопрос (kind `question`, привязан к предлагаемой стори) с вариантами
«▶️ Взять KEY / ⏭ Следующую / 💤 Не сейчас (N ч)». Ответ из любого канала (Telegram-кнопки,
веб, MCP `answer_question`) идёт через `answerAndDeliver` → новый реестр `onAnswer` →
`onIdleAnswer`. «Следующую» — сразу вопрос про следующую по номеру (по кругу), «Не сейчас»
и любой другой текст — тишина на `idlePushHours`. Если агент заработал (PM сам двинул
карточку) или бэклог опустел — открытый вопрос закрывается системой. Лимит: раннер проекта
`rate_limited` или все подписки пула проекта не годятся (`projectPoolExhausted`) — нет ни
запуска, ни пуша.
## Автомерж и закрытие
- Стори в ревью без PR — мержить нечего, сразу «после мержа».
- `prGate` не пройден: конфликт (`mergeable === false`) → агенту сообщение «rebase на свежий
main, force-with-lease, снова review» и стори в `in_progress` (живому раннеру — в терминал,
иначе новый раннер с этим промптом); один раз на head SHA. Красные/идущие проверки — их
уже ведёт обратная связь CI (PEP-57).
- Проверки зелёные → `autoMergeTask`: PR с изменением конвейера не мержится; вопрос PM теперь
`attention` по стори в ревью, т.е. сообщение ревью с кнопкой «Принять» (мержит
`mergeTaskPr`, который конвейер не проверяет — решение PM).
- После мержа: `after_merge` — открытые вопросы стори закрываются, стори `done` (раннер
останавливается), рабочая копия синхронизируется, людям проекта — короткое сообщение в
Telegram (без вопроса). `pm` / `after_hours` — одно сообщение «готово к ревью · PR смержен».
- `after_hours`: сообщение ревью без ответа N часов → `acceptTask(…, "system")`. Изменение
конвейера так не закрывается никогда (вопрос PM). Замечание PM отвечает на сообщение — и
автозакрытие не срабатывает.
- Хук Stop при `merge=auto` не шлёт «готово к ревью»: PM услышит только если автомерж
невозможен (конвейер) или по настройке закрытия.
## Рабочая копия (PEP-25)
`syncWorkspace` после «Принять» и автозакрытия: только если в проекте нет активных сессий,
дерево чистое и копия на основной ветке или на ветке этой стори: fetch, checkout main,
`merge --ff-only origin/main`, удалить локальные `task/<KEY>…` (`branch -d`, только слитые).
Иначе ничего не трогает. `PEPPA_WORKSPACE_SYNC=off` выключает. Ветку на сервере удаляет
Gitea (`delete_branch_after_merge`, уже было).
## Одобрение proposal
`proposal=pm`: строка в стартовом промпте и раздел «Автономность проекта» + другой «Следующий
шаг» в `get_task`; MCP `update_task(status: in_progress)` из `backlog`/`proposing` отклоняется
(из `awaiting_approval` — как и раньше). Одобрение PM переводит стори в `in_progress` само.
## Моки
Gitea — `MockGitea`, агенты — `mock-claude`. Мок-агент подставляет `"$TASK"` в аргументах MCP
ключом стори из стартового промпта: один сценарий на все стори проекта (тест диспетчера).
## Не сделано / дальше
- Приоритеты и ручной порядок бэклога (диспетчер берёт по номеру).
- Пуш при простое уходит обычным вопросом (бот рисует варианты кнопками); отдельной
«не сейчас на N часов» с выбором N нет — N из настроек.
- Ротация подписок при лимите — PEP-39.

View File

@ -0,0 +1,42 @@
# PEP-23 · PEP-24 · PEP-25: автономность проекта, диспетчер бэклога, приёмка = мерж
## Why
Эпик «Автономная фабрика»: проект должен доделываться сам — стори берутся из бэклога,
проверяются, мержатся и закрываются по настройкам проекта; PM нужен только на стопперы.
Простоя нет: либо агент работает, либо PM получил пуш. Сейчас всё это делает PM руками:
двигает карточки, жмёт «Принять», а при простое Пеппа молчит.
## What Changes
- **PEP-23 — настройки автономности проекта**: уровни «Ручной» (по умолчанию = поведение до
PEP-23), «С подсказками», «Автомат» и отдельные настройки: кто берёт стори (PM / Пеппа,
WIP-лимит), одобрение proposal (только стопперы / каждый), мерж (по «Принять» / авто после
зелёных проверок), закрытие (PM / сразу после мержа / само через N часов без замечаний),
пуш при простое (частота, тихие часы). Веб «⋯ Настройки проекта» → «Автономность», MCP
`get_project_settings` / `update_project_settings`, CLI `peppa project autonomy`. Агент
получает настройки в стартовом промпте и в `get_task`; при «PM одобряет каждый proposal»
MCP не даёт агенту самому перейти в `in_progress`.
- **PEP-24 — диспетчер бэклога** в `tick` вачдога: при «Пеппа берёт сама» — следующая стори
по номеру, пока не заполнен WIP-лимит; иначе (при включённом пуше) — один вопрос PM
«Агенты простаивают. Взять PEP-7?» с кнопками «Взять / Следующую / Не сейчас», не чаще
раза в N часов, не в тихие часы. Во время лимита (раннер проекта `rate_limited` или пул
подписок исчерпан) ничего не запускается и не предлагается. Неудачный запуск — стори
обратно в бэклог, PM одно сообщение, пауза 30 мин. Пустой бэклог в авто-режиме — одно
сообщение до появления новой стори.
- **PEP-25 — приёмка = мерж**: «Принять» уже мержит PR (PEP-57) с удалением ветки; теперь
ещё подтягивает рабочую копию проекта на свежий main (`syncWorkspace`). При «мерж авто»
Пеппа сама мержит зелёный PR без конфликтов (`autoMergeTask`), при конфликте просит
агента сделать rebase (один раз на head-коммит), PR с изменением конвейера ждёт «Принять»
PM (теперь это сообщение ревью с кнопкой). Хук в этом режиме не шлёт «готово к ревью».
## Capabilities
- New: `project-autonomy`.
## Impact
- Код: `core/autonomy.ts` (новый), `core/subscriptions.ts` (`projectPoolExhausted`),
`core/tasks.ts` (`TaskDetails.autonomy`), `runner/autonomy.ts`, `runner/workspace-sync.ts`
(новые), `runner/watchdog.ts`, `runner/flow.ts`, `runner/hook.ts`, `runner/sessions.ts`
(обработчики ответов `onAnswer`, `resolveTaskById` экспортирован), `runner/ci-feedback.ts`,
MCP (агент и PM), CLI, веб, `/help`, `template/RULES.md`, мок-агент (`$TASK` в аргументах).
- Данные: без миграций — настройки и состояние в `settings`
(`project.autonomy:<id>`, `autonomy.idle:<projectId>`, `autonomy.merge:<taskId>`).
- Живая система: после мержа у всех проектов «Ручной» — ничего не начинает запускаться само.

View File

@ -0,0 +1,89 @@
## ADDED Requirements
### Requirement: Уровни автономности проекта
У каждого проекта SHALL быть настройки автономности: кто берёт стори из бэклога (PM или
Пеппа, WIP-лимит), нужно ли одобрение PM каждого proposal, мерж PR (по «Принять» или
автоматически), закрытие стори (PM, сразу после мержа, само через N часов без замечаний) и
пуш при простое (частота, тихие часы). Уровни «Ручной», «С подсказками», «Автомат» задают
наборы этих настроек; другая комбинация — «Свой». Проект без настроек SHALL вести себя как
«Ручной» — так же, как до появления настроек. Настройки меняют владелец и участники в вебе,
через MCP `update_project_settings` и CLI.
#### Scenario: Проект без настроек
- **WHEN** у проекта никогда не меняли автономность и в бэклоге есть стори
- **THEN** ничего не запускается само и PM не получает пушей
#### Scenario: Уровень и отдельная настройка
- **WHEN** PM выбирает «Автомат», затем включает одобрение каждого proposal
- **THEN** уровень показывается как «Свой», остальные настройки «Автомата» сохраняются
### Requirement: Одобрение каждого proposal
Если в проекте PM одобряет каждый proposal, агент SHALL получить это в стартовом промпте и
в `get_task`, а MCP SHALL отклонить переход стори агентом из `backlog`/`proposing` в
`in_progress`; стори переходит в `in_progress` одобрением PM.
#### Scenario: Агент пытается начать Apply сам
- **WHEN** агент после proposal вызывает `update_task(status: in_progress)`
- **THEN** вызов отклонён с указанием запросить одобрение; после `request_approval` и ответа «ок» стори в `in_progress`
### Requirement: Диспетчер бэклога
Вачдог SHALL для проектов, где стори берёт Пеппа, запускать агентов на следующие стори
бэклога (наименьший номер), пока число работающих агентов проекта меньше WIP-лимита.
Работающий агент — активная сессия стори в `proposing`, `awaiting_approval`, `in_progress`
или `blocked`. Во время лимита (раннер проекта `rate_limited` или пул подписок проекта без
пригодных подписок) диспетчер SHALL ничего не запускать. Неудачный запуск SHALL вернуть
стори в бэклог, сообщить PM один раз и не повторять попытку 30 минут.
#### Scenario: Автомат проходит бэклог без человека
- **WHEN** проект в «Автомате», в бэклоге две стори, агент доводит первую до ревью
- **THEN** первая мержится и закрывается, и в том же тике вачдога агент берёт вторую
#### Scenario: Лимит
- **WHEN** раннер проекта упёрся в лимит подписки
- **THEN** новые стори не запускаются и PM не получает пуш о простое
### Requirement: Пуш при простое
Если стори берёт PM, пуш включён, ни один агент проекта не работает, а в бэклоге есть стори,
PM SHALL получить один вопрос «Агенты простаивают. Взять в работу KEY?» с вариантами
«Взять», «Следующую», «Не сейчас» — не чаще раза в N часов, не в тихие часы и не во время
лимита. «Взять» запускает агента, «Следующую» сразу предлагает следующую стори, «Не сейчас»
выключает пуши на N часов. Если агент заработал или бэклог опустел, открытый вопрос
закрывается сам.
#### Scenario: Простой
- **WHEN** в проекте «С подсказками» нет работающих агентов, в бэклоге PEP-7
- **THEN** PM получает один вопрос с кнопками; повторный тик вачдога второго не создаёт
#### Scenario: Тихие часы
- **WHEN** условия простоя наступили в 23:00 при тихих часах 22–9
- **THEN** пуш уходит не раньше 9:00
### Requirement: Приёмка мержит PR и обновляет рабочую копию
«Принять» SHALL мержить PR стори (зелёные проверки, без конфликтов), Gitea удаляет ветку, а
рабочая копия проекта SHALL подтянуть основную ветку — только если в проекте нет активных
сессий, дерево чистое и копия на основной ветке или на ветке этой стори; иначе копия не
трогается.
#### Scenario: Копия на ветке стори
- **WHEN** PR стори смержен, рабочая копия чистая и на ветке `task/KEY-N`
- **THEN** копия переключается на основную ветку, догоняет её, локальная ветка стори удаляется
### Requirement: Автомерж и автозакрытие
При «мерж авто» Пеппа SHALL мержить PR стори в ревью после зелёных проверок головного
коммита и без конфликтов; хук не шлёт PM «готово к ревью». При конфликте агент SHALL
получить просьбу сделать rebase (один раз на головной коммит). PR, меняющий конвейер, SHALL
не мержиться и не закрываться автоматически: PM получает одно сообщение ревью с кнопкой
«Принять». После мержа стори закрывается по настройке: сразу, по «Принять» PM или сама
через N часов без замечаний.
#### Scenario: Зелёный PR
- **WHEN** стори в ревью, проверки PR зелёные, конфликтов нет, закрытие «сразу после мержа»
- **THEN** PR смержен, стори в «Готово», её раннер остановлен
#### Scenario: Конфликт
- **WHEN** PR стори конфликтует с основной веткой
- **THEN** стори возвращается в работу, агент получает просьбу о rebase
#### Scenario: Закрытие по времени
- **WHEN** закрытие «через 2 часа», сообщение ревью без ответа 2 часа
- **THEN** стори принимается автоматически (PR мержится), ответ — «Принято автоматически»

View File

@ -0,0 +1,25 @@
# Tasks
## 1. Настройки (PEP-23)
- [x] 1.1 `core/autonomy.ts`: поля, уровни, `getAutonomy`/`setAutonomy` (в `settings`), валидация, тихие часы, описание
- [x] 1.2 Агент: строка в стартовом промпте, раздел и «следующий шаг» в `get_task`, гвард MCP при proposal=pm
- [x] 1.3 Веб «⋯ Настройки проекта» → «Автономность» (уровни + подробно), server action
- [x] 1.4 MCP PM `get_project_settings` / `update_project_settings`, инструкции сервера, `/help`
- [x] 1.5 CLI `peppa project autonomy <KEY> [уровень] [key=value…]`
- [x] 1.6 `template/RULES.md`, `AGENTS.md`
## 2. Диспетчер (PEP-24)
- [x] 2.1 `runner/autonomy.ts` `autonomyTick` в `tick` вачдога
- [x] 2.2 Авто: WIP-лимит, порядок по номеру, лимит/пул → пауза, неудачный старт → бэклог + сообщение + 30 мин
- [x] 2.3 Пуш при простое: вопрос с кнопками, дедуп, частота, тихие часы, «Следующую»/«Не сейчас»/«Взять» (`onAnswer` в `answerAndDeliver`)
- [x] 2.4 Пустой бэклог в авто — одно сообщение
## 3. Приёмка = мерж (PEP-25)
- [x] 3.1 Автомерж стори в ревью, rebase при конфликте, вопрос с «Принять» при изменении конвейера
- [x] 3.2 Закрытие: after_merge / pm / after_hours (без автозакрытия конвейера)
- [x] 3.3 Хук: без «готово к ревью» при merge=auto
- [x] 3.4 `syncWorkspace` после «Принять» и автозакрытия
## 4. Тесты и документация
- [x] 4.1 `packages/testkit/test/autonomy-levels.test.ts` (17 сценариев), `$TASK` в мок-агенте
- [x] 4.2 typecheck, весь e2e

View File

@ -0,0 +1,94 @@
# project-autonomy Specification
## Purpose
TBD - created by archiving change pep-23-autonomy. Update Purpose after archive.
## Requirements
### Requirement: Уровни автономности проекта
У каждого проекта SHALL быть настройки автономности: кто берёт стори из бэклога (PM или
Пеппа, WIP-лимит), нужно ли одобрение PM каждого proposal, мерж PR (по «Принять» или
автоматически), закрытие стори (PM, сразу после мержа, само через N часов без замечаний) и
пуш при простое (частота, тихие часы). Уровни «Ручной», «С подсказками», «Автомат» задают
наборы этих настроек; другая комбинация — «Свой». Проект без настроек SHALL вести себя как
«Ручной» — так же, как до появления настроек. Настройки меняют владелец и участники в вебе,
через MCP `update_project_settings` и CLI.
#### Scenario: Проект без настроек
- **WHEN** у проекта никогда не меняли автономность и в бэклоге есть стори
- **THEN** ничего не запускается само и PM не получает пушей
#### Scenario: Уровень и отдельная настройка
- **WHEN** PM выбирает «Автомат», затем включает одобрение каждого proposal
- **THEN** уровень показывается как «Свой», остальные настройки «Автомата» сохраняются
### Requirement: Одобрение каждого proposal
Если в проекте PM одобряет каждый proposal, агент SHALL получить это в стартовом промпте и
в `get_task`, а MCP SHALL отклонить переход стори агентом из `backlog`/`proposing` в
`in_progress`; стори переходит в `in_progress` одобрением PM.
#### Scenario: Агент пытается начать Apply сам
- **WHEN** агент после proposal вызывает `update_task(status: in_progress)`
- **THEN** вызов отклонён с указанием запросить одобрение; после `request_approval` и ответа «ок» стори в `in_progress`
### Requirement: Диспетчер бэклога
Вачдог SHALL для проектов, где стори берёт Пеппа, запускать агентов на следующие стори
бэклога (наименьший номер), пока число работающих агентов проекта меньше WIP-лимита.
Работающий агент — активная сессия стори в `proposing`, `awaiting_approval`, `in_progress`
или `blocked`. Во время лимита (раннер проекта `rate_limited` или пул подписок проекта без
пригодных подписок) диспетчер SHALL ничего не запускать. Неудачный запуск SHALL вернуть
стори в бэклог, сообщить PM один раз и не повторять попытку 30 минут.
#### Scenario: Автомат проходит бэклог без человека
- **WHEN** проект в «Автомате», в бэклоге две стори, агент доводит первую до ревью
- **THEN** первая мержится и закрывается, и в том же тике вачдога агент берёт вторую
#### Scenario: Лимит
- **WHEN** раннер проекта упёрся в лимит подписки
- **THEN** новые стори не запускаются и PM не получает пуш о простое
### Requirement: Пуш при простое
Если стори берёт PM, пуш включён, ни один агент проекта не работает, а в бэклоге есть стори,
PM SHALL получить один вопрос «Агенты простаивают. Взять в работу KEY?» с вариантами
«Взять», «Следующую», «Не сейчас» — не чаще раза в N часов, не в тихие часы и не во время
лимита. «Взять» запускает агента, «Следующую» сразу предлагает следующую стори, «Не сейчас»
выключает пуши на N часов. Если агент заработал или бэклог опустел, открытый вопрос
закрывается сам.
#### Scenario: Простой
- **WHEN** в проекте «С подсказками» нет работающих агентов, в бэклоге PEP-7
- **THEN** PM получает один вопрос с кнопками; повторный тик вачдога второго не создаёт
#### Scenario: Тихие часы
- **WHEN** условия простоя наступили в 23:00 при тихих часах 22–9
- **THEN** пуш уходит не раньше 9:00
### Requirement: Приёмка мержит PR и обновляет рабочую копию
«Принять» SHALL мержить PR стори (зелёные проверки, без конфликтов), Gitea удаляет ветку, а
рабочая копия проекта SHALL подтянуть основную ветку — только если в проекте нет активных
сессий, дерево чистое и копия на основной ветке или на ветке этой стори; иначе копия не
трогается.
#### Scenario: Копия на ветке стори
- **WHEN** PR стори смержен, рабочая копия чистая и на ветке `task/KEY-N`
- **THEN** копия переключается на основную ветку, догоняет её, локальная ветка стори удаляется
### Requirement: Автомерж и автозакрытие
При «мерж авто» Пеппа SHALL мержить PR стори в ревью после зелёных проверок головного
коммита и без конфликтов; хук не шлёт PM «готово к ревью». При конфликте агент SHALL
получить просьбу сделать rebase (один раз на головной коммит). PR, меняющий конвейер, SHALL
не мержиться и не закрываться автоматически: PM получает одно сообщение ревью с кнопкой
«Принять». После мержа стори закрывается по настройке: сразу, по «Принять» PM или сама
через N часов без замечаний.
#### Scenario: Зелёный PR
- **WHEN** стори в ревью, проверки PR зелёные, конфликтов нет, закрытие «сразу после мержа»
- **THEN** PR смержен, стори в «Готово», её раннер остановлен
#### Scenario: Конфликт
- **WHEN** PR стори конфликтует с основной веткой
- **THEN** стори возвращается в работу, агент получает просьбу о rebase
#### Scenario: Закрытие по времени
- **WHEN** закрытие «через 2 часа», сообщение ревью без ответа 2 часа
- **THEN** стори принимается автоматически (PR мержится), ответ — «Принято автоматически»

View File

@ -3,6 +3,10 @@ import { parseArgs } from "node:util";
import { resolve } from "node:path";
import {
backupDb,
describeAutonomy,
getAutonomy,
setAutonomy,
type AutonomyPatch,
createGoal,
createProject,
createTask,
@ -58,6 +62,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa project create <slug> <KEY> <name> [--existing] [--private] (repo in peppa-bot's Gitea namespace)
peppa project add <slug> <KEY> <name> [--owner peppa] [--repo <name>] [--path <dir>] (register only)
peppa project owner <KEY> <gitea-login|->
peppa project autonomy <KEY> [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes)
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
peppa project list
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
@ -246,6 +251,33 @@ async function main(): Promise<void> {
if (failed) process.exitCode = 1;
break;
}
case "project autonomy": {
// PEP-23: peppa project autonomy <KEY> [manual|assisted|auto] [key=value…]
const [key, ...rest] = args;
if (!key) throw new PeppaError("usage: peppa project autonomy <KEY> [manual|assisted|auto] [pick=pm|auto wipLimit=N proposal=agent|pm merge=manual|auto close=pm|after_merge|after_hours closeAfterHours=N idlePush=on|off idlePushHours=N quiet=22-9|off]");
const p = await getProject(db, key);
if (rest.length) {
const patch: AutonomyPatch = {};
for (const arg of rest) {
if (["manual", "assisted", "auto"].includes(arg)) {
patch.level = arg as AutonomyPatch["level"];
continue;
}
const [k, v = ""] = arg.split("=");
if (k === "quiet") {
const m = /^(\d+)-(\d+)$/.exec(v);
patch.quietFrom = m ? Number(m[1]) : null;
patch.quietTo = m ? Number(m[2]) : null;
} else if (k === "idlePush") patch.idlePush = v === "on" || v === "true";
else if (k === "wipLimit" || k === "closeAfterHours" || k === "idlePushHours") patch[k] = Number(v);
else if (k === "pick" || k === "proposal" || k === "merge" || k === "close") (patch as Record<string, string>)[k] = v;
else throw new PeppaError(`unknown setting: ${k}`);
}
await setAutonomy(db, p.id, patch);
}
console.log(`${p.key}\n${describeAutonomy(await getAutonomy(db, p.id))}`);
break;
}
case "project list":
for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`);
break;

View File

@ -0,0 +1,160 @@
// 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" | "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 },
// 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: "С подсказками",
auto: "Автомат",
custom: "Свой",
};
export const AUTONOMY_LEVEL_HINT: Record<AutonomyLevel, string> = {
manual: "PM двигает карточки и принимает стори; при простое Пеппа молчит.",
assisted: "PM решает сам, но если агенты простаивают, а в бэклоге есть стори, — пуш с кнопками «Взять / Следующую / Не сейчас».",
auto: "Стори берутся из бэклога сами, зелёный PR мержится, стори закрывается после мержа. PM — только на стопперы и изменения конвейера.",
};
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;
}

View File

@ -25,3 +25,4 @@ export * from "./reviews.ts";
export * from "./webpush.ts";
export * from "./notifications.ts";
export * from "./digest.ts";
export * from "./autonomy.ts";

View File

@ -268,3 +268,13 @@ export async function projectPool(db: Db, projectId: number): Promise<Subscripti
.where(and(eq(projects.id, projectId)));
return row?.pool ?? null;
}
/**
* PEP-24: true when the project's pool has no usable subscription right now (all limited or
* broken) — the dispatcher neither starts agents nor offers stories then. No pool = false.
*/
export async function projectPoolExhausted(db: Db, projectId: number, now = new Date()): Promise<boolean> {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
if (p?.poolId == null) return false;
return !(await poolSubscriptions(db, p.poolId)).some((s) => isUsable(s, now));
}

View File

@ -7,6 +7,7 @@ import { getGoal, getProject, type Goal, type Project } from "./projects.ts";
import { incidentForTask, type Incident } from "./incidents.ts";
import { taskCiSummary, type CiSummary } from "./ci.ts";
import { latestReview, type CodeReview } from "./reviews.ts";
import { getAutonomy, type AutonomySettings } from "./autonomy.ts";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@ -131,6 +132,8 @@ export interface TaskDetails {
ci: CiSummary;
/** Latest review by the project's reviewer agent (PEP-26), if any. */
review: CodeReview | null;
/** The project's autonomy settings (PEP-23): agents follow them. */
autonomy: AutonomySettings;
}
export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails> {
@ -143,7 +146,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails>
.orderBy(desc(events.id))
.limit(20);
const incident = await incidentForTask(db, ref.task.id);
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id) };
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id) };
}
export interface NewQuestion {

View File

@ -1,4 +1,4 @@
import { formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
import { agentAutonomyNote, formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
const NEXT_STEP: Record<TaskStatus, string> = {
backlog: "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → если нет архитектурных решений, сразу update_task(status: in_progress) и Apply в этом же ходе.",
@ -41,7 +41,14 @@ export function formatTask(d: TaskDetails): string {
lines.push("", "## Последний прогресс");
for (const e of progress.slice(-5)) lines.push(`- ${e.createdAt.toISOString().slice(0, 16)} ${(e.payload as { text: string }).text}`);
}
lines.push("", "## Следующий шаг", "", NEXT_STEP[task.status]);
// PEP-23: the project's autonomy changes the next step (PM approves every proposal).
const pmApproves = d.autonomy?.proposal === "pm" && (task.status === "backlog" || task.status === "proposing");
const next = pmApproves
? "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → в этом проекте PM одобряет каждый proposal: request_approval и конец хода. Apply — только после одобрения."
: NEXT_STEP[task.status];
lines.push("", "## Следующий шаг", "", next);
const note = d.autonomy ? agentAutonomyNote(d.autonomy) : null;
if (note) lines.push("", "## Автономность проекта", "", note);
return lines.join("\n");
}

View File

@ -7,6 +7,7 @@ import {
createTask,
findProjectFile,
getIncident,
getAutonomy,
getProject,
getTaskDetails,
incidentStatuses,
@ -132,6 +133,11 @@ tool(
if (status === "in_progress" && ref.task.status === "awaiting_approval") {
throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress.");
}
// PEP-23: a project where the PM approves every proposal — Apply only after the approval
// (the PM's answer moves the story to in_progress itself).
if (status === "in_progress" && (ref.task.status === "backlog" || ref.task.status === "proposing") && (await getAutonomy(db, ref.project.id)).proposal === "pm") {
throw new PeppaError("In this project the PM approves every proposal: call request_approval with the proposal summary and end your turn.");
}
if (status === "review" && ref.task.status !== "review") {
// PEP-57: review only with green checks of the PR head (the PR given now counts).
const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } });

View File

@ -3,6 +3,9 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
createEpic,
describeAutonomy,
getAutonomy,
setAutonomy,
createTask,
getEpic,
updateEpic,
@ -54,6 +57,7 @@ Good habits:
- Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user.
- Projects can be shared: add_member / remove_member (owner only); members can do everything else. Repos are public by default; set_project_visibility (owner only) makes one private or public again.
- CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks.
- Autonomy (get_project_settings / update_project_settings): manual by default; "auto" lets Peppa take stories from the backlog, merge green PRs and close stories itself; "assisted" only pushes the user when agents idle. Change it only when the user asks.
- Production errors (Bugsink) arrive as incidents: list_incidents. What happens to a new one is the project's incident policy (get_incident_policy / set_incident_policy: notify, backlog — default, start, ask, triage with the user's mini-prompt). Pending ones wait for decide_incident (backlog / start / ignore); resolve_incident marks one fixed.`;
export function createManagerServer(db: Db, user: User, webUrl: string): McpServer {
@ -189,6 +193,49 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
},
);
// PEP-23: autonomy of a project — levels and individual settings (owner or member).
tool("get_project_settings", "A project's autonomy settings: who takes stories from the backlog, PM approval of proposals, merge and closing mode, idle pushes.", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
return describeAutonomy(await getAutonomy(db, p.id));
});
tool(
"update_project_settings",
"Change a project's autonomy. level: manual (the user moves cards and accepts; default), assisted (as manual + a push when agents idle with a non-empty backlog), auto (Peppa takes stories from the backlog itself, merges green PRs and closes stories after the merge). Individual fields override the level. Only when the user asks.",
{
project: projectArg,
level: z.enum(["manual", "assisted", "auto"]).optional(),
pick: z.enum(["pm", "auto"]).optional().describe("Who takes stories from the backlog"),
wip_limit: z.number().int().min(1).max(5).optional().describe("Stories in work at once when pick=auto"),
proposal: z.enum(["agent", "pm"]).optional().describe("pm = the user approves every proposal"),
merge: z.enum(["manual", "auto"]).optional().describe("auto = merge green PRs without conflicts (pipeline changes always need the user)"),
close: z.enum(["pm", "after_merge", "after_hours"]).optional(),
close_after_hours: z.number().int().min(1).max(336).optional(),
idle_push: z.boolean().optional().describe("Push the user when no agent works and the backlog is not empty"),
idle_push_hours: z.number().int().min(1).max(168).optional(),
quiet_from: z.number().int().min(0).max(23).nullable().optional(),
quiet_to: z.number().int().min(0).max(23).nullable().optional(),
},
false,
async (a) => {
const p = await ownedProject(a.project);
const s = await setAutonomy(db, p.id, {
level: a.level,
pick: a.pick,
wipLimit: a.wip_limit,
proposal: a.proposal,
merge: a.merge,
close: a.close,
closeAfterHours: a.close_after_hours,
idlePush: a.idle_push,
idlePushHours: a.idle_push_hours,
quietFrom: a.quiet_from,
quietTo: a.quiet_to,
});
return `${p.key}:\n${describeAutonomy(s)}`;
},
);
tool(
"list_tasks",
"List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column.",

View File

@ -0,0 +1,332 @@
// 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,
enqueueTelegram,
getAutonomy,
getSetting,
giteaForBot,
inAutonomyQuietHours,
listProjects,
listSessions,
listTasks,
pipelineChanges,
prGate,
projectPoolExhausted,
questionRecipients,
raiseSessionQuestion,
setSetting,
taskPrNumber,
type AutonomySettings,
type GiteaClient,
type Project,
type Question,
type SessionView,
type Task,
type TaskRef,
} from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, eq, 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<IdleState>(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<void> {
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<MergeState>(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<MergeState>(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"] });
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") {
if (limited || (state.failUntil ?? 0) > now.getTime()) return;
let slots = a.wipLimit - working.length;
for (const task of backlog) {
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 || !backlog.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, backlog[0]!, now);
log(`${project.key}: idle push (${formatTaskKey(project.key, backlog[0]!.number)})`);
}
/** Sessions that hold a WIP slot: their story is being worked on (not in review). */
async function workingSessions(db: Db, sessions: SessionView[]): Promise<SessionView[]> {
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<boolean> {
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 listTasks(db, { projectId: q.projectId, statuses: ["backlog"] });
const next = backlog.find((t) => t.number > ref.task.number) ?? backlog[0];
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);

View File

@ -230,9 +230,10 @@ export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = g
if (!gate.ok) return { merged: false, reason: gate.reason };
const changes = await pipelineChanges(ref, gate.pull, gitea);
if (changes.length) {
// An "attention" on a story in review is its review message: the PM gets «Принять» (merges).
await askPm(db, ref, {
kind: "question",
text: `⚠️ ${ref.key}: PR меняет конвейер — автомерж отключён, нужно ваше ревью.\n${changes.map((c) => `• ${c}`).join("\n")}\nPR: ${gate.pull.html_url}`,
kind: "attention",
text: `⚠️ ${ref.key}: PR меняет конвейер — автомерж отключён, нужно ваше ревью.\n${changes.map((c) => `• ${c}`).join("\n")}\nPR: ${gate.pull.html_url}\n«Принять» смержит PR.`,
});
return { merged: false, reason: "изменение конвейера требует ревью PM" };
}

View File

@ -5,6 +5,7 @@ import { formatTaskKey } from "@peppa/shared";
import { eq } from "drizzle-orm";
import { startSession, stopSession, type StartOptions } from "./sessions.ts";
import { mergeTaskPr } from "./ci-feedback.ts";
import { syncWorkspace } from "./workspace-sync.ts";
export type BoardColumn = "backlog" | "in_progress" | "review" | "done";
@ -61,9 +62,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
/**
* "Accept" on a ready-for-review message: the task's PR is merged (green checks, no
* conflicts — otherwise nothing changes and the PM sees why), task done, session stopped.
* conflicts — otherwise nothing changes and the PM sees why; Gitea deletes the branch),
* task done, session stopped, the working copy fast-forwarded to main.
*/
export async function acceptTask(db: Db, questionId: number, via: NonNullable<Question["answeredVia"]>): Promise<TaskRef> {
export async function acceptTask(db: Db, questionId: number, via: NonNullable<Question["answeredVia"]>, answer = "✅ Принято"): Promise<TaskRef> {
const q = await getQuestion(db, questionId);
if (!q.taskId) throw new PeppaError("Вопрос не привязан к стори");
if (q.answeredAt) throw new PeppaError(`Уже отвечено (${q.answeredVia}): ${q.answer}`);
@ -75,8 +77,10 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable<Qu
const ref = await resolveTask(db, formatTaskKey(t!.key, t!.number));
if (ref.task.status !== "review") throw new PeppaError(`${ref.key} не в ревью (сейчас ${ref.task.status})`);
await mergeTaskPr(ref);
await answerQuestion(db, q.id, "✅ Принято", via);
await answerQuestion(db, q.id, answer, via);
await moveTask(db, ref, "done");
// PEP-25: the merged main lands in the working copy (best effort, never fails the accept).
await syncWorkspace(db, ref).catch(() => {});
return ref;
}

View File

@ -7,6 +7,7 @@ import { appendFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import {
answerQuestion,
getAutonomy,
getQuestion,
getReviewSettings,
latestReview,
@ -184,6 +185,12 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
return null;
}
const [task] = s.taskId ? await db.select().from(tasks).where(eq(tasks.id, s.taskId)) : [];
if (task?.status === "review" && (await getAutonomy(db, task.projectId)).merge === "auto") {
// PEP-25: Peppa merges this PR itself (watchdog); the PM hears only if it can't.
await logSessionEvent(db, s, "awaiting_automerge", { pr: task.prUrl });
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
if (task?.status === "review") {
// PEP-26: what the reviewer agent said (approved, findings left after the limit, failed).
const settings = await getReviewSettings(db, task.projectId);

View File

@ -21,3 +21,5 @@ export * from "./code.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
export * from "./autonomy.ts";
export * from "./workspace-sync.ts";

View File

@ -1,7 +1,9 @@
import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
agentAutonomyNote,
answerQuestion,
getAutonomy,
getSubscription,
pickSubscription,
createSession,
@ -56,7 +58,9 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider, subscriptionId: sub?.id ?? null });
const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName });
const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n");
// PEP-23: the project's autonomy (PM approves proposals, Peppa merges) goes into the prompt.
const note = agentAutonomyNote(await getAutonomy(db, ref.project.id));
const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, note, opts.prompt].filter(Boolean).join("\n\n");
return launch(db, await getSession(db, session.id), cwd, { ...opts, prompt });
}
@ -161,6 +165,13 @@ export async function stopSession(db: Db, sessionId: number): Promise<void> {
await logSessionEvent(db, s, "stopped");
}
/** Handlers that consume an answer themselves (true = handled, not typed into a session). */
export type AnswerHandler = (db: Db, q: Question, answer: string) => Promise<boolean>;
const answerHandlers: AnswerHandler[] = [];
export function onAnswer(h: AnswerHandler) {
answerHandlers.push(h);
}
const APPROVE_RE = /^\s*(ok|ок|да|yes|approve|approved|одобр|lgtm|go|погнали|делай)/i;
// Claude Code permission prompt: 1 = yes, 2 = yes and don't ask again, 3 = no.
const PERMISSION_KEYS: Record<string, string> = { allow: "1", always: "2", deny: "3" };
@ -193,6 +204,8 @@ export async function answerAndDeliver(
message = `Ответ PM на вопрос #${q.id}: ${answer}`;
}
// Other answer handlers (PEP-24: "agents are idle" push).
for (const h of answerHandlers) if (await h(db, q, answer)) return { delivered: true, question: q };
// "Deploy to prod" on a "staging updated" message (PEP-57).
if (await onReleaseAnswer(db, q, answer, `PM (${via})`)) return { delivered: true, question: q };
// A task question asked outside a session (red CI, a manual session) goes to the agent
@ -213,7 +226,7 @@ export async function answerAndDeliver(
return { delivered: true, question: q };
}
async function resolveTaskById(db: Db, taskId: number) {
export async function resolveTaskById(db: Db, taskId: number) {
const [row] = await db
.select({ key: projects.key, number: tasks.number })
.from(tasks)

View File

@ -20,6 +20,7 @@ import { monitorTick } from "./monitor.ts";
import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
import { autonomyTick } from "./autonomy.ts";
export interface WatchdogOptions {
/** Current time (tests move it instead of waiting). */
@ -51,6 +52,8 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise<void> {
log(`session #${s.id}: ${(e as Error).message}`);
}
}
// Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher.
await autonomyTick(db, { now: opts.now, log }).catch((e) => log(`autonomy: ${(e as Error).message}`));
// Errors of running products (PEP-58): Bugsink poll + incident policies.
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
// Daily digest at each user's time (PEP-29); a no-op outside their window.

View File

@ -0,0 +1,31 @@
// PEP-25: after a story is accepted/merged, the project's working copy follows main.
import { existsSync } from "node:fs";
import { join } from "node:path";
import { listSessions, type TaskRef } from "@peppa/core";
import type { Db } from "@peppa/db";
import { git } from "./git.ts";
/**
* Brings the project's working copy to the merged main: fetch, and — when no agent works
* there, the tree is clean and it is on main or on the story's branch — checkout main,
* fast-forward, delete the merged local story branch. Anything else is left alone.
* `PEPPA_WORKSPACE_SYNC=off` disables it.
*/
export async function syncWorkspace(db: Db, ref: TaskRef): Promise<"synced" | "busy" | "dirty" | "other_branch" | "no_git" | "off"> {
if (process.env.PEPPA_WORKSPACE_SYNC === "off") return "off";
const dir = ref.project.workspacePath;
if (!existsSync(join(dir, ".git"))) return "no_git";
if ((await listSessions(db, { active: true })).some((s) => s.projectId === ref.project.id)) return "busy";
const def = ref.project.defaultBranch;
const branch = (await git(dir, "rev-parse", "--abbrev-ref", "HEAD")).stdout.trim();
const storyBranch = `task/${ref.key}`.toLowerCase();
if (branch !== def && !branch.toLowerCase().startsWith(storyBranch)) return "other_branch";
if ((await git(dir, "status", "--porcelain")).stdout.trim()) return "dirty";
await git(dir, "fetch", "--prune", "origin");
if (branch !== def) await git(dir, "checkout", def);
await git(dir, "merge", "--ff-only", `origin/${def}`);
const local = (await git(dir, "branch", "--format=%(refname:short)")).stdout.split("\n").map((b) => b.trim());
for (const b of local.filter((b) => b.toLowerCase().startsWith(storyBranch))) await git(dir, "branch", "-d", b).catch(() => {});
return "synced";
}

View File

@ -141,7 +141,14 @@ function mcpCommand(): string {
return process.env.PEPPA_MOCK_MCP_BIN ?? cfg.mcpServers?.peppa?.command ?? "peppa-mcp";
}
async function callMcp(tool: string, toolArgs: Record<string, unknown>) {
// "$TASK" in MCP args = the story the runner started this agent on ("Работай над стори KEY-N"),
// so one scenario serves every story of a project (PEP-24 dispatcher tests).
const startTask = /стори ([A-Z][A-Z0-9]*-\d+)/.exec(args.prompt ?? "")?.[1] ?? null;
const withTask = (v: Record<string, unknown>) =>
Object.fromEntries(Object.entries(v).map(([k, x]) => [k, x === "$TASK" && startTask ? startTask : x]));
async function callMcp(tool: string, rawArgs: Record<string, unknown>) {
const toolArgs = withTask(rawArgs);
if (!mcp) {
mcp = new Client({ name: `mock-${provider}`, version: "0" });
await mcp.connect(new StdioClientTransport({ command: mcpCommand(), cwd, env: process.env as Record<string, string> }));

View File

@ -0,0 +1,375 @@
// PEP-23/24/25, spec project-autonomy: levels, dispatcher (no idle without a push),
// auto-merge and closing, working copy after the merge — mock-claude runners, mock Gitea.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { projects } from "@peppa/db";
import { eq } from "drizzle-orm";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-auto-")), "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" };
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
});
after(async () => {
await gitea.stop();
await teardown();
});
const projectOf = (p: TestProject) => core.getProject(db, p.key);
const taskOf = async (key: string) => (await core.resolveTask(db, key)).task;
const openQuestions = async (projectId: number) => core.pendingQuestions(db, projectId);
const activeOf = async (projectId: number) => (await core.listSessions(db, { active: true })).filter((s) => s.projectId === projectId);
const autonomy = (now = new Date()) => runner.autonomyTick(db, { now });
/** Settings without quiet hours: tests run at any time of day. */
const NO_QUIET = { quietFrom: null, quietTo: null } as const;
describe("autonomy settings", () => {
test("a project without settings is manual; presets and custom combinations; validation", async () => {
const p = await projectOf(await project({ turns: [] }));
const s = await core.getAutonomy(db, p.id);
assert.equal(core.autonomyLevel(s), "manual");
assert.deepEqual({ pick: s.pick, merge: s.merge, close: s.close, idlePush: s.idlePush }, { pick: "pm", merge: "manual", close: "pm", idlePush: false });
const auto = await core.setAutonomy(db, p.id, { level: "auto" });
assert.equal(core.autonomyLevel(auto), "auto");
assert.deepEqual({ pick: auto.pick, merge: auto.merge, close: auto.close }, { pick: "auto", merge: "auto", close: "after_merge" });
const custom = await core.setAutonomy(db, p.id, { proposal: "pm", close: "after_hours", closeAfterHours: 6 });
assert.equal(core.autonomyLevel(custom), "custom");
assert.equal(custom.pick, "auto", "fields override the current settings");
assert.match(core.describeAutonomy(custom), /каждый одобряет PM[\s\S]*через 6 ч/);
await assert.rejects(core.setAutonomy(db, p.id, { wipLimit: 0 }), /wipLimit/);
await assert.rejects(core.setAutonomy(db, p.id, { merge: "yolo" as never }), /merge/);
await core.setAutonomy(db, p.id, { level: "manual" });
assert.equal(await core.getSetting(db, `project.autonomy:${p.id}`), null, "manual = no row, as before PEP-23");
});
test("quiet hours wrap over midnight", () => {
const q = { quietFrom: 22, quietTo: 9 };
assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 23, 30)), true);
assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 8, 59)), true);
assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 12, 0)), false);
assert.equal(core.inAutonomyQuietHours({ quietFrom: null, quietTo: null }, new Date(2026, 10, 14, 23)), false);
});
});
describe("dispatcher", () => {
test("manual (default): nothing starts by itself and the PM gets no push", async () => {
const tp = await project({ turns: [] });
const p = await projectOf(tp);
await runner.tick(db, { intervalMs: 0, stallMs: 60_000 });
assert.equal((await activeOf(p.id)).length, 0);
assert.equal((await openQuestions(p.id)).length, 0);
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
});
test("auto: backlog → work → review → merged → done → next story, without a human; then 'backlog empty' once", async () => {
const tp = await project({ turns: [[{ mcp: "update_task", args: { task: "$TASK", status: "review" } }, { say: "Готово, PR открыт." }]] });
const p = await projectOf(tp);
const second = await core.createTask(db, { projectId: p.id, title: "вторая стори" });
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
// The watchdog tick runs the dispatcher: the lowest number first, WIP 1.
await runner.tick(db, { intervalMs: 0, stallMs: 600_000 });
let active = await activeOf(p.id);
assert.equal(active.length, 1);
assert.equal(active[0]!.taskKey, tp.taskKey);
assert.equal((await taskOf(second.key)).status, "backlog", "WIP limit 1: the second story waits");
await waitFor("first story in review", async () => (await taskOf(tp.taskKey)).status === "review");
await waitFor("agent finished its turn", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input");
assert.equal((await openQuestions(p.id)).length, 0, "merge=auto: no 'ready for review' for the PM");
await autonomy();
assert.equal((await taskOf(tp.taskKey)).status, "done", "no PR → nothing to merge → closed after merge");
assert.equal((await core.getSession(db, active[0]!.id)).status, "done", "its agent stopped");
active = await activeOf(p.id);
assert.equal(active[0]?.taskKey, second.key, "the next story was taken in the same tick");
await waitFor("second story in review", async () => (await taskOf(second.key)).status === "review");
await waitFor("second agent idle", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input");
await autonomy();
assert.equal((await taskOf(second.key)).status, "done");
const empty = (await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст"));
assert.equal(empty.length, 1);
await autonomy();
assert.equal((await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")).length, 1, "told once");
});
test("auto: nothing starts while a runner of the project is rate-limited or its pool is exhausted", async () => {
const tp = await project({ turns: [] });
const p = await projectOf(tp);
const other = await core.createTask(db, { projectId: p.id, title: "другая" });
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
// A rate-limited runner on another story of the project.
const s = await core.createSession(db, { projectId: p.id, taskId: other.task.id });
await core.updateSession(db, s.id, { status: "rate_limited", resumeAt: new Date(Date.now() + 3_600_000) });
await autonomy();
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
await core.updateSession(db, s.id, { status: "done" });
const sub = await core.createSubscription(db, { provider: "claude", name: `mock-sub-${p.key}`, authKind: "oauth", secret: "mock-token" });
await core.updateSubscription(db, sub.id, { status: "limited", limitedUntil: new Date(Date.now() + 3_600_000) });
const pool = await core.createPool(db, { name: `mock-pool-${p.key}`, subscriptionIds: [sub.id] });
await core.setProjectPool(db, p.id, pool.id);
assert.equal(await core.projectPoolExhausted(db, p.id), true);
await autonomy();
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
assert.equal((await openQuestions(p.id)).length, 0, "no push during a limit either");
});
test("auto: a failed start puts the story back, tells the PM once and backs off", async () => {
const tp = await project({ turns: [] });
const p = await projectOf(tp);
await db.update(projects).set({ workspacePath: "/nonexistent/mock-ws" }).where(eq(projects.id, p.id));
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
const now = new Date();
await autonomy(now);
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
const qs = await openQuestions(p.id);
assert.equal(qs.length, 1);
assert.match(qs[0]!.text, /не смог запустить агента/);
await autonomy(new Date(now.getTime() + 60_000));
assert.equal((await openQuestions(p.id)).length, 1, "no retry storm within the back-off");
});
test("assisted: idle push with buttons — no duplicates; Next offers the next story; Not now snoozes; Take starts", async () => {
const tp = await project({ turns: [[{ say: "работаю" }]] });
const p = await projectOf(tp);
const second = await core.createTask(db, { projectId: p.id, title: "вторая" });
await core.setAutonomy(db, p.id, { level: "assisted", ...NO_QUIET });
await autonomy();
let [q] = await openQuestions(p.id);
assert.ok(q, "pushed");
assert.match(q.text, /агенты простаивают/);
assert.match(q.text, new RegExp(`Взять в работу ${tp.taskKey}`));
assert.equal(q.options?.length, 3);
await autonomy();
assert.equal((await openQuestions(p.id)).length, 1, "one open push at a time");
await runner.answerAndDeliver(db, q.id, runner.IDLE_NEXT, "telegram");
[q] = await openQuestions(p.id);
assert.match(q!.text, new RegExp(`Взять в работу ${second.key}`), "Next → the next story right away");
await runner.answerAndDeliver(db, q!.id, q!.options![2]!, "telegram");
assert.equal((await openQuestions(p.id)).length, 0);
await autonomy();
assert.equal((await openQuestions(p.id)).length, 0, "Not now → quiet for idlePushHours");
await autonomy(new Date(Date.now() + 5 * 3_600_000));
[q] = await openQuestions(p.id);
assert.ok(q, "pushed again after the snooze");
await runner.answerAndDeliver(db, q.id, q.options![0]!, "web");
assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "Take → the story is in work");
const active = await activeOf(p.id);
assert.equal(active.length, 1);
await autonomy();
assert.equal((await openQuestions(p.id)).filter((x) => x.text.includes("простаивают")).length, 0, "an agent works: no push");
await runner.stopSession(db, active[0]!.id);
});
test("assisted: no push in quiet hours, nor more often than idlePushHours; a manual move closes the push", async () => {
const tp = await project({ turns: [[{ say: "работаю" }]] });
const p = await projectOf(tp);
await core.setAutonomy(db, p.id, { level: "assisted", quietFrom: 22, quietTo: 9, idlePushHours: 4 });
await autonomy(new Date(2026, 10, 14, 23, 0));
assert.equal((await openQuestions(p.id)).length, 0, "quiet hours");
await autonomy(new Date(2026, 10, 14, 10, 0));
const [q] = await openQuestions(p.id);
assert.ok(q);
// The PM starts the story from the board instead: the push is moot.
const { started } = await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "in_progress");
await autonomy(new Date(2026, 10, 14, 10, 1));
assert.equal((await core.getQuestion(db, q.id)).answeredVia, "system");
await runner.stopSession(db, started!);
await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "backlog");
await autonomy(new Date(2026, 10, 14, 11, 0));
assert.equal((await openQuestions(p.id)).length, 0, "not more often than every 4 h");
await autonomy(new Date(2026, 10, 14, 14, 1));
assert.equal((await openQuestions(p.id)).length, 1);
});
});
interface PrTask {
tp: TestProject;
proj: Awaited<ReturnType<typeof core.getProject>>;
pr: { number: number };
push(files?: Record<string, string>): string;
green(sha: string): void;
}
/** A story in review with an open PR (task/<KEY>-1) in mock Gitea. */
async function prTask(level: Parameters<typeof core.setAutonomy>[2]): Promise<PrTask> {
const tp = await project({ turns: [] });
const proj = await projectOf(tp);
const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS });
writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
let n = 0;
const push = (files: Record<string, string> = {}) => gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { [`f${n++}.txt`]: String(n), ...files });
const sha = push();
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
const green = (s: string) => {
for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, s, `peppa/${c}`, "success");
};
green(sha);
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
await core.setAutonomy(db, proj.id, { ...level, ...NO_QUIET });
return { tp, proj, pr, push, green };
}
const pull = (t: PrTask) => gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[t.pr.number - 1]!;
describe("auto-merge and closing", () => {
test("merge=auto, close=after_merge: a green PR is merged and the story closed", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
await autonomy();
assert.equal(pull(t).merged, true);
assert.equal((await taskOf(t.tp.taskKey)).status, "done");
});
test("merge=auto, close=pm: merged, then 'ready for review' with Accept → done", async () => {
const t = await prTask({ merge: "auto", close: "pm" });
await autonomy();
assert.equal(pull(t).merged, true);
assert.equal((await taskOf(t.tp.taskKey)).status, "review");
const [q] = await openQuestions(t.proj.id);
assert.match(q!.text, /PR смержен автоматически/);
assert.ok(await runner.isReviewQuestion(db, q!));
await autonomy();
assert.equal((await openQuestions(t.proj.id)).length, 1, "asked once");
await runner.acceptTask(db, q!.id, "telegram");
assert.equal((await taskOf(t.tp.taskKey)).status, "done");
});
test("pending checks: nothing merged yet", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
t.push(); // new head without statuses
await autonomy();
assert.equal(pull(t).merged, false);
assert.equal((await taskOf(t.tp.taskKey)).status, "review");
});
test("conflicts: the agent is asked to rebase (once per head commit)", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
pull(t).mergeable = false;
await autonomy();
assert.equal(pull(t).merged, false);
assert.equal((await taskOf(t.tp.taskKey)).status, "in_progress", "back to work");
const [s] = await activeOf(t.proj.id);
assert.ok(s, "an agent was started for the rebase");
const ev = await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase"));
assert.match(String(ev.prompt), /force-with-lease/);
await runner.stopSession(db, s!.id);
});
test("pipeline change: not merged, the PM gets one review message with Accept", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
t.green(t.push({ ".gitea/workflows/ci.yml": "on: push\n" }));
await autonomy();
await autonomy();
assert.equal(pull(t).merged, false);
const qs = (await openQuestions(t.proj.id)).filter((q) => q.text.includes("меняет конвейер"));
assert.equal(qs.length, 1, "asked once per head commit");
assert.ok(await runner.isReviewQuestion(db, qs[0]!), "with «Принять»");
await runner.acceptTask(db, qs[0]!.id, "web");
assert.equal(pull(t).merged, true, "the PM's Accept merges it");
});
test("close=after_hours: 'ready for review' without comments for N hours → accepted (PR merged)", async () => {
const t = await prTask({ close: "after_hours", closeAfterHours: 2 });
const q = await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" });
await autonomy(new Date(Date.now() + 3_600_000));
assert.equal((await taskOf(t.tp.taskKey)).status, "review", "not yet");
await autonomy(new Date(Date.now() + 2 * 3_600_000 + 60_000));
assert.equal((await taskOf(t.tp.taskKey)).status, "done");
assert.equal(pull(t).merged, true);
assert.match((await core.getQuestion(db, q.id)).answer ?? "", /автоматически/);
});
test("close=after_hours never accepts a pipeline change by itself", async () => {
const t = await prTask({ close: "after_hours", closeAfterHours: 1 });
t.green(t.push({ ".gitea/peppa-check.sh": "exit 0\n" }));
await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" });
await autonomy(new Date(Date.now() + 2 * 3_600_000));
assert.equal((await taskOf(t.tp.taskKey)).status, "review");
assert.equal(pull(t).merged, false);
assert.ok((await openQuestions(t.proj.id)).some((q) => q.text.includes("меняет конвейер")));
});
});
describe("proposal approval and the working copy", () => {
test("proposal=pm: the agent can't start Apply itself; the prompt says to request approval", async () => {
const tp = await project({
turns: [
[
{ mcp: "update_task", args: { task: "$TASK", status: "proposing", openspec_change: "x-1" } },
{ mcp: "update_task", args: { task: "$TASK", status: "in_progress" } },
{ mcp: "request_approval", args: { task: "$TASK", summary: "Proposal: сделать X без новых зависимостей" } },
],
],
});
const p = await projectOf(tp);
await core.setAutonomy(db, p.id, { proposal: "pm" });
const sid = await tp.start();
const refused = await tp.waitLog("refused apply", (e) => e.ev === "mcp" && e.tool === "update_task" && e.isError === true);
assert.match(String(refused.text), /approves every proposal/);
assert.ok(tp.log().some((e) => e.ev === "prompt" && String(e.prompt).includes("PM одобряет каждый proposal")));
const q = await tp.waitQuestion(sid, "approval");
assert.equal((await taskOf(tp.taskKey)).status, "awaiting_approval");
await runner.answerAndDeliver(db, q.id, "ок", "web");
assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "the PM's approval starts Apply");
await runner.stopSession(db, sid);
});
test("syncWorkspace: the working copy on the story branch goes to the merged main; the local branch is deleted", async () => {
const root = mkdtempSync(join(tmpdir(), "peppa-sync-"));
const g = (cwd: string, ...a: string[]) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...a], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
const origin = join(root, "origin.git");
execFileSync("git", ["init", "--bare", "-b", "main", origin], { stdio: "ignore" });
const ws = join(root, "ws");
execFileSync("git", ["clone", origin, ws], { stdio: "ignore" });
g(ws, "checkout", "-b", "main");
writeFileSync(join(ws, "a.txt"), "1");
g(ws, "add", ".");
g(ws, "commit", "-m", "init");
g(ws, "push", "-u", "origin", "main");
const tp = await project({ turns: [] });
const p = await projectOf(tp);
await db.update(projects).set({ workspacePath: ws }).where(eq(projects.id, p.id));
g(ws, "checkout", "-b", `task/${tp.taskKey}`);
writeFileSync(join(ws, "b.txt"), "2");
g(ws, "add", "b.txt");
g(ws, "commit", "-m", "story");
g(ws, "push", "origin", `task/${tp.taskKey}`);
// The PR is merged on the server: main gets the story's commit.
g(ws, "push", "origin", `task/${tp.taskKey}:main`);
const ref = await core.resolveTask(db, tp.taskKey);
assert.equal(await runner.syncWorkspace(db, ref), "synced");
assert.equal(g(ws, "rev-parse", "--abbrev-ref", "HEAD"), "main");
assert.equal(g(ws, "rev-parse", "HEAD"), g(ws, "rev-parse", "origin/main"));
assert.equal(g(ws, "branch", "--list", `task/${tp.taskKey}`), "", "merged local branch deleted");
// Another branch or uncommitted changes: left alone.
g(ws, "checkout", "-b", "feature/other");
assert.equal(await runner.syncWorkspace(db, ref), "other_branch");
g(ws, "checkout", "main");
writeFileSync(join(ws, "a.txt"), "dirty");
assert.equal(await runner.syncWorkspace(db, ref), "dirty");
});
});

View File

@ -99,7 +99,7 @@ describe("PM tools over MCP", () => {
await core.setProjectOwner(db, proj.id, owner.id);
const { client, call } = await mcpAs(owner);
const tools = (await client.listTools()).tools;
assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_task"]);
assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_project_settings", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]);
assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true);
assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false);
@ -124,6 +124,11 @@ describe("PM tools over MCP", () => {
assert.ok((await s.call("answer_question", { question_id: q.id, answer: "x" })).isError);
assert.match((await call("move_task", { task: `${p.key}-2`, to: "backlog" })).text, /1 session\(s\) stopped/);
// PEP-23: autonomy settings of the project; strangers can't touch them.
assert.match((await call("get_project_settings", { project: p.key })).text, /Уровень: Ручной/);
assert.match((await call("update_project_settings", { project: p.key, level: "auto", proposal: "pm" })).text, /Уровень: Свой[\s\S]*каждый одобряет PM/);
assert.ok((await s.call("update_project_settings", { project: p.key, level: "manual" })).isError);
await call("update_project_settings", { project: p.key, level: "manual" });
});
});

View File

@ -64,7 +64,18 @@ PM отвечает только на **архитектурные стоппе
- Запушь ветку и открой PR в Gitea (ссылка на стори и резюме change).
- `peppa.update_task` → `status: review`, `pr_url: …` и закончи ход. PM получит «готово
к ревью»: кнопка «Принять» закрывает стори, текстом — замечания, их доделываешь.
- Статус `done` ставит только PM.
- Статус `done` ставит только PM (или Пеппа по настройкам автономности проекта).
### Автономность проекта
- У проекта есть настройки автономности (PM меняет их в вебе). Что касается тебя, Пеппа
добавляет в стартовый промпт и в `get_task` (раздел «Автономность проекта»):
- «PM одобряет каждый proposal» — после proposal `request_approval` и конец хода;
`update_task(status: in_progress)` из proposing в таком проекте отклоняется.
- «PR мержит Пеппа» — не мержи PR сам; после зелёных проверок Пеппа смержит его и закроет
стори. Попросит rebase из-за конфликтов — rebase на свежую основную ветку, проверки,
`git push --force-with-lease` в ту же ветку, снова `status: review`.
- Стори может взять в работу сама Пеппа («Стори взята из бэклога автоматически») — работай
как обычно.
## CI: проверки перед PR