Compare commits

..

1 Commits

Author SHA1 Message Date
64255e6550 PEP-268: сбои платформы не списывают попытки задачи
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 34с
peppa/test test: success за 1510с
peppa-ci / ci (pull_request) Successful in 27m11s
Пропавшая сессия tmux, зависание Claude до SessionStart и запуск с HostUnreachable/
TMUX_SERVER_DOWN — planPlatformRetry: свой счётчик watch_state.platformFails, бесплатный
перезапуск через 1/5/15/30 мин, суперадмину одно сообщение на третьем сбое, владельцу —
строка «Сбой на нашей стороне, чиним». Тест platform-failures-free.test.ts; change
архивирован, требование в openspec/specs/watchdog-recovery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 13:18:46 +00:00
64 changed files with 473 additions and 1458 deletions

View File

@ -34,8 +34,6 @@
- `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299).
- Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265).
- Песочница раннера: нет tmux, Node 26 (без 26 тесты падают на импортах — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp). tmux — .deb deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, тесты хостов в sandbox-hosts.test.ts (нет ssh).
- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287).
- Пропал `.git/worktrees/s<id>`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`.
- Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <cli> <версия>` (json + оба Dockerfile), откат `--rollback`.
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
@ -53,12 +51,13 @@
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
- Задача не от человека — `createTask` с origin сама в «Предложено» (PEP-295), путь — проверить `proposalRoom` до создания; новый вызов `createTask` — в список `proposals-only.test.ts`; автомерж — autonomy.acceptOwn.
- Задачу агента — createTask с origin (acceptance|incident|analyst|agent) через fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + proposed; суточный предел предложений — `proposalRoom` (PEP-270); автомерж — autonomy.acceptOwn.
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
- Access Hub (PEP-249): новый HTTP-сервис — карточка в `core/connection-catalog.ts` (тест сверяет каждую); меняет данные через GET (Slack) — чтение по методам. Новый не-HTTP вид (PEP-251) — операция в `PROTOCOL_OPERATIONS`, драйвер `GatewayDrivers` (получает проверенный `address`, сам DNS не разрешает) и мок в testkit/mock-access.ts. Ответ сервиса агенту (PEP-258) — только через `connectionKeyForms`+`maskConnectionKey`; новый способ ключа — в тест-ловушку access-hub.test.ts.
- act_runner (PEP-233/248): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь; `not_taken` — pending, а другие проекты отчитываются.
- Конфликт PR с main (PEP-269) — только `conflictStep` (runner/conflict-step.ts), не `requestRebase` напрямую.
- Новый вид сбоя платформы — `planPlatformRetry` (recovery.ts, PEP-268): `platformFails`, `restarts` не трогать. Мок — `hangAtStart`.
## Решения
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.

File diff suppressed because one or more lines are too long

View File

@ -26,8 +26,6 @@ import {
type IncidentPolicy,
getUser,
isSuperadmin,
getDirectOrigins,
setDirectOrigins,
setUserDisabled,
setSuperadmin,
mergeAccounts,
@ -688,17 +686,6 @@ export async function connectErrorTrackingAction(f: FormData) {
});
}
/** PEP-295: the owner's exception — errors of the product go to work without «Делать». */
export async function setDirectIncidentsAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
if (p.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError(m("Это решает владелец проекта."));
const rest = (await getDirectOrigins(db, p.id)).filter((o) => o !== "incident");
await setDirectOrigins(db, p.id, str(f, "on") === "yes" ? [...rest, "incident"] : rest);
});
}
export async function saveIncidentSettings(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {

View File

@ -5,7 +5,7 @@ import { PublishPanel } from "@/components/PublishPanel";
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getDirectOrigins, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { productNeeds, lastProductReview } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
@ -103,7 +103,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const tab = visibleTabs.find((x) => x.id === tabParam)?.id ?? "board";
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps, directOrigins] = await Promise.all([
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
board(p.id),
listEpics(db, p.id),
projectSessions(p.id),
@ -117,7 +117,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
getReviewSettings(db, p.id),
epicProgress(db, p.id),
blockersMap(db, p.id),
getDirectOrigins(db, p.id),
]);
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
@ -361,7 +360,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
projectId={p.id}
back={back}
isOwner={isOwner}
direct={directOrigins.includes("incident")}
settings={incidentSettings}
sources={sources}
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}

View File

@ -1,7 +1,7 @@
// Project page «Баги» (PEP-58, PEP-66): incidents list (tab) and Bugsink settings (⋯ Настройки проекта).
import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings, setDirectIncidentsAction } from "@/app/(app)/actions";
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge";
@ -61,8 +61,6 @@ export async function IncidentSettingsPanel(props: {
settings: IncidentSettings | null;
sources: ErrorSource[];
webhookUrl: string | null;
/** PEP-295: the owner let errors of the product go to work without «Делать». */
direct: boolean;
w: Words;
}) {
const { projectId, back, settings: s, w } = props;
@ -85,35 +83,10 @@ export async function IncidentSettingsPanel(props: {
</div>
);
}
// PEP-295: whether errors go to work without «Делать» is the owner's decision — shown in both views.
const direct = (
<div className="flex flex-col gap-1.5 text-sm">
<span>
{props.direct
? t("Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».")
: t("Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».")}
</span>
{props.isOwner && (
<form action={setDirectIncidentsAction}>
<Hidden fields={{ projectId, back, on: props.direct ? "no" : "yes" }} />
<Button size="sm" variant="outline">
{props.direct ? t("Ждать моего решения") : t("Брать в работу сразу")}
</Button>
</form>
)}
</div>
);
// PEP-123: addresses, variables and the policy of incidents are an engineer's settings.
if (w.product)
return (
<div className="flex flex-col gap-3">
<p className="m-0 text-sm text-muted-foreground">{t("Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.")}</p>
{direct}
</div>
);
if (w.product) return <p className="m-0 text-sm text-muted-foreground">{t("Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.")}</p>;
return (
<div className="flex flex-col gap-3 text-sm">
{direct}
{props.sources.map((src) => (
<div key={src.id} className="flex flex-col gap-1">
<span className="font-medium">{src.kind === "web" ? t("DSN фронта (web)") : t("DSN бэка (api)")}</span>

View File

@ -41,7 +41,7 @@ export async function ProposalList({ items, back }: { items: ProposalItem[]; bac
</Button>
</form>
) : (
<span className="text-xs text-muted-foreground">{i.decision === "rejected" ? t("Отклонено") : t("Взято в бэклог")}</span>
<span className="text-xs text-muted-foreground">{i.decision === "rejected" ? t("Отклонено") : i.severity === "breakage" ? t("Уже в бэклоге") : t("Взято в бэклог")}</span>
)}
</div>
))}

View File

@ -141,22 +141,6 @@ Claude Code, Codex и OpenCode закреплены в `infra/agent-versions.jso
- Что работает на самом деле — вачдог раз в час (`agentVersionsTick`): страница «Платформа» → «Версии программ
агентов», `platform_status`; расхождение — одно сообщение суперадмину на версию.
## Диск сервера (PEP-287)
Убирает сама платформа, чужие образы, контейнеры и тома не трогает (сервер общий):
- папки агентов `~/peppa/home/sandboxes/s<id>` — вачдог раз в 10 мин удаляет папки законченных сессий без
контейнера, если задача в «Готово» или в архиве; сессий без задачи (свободные агенты, дымовой тест) — через
сутки. Не больше 20 за проход, каждое удаление — событие `sandbox_removed` в журнале платформы. Выключить —
`PEPPA_DISK_CLEANUP=off` в `.env` (выключает и два пункта ниже).
- кэш сборки docker — вачдог раз в час: `docker builder prune -f --keep-storage <предел>` (клиент 20.10 в образе
не знает `--reserved-space`; новый клиент — `--reserved-space`), без `-a`. Предел —
`docker exec peppa-watchdog peppa platform watchdog buildCacheGb=40` (0 — выкл), итог — событие `build_cache_pruned`.
- образы `peppa/platform` — `platform-deploy.sh` после удачной выкатки оставляет три (текущий и два для отката).
- сторож: свободно меньше `diskFreeAlertPct` (15%) — одно сообщение суперадминам на эпизод.
- Временная строка cron `peppa-build-cache-prune` (26.11) и `~/peppa/bin/disk-prune.sh` убираются первой выкаткой
с PEP-287 сами (в журнале выкатки — «временная чистка кэша сборки … убрана»). Если нет:
`crontab -l | grep -v peppa-build-cache-prune | crontab - && rm -f ~/peppa/bin/disk-prune.sh`.
## Полезное
- Здоровье: `curl -s http://127.0.0.1:3100/api/health` (коммит и сервисы).
- Логи: `docker logs --tail 200 peppa-watchdog` (так же `peppa-web`, `peppa-bot`, `peppa-observer`).

View File

@ -0,0 +1,34 @@
## Контекст
Попытки задачи — `watch_state.restarts` (время авто-перезапусков, предел `restartMax` в окне
`restartWindowMin`). PEP-205 уже сделал «бесплатный» повтор для сбоя входа (`restartFree`,
`loginFails`), PEP-227 — для потерянного разговора. Остальные сбои платформы шли через
`onRunnerCrash`/`restartStalled` и тратили попытки.
## Решения
- **Классификация** (`platformFailure` по месту вызова, без эвристик по тексту экрана):
- `onRunnerCrash(…, "gone")` — сессия tmux пропала. У сессий `remain-on-exit on`: процесс
агента, упав, оставляет мёртвую панель (это `crash`, ошибка агента/задачи). Пропавшая сессия —
значит, её убил кто-то снаружи (рестарт сервера tmux, выкатка, OOM) — платформа.
- `restartStalled` — зависание считается сбоем платформы, если после последнего `started`/`resumed`
у Claude не было хука SessionStart (событие `claude_session`): программа агента так и не
запустилась. Агент, который начал работу и завис, тратит попытку как раньше. Codex/OpenCode
такого хука не шлют — для них зависание по-прежнему тратит попытку.
- `restartTick`: `resumeSession` бросил `HostUnreachable` или ошибку `TMUX_SERVER_DOWN` —
запуск не состоялся по вине платформы, попытка возвращается, повтор по расписанию платформы.
- Сбой входа (PEP-205) — без изменений (уже бесплатный).
- **Счётчик** `platformFails: number[]` — время сбоев в окне `restartWindowMin`. Нужен для паузы
(`PLATFORM_RETRY_MIN[n]`, последняя 30 мин повторяется) и для одного сообщения суперадмину на
третьем сбое. Сброс не нужен: окно сдвигается само.
- **Без исчерпания**: сбой платформы не делает задачу `exhausted` — задача ждёт и продолжает сама.
Прочие блокеры (`задача не в работе`, лимит, бюджет) действуют как раньше.
- **Строка владельцу**: задержка `agent` с `state: "platform"` → `taskDelayLine` пишет «Сбой на
нашей стороне, чиним — задача продолжится сама. Следующая попытка в ЧЧ:ММ».
- Промпт перезапуска: «Прошлый запуск оборвался из-за сбоя платформы, не по твоей вине…»;
событие `platform_retried` вместо `auto_restarted`.
## Риски
- Постоянный сбой платформы (сервер tmux не поднимается) — задача повторяет раз в 30 мин без
конца; суперадмин узнаёт на третьем сбое, это его работа.

View File

@ -0,0 +1,32 @@
## Why
Отчёт тестирования (F-05): сбой самой платформы — пропавшая сессия tmux (выкатка, рестарт
сервера tmux), зависание агента на старте, недоступный хост или сервер tmux при перезапуске —
списывал попытки задачи (`restartMax`, 3 за сутки). После трёх таких сбоев задача оставалась без
попыток и шла к администратору, хотя агент ни в чём не ошибался. Метрика эпика #17 — 0 списанных
попыток задачи из-за сбоев платформы.
## What Changes
- Сбой платформы — отдельный счётчик `watch_state.platformFails` (время сбоев в окне
`restartWindowMin`), а не `watch_state.restarts`. Перезапуск после него «бесплатный»
(`restartFree`), предел попыток задачи не тратится и не проверяется.
- Что считается сбоем платформы: сессия tmux пропала (`gone`); агент Claude завис, не дойдя
до начала сессии (зависание на старте); перезапуск упал с недоступным хостом или
без сервера tmux; сбой входа подписки (как раньше, PEP-205).
- Паузы перед повтором — `PLATFORM_RETRY_MIN` 1, 5, 15, 30 мин (последняя повторяется), задача
не исчерпывается: ждёт, пока платформа починится. Суперадмин узнаёт один раз — на третьем сбое
в окне (задержка `agent`, состояние `platform`).
- Владелец видит строку «Сбой на нашей стороне, чиним — задача продолжится сама. Следующая
попытка в ЧЧ:ММ».
## Capabilities
### Modified Capabilities
- `watchdog-recovery`: сбои платформы не списывают авто-перезапуски задачи.
## Impact
- `packages/runner/src/recovery.ts`, `watchdog.ts`, `packages/db/src/schema.ts` (тип `WatchState`,
без миграции), `packages/core/src/platform-delay.ts` (строка владельцу), переводы.
- Тест `platform-failures-free.test.ts`.

View File

@ -0,0 +1,32 @@
## ADDED Requirements
### Requirement: Сбои платформы не списывают попытки задачи
Сбой платформы (сессия tmux пропала, агент Claude завис до начала сессии, перезапуск не состоялся
из-за недоступного хоста или сервера tmux, сбой входа подписки) SHALL вести отдельный счётчик
`watch_state.platformFails` и перезапускать задачу без траты авто-перезапусков (`restartMax`).
Паузы — 1, 5, 15, 30 минут (последняя повторяется); задача по сбоям платформы не исчерпывается и
продолжается сама. Суперадмин SHALL получить одно сообщение на третьем сбое в окне. Владелец видит
строку «Сбой на нашей стороне, чиним — задача продолжится сама».
#### Scenario: Три сбоя платформы — весь запас попыток
- **GIVEN** задача в работе, `restartMax` = 3, у агента не было авто-перезапусков
- **WHEN** сессия tmux агента три раза подряд пропадает и вачдог каждый раз перезапускает агента
- **THEN** у сессии по-прежнему 0 списанных авто-перезапусков из 3
- **AND** `platformFails` содержит 3 сбоя
- **AND** суперадмин получил одно сообщение о сбое платформы
#### Scenario: Падение агента тратит попытку
- **GIVEN** задача в работе, у агента не было авто-перезапусков
- **WHEN** процесс агента завершается с ошибкой (код 1) и вачдог перезапускает его
- **THEN** списан 1 авто-перезапуск из 3
#### Scenario: Перезапуск не состоялся — хост недоступен
- **GIVEN** запланированный перезапуск после падения агента
- **WHEN** запуск падает с ошибкой «хост недоступен»
- **THEN** попытка не списана, следующий повтор запланирован по расписанию платформы
#### Scenario: Строка владельцу
- **GIVEN** у задачи задержка агента в состоянии «сбой платформы» со следующей попыткой в 14:05
- **WHEN** владелец открывает задачу
- **THEN** он видит «Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в 14:05»

View File

@ -0,0 +1,17 @@
## 1. Счётчик сбоев платформы
- [x] 1.1 `WatchState.platformFails`; `PLATFORM_RETRY_MIN`, `planPlatformRetry` в recovery.ts
- [x] 1.2 `onRunnerCrash(gone)` → сбой платформы, `restarts` не трогается
- [x] 1.3 `restartStalled`: зависание Claude до SessionStart → сбой платформы
- [x] 1.4 `restartTick`: перезапуск упал с `HostUnreachable`/`TMUX_SERVER_DOWN` → попытка возвращается
- [x] 1.5 Промпт и событие `platform_retried` для бесплатного перезапуска после сбоя платформы
## 2. Владелец и суперадмин
- [x] 2.1 `taskDelayLine` — строка «Сбой на нашей стороне, чиним…» для состояния `platform` (ru/en/kk)
- [x] 2.2 Суперадмину одно сообщение на третьем сбое в окне
## 3. Проверка
- [x] 3.1 Тест `platform-failures-free.test.ts`: 3 сбоя платформы — весь запас попыток; падение агента тратит попытку
- [x] 3.2 Прогон соседних тестов (watchdog, platform-delays), `pnpm lint`, typecheck

View File

@ -1,38 +0,0 @@
# Design: PEP-287
## Папки агентов
- Список — `readdir($PEPPA_HOME/sandboxes)`, имя строго `s<число>`; путь собирается заново из id и
проверяется `lstat`: каталог, не ссылка, `realpath` внутри `sandboxes`. Размер не считаем (`du` идёт минутами).
- Удаляем, если сессия есть, её статус `done`/`failed`, она не на отдельном хосте, контейнера
`peppa-s<id>` нет в `docker ps` и: задача `done` или в архиве — сразу; задачи нет — через 24 ч
после `ended_at`. Сессии в базе нет — папка старше 24 ч (mtime). Незакрытая задача — папка
остаётся: в ней разговор для `--resume`.
- `docker ps` не ответил — проход пропускается (состояние неизвестно).
- Тик раз в 10 минут, ≤20 удалений, событие `sandbox_removed` (сессии — в журнал её проекта,
иначе платформенного). Выключатель `PEPPA_DISK_CLEANUP=off` (в тестах выключен в helpers.ts).
## Кэш сборки
- Раз в час (`disk.prune.last` в settings переживает рестарт), не дожидаясь в цикле вачдога
(prune идёт минутами): флаг «идёт» в процессе.
- `--reserved-space` (docker ≥ 25) — первым; ответ клиента «unknown flag» → `--keep-storage`
(клиент 20.10 в образе платформы; на сервере проверено — результат тот же). Выбор запоминается
на процесс. `-a` не используем: с ним в счёт идут записи, общие с образами, и предел не держится.
- Только `builder prune`: образы, контейнеры и тома не трогаем — сервер общий.
- Итог (`Total reclaimed space`) — событие `build_cache_pruned` платформенного проекта.
## Сторож места
- `statfs($PEPPA_HOME)` (из контейнера это диск сервера), свободно = `bavail/blocks`.
- Ниже `diskFreeAlertPct` → `alertAdmins` с ключом эпизода, состояние `disk.low` `{since, pct}`;
эпизод кончается, когда свободно ≥ порога + 2% (без дребезга), — тогда `disk.low` стирается.
## Образы платформы
- Выбор — чистая функция bash `platform_images_to_remove <текущий> <откат>` (`scripts/lib/platform-images.sh`):
вход — строки `CreatedAt<TAB>tag` из `docker image ls peppa/platform`, теги только hex; остаются
текущий, тег отката и самые новые до трёх; прочие — `docker rmi` (без `-f`: занятый образ docker
не удалит, это не ошибка).
- Временная строка cron `peppa-build-cache-prune` (26.11, ручная мера) и `~/peppa/bin/disk-prune.sh`
убираются той же выкаткой: вачдог новой версии уже делает эту работу.
## Настройки
`buildCacheGb` (40) и `diskFreeAlertPct` (15) — в `platform.watchdog`: `peppa platform watchdog
buildCacheGb=60`, env `PEPPA_WATCHDOG_BUILD_CACHE_GB`.

View File

@ -1,23 +0,0 @@
# PEP-287: уборка диска сервера
## Why
Диск сервера занят на 78% и растёт на 20–50 ГБ в сутки: домашние папки контейнеров агентов
(`$PEPPA_HOME/sandboxes/s<id>`) не удаляются никогда, каждая выкатка оставляет образ
`peppa/platform` (~4 ГБ), кэш сборки docker вырос до 167 ГБ. О нехватке места никто не узнаёт.
## What Changes
- Вачдог удаляет `sandboxes/s<id>` законченных сессий без контейнера, у которых задача закрыта
(`done`) или в архиве; сессий без задачи — через сутки после конца. Не больше 20 за проход,
событие `sandbox_removed` в журнале платформы, `PEPPA_DISK_CLEANUP=off`.
- `scripts/platform-deploy.sh` после удачной выкатки оставляет три образа `peppa/platform`
(текущий и два предыдущих по времени создания + тег отката), остальные удаляет; занятый
контейнером образ — не ошибка. Там же убирается временная строка cron `peppa-build-cache-prune`.
- Раз в час вачдог держит кэш сборки в пределе `buildCacheGb` (40 ГБ, настройка
`platform.watchdog`): `docker builder prune -f --reserved-space <предел>`, клиент без этого
ключа (20.10 в образе) — `--keep-storage`; без `-a`.
- Сторож места: свободно меньше `diskFreeAlertPct` (15%) — одно сообщение суперадминам на эпизод.
## Impact
- runner: новый `disk-cleanup.ts`, вызовы в `watchdog.ts`, `recovery.ts` (две настройки).
- scripts: `platform-deploy.sh`, `scripts/lib/platform-images.sh`.
- testkit: `mock-docker` (`builder prune`), тест `disk-cleanup.test.ts`.

View File

@ -1,60 +0,0 @@
## ADDED Requirements
### Requirement: Папки агентов законченных задач удаляются
Вачдог SHALL удалять `$PEPPA_HOME/sandboxes/s<id>` законченной сессии без контейнера, если её задача закрыта или в архиве, а сессии без задачи — через сутки после конца; папку незакрытой задачи SHALL оставлять.
#### Scenario: Задача закрыта
- **GIVEN** сессия 41 закончена, её задача в «Готово», контейнера `peppa-s41` нет
- **WHEN** проходит уборка
- **THEN** папки `sandboxes/s41` нет
- **AND** в журнале событие `sandbox_removed`
#### Scenario: Задача ещё в работе
- **GIVEN** сессия 42 закончена, её задача «В работе»
- **WHEN** проходит уборка
- **THEN** папка `sandboxes/s42` остаётся
#### Scenario: Свободный агент
- **GIVEN** сессия 43 без задачи закончилась 2 часа назад
- **WHEN** проходит уборка
- **THEN** папка остаётся
- **AND** через сутки после конца сессии её нет
#### Scenario: Ссылка вместо папки
- **GIVEN** `sandboxes/s44` — символическая ссылка
- **WHEN** проходит уборка
- **THEN** ни ссылка, ни то, на что она указывает, не удаляются
### Requirement: Кэш сборки держится в пределе
Вачдог SHALL раз в час вызывать `docker builder prune -f --reserved-space <buildCacheGb>GB` без `-a`; клиент без этого ключа — `--keep-storage`.
#### Scenario: Раз в час
- **GIVEN** предел 40 ГБ
- **WHEN** вачдог тикает 30 минут, потом ещё час
- **THEN** вызвано ровно две чистки `docker builder prune -f --reserved-space 40GB`
#### Scenario: Старый клиент docker
- **GIVEN** клиент docker не знает `--reserved-space`
- **WHEN** приходит время чистки
- **THEN** вызывается `docker builder prune -f --keep-storage 40GB`
### Requirement: Нехватка места — одно сообщение на эпизод
Вачдог SHALL сообщать суперадминам, когда свободно меньше `diskFreeAlertPct` процентов диска, один раз за эпизод.
#### Scenario: Места мало
- **GIVEN** свободно 10% при пороге 15%
- **WHEN** вачдог проверяет диск три раза
- **THEN** суперадмин получает одно сообщение
#### Scenario: Новый эпизод
- **GIVEN** место освободилось до 30%, потом снова 10%
- **WHEN** вачдог проверяет диск
- **THEN** приходит второе сообщение
### Requirement: Выкатка оставляет три образа платформы
После удачной выкатки `platform-deploy.sh` SHALL оставлять текущий образ `peppa/platform`, тег отката и самые новые до трёх, остальные удалять.
#### Scenario: Пять выкаток подряд
- **GIVEN** образов платформы нет
- **WHEN** прошло пять выкаток подряд
- **THEN** образов `peppa/platform` три — текущий и два предыдущих

View File

@ -1,12 +0,0 @@
## 1. Вачдог
- [x] 1.1 Настройки `buildCacheGb`, `diskFreeAlertPct` в `platform.watchdog`
- [x] 1.2 `runner/disk-cleanup.ts`: уборка `sandboxes`, кэш сборки, сторож места
- [x] 1.3 Вызовы в `watchdog.ts`, выключатели в тестах
## 2. Выкатка
- [x] 2.1 `scripts/lib/platform-images.sh` + уборка образов в `platform-deploy.sh`
- [x] 2.2 Снятие временной строки cron в `platform-deploy.sh`
## 3. Тесты и документы
- [x] 3.1 `mock-docker builder prune`, тест `disk-cleanup.test.ts`
- [x] 3.2 docs/SERVER.md, AGENTS.md, память

View File

@ -1,62 +0,0 @@
# Design — PEP-295
## Одна точка: `createTask`
Правило проверяется там, где задача рождается, а не в каждом вызывающем: `createTask` при
`origin` ≠ `human` ставит `proposed = true`, игнорируя переданный `proposed`. Снять флаг при
создании могут только:
- `decidedByPerson: true` — вызывающий передаёт решение человека, которое уже было (кнопка
у ошибки продукта — `decideIncident`, `decidedBy = pm`);
- исключение владельца: происхождение есть в `project.direct-origins:<projectId>`
(`getDirectOrigins`/`setDirectOrigins` в core/task-origin.ts; без миграции, нет строки = пусто).
Так новый путь создания задачи не сможет забыть правило — он получает его по умолчанию.
## Исключение владельца
Задача формулирует исключение как «например, ошибки из прода брать сразу». Делаем общий
список происхождений в ядре (`incident`, `acceptance`, `analyst`, `agent`), а в вебе
показываем владельцу одну галочку — «Ошибки продукта брать в работу сразу» в «⋯ Настройки
проекта → Баги» (видна и в «Продакте»: это решение владельца, не техническое). Остальные —
через CLI `peppa project direct <KEY> [origin=on|off …]` для суперадмина. Менять может только
владелец (или суперадмин) — `isOwner` как у прочих настроек владельца.
## Предел в сутки — общий
`proposalsToday` считает задачи с `origin` ≠ `human` за 24 часа, кроме созданных решением
человека (задача ошибки продукта с `decided_by = pm` — подзапрос по `incidents`). Каждый путь
сверяется с `proposalRoom` до создания и при нехватке места:
- агент разработки — отказ (как в PEP-270);
- приёмка — в недельную сводку (как в PEP-270), теперь и поломки;
- ошибка продукта — сообщение «решите сами» с кнопками (как при пределе задач из ошибок);
- разбивка аналитика — лишние части не заводятся, их названия дописываются к задаче человека
заметкой аналитика;
- системная задача о ссылке — не заводится в этот тик, повтор следующим тиком;
- возврат ошибки (регрессия старше окна) — без новой задачи, сообщение «решите, что делать».
Отказ — событие `proposal_limited` с `via`.
## Ошибки продукта
Политика `start` при задаче в «Предложено» агента не запускает. Сообщение владельцу о задаче
в «Предложено» несёт кнопки `p:<taskId>:do|no` — их уже понимает бот (`decideProposals`).
## Разбивка
`confirmTaskDecision` для решения `split` одобряет части (`approveProposal`): «Подходит» —
это «Делать». `undoSplit` архивирует их, как и раньше.
## Агент приёмки
`fileStories`: поломка тоже в «Предложено» (метка «Поломка» остаётся, «Делать важные» её
берёт). Кнопки в сообщении — у всех находок, включая поломки.
## Ревьюер и агент обратной связи
Задач не заводят (ревьюер шлёт замечания агенту, обращение становится задачей только решением
суперадмина `fixFeedback`). Закрепляем тестом: структурный тест перечисляет все вызовы
`createTask` в packages/core|runner|mcp|apps и требует для каждого известный путь — новый
вызов без явной классификации ронять тест.
## Запрос для приёмки (48 часов)
```sql
SELECT p.key, t.number, t.origin, e.created_at
FROM events e JOIN tasks t ON t.id = e.task_id JOIN projects p ON p.id = t.project_id
WHERE e.type = 'task_updated' AND json_extract(e.payload,'$.to') = 'in_progress'
AND t.origin <> 'human' AND p.key IN ('BRM','TPTIP','TR','DIK')
AND e.created_at > unixepoch('now','-2 days')*1000
AND NOT EXISTS (SELECT 1 FROM events a WHERE a.task_id = t.id AND a.type = 'proposal_approved');
```
Пустой результат после выкатки — приёмка выполнена (выполнить на живой базе после мержа).

View File

@ -1,29 +0,0 @@
# PEP-295: Одно правило для всех задач не от человека — в работу только через «Предложено»
## Why
PEP-270 закрыла обход через `create_task` агента, но остались пути, по которым задача не от
человека уходит в работу без решения владельца: «поломка» агента приёмки (важность ставит сам
агент — за 24–25.11 так ушли 11 из 39 его задач), ошибки из прода (политика `backlog`/`start`),
системная задача «Продукт должен открываться по ссылке» (встаёт первой и берётся сама), части
разбивки аналитика. Диспетчер за 48 часов взял 8 таких задач без одобрения.
## What Changes
- `createTask` сам ставит «Предложено» любой задаче с `origin` ≠ `human`; вызывающий не может
это обойти. Задача без флага — только если человек уже решил (`decidedByPerson`: кнопка
«В бэклог»/«В работу» у ошибки) или владелец включил исключение для этого происхождения.
- Исключение — настройка проекта `project.direct-origins:<id>` (список происхождений), по
умолчанию пусто. В вебе владелец включает одно: «Ошибки продукта брать в работу сразу».
- Предел `perDay` (5) — общий для всех задач не от человека: агент разработки, приёмка (и
поломки), ошибки продукта, разбивка аналитика, системная задача о ссылке. Задачи, созданные
решением человека, предел не тратят.
- Ошибка продукта: по политике `backlog`/`start`/`triage` без исключения задача идёт в
«Предложено» с кнопками «Делать»/«Не надо»; политика `start` не запускает агента.
- «Подходит» у решения «разбить» = «Делать» для частей.
- Тест на каждый путь создания задачи, включая ревьюера и агента обратной связи (они задач не
заводят).
## Impact
- core: `tasks.ts` (`createTask`), `task-origin.ts` (исключения, предел), `incidents.ts`.
- runner: `incidents.ts`, `product-review.ts`, `product-link.ts`, `intake.ts`, `decisions.ts`.
- web: настройка в «⋯ Настройки проекта → Баги»; CLI `peppa project direct`.
- Без миграций.

View File

@ -1,90 +0,0 @@
## REMOVED Requirements
### Requirement: Задачи агентов не берутся в работу сами
**Reason**: поломка от агента приёмки больше не идёт в бэклог сама — заменено требованием «Задача не от человека — только через «Предложено»».
**Migration**: поломки появляются в «Предложено» с пометкой «Поломка»; «Делать важные» берёт их.
### Requirement: Не больше N предложений агентов в сутки на проект
**Reason**: предел стал общим для всех путей — заменено требованием «Не больше N задач не от человека в сутки на проект».
**Migration**: настройка `perDay` прежняя.
## ADDED Requirements
### Requirement: Задача не от человека — только через «Предложено»
Любая задача с происхождением не «человек» (агент разработки, агент приёмки — в том числе с пометкой «Поломка», ошибка продукта, часть разбивки аналитика, системная задача FORGE) SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец или участник не нажал «Делать». Задача без «Предложено» создаётся только по решению человека или по исключению, которое владелец включил для этого происхождения в своём проекте (по умолчанию исключений нет).
#### Scenario: Улучшение от агента приёмки
- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом
- **WHEN** агент приёмки находит улучшение
- **THEN** задача появляется в «Предложено»
- **AND** диспетчер её не берёт
#### Scenario: Поломка от агента приёмки
- **GIVEN** проект с режимом «Сам берёт»
- **WHEN** агент приёмки находит поломку «Кнопка оплаты не работает»
- **THEN** задача появляется в «Предложено» с пометкой «Поломка»
- **AND** диспетчер её не берёт, пока владелец не нажал «Делать»
#### Scenario: Ошибка продукта по политике «в работу»
- **GIVEN** проект с политикой ошибок «в работу» и без исключения
- **WHEN** приходит новая ошибка продукта
- **THEN** задача появляется в «Предложено»
- **AND** агент не запускается
- **AND** владелец получает сообщение с кнопками «Делать» и «Не надо»
#### Scenario: Владелец разрешил брать ошибки сразу
- **GIVEN** владелец включил «Ошибки продукта брать в работу сразу»
- **AND** политика ошибок «в работу»
- **WHEN** приходит новая ошибка продукта
- **THEN** задача создаётся в работе и агент запускается
#### Scenario: Решение человека по ошибке
- **GIVEN** ошибка продукта ждёт решения
- **WHEN** владелец нажимает «В бэклог»
- **THEN** задача создаётся в бэклоге, не в «Предложено»
#### Scenario: Системная задача о ссылке
- **GIVEN** у проекта есть принятые задачи и нет версии для проверки
- **WHEN** FORGE заводит задачу «Продукт должен открываться по ссылке»
- **THEN** задача стоит в «Предложено» и диспетчер её не берёт
#### Scenario: Части разбивки аналитика
- **GIVEN** аналитик разбил задачу человека на 3 части
- **WHEN** части заведены
- **THEN** вторая и третья части стоят в «Предложено»
- **AND** «Подходит» у решения «разбить» переводит их в бэклог
#### Scenario: Ревьюер и агент обратной связи задач не заводят
- **GIVEN** ревьюер вернул замечания, агент обратной связи разобрал обращение
- **WHEN** их проходы закончились
- **THEN** число задач проекта не изменилось
### Requirement: Не больше N задач не от человека в сутки на проект
Проект SHALL получать не больше `perDay` задач не от человека за последние 24 часа (по умолчанию 5, настройка своя у каждого проекта) — общий предел для всех путей: агент разработки, агент приёмки, ошибки продукта, разбивка аналитика, системные задачи FORGE. Задачи, созданные решением человека (кнопка у ошибки продукта), предел не тратят.
#### Scenario: Шестая задача агента за сутки
- **GIVEN** в проекте за последние 24 часа агенты завели 5 задач
- **WHEN** агент вызывает `create_task` ещё раз
- **THEN** задача не создаётся
- **AND** агент получает ответ, что предел предложений на сутки исчерпан
#### Scenario: Приёмка нашла больше, чем осталось
- **GIVEN** за сутки агенты завели 4 задачи
- **WHEN** агент приёмки находит 3 улучшения
- **THEN** заводится 1 задача, 2 находки ждут недельной сводки
#### Scenario: Ошибка продукта при исчерпанном пределе
- **GIVEN** за сутки заведено 5 задач не от человека
- **WHEN** приходит новая ошибка продукта с политикой «в бэклог»
- **THEN** задача не создаётся
- **AND** владелец получает сообщение с кнопками решения
#### Scenario: Решение человека не тратит предел
- **GIVEN** за сутки заведено 5 задач не от человека
- **WHEN** владелец нажимает «В бэклог» у ошибки продукта
- **THEN** задача создаётся
#### Scenario: Свой предел у проекта
- **GIVEN** проекту задан предел 2 в сутки
- **WHEN** агент заводит третью задачу за сутки
- **THEN** задача не создаётся

View File

@ -1,19 +0,0 @@
## 1. Ядро
- [x] 1.1 `createTask`: `origin` ≠ `human` → «Предложено», кроме `decidedByPerson` и исключения владельца
- [x] 1.2 Исключения `project.direct-origins:<id>` (`getDirectOrigins`/`setDirectOrigins`)
- [x] 1.3 `proposalsToday` — все задачи не от человека, кроме решений человека по ошибкам
## 2. Пути создания
- [x] 2.1 Ошибки продукта: «Предложено», `start` без исключения не запускает, предел, кнопки «Делать»/«Не надо», регрессия
- [x] 2.2 Агент приёмки: поломка тоже в «Предложено», кнопки у всех находок
- [x] 2.3 Системная задача о ссылке: «Предложено», предел
- [x] 2.4 Разбивка аналитика: части в «Предложено», предел, «Подходит» одобряет части
## 3. Настройка владельца
- [x] 3.1 Веб: «Ошибки продукта брать в работу сразу» в «⋯ Настройки проекта → Баги» (переводы, словарь)
- [x] 3.2 CLI `peppa project direct`
## 4. Тесты и завершение
- [x] 4.1 Тест на каждый путь: MCP агента, приёмка (с поломкой), ошибки продукта, разбивка, ссылка, ревьюер, обратная связь
- [x] 4.2 Обновить существующие тесты под новое правило; typecheck, lint, тесты
- [x] 4.3 AGENTS.md, память, archive, PR

View File

@ -5,6 +5,20 @@ TBD - created by archiving change pep-197-no-task-loop. Update Purpose after arc
## Requirements
### Requirement: Задачи агентов не берутся в работу сами
Задача, заведённая агентом приёмки, SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец не нажал «Делать». Поломка SHALL идти в бэклог сразу с пометкой «Поломка».
#### Scenario: Улучшение от агента приёмки
- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом
- **WHEN** агент приёмки находит улучшение
- **THEN** задача появляется в «Предложено»
- **AND** диспетчер её не берёт
#### Scenario: Поломка критерия задачи человека
- **GIVEN** задача человека с критерием приёмки
- **WHEN** агент приёмки находит, что критерий не выполнен
- **THEN** задача создаётся в бэклоге с пометкой «Поломка»
### Requirement: Без дублей
Перед созданием задачи агентом SHALL выполняться проверка повтора по открытым задачам и сделанным за 60 дней.
@ -53,57 +67,8 @@ TBD - created by archiving change pep-197-no-task-loop. Update Purpose after arc
- **WHEN** владелец нажимает «Делать»
- **THEN** задача уходит в бэклог и диспетчер может взять её в работу
### Requirement: Задача не от человека — только через «Предложено»
Любая задача с происхождением не «человек» (агент разработки, агент приёмки — в том числе с пометкой «Поломка», ошибка продукта, часть разбивки аналитика, системная задача FORGE) SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец или участник не нажал «Делать». Задача без «Предложено» создаётся только по решению человека или по исключению, которое владелец включил для этого происхождения в своём проекте (по умолчанию исключений нет).
#### Scenario: Улучшение от агента приёмки
- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом
- **WHEN** агент приёмки находит улучшение
- **THEN** задача появляется в «Предложено»
- **AND** диспетчер её не берёт
#### Scenario: Поломка от агента приёмки
- **GIVEN** проект с режимом «Сам берёт»
- **WHEN** агент приёмки находит поломку «Кнопка оплаты не работает»
- **THEN** задача появляется в «Предложено» с пометкой «Поломка»
- **AND** диспетчер её не берёт, пока владелец не нажал «Делать»
#### Scenario: Ошибка продукта по политике «в работу»
- **GIVEN** проект с политикой ошибок «в работу» и без исключения
- **WHEN** приходит новая ошибка продукта
- **THEN** задача появляется в «Предложено»
- **AND** агент не запускается
- **AND** владелец получает сообщение с кнопками «Делать» и «Не надо»
#### Scenario: Владелец разрешил брать ошибки сразу
- **GIVEN** владелец включил «Ошибки продукта брать в работу сразу»
- **AND** политика ошибок «в работу»
- **WHEN** приходит новая ошибка продукта
- **THEN** задача создаётся в работе и агент запускается
#### Scenario: Решение человека по ошибке
- **GIVEN** ошибка продукта ждёт решения
- **WHEN** владелец нажимает «В бэклог»
- **THEN** задача создаётся в бэклоге, не в «Предложено»
#### Scenario: Системная задача о ссылке
- **GIVEN** у проекта есть принятые задачи и нет версии для проверки
- **WHEN** FORGE заводит задачу «Продукт должен открываться по ссылке»
- **THEN** задача стоит в «Предложено» и диспетчер её не берёт
#### Scenario: Части разбивки аналитика
- **GIVEN** аналитик разбил задачу человека на 3 части
- **WHEN** части заведены
- **THEN** вторая и третья части стоят в «Предложено»
- **AND** «Подходит» у решения «разбить» переводит их в бэклог
#### Scenario: Ревьюер и агент обратной связи задач не заводят
- **GIVEN** ревьюер вернул замечания, агент обратной связи разобрал обращение
- **WHEN** их проходы закончились
- **THEN** число задач проекта не изменилось
### Requirement: Не больше N задач не от человека в сутки на проект
Проект SHALL получать не больше `perDay` задач не от человека за последние 24 часа (по умолчанию 5, настройка своя у каждого проекта) — общий предел для всех путей: агент разработки, агент приёмки, ошибки продукта, разбивка аналитика, системные задачи FORGE. Задачи, созданные решением человека (кнопка у ошибки продукта), предел не тратят.
### Requirement: Не больше N предложений агентов в сутки на проект
Проект SHALL получать от агентов (разработки и приёмки) не больше `perDay` задач за последние 24 часа (по умолчанию 5, настройка своя у каждого проекта). Задачи из ошибок продукта и части разбивки задачи человека предел не тратят.
#### Scenario: Шестая задача агента за сутки
- **GIVEN** в проекте за последние 24 часа агенты завели 5 задач
@ -116,16 +81,10 @@ TBD - created by archiving change pep-197-no-task-loop. Update Purpose after arc
- **WHEN** агент приёмки находит 3 улучшения
- **THEN** заводится 1 задача, 2 находки ждут недельной сводки
#### Scenario: Ошибка продукта при исчерпанном пределе
- **GIVEN** за сутки заведено 5 задач не от человека
- **WHEN** приходит новая ошибка продукта с политикой «в бэклог»
- **THEN** задача не создаётся
- **AND** владелец получает сообщение с кнопками решения
#### Scenario: Решение человека не тратит предел
- **GIVEN** за сутки заведено 5 задач не от человека
- **WHEN** владелец нажимает «В бэклог» у ошибки продукта
- **THEN** задача создаётся
#### Scenario: Ошибка продукта не тратит предел
- **GIVEN** за сутки агенты завели 5 задач
- **WHEN** из ошибки продукта заводится задача
- **THEN** задача создаётся, а агент снова не может завести задачу до конца окна
#### Scenario: Свой предел у проекта
- **GIVEN** проекту задан предел 2 в сутки

View File

@ -1,65 +0,0 @@
# disk-cleanup Specification
## Purpose
TBD - created by archiving change pep-287-disk-cleanup. Update Purpose after archive.
## Requirements
### Requirement: Папки агентов законченных задач удаляются
Вачдог SHALL удалять `$PEPPA_HOME/sandboxes/s<id>` законченной сессии без контейнера, если её задача закрыта или в архиве, а сессии без задачи — через сутки после конца; папку незакрытой задачи SHALL оставлять.
#### Scenario: Задача закрыта
- **GIVEN** сессия 41 закончена, её задача в «Готово», контейнера `peppa-s41` нет
- **WHEN** проходит уборка
- **THEN** папки `sandboxes/s41` нет
- **AND** в журнале событие `sandbox_removed`
#### Scenario: Задача ещё в работе
- **GIVEN** сессия 42 закончена, её задача «В работе»
- **WHEN** проходит уборка
- **THEN** папка `sandboxes/s42` остаётся
#### Scenario: Свободный агент
- **GIVEN** сессия 43 без задачи закончилась 2 часа назад
- **WHEN** проходит уборка
- **THEN** папка остаётся
- **AND** через сутки после конца сессии её нет
#### Scenario: Ссылка вместо папки
- **GIVEN** `sandboxes/s44` — символическая ссылка
- **WHEN** проходит уборка
- **THEN** ни ссылка, ни то, на что она указывает, не удаляются
### Requirement: Кэш сборки держится в пределе
Вачдог SHALL раз в час вызывать `docker builder prune -f --reserved-space <buildCacheGb>GB` без `-a`; клиент без этого ключа — `--keep-storage`.
#### Scenario: Раз в час
- **GIVEN** предел 40 ГБ
- **WHEN** вачдог тикает 30 минут, потом ещё час
- **THEN** вызвано ровно две чистки `docker builder prune -f --reserved-space 40GB`
#### Scenario: Старый клиент docker
- **GIVEN** клиент docker не знает `--reserved-space`
- **WHEN** приходит время чистки
- **THEN** вызывается `docker builder prune -f --keep-storage 40GB`
### Requirement: Нехватка места — одно сообщение на эпизод
Вачдог SHALL сообщать суперадминам, когда свободно меньше `diskFreeAlertPct` процентов диска, один раз за эпизод.
#### Scenario: Места мало
- **GIVEN** свободно 10% при пороге 15%
- **WHEN** вачдог проверяет диск три раза
- **THEN** суперадмин получает одно сообщение
#### Scenario: Новый эпизод
- **GIVEN** место освободилось до 30%, потом снова 10%
- **WHEN** вачдог проверяет диск
- **THEN** приходит второе сообщение
### Requirement: Выкатка оставляет три образа платформы
После удачной выкатки `platform-deploy.sh` SHALL оставлять текущий образ `peppa/platform`, тег отката и самые новые до трёх, остальные удалять.
#### Scenario: Пять выкаток подряд
- **GIVEN** образов платформы нет
- **WHEN** прошло пять выкаток подряд
- **THEN** образов `peppa/platform` три — текущий и два предыдущих

View File

@ -133,3 +133,34 @@
- **GIVEN** агент уже дважды зависал на старте и перезапускался
- **WHEN** он зависает в третий раз
- **THEN** агент остановлен без перезапуска, карточка суперадмина помечена «попытки исчерпаны» с кнопкой «Перезапустить»
### Requirement: Сбои платформы не списывают попытки задачи
Сбой платформы (сессия tmux пропала, агент Claude завис до начала сессии, перезапуск не состоялся
из-за недоступного хоста или сервера tmux, сбой входа подписки) SHALL вести отдельный счётчик
`watch_state.platformFails` и перезапускать задачу без траты авто-перезапусков (`restartMax`).
Паузы — 1, 5, 15, 30 минут (последняя повторяется); задача по сбоям платформы не исчерпывается и
продолжается сама. Суперадмин SHALL получить одно сообщение на третьем сбое в окне. Владелец видит
строку «Сбой на нашей стороне, чиним — задача продолжится сама».
#### Scenario: Три сбоя платформы — весь запас попыток
- **GIVEN** задача в работе, `restartMax` = 3, у агента не было авто-перезапусков
- **WHEN** сессия tmux агента три раза подряд пропадает и вачдог каждый раз перезапускает агента
- **THEN** у сессии по-прежнему 0 списанных авто-перезапусков из 3
- **AND** `platformFails` содержит 3 сбоя
- **AND** суперадмин получил одно сообщение о сбое платформы
#### Scenario: Падение агента тратит попытку
- **GIVEN** задача в работе, у агента не было авто-перезапусков
- **WHEN** процесс агента завершается с ошибкой (код 1) и вачдог перезапускает его
- **THEN** списан 1 авто-перезапуск из 3
#### Scenario: Перезапуск не состоялся — хост недоступен
- **GIVEN** запланированный перезапуск после падения агента
- **WHEN** запуск падает с ошибкой «хост недоступен»
- **THEN** попытка не списана, следующий повтор запланирован по расписанию платформы
#### Scenario: Строка владельцу
- **GIVEN** у задачи задержка агента в состоянии «сбой платформы» со следующей попыткой в 14:05
- **WHEN** владелец открывает задачу
- **THEN** он видит «Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в 14:05»

View File

@ -77,7 +77,7 @@ import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId,
import { internalHosts, writeInternalHosts, createEdgeTunnel, edgeConfig, edgeHosts, formatEdgeSync, syncEdge, isProjectPaused, setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner";
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits, DIRECT_ORIGINS, getDirectOrigins, setDirectOrigins } from "@peppa/core";
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits } from "@peppa/core";
import { tidyAgentTasks, findForeignPaths, fixForeignPaths } from "@peppa/runner";
import { installCrashReporting, PROVIDER_LABEL, requestSmoke, smokeStatus, type SmokeRun } from "@peppa/core";
import { pushTemplateOrAlert, syncTemplate } from "@peppa/runner";
@ -96,7 +96,6 @@ const USAGE = `peppa — FORGE software factory CLI
peppa project agent <KEY|KEY-N|--platform> [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel claudeModel codexModel opencodeModel; value - = inherit)
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
peppa project agent-limits <KEY> [inWork=N perPass=N inRepo=N perDay=N|reset] (PEP-197/270: limits for stories made by agents)
peppa project direct <KEY> [incident|acceptance|analyst|agent=on|off …] (PEP-295: owner's exceptions to «Предложено»)
peppa agent-tasks report | tidy [KEY] [--dry-run] (PEP-197: people vs agents per project; one-off tidy)
peppa project pause|resume <KEY> (PEP-174: agents stop, nothing is sent; resume continues them)
peppa project transfer <KEY> <owner> (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook)
@ -476,20 +475,6 @@ async function main(): Promise<void> {
console.log(`${p.key}: stories of agents in work at once ≤ ${limits.inWork}, proposals per pass ≤ ${limits.perPass}, stories of one repository in work ≤ ${limits.inRepo || "no limit"}, proposals of agents per 24 hours ≤ ${limits.perDay}`);
break;
}
case "project direct": {
// PEP-295: the owner's exceptions — stories of these origins skip «Предложено».
if (!args[0]) throw new PeppaError(`usage: peppa project direct <KEY> [origin=on|off …] (origins: ${DIRECT_ORIGINS.join(", ")})`);
const p = await getProject(db, args[0]);
let list: string[] = await getDirectOrigins(db, p.id);
for (const arg of args.slice(1)) {
const [k = "", v = ""] = arg.split("=");
if (v !== "on" && v !== "off") throw new PeppaError(`expected ${k}=on|off`);
list = v === "on" ? [...list.filter((o) => o !== k), k] : list.filter((o) => o !== k);
}
if (args.length > 1) list = await setDirectOrigins(db, p.id, list);
console.log(`${p.key}: straight to work without «Делать»: ${list.length ? list.join(", ") : "nothing (everything not from a person waits in «Предложено»)"}`);
break;
}
case "agent-tasks report":
console.log(agentTaskTable(await agentTaskSummary(db)));
break;

View File

@ -274,11 +274,9 @@ export async function createBugTask(
goalId: settings?.goalId ?? undefined,
title: bugTaskTitle(i),
description: bugTaskDescription(i, reason),
// PEP-197: an error of the product's users is a breakage, marked. PEP-295: not decided by a person
// (policy, triage) → «Предложено», unless the owner lets errors go to work at once.
// PEP-197: an error of the product's users is a breakage — to the backlog at once, marked.
origin: "incident",
severity: "breakage",
decidedByPerson: by === "pm",
});
// PEP-270: the decision lands with the status — a reader never sees «task» without what was decided.
await updateIncident(db, i.id, { ...decided, taskId: ref.task.id, taskCreatedAt: new Date(), status: "task", decidedBy: by });
@ -291,7 +289,7 @@ const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replac
export type IncidentMessage =
| { kind: "notify" }
| { kind: "task"; task: TaskRef; started?: boolean; reason?: string | null; proposed?: boolean }
| { kind: "task"; task: TaskRef; started?: boolean; reason?: string | null }
| { kind: "ask"; note?: string | null }
| { kind: "regressed"; task?: TaskRef | null };
@ -317,27 +315,13 @@ export function renderIncidentMessage(project: Pick<Project, "key" | "name">, i:
if (i.url) lines.push(`<a href="${esc(i.url)}">${tr("Подробности ошибки")}</a>`);
const taskLink = (t: TaskRef) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a>`;
if (m.kind === "task") {
lines.push(
"",
m.started
? tr("▶️ Агент взялся: {link}", { link: taskLink(m.task) })
: m.proposed
? tr("💡 Задача ждёт вашего решения в «Предложено»: {link}", { link: taskLink(m.task) })
: tr("📥 Задача в бэклоге: {link}", { link: taskLink(m.task) }),
);
lines.push("", m.started ? tr("▶️ Агент взялся: {link}", { link: taskLink(m.task) }) : tr("📥 Задача в бэклоге: {link}", { link: taskLink(m.task) }));
if (m.reason) lines.push(tr("🤖 Триажёр: {reason}", { reason: asIs(esc(clip(m.reason, 500))) }));
} else if (m.kind === "ask") {
if (m.note) lines.push("", `<i>${esc(clip(m.note, 500))}</i>`);
lines.push("", tr("Что делаем?"));
} else if (m.kind === "regressed") {
lines.push(
"",
m.task
? m.task.task.proposed
? tr("💡 Задача ждёт вашего решения в «Предложено»: {link}", { link: taskLink(m.task) })
: tr("Задача {link} снова в бэклоге.", { link: taskLink(m.task) })
: tr("Задачи нет — решите, что делать."),
);
lines.push("", m.task ? tr("Задача {link} снова в бэклоге.", { link: taskLink(m.task) }) : tr("Задачи нет — решите, что делать."));
} else {
lines.push("", `<a href="${esc(`${webUrl}/p/${project.key}`)}">${tr("Ошибки проекта")}</a>`);
}
@ -351,14 +335,8 @@ export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessag
const [project] = await db.select().from(projects).where(eq(projects.id, i.projectId));
if (!project) return 0;
const text = renderIncidentMessage(project, i, m, loadEnv().PEPPA_WEB_URL);
// PEP-295: a proposed story carries «Делать» / «Не надо» (the bot knows `p:<task>:do|no`).
const markup =
m.kind === "ask" || (m.kind === "regressed" && !m.task)
? { inline_keyboard: incidentButtons(i.id) }
: (m.kind === "task" && m.proposed) || (m.kind === "regressed" && m.task?.task.proposed)
? { inline_keyboard: [[{ text: `✅ ${tr("Делать")}`, callback_data: `p:${m.task!.task.id}:do` }, { text: `✖️ ${tr("Не надо")}`, callback_data: `p:${m.task!.task.id}:no` }]] }
: undefined;
const kind = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? "ask" : m.kind;
const markup = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? { inline_keyboard: incidentButtons(i.id) } : undefined;
const kind = m.kind === "ask" || markup ? "ask" : m.kind;
const taskKey = m.kind === "task" ? m.task.key : m.kind === "regressed" ? m.task?.key : null;
let sent = 0;
for (const u of audience) {

View File

@ -289,10 +289,15 @@ export async function taskDelayLine(db: Db, taskId: number, o: { now?: Date; tim
if (list.some((d) => d.exhausted)) return tr("Нужен администратор, мы ему сообщили");
const now = (o.now ?? new Date()).getTime();
const next = list.map((d) => d.retryAt).filter((x): x is number => x != null && x > now - 60_000).sort((a, b) => a - b)[0];
if (next == null) return tr("Задерживается на нашей стороне, мы этим занимаемся");
// PEP-268: a failure of the platform itself — the story keeps all its attempts and goes on by itself.
const platform = list.some((d) => d.state === "platform");
if (next == null) return platform ? tr("Сбой на нашей стороне, чиним — задача продолжится сама") : tr("Задерживается на нашей стороне, мы этим занимаемся");
const tz = o.timeZone ?? process.env.PEPPA_TZ ?? undefined;
const time = new Intl.DateTimeFormat("ru-RU", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(Math.max(next, now)));
const day = (t: number) => new Intl.DateTimeFormat("en-CA", { timeZone: tz }).format(new Date(t));
if (platform) return day(next) !== day(now)
? tr("Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка завтра в {time}", { time })
: tr("Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в {time}", { time });
if (day(next) !== day(now)) return tr("Задерживается на нашей стороне. Следующая попытка завтра в {time}", { time });
return tr("Задерживается на нашей стороне. Следующая попытка в {time}", { time });
}

View File

@ -43,7 +43,7 @@ export interface AgentLimits {
perPass: number;
/** PEP-205: stories of one repository in work at once, whoever made them (0 — no limit); the rest wait «В очереди». */
inRepo: number;
/** PEP-270/295: stories not from a person (every path) per project in the last 24 hours. */
/** PEP-270: proposals of agents (developing and acceptance) per project in the last 24 hours. */
perDay: number;
}
export const DEFAULT_AGENT_LIMITS: AgentLimits = { inWork: 3, perPass: 5, inRepo: 4, perDay: 5 };
@ -76,48 +76,18 @@ export async function agentTasksInWork(db: Db, projectId: number): Promise<numbe
return Number(r?.n ?? 0);
}
// ── PEP-295: exceptions of the owner ───────────────────────────────────────────
/** Origins whose stories may skip «Предложено» — only by the owner's explicit choice (none by default). */
export const DIRECT_ORIGINS = ["incident", "acceptance", "analyst", "agent"] as const;
export type DirectOrigin = (typeof DIRECT_ORIGINS)[number];
const directKey = (projectId: number) => `project.direct-origins:${projectId}`;
export async function getDirectOrigins(db: Db, projectId: number): Promise<DirectOrigin[]> {
const v = await getSetting<string[]>(db, directKey(projectId));
return (v ?? []).filter((o): o is DirectOrigin => (DIRECT_ORIGINS as readonly string[]).includes(o));
}
export async function setDirectOrigins(db: Db, projectId: number, list: string[]): Promise<DirectOrigin[]> {
const bad = list.filter((o) => !(DIRECT_ORIGINS as readonly string[]).includes(o));
if (bad.length) throw new PeppaError(tr("Неизвестное происхождение задачи: {name}", { name: bad.join(", ") }));
const next = [...new Set(list)] as DirectOrigin[];
if (next.length) await setSetting(db, directKey(projectId), next);
else await deleteSetting(db, directKey(projectId));
await logEvent(db, { projectId, type: "direct_origins_changed", payload: { origins: next } });
return next;
}
// ── PEP-270 / PEP-295: stories not from a person, per day ──────────────────────
// ── PEP-270: proposals per day ─────────────────────────────────────────────────
/** Origins that spend the daily limit: what agents thought up themselves (not bugs of users, not parts of a person's story). */
export const PROPOSAL_ORIGINS = ["agent", "acceptance"] as const;
export const PROPOSAL_WINDOW_MS = 86_400_000;
/**
* Stories not from a person filed in the project during the last 24 hours, by every path (archived —
* declined — ones count too). A story a person decided to make (the button under an error) does not.
*/
/** Stories agents filed in the project during the last 24 hours (archived — declined — ones count too). */
export async function proposalsToday(db: Db, projectId: number, now = new Date()): Promise<number> {
const [r] = await db
.select({ n: sql<number>`count(*)` })
.from(tasks)
.where(
and(
eq(tasks.projectId, projectId),
ne(tasks.origin, "human"),
gte(tasks.createdAt, new Date(now.getTime() - PROPOSAL_WINDOW_MS)),
sql`${tasks.id} NOT IN (SELECT task_id FROM incidents WHERE task_id IS NOT NULL AND decided_by = 'pm')`,
),
);
.where(and(eq(tasks.projectId, projectId), inArray(tasks.origin, [...PROPOSAL_ORIGINS]), gte(tasks.createdAt, new Date(now.getTime() - PROPOSAL_WINDOW_MS))));
return Number(r?.n ?? 0);
}

View File

@ -20,7 +20,7 @@ import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-tex
import { defaultMessageType, type MessageType } from "./questions.ts";
import { renderMain, type AgentMessage } from "./agent-message.ts";
import { insertQuestion, setMessageDetails } from "./message-details.ts";
import { getDirectOrigins, touchVersion } from "./task-origin.ts";
import { touchVersion } from "./task-origin.ts";
import { clearRolloutWait, rolloutTracked, setRolloutWait } from "./rollout.ts";
export type Task = typeof tasks.$inferSelect;
@ -59,22 +59,14 @@ export interface NewTask {
goalId?: number;
title: string;
description?: string;
/** PEP-197: who made it (default: a person). PEP-295: anything not from a person is «Предложено». */
/** PEP-197: who made it (default: a person); agents' stories are «Предложено» unless a breakage. */
origin?: "human" | "acceptance" | "incident" | "analyst" | "agent";
/** Only for a person's story; for the others `createTask` decides (PEP-295). */
proposed?: boolean;
/** PEP-295: a person already decided to do it (the button under an error of the product): not a proposal. */
decidedByPerson?: boolean;
severity?: "breakage" | "important" | "minor" | null;
}
export async function createTask(db: Db, input: NewTask): Promise<TaskRef> {
const { decidedByPerson, ...t } = input;
export async function createTask(db: Db, t: NewTask): Promise<TaskRef> {
if (t.goalId != null) await getGoal(db, t.projectId, t.goalId);
// PEP-295: one rule for every path — a story not from a person waits for «Делать» in «Предложено»,
// unless a person already decided or the owner made an exception for its origin in this project.
const origin = t.origin ?? "human";
if (origin !== "human") t.proposed = !decidedByPerson && !(await getDirectOrigins(db, t.projectId)).includes(origin);
// Hand out the per-project number atomically. SQLite transactions are synchronous: no
// await inside (the driver refuses an async callback).
const made = db.transaction(

View File

@ -429,6 +429,8 @@ export type WatchState = {
restartFree?: boolean;
/** PEP-205: sign-in failures of the agent CLI in a row («account/read failed … timed out»). */
loginFails?: number;
/** PEP-268: times (ms) of failures of the platform itself (tmux gone, a hang before the first step, host or tmux server down) — not the story's restarts. */
platformFails?: number[];
/** PEP-205: when the watchdog last answered the CLI's «Switch to <model>?» menu (ms). */
menuAt?: number;
/** PEP-227: the generation whose «now uses usage credits» dialog (without «Switch to Opus») the superadmin was told about. */

View File

@ -5,7 +5,6 @@
// them back into the first story's description.
import { m } from "@peppa/shared/i18n";
import {
approveProposal,
addStoryComment,
changeDecision,
clearSplitPart,
@ -26,9 +25,7 @@ import { resolveTaskById, sendToSession } from "./sessions.ts";
export type DecisionOutcome = "confirmed" | "refine" | "agent" | "fix" | "noted" | "unsplit";
export async function confirmTaskDecision(db: Db, ref: TaskRef, id: number, by: { login: string }): Promise<DecisionOutcome> {
const d = await confirmDecision(db, ref.task, id, by.login);
// PEP-295: «Подходит» on the split is the owner's «Делать» for its parts.
if (d.kind === "split") for (const part of d.parts ?? []) await approveProposal(db, part, by.login);
await confirmDecision(db, ref.task, id, by.login);
return "confirmed";
}

View File

@ -1,248 +0,0 @@
// PEP-287: the server's disk does not fill up by itself. Three sweeps of the watchdog:
// • `$PEPPA_HOME/sandboxes/s<id>` — the agent container's HOME (its conversation for --resume) —
// is removed once the session is over, its container is gone and the story is closed or archived
// (sessions without a story — a day after their end);
// • the docker build cache is pruned hourly down to `buildCacheGb` (never `-a`: with it the entries
// shared with images count too and the limit is not held; images, containers, volumes — untouched);
// • free space below `diskFreeAlertPct` — one message to the superadmins per episode.
import { execFile } from "node:child_process";
import { lstatSync, readdirSync, realpathSync, rmSync, statfsSync } from "node:fs";
import { join, sep } from "node:path";
import { promisify } from "node:util";
import { alertAdmins, deleteSetting, getProject, getSetting, logEvent, parseDockerPs, platformProjectKey, setSetting } from "@peppa/core";
import { sessions, tasks, type Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared";
import { m } from "@peppa/shared/i18n";
import { eq } from "drizzle-orm";
import { getWatchdogSettings } from "./recovery.ts";
import { dockerBin } from "./sandbox.ts";
const run = promisify(execFile);
const off = () => process.env.PEPPA_DISK_CLEANUP === "off";
/** Folders removed in one pass — the rest wait for the next one. */
export const SANDBOX_MAX_PER_PASS = 20;
/** A finished session without a story (free runner, launch smoke) keeps its folder this long. */
export const SANDBOX_FREE_KEEP_MS = 24 * 3600_000;
const SANDBOX_EVERY_MS = 10 * 60_000;
const PRUNE_EVERY_MS = 3600_000;
/** The low-space episode ends only this many percent above the threshold (no flapping). */
const DISK_RECOVER_MARGIN = 2;
const DIR_RE = /^s(\d+)$/;
const sandboxesDir = () => join(peppaHome(), "sandboxes");
async function platformProjectId(db: Db): Promise<number | null> {
return (await getProject(db, platformProjectKey()).catch(() => null))?.id ?? null;
}
// ── agents' folders ────────────────────────────────────────────────────────────────
export interface SandboxRemoved {
sessionId: number;
reason: "task_closed" | "no_task" | "no_session";
}
let lastSandboxPass = 0;
/** Why the folder of this session may go, or null — it stays. */
async function sandboxVerdict(db: Db, sessionId: number, dir: string, now: number, running: Set<string>): Promise<SandboxRemoved["reason"] | null> {
if (running.has(`peppa-s${sessionId}`)) return null;
const [row] = await db
.select({ status: sessions.status, endedAt: sessions.endedAt, hostId: sessions.hostId, taskId: sessions.taskId, taskStatus: tasks.status, archivedAt: tasks.archivedAt })
.from(sessions)
.leftJoin(tasks, eq(tasks.id, sessions.taskId))
.where(eq(sessions.id, sessionId));
if (!row) {
// The row is gone (a deleted project): nothing can resume it; still, a day of quiet first.
return now - lstatSync(dir).mtimeMs >= SANDBOX_FREE_KEEP_MS ? "no_session" : null;
}
if (row.status !== "done" && row.status !== "failed") return null;
if (row.hostId != null) return null; // its HOME lives on the runner host — not ours to clean
if (row.taskId != null && row.taskStatus != null) {
// An open story may get the same conversation back — the folder holds it.
return row.taskStatus === "done" || row.archivedAt != null ? "task_closed" : null;
}
const ended = row.endedAt?.getTime() ?? lstatSync(dir).mtimeMs;
return now - ended >= SANDBOX_FREE_KEEP_MS ? "no_task" : null;
}
/** The folder is a real directory right inside `sandboxes` — never a link, never elsewhere. */
function safeSandboxDir(root: string, sessionId: number): string | null {
const dir = join(root, `s${sessionId}`);
try {
const st = lstatSync(dir);
if (!st.isDirectory() || st.isSymbolicLink()) return null;
const real = realpathSync(dir);
const realRoot = realpathSync(root);
return real === join(realRoot, `s${sessionId}`) && real.startsWith(realRoot + sep) ? dir : null;
} catch {
return null;
}
}
async function runningAgentContainers(): Promise<Set<string>> {
const { stdout } = await run(dockerBin(null), ["ps", "--no-trunc", "--format", "{{.ID}}\t{{.Names}}\t{{.Ports}}\t{{.Labels}}"], { timeout: 20_000, maxBuffer: 16 * 1024 * 1024 });
return new Set(parseDockerPs(stdout).map((c) => c.name));
}
/** Removes folders of finished sessions; every ten minutes unless `force`. */
export async function sandboxCleanupTick(db: Db, o: { now?: Date; log?: (m: string) => void; force?: boolean } = {}): Promise<SandboxRemoved[]> {
if (off()) return [];
const log = o.log ?? (() => {});
const now = (o.now ?? new Date()).getTime();
if (!o.force && now - lastSandboxPass < SANDBOX_EVERY_MS) return [];
lastSandboxPass = now;
const root = sandboxesDir();
let names: string[];
try {
names = readdirSync(root);
} catch {
return [];
}
const ids = names.map((n) => DIR_RE.exec(n)).filter((x): x is RegExpExecArray => !!x).map((x) => Number(x[1])).sort((a, b) => a - b);
if (!ids.length) return [];
let running: Set<string>;
try {
running = await runningAgentContainers();
} catch (e) {
log(`sandbox cleanup: docker ps: ${(e as Error).message.split("\n")[0]} — skipped`);
return [];
}
const removed: SandboxRemoved[] = [];
const pid = await platformProjectId(db);
for (const id of ids) {
if (removed.length >= SANDBOX_MAX_PER_PASS) break;
const dir = safeSandboxDir(root, id);
if (!dir) continue;
const reason = await sandboxVerdict(db, id, dir, now, running);
if (!reason) continue;
try {
rmSync(dir, { recursive: true, force: true });
} catch (e) {
log(`sandbox cleanup: s${id}: ${(e as Error).message}`);
continue;
}
removed.push({ sessionId: id, reason });
if (pid) await logEvent(db, { projectId: pid, type: "sandbox_removed", payload: { sessionId: id, reason, dir } });
}
if (removed.length) log(`sandbox cleanup: removed ${removed.length} (${removed.map((r) => `s${r.sessionId}`).join(", ")})`);
return removed;
}
// ── docker build cache ─────────────────────────────────────────────────────────────
const PRUNE_KEY = "disk.prune.last";
let pruneRunning: Promise<unknown> | null = null;
/** The client in the platform image (20.10) does not know `--reserved-space`; remembered per process. */
let oldClient = false;
export interface PruneResult {
args: string[];
reclaimed: string | null;
}
const reclaimedOf = (out: string) => /Total reclaimed space:\s*(.+)/i.exec(out)?.[1]?.trim() ?? null;
async function prune(gb: number): Promise<PruneResult> {
const bin = dockerBin(null);
const opts = { timeout: 30 * 60_000, maxBuffer: 64 * 1024 * 1024 };
if (!oldClient) {
const args = ["builder", "prune", "-f", "--reserved-space", `${gb}GB`];
try {
const { stdout } = await run(bin, args, opts);
return { args, reclaimed: reclaimedOf(stdout) };
} catch (e) {
const err = e as Error & { stderr?: string };
if (!/unknown flag|flag provided but not defined/i.test(`${err.stderr ?? ""}${err.message}`)) throw e;
oldClient = true;
}
}
const args = ["builder", "prune", "-f", "--keep-storage", `${gb}GB`];
const { stdout } = await run(bin, args, opts);
return { args, reclaimed: reclaimedOf(stdout) };
}
/** Hourly prune of the build cache down to the limit. Does not block the watchdog loop unless `wait`. */
export async function buildCachePruneTick(db: Db, o: { now?: Date; log?: (m: string) => void; wait?: boolean } = {}): Promise<PruneResult | null> {
if (off() || pruneRunning) return null;
const log = o.log ?? (() => {});
const now = o.now ?? new Date();
const { buildCacheGb } = await getWatchdogSettings(db);
if (!buildCacheGb) return null;
const last = await getSetting<string>(db, PRUNE_KEY);
if (last && now.getTime() - new Date(last).getTime() < PRUNE_EVERY_MS) return null;
await setSetting(db, PRUNE_KEY, now.toISOString());
const job = prune(buildCacheGb)
.then(async (r) => {
log(`build cache: ${r.args.join(" ")} — reclaimed ${r.reclaimed ?? "?"}`);
const pid = await platformProjectId(db);
if (pid) await logEvent(db, { projectId: pid, type: "build_cache_pruned", payload: { limitGb: buildCacheGb, flag: r.args[3], reclaimed: r.reclaimed } });
return r;
})
.finally(() => {
pruneRunning = null;
});
pruneRunning = job;
if (o.wait) return job;
job.catch((e) => log(`build cache prune failed: ${(e as Error).message.split("\n")[0]}`));
return null;
}
/** Tests: forget the per-process state. */
export function resetDiskCleanupState(): void {
lastSandboxPass = 0;
oldClient = false;
pruneRunning = null;
}
// ── free space ─────────────────────────────────────────────────────────────────────
const LOW_KEY = "disk.low";
export interface DiskSpace {
freeBytes: number;
totalBytes: number;
}
type StatFs = (path: string) => DiskSpace;
const realStatFs: StatFs = (path) => {
const s = statfsSync(path);
return { freeBytes: s.bavail * s.bsize, totalBytes: s.blocks * s.bsize };
};
const gb = (b: number) => Math.round(b / 1024 ** 3);
/** One message to the superadmins when free space of `$PEPPA_HOME`'s disk drops below the threshold. */
export async function diskSpaceTick(db: Db, o: { now?: Date; log?: (m: string) => void; statfs?: StatFs } = {}): Promise<"alerted" | "low" | "ok" | null> {
if (off()) return null;
const log = o.log ?? (() => {});
const { diskFreeAlertPct } = await getWatchdogSettings(db);
if (!diskFreeAlertPct) return null;
let d: DiskSpace;
try {
d = (o.statfs ?? realStatFs)(peppaHome());
} catch {
return null;
}
if (!d.totalBytes) return null;
const pct = Math.round((d.freeBytes / d.totalBytes) * 1000) / 10;
const low = await getSetting<{ since: string; pct: number }>(db, LOW_KEY);
if (pct < diskFreeAlertPct) {
if (low) return "low";
const since = (o.now ?? new Date()).toISOString();
await setSetting(db, LOW_KEY, { since, pct });
await alertAdmins(
db,
`disk:low:${since}`,
m("💾 На диске сервера свободно {pct}% ({free} из {total} ГБ) — меньше порога {limit}%. Папки агентов и кэш сборки FORGE убирает сама; посмотрите, что ещё занимает место.", {
pct,
free: gb(d.freeBytes),
total: gb(d.totalBytes),
limit: diskFreeAlertPct,
}),
log,
);
return "alerted";
}
if (low && pct >= diskFreeAlertPct + DISK_RECOVER_MARGIN) await deleteSetting(db, LOW_KEY);
return "ok";
}

View File

@ -6,8 +6,6 @@ import { bugsinkFromEnv, issueFromEvent, parseWebhook, type BugsinkClient, type
import {
addErrorSource,
autoIncidentTasksToday,
logEvent,
proposalRoom,
claimNewIncidents,
closeIncidentAsks,
createBugTask,
@ -135,20 +133,10 @@ async function execute(
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
return row;
}
// PEP-295: the daily limit of stories not from a person is shared by every path.
if ((await proposalRoom(db, i.projectId, o.now)).room <= 0) {
const limitNote = m("Предел задач без вашего решения на сегодня исчерпан — задача не создана.");
await logEvent(db, { projectId: i.projectId, type: "proposal_limited", payload: { title: i.title, via: "incident", incident: i.id } });
const row = await updateIncident(db, i.id, { decision: "ask", decidedBy: by, status: "pending", decisionReason: limitNote });
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
return row;
}
const ref = await createBugTask(db, i, by, by === "triage" ? reason : null, { decision: base.decision, decisionReason: base.decisionReason });
// PEP-295: a story waiting for «Делать» is never started by the policy.
const proposed = ref.task.proposed;
const started = action === "start" && !proposed ? await startBugTask(db, ref, o) : false;
const started = action === "start" ? await startBugTask(db, ref, o) : false;
const row = await getIncident(db, i.id);
await sendIncidentMessage(db, row, { kind: "task", task: ref, started, proposed, reason: by === "triage" ? reason : null });
await sendIncidentMessage(db, row, { kind: "task", task: ref, started, reason: by === "triage" ? reason : null });
return row;
}
@ -230,15 +218,8 @@ export async function handleRegression(db: Db, i: Incident, o: IncidentOptions =
let ref = i.taskId ? await taskRefOf(db, i.taskId) : null;
const stamp = `${(o.now ?? new Date()).toISOString().slice(0, 16).replace("T", " ")} UTC`;
if (ref && ref.task.status === "done" && (o.now ?? new Date()).getTime() - ref.task.updatedAt.getTime() > REOPEN_WINDOW_MS) {
// PEP-295: a new story is a proposal and spends the shared daily limit; without room the people decide.
if ((await proposalRoom(db, i.projectId, o.now)).room <= 0) {
await logEvent(db, { projectId: i.projectId, type: "proposal_limited", payload: { title: i.title, via: "incident", incident: i.id } });
ref = null;
await updateIncident(db, i.id, { status: "regressed", taskId: null });
} else {
ref = await createBugTask(db, i, "policy", null);
await updateIncident(db, i.id, { status: "regressed" });
}
ref = await createBugTask(db, i, "policy", null);
await updateIncident(db, i.id, { status: "regressed" });
} else if (ref) {
await moveTask(db, ref, "backlog");
ref = await resolveTask(db, ref.key);

View File

@ -76,7 +76,6 @@ export * from "./limit-delay.ts";
export * from "./platform-delays.ts";
export * from "./domain-guard.ts";
export * from "./orphan-containers.ts";
export * from "./disk-cleanup.ts";
export * from "./act-runner.ts";
export * from "./pipeline-guard.ts";
export * from "./pause.ts";

View File

@ -21,8 +21,6 @@ import {
intakePending,
intakePrompt,
listTasks,
logEvent,
proposalRoom,
markSplitPart,
openDecisions,
parseIntakeNote,
@ -67,22 +65,14 @@ async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) =
const note = parseIntakeNote(out.text, task.title);
if (!note) throw new Error(m("аналитик ответил не по формату"));
// The parts of the request: each checked for a repeat first (3.5), then filed after this story.
// PEP-295: the parts are proposals (they wait for «Делать» — or «Подходит» on the split) and spend
// the shared daily limit; the parts beyond it stay in this story's text.
const parts: TaskRef[] = [];
const repeats: string[] = [];
const limited: string[] = [];
for (const s of note.split) {
const dup = await checkDuplicate(db, project, s, { log, origin: "analyst" });
if (dup.kind !== "none" && dup.task.id !== task.id) {
repeats.push(`«${s.title}» — ${dup.key}`);
continue;
}
if ((await proposalRoom(db, project.id)).room <= 0) {
limited.push(s.title);
await logEvent(db, { projectId: project.id, taskId: task.id, type: "proposal_limited", payload: { title: s.title, via: "analyst" } });
continue;
}
const part = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: `${s.description}\n\n_${m("Из разбивки {key}.", { key: ref.key })}_`, origin: "analyst" });
// Formulated by the analyst already: the part does not go through intake again.
await setIntakeState(db, part.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: `из разбивки ${ref.key}` });
@ -96,7 +86,6 @@ async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) =
const splitText = parts.length ? m("Разделила на {n} задач: {list}", { n: parts.length + 1, list: [ref.key, ...parts.map((p) => p.key)].join(", ") }) : "";
const decisions = await setDecisions(db, task.id, note.decisions, parts.length ? { text: splitText, parts: parts.map((p) => p.task.id), deferred: note.deferred } : undefined);
await addIntakeNote(db, task, "analyst", intakeMessage(ref.key, note, { parts: parts.map((p) => p.key), repeats, decisions: openDecisions(decisions) }));
if (limited.length) await addIntakeNote(db, task, "analyst", m("Не завела отдельными задачами — на сегодня предел новых задач: {list}. Их можно сделать в этой задаче или завести позже.", { list: limited.map((t) => `«${t}»`).join(", ") }));
return { ...state, stage: "done", product: { goal: note.goal, comment: note.comment, title: note.title, split: note.split }, analyst, attempts: 0 };
}

View File

@ -5,7 +5,6 @@
// one-time offer of that mode to projects created before it existed.
import { m } from "@peppa/shared/i18n";
import {
proposalRoom,
archivedLog,
askPmProject,
createTask,
@ -85,14 +84,9 @@ export async function ensureProductLinkTask(db: Db, project: Project, o: Product
const healthy = recent.some((r) => r.status === "healthy") || !!(await currentReleases(db, project.id)).staging;
if (!failed && (healthy || done.length === 0)) return null;
// PEP-295: the system story is a proposal too and spends the shared daily limit; no room — the next tick tries again.
if ((await proposalRoom(db, project.id, o.now)).room <= 0) {
o.log?.(`product link ${project.key}: daily limit of proposals reached`);
return null;
}
const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail ?? archivedLog("releases", failed.id, failed.updatedAt), runUrl: failed.runUrl } : null });
const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description, origin: "acceptance", severity: "breakage" });
// Already formulated: the analyst of the intake skips it. It waits for «Делать» in «Предложено» (PEP-295).
// Already formulated: «продакт» and «аналитик» of the intake skip it.
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: PRODUCT_LINK_TITLE, description }, attempts: 0, note: "заведена FORGE: продукт не открывается по ссылке" });
await reorderTask(db, ref, { to: "top" });
await setProductLinkState(db, project.id, { taskId: ref.task.id, at: now });

View File

@ -197,13 +197,12 @@ interface Filed {
key: string;
title: string;
severity: Severity;
proposed: boolean;
}
/**
* Files the stories the acceptance agent found: not more than the project's limit per pass,
* never what the owner declined, never a repeat (a remark goes to the open story instead).
* Every finding waits in «Предложено» (PEP-295: a breakage too — the agent sets the severity itself), marked.
* An improvement waits in «Предложено»; a breakage goes to the backlog at once, marked.
* After the version's finish only breakages are filed; the rest is kept for the weekly message.
*/
export async function fileStories(db: Db, project: Project, stories: ProductReviewReply["stories"], o: { envLabel: string; url: string; log?: (m: string) => void; ignoreFinish?: boolean }): Promise<{ created: Filed[]; breakage: boolean; kept: number }> {
@ -235,18 +234,18 @@ export async function fileStories(db: Db, project: Project, stories: ProductRevi
// glossary-user: описание задачи, которое читает владелец
let description = `${s.description}\n\n_Заведено агентом приёмки${o.url ? `: ${o.envLabel}, ${o.url}` : ""}._`;
if (dup.kind === "done") description += `\n\n_${dedupSimilarNote(dup.key, dup.doneAt.toISOString().slice(0, 10))}_`;
const ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity });
const isBreakage = s.severity === "breakage";
const ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity, proposed: !isBreakage });
// Already formulated: «продакт» and «аналитик» of the intake skip it.
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена агентом приёмки" });
created.push({ id: ref.task.id, key: ref.key, title: s.title, severity: s.severity, proposed: ref.task.proposed });
created.push({ id: ref.task.id, key: ref.key, title: s.title, severity: s.severity });
}
return { created, breakage, kept };
}
/** Telegram buttons under the message: per item «Делать» / «Не надо» (`p:<task>:do|no`), then for all. */
export function proposalButtons(items: Array<{ id: number; key: string; severity: string; proposed?: boolean }>, locale: Locale): Array<Array<{ text: string; callback_data: string }>> {
// PEP-295: every finding is a proposal unless the owner let them go to work at once.
const open = items.filter((i) => i.proposed !== false);
export function proposalButtons(items: Array<{ id: number; key: string; severity: string }>, locale: Locale): Array<Array<{ text: string; callback_data: string }>> {
const open = items.filter((i) => i.severity !== "breakage");
if (!open.length) return [];
const rows = open.map((i) => [
{ text: `✅ ${t(locale, "Делать")} ${i.key}`, callback_data: `p:${i.id}:do` },

View File

@ -2,7 +2,7 @@
// stalled runner within a limit), reminds about unanswered questions and escalates them,
// and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env.
import { asIs, m } from "@peppa/shared/i18n";
import { and, eq, gte, inArray, isNull, sql } from "drizzle-orm";
import { and, desc, eq, gt, gte, inArray, isNull, sql } from "drizzle-orm";
import {
alertAdmins,
getSubscription,
@ -31,9 +31,10 @@ import {
isProjectPaused,
pausedProjectIds,
} from "@peppa/core";
import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
import { events, projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
import { HostUnreachable } from "./exec.ts";
import * as tmux from "./tmux.ts";
import type { StartQuestion } from "./start-screen.ts";
@ -63,10 +64,6 @@ export interface WatchdogSettings {
checksStuckMin: number;
/** PEP-265: a new agent with no action this long and a question of its CLI on screen is a start hang; 0 = off. */
startHangSec: number;
/** PEP-287: the docker build cache is pruned hourly down to this many GB; 0 = off. */
buildCacheGb: number;
/** PEP-287: free space of the disk below this percent — one message to the superadmins; 0 = off. */
diskFreeAlertPct: number;
}
export const WATCHDOG_DEFAULTS: WatchdogSettings = {
@ -85,8 +82,6 @@ export const WATCHDOG_DEFAULTS: WatchdogSettings = {
reviewReleaseMin: 30,
checksStuckMin: 30,
startHangSec: 90,
buildCacheGb: 40,
diskFreeAlertPct: 15,
};
const KEY = "platform.watchdog";
@ -174,6 +169,9 @@ export async function onRunnerCrash(
o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void; /** PEP-188: a restart cannot help (the launch line itself is wrong) */ noRestart?: string },
): Promise<boolean> {
const now = o.now.getTime();
// PEP-268: the tmux session vanished (an agent that exits leaves a dead pane: remain-on-exit) —
// someone outside killed it (a tmux server restart, a deploy). Not the story's attempt.
if (reason === "gone" && !o.noRestart) return planPlatformRetry(db, s, "gone", alert, o);
const blocker = o.noRestart ?? (await restartBlocker(db, s, o.cfg, now));
if (!blocker) {
const n = restartsInWindow(s, o.cfg, now).length;
@ -192,6 +190,77 @@ export async function onRunnerCrash(
return false;
}
/** PEP-268: pauses (minutes) before the retries after a failure of the platform itself (the last one repeats). */
export const PLATFORM_RETRY_MIN = [1, 5, 15, 30];
/** PEP-268: the superadmin hears once — on this failure of the platform within the window. */
export const PLATFORM_ALERT_AT = 3;
const platformFailsInWindow = (s: SessionView, cfg: WatchdogSettings, now: number) => (s.watchState?.platformFails ?? []).filter((t) => now - t < cfg.restartWindowMin * 60_000);
/** PEP-268: the launch did not happen because of the platform (host unreachable, no tmux server). */
export function isPlatformError(e: unknown): boolean {
return e instanceof HostUnreachable || (e instanceof Error && e.message.includes(tmux.TMUX_SERVER_DOWN));
}
/**
* PEP-268: did this Claude launch never reach its SessionStart hook (the CLI hung while starting —
* the platform's failure, not the agent's work)? Codex/OpenCode have no such hook — no way to tell.
*/
async function hungAtStart(db: Db, s: SessionView): Promise<boolean> {
if (s.provider !== "claude") return false;
const [launch] = await db
.select({ id: events.id })
.from(events)
.where(and(eq(events.sessionId, s.id), inArray(events.type, ["started", "resumed"])))
.orderBy(desc(events.id))
.limit(1);
if (!launch) return false;
const [started] = await db
.select({ id: events.id })
.from(events)
.where(and(eq(events.sessionId, s.id), eq(events.type, "claude_session"), gt(events.id, launch.id)))
.limit(1);
return !started;
}
/**
* PEP-268: a failure of the platform itself (tmux gone, a hang before the first step, host or tmux
* server down at the restart). Its own count (`platformFails`), a restart that spends none of the
* story's automatic restarts, pauses 1/5/15/30 min and no «attempts ran out»: the story waits until
* the platform is fixed and goes on by itself. The superadmin hears once, on the third failure.
*/
export async function planPlatformRetry(
db: Db,
s: SessionView,
what: "gone" | "stall" | "launch",
details: string,
o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void },
): Promise<boolean> {
const now = o.now.getTime();
const blocker = await restartBlocker(db, s, o.cfg, now, true);
if (blocker) {
await updateSession(db, s.id, { status: "failed", endedAt: o.now });
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: `${details}\n\n${m("Сам не перезапустится: {reason}.", { reason: blocker })}`, now: o.now, log: o.log });
return false;
}
const fails = [...platformFailsInWindow(s, o.cfg, now), now];
const at = now + PLATFORM_RETRY_MIN[Math.min(fails.length - 1, PLATFORM_RETRY_MIN.length - 1)]! * 60_000;
await patchWatch(db, s, { platformFails: fails, restartAt: at, restartReason: `platform:${what}`, restartFree: true }, { status: "failed", endedAt: o.now });
await logSessionEvent(db, s, "platform_retry_planned", { what, failures: fails.length, at: new Date(at).toISOString() });
o.log(`#${s.id} ${s.taskKey ?? ""}: platform failure (${what}) ${fails.length}, retry at ${new Date(at).toISOString()} — no restart spent`);
await sessionDelay(db, s, {
reason: "agent",
state: "platform",
quiet: fails.length !== PLATFORM_ALERT_AT,
retryAt: at,
resume: s.id,
details: `${m("{who}: сбой платформы (№{n} подряд) — попытки задачи не тратятся, повторяем сами.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), n: fails.length })}\n\n${details}`,
now: o.now,
log: o.log,
});
return true;
}
/** PEP-205: pauses (minutes) before the retries after a sign-in failure of the agent CLI. */
export const LOGIN_RETRY_MIN = [1, 5, 15];
@ -322,7 +391,9 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: агент остановился с ошибкой, сам не перезапустился: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log });
continue;
}
const restarts = free ? restartsInWindow(s, o.cfg, o.now.getTime()) : [...restartsInWindow(s, o.cfg, o.now.getTime()), o.now.getTime()];
const before = restartsInWindow(s, o.cfg, o.now.getTime());
const restarts = free ? before : [...before, o.now.getTime()];
const platform = !!ws.restartReason?.startsWith("platform:");
await patchWatch(db, s, { ...clear, restarts, screen: undefined, stallAlertAt: undefined });
try {
await resumeSession(db, s.id, {
@ -330,17 +401,27 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
? "Прошлый разговор потерян (Claude не нашёл его при resume) — это новый разговор. Сверься с peppa.get_task и tasks.md и продолжай с первого невыполненного пункта."
: ws.restartReason === "start_hang"
? "Прошлый запуск завис на старте (CLI ждал ответа на экране) — это повтор. Продолжай работу с того места, где остановился."
: platform
? "Прошлый запуск оборвался из-за сбоя платформы, не по твоей вине — это повтор. Продолжай работу с того места, где остановился."
: free
? "Прошлый запуск не смог войти в аккаунт (сбой связи) — это повтор. Продолжай работу с того места, где остановился."
: `Раннер ${ws.restartReason === "stall" ? "завис" : "упал"} и перезапущен вачдогом автоматически (попытка ${restarts.length} из ${o.cfg.restartMax}).`,
});
if (ws.restartReason === "conversation_lost") await logSessionEvent(db, s, "conversation_restarted", {});
else if (ws.restartReason === "start_hang") await logSessionEvent(db, s, "start_hang_retried", { attempt: ws.hangs ?? 1 });
else if (platform) await logSessionEvent(db, s, "platform_retried", { what: ws.restartReason!.slice("platform:".length), failures: platformFailsInWindow(s, o.cfg, o.now.getTime()).length });
else await logSessionEvent(db, s, free ? "login_retried" : "auto_restarted", { reason: ws.restartReason, attempt: free ? (ws.loginFails ?? 1) : restarts.length, of: free ? LOGIN_RETRY_MIN.length : o.cfg.restartMax });
o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`);
if (s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "agent");
} catch (e) {
await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message });
// PEP-268: the host or the tmux server is down — the launch never happened: the attempt is
// given back and the story waits for the platform on its own schedule.
if (isPlatformError(e)) {
await patchWatch(db, s, { restarts: before });
await planPlatformRetry(db, s, "launch", m("{who}: не удалось запустить агента — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message }), o);
continue;
}
// PEP-150: a failed restart is an attempt — the next one follows the same schedule; the
// superadmin is told once the attempts have run out. The error itself goes to Bugsink.
const fresh = await getSession(db, s.id).catch(() => s);
@ -371,7 +452,9 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<boolean> {
const at = s.watchState?.stallAlertAt;
if (!at || o.cfg.stallRestartMin <= 0 || o.now.getTime() - at < o.cfg.stallRestartMin * 60_000) return false;
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime());
// PEP-268: the agent hung before its first step — the launch is the platform's failure.
const hung = await hungAtStart(db, s);
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime(), hung);
if (blocker) {
await patchWatch(db, s, { stallAlertAt: undefined });
await logSessionEvent(db, s, "restart_skipped", { reason: "stall", why: blocker });
@ -379,6 +462,10 @@ export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg
return false;
}
await killRunner(s).catch(() => {});
if (hung) {
await patchWatch(db, s, { stallAlertAt: undefined });
return planPlatformRetry(db, s, "stall", m("{who}: агент завис на старте — программа агента так и не запустилась.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }) }), o);
}
await patchWatch(db, s, { stallAlertAt: undefined, restartAt: o.now.getTime(), restartReason: "stall" }, { status: "failed", endedAt: o.now });
await logSessionEvent(db, s, "restart_planned", { reason: "stall", attempt: restartsInWindow(s, o.cfg, o.now.getTime()).length + 1, of: o.cfg.restartMax });
await restartTick(db, o);

View File

@ -44,7 +44,6 @@ import { rolloutTick } from "./rollout.ts";
import { connectionCheckTick, connectionJournalTick, grantExpiryTick } from "@peppa/core";
import { domainGuardTick } from "./domain-guard.ts";
import { orphanContainersTick } from "./orphan-containers.ts";
import { buildCachePruneTick, diskSpaceTick, sandboxCleanupTick } from "./disk-cleanup.ts";
import { removeContainer } from "./sandbox.ts";
import { edgeDnsTick } from "./edge-dns.ts";
import { actRunnerTick } from "./act-runner.ts";
@ -482,10 +481,6 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
await domainGuardTick(db, { log }).catch(failed(db, log, "domain guard failed"));
// PEP-244: containers of agents whose session is over or gone (a deploy took the tmux server).
await orphanContainersTick(db, { log }).catch(failed(db, log, "orphan containers failed"));
// PEP-287: the server's disk — agents' folders of closed stories, the build cache (hourly), low free space.
await sandboxCleanupTick(db, { log }).catch(failed(db, log, "sandbox cleanup failed"));
await buildCachePruneTick(db, { log }).catch(failed(db, log, "build cache prune failed"));
await diskSpaceTick(db, { log }).catch(failed(db, log, "disk space failed"));
// PEP-205: the checks executor is alive and takes jobs; otherwise it is restarted.
await actRunnerTick(db, { log }).catch(failed(db, log, "act runner guard failed"));
}

View File

@ -97,4 +97,7 @@ export const acceptScreen: Dict = {
"Ответьте на вопрос о бюджете или поменяйте бюджет задачи.": "Answer the budget question or change the task's budget.",
"После этого агент продолжит работу.": "Then the agent will continue the work.",
"агент по задаче ни разу не запускался": "no agent has ever started on the task",
"Сбой на нашей стороне, чиним — задача продолжится сама": "A failure on our side, we are fixing it — the task will continue by itself",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка завтра в {time}": "A failure on our side, we are fixing it — the task will continue by itself. Next attempt tomorrow at {time}",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в {time}": "A failure on our side, we are fixing it — the task will continue by itself. Next attempt at {time}",
};

View File

@ -16,6 +16,4 @@ export const domainGuard: Dict = {
"🌐 {url} всё ещё не открывается снаружи — {min} мин: {reason}. Ответ: {what}": "🌐 {url} still does not open from outside — {min} min: {reason}. Answer: {what}",
"туннель адресов на сервере (peppa-cloudflared) не на связи с Cloudflare": "the address tunnel on the server (peppa-cloudflared) is not connected to Cloudflare",
"нет связи Mac → сервер — адреса пока идут через Mac (туннель launchd quest.telecom.peppa.tunnel)": "no connection Mac → server — addresses still go through the Mac (launchd tunnel quest.telecom.peppa.tunnel)",
// PEP-287: low free space on the server.
"💾 На диске сервера свободно {pct}% ({free} из {total} ГБ) — меньше порога {limit}%. Папки агентов и кэш сборки FORGE убирает сама; посмотрите, что ещё занимает место.": "💾 The server's disk has {pct}% free ({free} of {total} GB) — below the {limit}% threshold. FORGE cleans agents' folders and the build cache itself; check what else takes the space.",
};

View File

@ -41,14 +41,4 @@ export const proposals: Record<string, string> = {
"Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Once a week: improvements found: {n} (important: {k}).",
"По этим задачам решение уже принято.": "A decision on these tasks has already been made.",
"Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "We tidied up: tasks the factory made itself that wait for your decision: {n}. They are in «Suggested» on the board. Nothing was deleted.",
// PEP-295
"Это решает владелец проекта.": "This is the project owner's decision.",
"Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».": "Agents take tasks from product errors into work right away, without your «Do it».",
"Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».": "Tasks from product errors wait for your «Do it» in «Suggested».",
"Ждать моего решения": "Wait for my decision",
"Брать в работу сразу": "Take into work right away",
"💡 Задача ждёт вашего решения в «Предложено»: {link}": "💡 The task waits for your decision in «Suggested»: {link}",
"Неизвестное происхождение задачи: {name}": "Unknown task origin: {name}",
"Предел задач без вашего решения на сегодня исчерпан — задача не создана.": "Today's limit of tasks without your decision is reached — the task was not created.",
"Не завела отдельными задачами — на сегодня предел новых задач: {list}. Их можно сделать в этой задаче или завести позже.": "Not filed as separate tasks — today's limit of new tasks is reached: {list}. They can be done in this task or filed later.",
};

View File

@ -509,4 +509,7 @@ export const runner: Dict = {
"зависает на старте {n} раза подряд": "hangs at start {n} times in a row",
"агент остановлен, перезапуск в {time}": "the agent is stopped, restart at {time}",
"Попытки задачи не тратятся, FORGE перезапустит агента сама.": "The task's attempts are not spent; FORGE restarts the agent by itself.",
"{who}: сбой платформы (№{n} подряд) — попытки задачи не тратятся, повторяем сами.": "{who}: platform failure (#{n} in a row) — the task's attempts are not spent, retrying by ourselves.",
"{who}: не удалось запустить агента — {error}": "{who}: could not start the agent — {error}",
"{who}: агент завис на старте — программа агента так и не запустилась.": "{who}: the agent hung at the start — the agent program never started.",
};

View File

@ -97,4 +97,7 @@ export const acceptScreen: Dict = {
"Ответьте на вопрос о бюджете или поменяйте бюджет задачи.": "Бюджет туралы сұраққа жауап беріңіз немесе тапсырманың бюджетін өзгертіңіз.",
"После этого агент продолжит работу.": "Осыдан кейін агент жұмысын жалғастырады.",
"агент по задаче ни разу не запускался": "тапсырма бойынша агент бірде-бір рет іске қосылмаған",
"Сбой на нашей стороне, чиним — задача продолжится сама": "Біз жақта ақау, түзетіп жатырмыз — тапсырма өздігінен жалғасады",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка завтра в {time}": "Біз жақта ақау, түзетіп жатырмыз — тапсырма өздігінен жалғасады. Келесі әрекет ертең {time}",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в {time}": "Біз жақта ақау, түзетіп жатырмыз — тапсырма өздігінен жалғасады. Келесі әрекет {time}",
};

View File

@ -16,6 +16,4 @@ export const domainGuard: Dict = {
"🌐 {url} всё ещё не открывается снаружи — {min} мин: {reason}. Ответ: {what}": "🌐 {url} сырттан әлі ашылмайды — {min} мин: {reason}. Жауап: {what}",
"туннель адресов на сервере (peppa-cloudflared) не на связи с Cloudflare": "серверадегі мекенжай туннелі (peppa-cloudflared) Cloudflare-мен байланыспайды",
"нет связи Mac → сервер — адреса пока идут через Mac (туннель launchd quest.telecom.peppa.tunnel)": "Mac → сервер байланысы жоқ — мекенжайлар әзірге Mac арқылы өтеді (launchd туннелі quest.telecom.peppa.tunnel)",
// PEP-287: low free space on the server.
"💾 На диске сервера свободно {pct}% ({free} из {total} ГБ) — меньше порога {limit}%. Папки агентов и кэш сборки FORGE убирает сама; посмотрите, что ещё занимает место.": "💾 Сервер дискінде {pct}% бос ({free} / {total} ГБ) — {limit}% шегінен аз. Агенттер қалталары мен құрастыру кэшін FORGE өзі тазалайды; орынды тағы не алып жатқанын қараңыз.",
};

View File

@ -41,14 +41,4 @@ export const proposals: Record<string, string> = {
"Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Аптасына бір рет: табылған жақсартулар: {n} (маңыздысы: {k}).",
"По этим задачам решение уже принято.": "Бұл тапсырмалар бойынша шешім қабылданған.",
"Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "Тәртіпке келтірдік: фабрика өзі қосқан және сіздің шешіміңізді күтетін тапсырмалар: {n}. Олар тақтадағы «Ұсынылған» бөлімінде. Ештеңе жойылған жоқ.",
// PEP-295
"Это решает владелец проекта.": "Мұны жоба иесі шешеді.",
"Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».": "Өнім қателерінен туған тапсырмаларды агенттер сіздің «Орындау» батырмаңызсыз бірден жұмысқа алады.",
"Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».": "Өнім қателерінен туған тапсырмалар «Ұсынылған» ішінде сіздің «Орындау» батырмаңызды күтеді.",
"Ждать моего решения": "Менің шешімімді күту",
"Брать в работу сразу": "Бірден жұмысқа алу",
"💡 Задача ждёт вашего решения в «Предложено»: {link}": "💡 Тапсырма «Ұсынылған» ішінде сіздің шешіміңізді күтеді: {link}",
"Неизвестное происхождение задачи: {name}": "Тапсырманың белгісіз шығу тегі: {name}",
"Предел задач без вашего решения на сегодня исчерпан — задача не создана.": "Бүгінге сіздің шешіміңізсіз тапсырмалар шегі таусылды — тапсырма құрылмады.",
"Не завела отдельными задачами — на сегодня предел новых задач: {list}. Их можно сделать в этой задаче или завести позже.": "Бөлек тапсырма етіп қоспадым — бүгінге жаңа тапсырмалар шегі таусылды: {list}. Оларды осы тапсырмада жасауға немесе кейін қосуға болады.",
};

View File

@ -417,4 +417,7 @@ export const runner: Dict = {
"зависает на старте {n} раза подряд": "іске қосылғанда қатарынан {n} рет тоқтап қалды",
"агент остановлен, перезапуск в {time}": "агент тоқтатылды, қайта іске қосу {time}",
"Попытки задачи не тратятся, FORGE перезапустит агента сама.": "Тапсырманың әрекеттері жұмсалмайды, FORGE агентті өзі қайта іске қосады.",
"{who}: сбой платформы (№{n} подряд) — попытки задачи не тратятся, повторяем сами.": "{who}: платформа ақауы (қатарынан №{n}) — тапсырманың әрекеттері жұмсалмайды, өзіміз қайталаймыз.",
"{who}: не удалось запустить агента — {error}": "{who}: агентті іске қосу мүмкін болмады — {error}",
"{who}: агент завис на старте — программа агента так и не запустилась.": "{who}: агент басында қатып қалды — агент бағдарламасы іске қосылмады.",
};

View File

@ -11,7 +11,6 @@
# Each run is logged to $MOCK_DOCKER_STATE/runs.jsonl (name, image, mounts, env names, argv).
# `docker rm -f <name>` drops containers/<name>; MOCK_DOCKER_RUNNER_FAIL=1 fails a runner run.
# PEP-189: `docker ps` prints $st/ps, `docker stop` removes its row and appends to $st/stopped.
# PEP-287: `docker builder prune` — MOCK_DOCKER_OLD_CLIENT=1 rejects --reserved-space like client 20.10.
set -uo pipefail
# Called through symlinks (a `docker` on PATH): resolve to this file to find the repo.
_src="$0"; while [[ -L "$_src" ]]; do _l="$(readlink "$_src")"; [[ "$_l" == /* ]] && _src="$_l" || _src="$(dirname "$_src")/$_l"; done
@ -78,11 +77,6 @@ case "$1" in
[[ -f "$st/containers/$c" ]] || { echo "Error response from daemon: No such container: $c" >&2; exit 1; }
echo "$c" >> "$st/restarted"; echo running > "$st/containers/$c"; echo "$c" ;;
version) echo "27.3.1-mock" ;;
builder) # PEP-287: docker builder prune -f (--reserved-space|--keep-storage) <N>GB
[[ "$2" == prune ]] || { echo "mock-docker: unsupported: $*" >&2; exit 1; }
for a in "$@"; do [[ "$a" == -a || "$a" == --all ]] && { echo "mock-docker: prune -a is not allowed" >&2; exit 1; }; done
if [[ -n "${MOCK_DOCKER_OLD_CLIENT:-}" && " $* " == *" --reserved-space "* ]]; then echo "unknown flag: --reserved-space" >&2; exit 125; fi
echo "Total reclaimed space: 12.5GB" ;;
ps) # PEP-189: docker ps … --format '{{.ID}}\t{{.Names}}\t{{.Ports}}\t{{.Labels}}' — rows of $st/ps (that format)
[[ -n "${MOCK_DOCKER_PS_FAIL:-}" ]] && { echo "Cannot connect to the Docker daemon" >&2; exit 1; }
[[ -f "$st/ps" ]] && cat "$st/ps"; exit 0 ;;

View File

@ -560,6 +560,10 @@ async function main() {
}
out(`${provider === "claude" ? "✻ Mock Claude Code" : provider === "opencode" ? "▣ Mock OpenCode" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`);
if (provider === "claude" && scenario.hangAtStart && (process.env.PEPPA_GENERATION ?? "1") === "1") {
log("hang_at_start");
await new Promise(() => {});
}
if (provider === "claude") await fireHook("SessionStart", { source: args.resume ? "resume" : "startup" }, args.resume ? "resume" : "startup");
// PEP-265: a question of the CLI itself before any work (trust, model, sign-in) — keys are ignored.

View File

@ -39,6 +39,8 @@ export interface Scenario {
resumeTurns?: Action[][];
/** PEP-227: Claude forgot every conversation — `--resume <id>` prints «No conversation found…» and exits 1. */
forgetResume?: boolean;
/** PEP-268: the first generation hangs before Claude's SessionStart — the launch itself is stuck. */
hangAtStart?: boolean;
/** PEP-54: env variables the mock prints as `NAME=value` at start and logs (secrets tests). */
echoEnv?: string[];
/** PEP-265: the CLI shows this question at start and waits forever — no hook, no turn (a start hang). */

View File

@ -11,15 +11,9 @@ describe("PEP-197: уборка и сводка", () => {
test("not started stories of agents go to «Предложено»; started ones stay; repeats are marked; one message; nothing deleted", async () => {
const tp = await project({ turns: [] });
const p = await core.getProject(db, tp.key);
// Stories filed before PEP-295 (no «Предложено» flag): what the tidy is for.
const legacy = async (t: Parameters<typeof core.createTask>[1]) => {
const ref = await core.createTask(db, t);
await db.update(tasks).set({ proposed: false }).where(eq(tasks.id, ref.task.id));
return ref;
};
const idle = await legacy({ projectId: p.id, title: "Подписать кнопки", origin: "acceptance", severity: "important" });
const repeat = await legacy({ projectId: p.id, title: "Подписать кнопки!", origin: "acceptance", severity: "important" });
const going = await legacy({ projectId: p.id, title: "Другая тема", origin: "acceptance" });
const idle = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки", origin: "acceptance", severity: "important" });
const repeat = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки!", origin: "acceptance", severity: "important" });
const going = await core.createTask(db, { projectId: p.id, title: "Другая тема", origin: "acceptance" });
await core.updateTask(db, going, { status: "in_progress" });
const mine = await core.createTask(db, { projectId: p.id, title: "Просьба человека" });
@ -48,7 +42,7 @@ describe("PEP-197: уборка и сводка", () => {
await core.createTask(db, { projectId: p.id, title: "Первая от агента", origin: "acceptance", proposed: true });
await core.createTask(db, { projectId: p.id, title: "Вторая от агента", origin: "incident" });
const row = (await core.agentTaskSummary(db)).find((r) => r.key === p.key)!;
assert.deepEqual([row.human, row.agents, row.proposed, row.agentsMoreThanHuman], [1, 2, 2, true], "PEP-295: an error's story is a proposal too");
assert.match(core.agentTaskTable([row]), new RegExp(`${p.key} \\| 1 \\| 2 \\| 2 \\|`));
assert.deepEqual([row.human, row.agents, row.proposed, row.agentsMoreThanHuman], [1, 2, 1, true]);
assert.match(core.agentTaskTable([row]), new RegExp(`${p.key} \\| 1 \\| 2 \\| 1 \\|`));
});
});

View File

@ -264,7 +264,6 @@ describe("PEP-197: stories of agents in work", () => {
await core.setAutonomy(db, p.id, { level: "auto", wipLimit: 5, ...NO_QUIET });
const make = async (title: string, status: "backlog" | "in_progress") => {
const ref = await core.createTask(db, { projectId: p.id, title, origin: "acceptance", severity: "breakage" });
await core.approveProposal(db, ref.task.id); // PEP-295: the owner said «Делать»
if (status === "in_progress") await core.updateTask(db, ref, { status });
return ref;
};

View File

@ -1,210 +0,0 @@
// PEP-287: the server's disk — agents' folders of closed stories go, the build cache is held at its
// limit hourly, old platform images are pruned by the deploy, low free space — one message per episode.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, beforeEach, describe, test } from "node:test";
import { and, eq, like } from "drizzle-orm";
import { events, settings, tasks, telegramOutbox } from "@peppa/db";
import { core, db, project, runner, superadmin, teardown, type TestProject } from "./helpers.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const state = mkdtempSync(join(tmpdir(), "mock-docker-disk-"));
process.env.PEPPA_DOCKER_BIN = join(ROOT, "packages/testkit/bin/mock-docker");
process.env.MOCK_DOCKER_STATE = state;
const sandboxes = join(process.env.PEPPA_HOME!, "sandboxes");
const folder = (id: number) => join(sandboxes, `s${id}`);
function makeFolder(id: number) {
mkdirSync(join(folder(id), "home", ".claude"), { recursive: true });
writeFileSync(join(folder(id), "home", ".claude.json"), "{}");
}
const calls = () => (existsSync(join(state, "calls.log")) ? readFileSync(join(state, "calls.log"), "utf8").split("\n").filter((l) => l.includes("builder prune")) : []);
const H = 3600_000;
let p: TestProject;
let projectId: number;
let taskId: number;
async function session(o: { task?: number | null; status?: "running" | "done" | "failed"; endedAt?: Date } = {}) {
const s = await core.createSession(db, { projectId, taskId: o.task === undefined ? taskId : o.task });
const status = o.status ?? "done";
await core.updateSession(db, s.id, { status, ...(status === "running" ? {} : { endedAt: o.endedAt ?? new Date() }) });
makeFolder(s.id);
return s.id;
}
async function newTask(status: "in_progress" | "done" | "review") {
const t = await core.createTask(db, { projectId, title: `PEP-287 ${status} ${Math.random()}` });
await db.update(tasks).set({ status }).where(eq(tasks.id, t.task.id));
return t.task.id;
}
before(async () => {
process.env.PEPPA_DISK_CLEANUP = "on";
p = await project({ turns: [] });
process.env.PEPPA_PLATFORM_KEY = p.key;
projectId = (await core.getProject(db, p.key)).id;
taskId = await newTask("in_progress");
});
after(teardown);
beforeEach(() => {
for (const f of ["ps", "calls.log"]) writeFileSync(join(state, f), "");
runner.resetDiskCleanupState();
delete process.env.MOCK_DOCKER_OLD_CLIENT;
});
describe("PEP-287: папки агентов", () => {
test("Задача закрыта — папки нет; Задача ещё в работе — папка остаётся", async () => {
const done = await newTask("done");
const archived = await newTask("review");
await db.update(tasks).set({ archivedAt: new Date() }).where(eq(tasks.id, archived));
const a = await session({ task: done });
const b = await session({ task: archived, status: "failed" });
const open = await session({ task: taskId });
const live = await session({ task: done, status: "running" });
const r = await runner.sandboxCleanupTick(db, { force: true });
assert.deepEqual(r.map((x) => x.sessionId).sort(), [a, b].sort());
assert.ok(!existsSync(folder(a)) && !existsSync(folder(b)));
assert.ok(existsSync(folder(open)), "an open story keeps the conversation");
assert.ok(existsSync(folder(live)), "a running session keeps its home");
const ev = await db.select().from(events).where(and(eq(events.projectId, projectId), eq(events.type, "sandbox_removed")));
assert.ok(ev.some((e) => (e.payload as { sessionId: number }).sessionId === a));
});
test("Контейнер ещё запущен — папка остаётся", async () => {
const done = await newTask("done");
const id = await session({ task: done });
writeFileSync(join(state, "ps"), `id-x\tpeppa-s${id}\t\t\n`);
assert.deepEqual(await runner.sandboxCleanupTick(db, { force: true }), []);
assert.ok(existsSync(folder(id)));
writeFileSync(join(state, "ps"), "");
assert.deepEqual((await runner.sandboxCleanupTick(db, { force: true })).map((x) => x.sessionId), [id]);
});
test("Свободный агент — через сутки после конца", async () => {
const now = new Date();
const id = await session({ task: null, endedAt: new Date(now.getTime() - 2 * H) });
assert.deepEqual(await runner.sandboxCleanupTick(db, { force: true, now }), []);
assert.ok(existsSync(folder(id)));
const r = await runner.sandboxCleanupTick(db, { force: true, now: new Date(now.getTime() + 23 * H) });
assert.deepEqual(r.map((x) => [x.sessionId, x.reason]), [[id, "no_task"]]);
});
test("Ссылка вместо папки — не трогаем; не больше 20 за проход", async () => {
const done = await newTask("done");
const outside = mkdtempSync(join(tmpdir(), "pep287-outside-"));
writeFileSync(join(outside, "keep"), "x");
const s = await core.createSession(db, { projectId, taskId: done });
await core.updateSession(db, s.id, { status: "done", endedAt: new Date() });
mkdirSync(sandboxes, { recursive: true });
symlinkSync(outside, folder(s.id));
const ids: number[] = [];
for (let i = 0; i < 25; i++) ids.push(await session({ task: done }));
const first = await runner.sandboxCleanupTick(db, { force: true });
assert.equal(first.length, runner.SANDBOX_MAX_PER_PASS);
assert.ok(existsSync(join(outside, "keep")), "the link's target is untouched");
const second = await runner.sandboxCleanupTick(db, { force: true });
assert.equal(second.length, 5);
assert.ok(existsSync(join(outside, "keep")));
});
test("docker не ответил — проход пропускается", async () => {
const done = await newTask("done");
const id = await session({ task: done });
process.env.MOCK_DOCKER_PS_FAIL = "1";
try {
assert.deepEqual(await runner.sandboxCleanupTick(db, { force: true }), []);
} finally {
delete process.env.MOCK_DOCKER_PS_FAIL;
}
assert.ok(existsSync(folder(id)));
});
});
describe("PEP-287: кэш сборки", () => {
test("Раз в час, без -a, в пределе из настроек", async () => {
await db.delete(settings).where(eq(settings.key, "disk.prune.last"));
const t0 = new Date("2026-11-26T10:00:00Z");
const r = await runner.buildCachePruneTick(db, { now: t0, wait: true });
assert.deepEqual(r?.args, ["builder", "prune", "-f", "--reserved-space", "40GB"]);
assert.equal(r?.reclaimed, "12.5GB");
for (const min of [1, 10, 30, 59]) assert.equal(await runner.buildCachePruneTick(db, { now: new Date(t0.getTime() + min * 60_000), wait: true }), null);
await runner.buildCachePruneTick(db, { now: new Date(t0.getTime() + 61 * 60_000), wait: true });
assert.deepEqual(calls(), ["docker builder prune -f --reserved-space 40GB", "docker builder prune -f --reserved-space 40GB"]);
const ev = await db.select().from(events).where(and(eq(events.projectId, projectId), eq(events.type, "build_cache_pruned")));
assert.equal(ev.length, 2);
});
test("Старый клиент docker — --keep-storage", async () => {
await db.delete(settings).where(eq(settings.key, "disk.prune.last"));
await runner.setWatchdogSettings(db, ["buildCacheGb=60"]);
process.env.MOCK_DOCKER_OLD_CLIENT = "1";
try {
const r = await runner.buildCachePruneTick(db, { now: new Date(), wait: true });
assert.deepEqual(r?.args, ["builder", "prune", "-f", "--keep-storage", "60GB"]);
assert.deepEqual(calls(), ["docker builder prune -f --reserved-space 60GB", "docker builder prune -f --keep-storage 60GB"]);
} finally {
await runner.setWatchdogSettings(db, ["buildCacheGb=40"]);
}
});
});
describe("PEP-287: место на диске", () => {
test("Одно сообщение на эпизод", async () => {
await superadmin();
const TB = 1024 ** 4;
const disk = (freePct: number) => () => ({ freeBytes: (TB * freePct) / 100, totalBytes: TB });
const sent = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "disk:low:%"))).map((r) => String(r.params.text));
assert.equal(await runner.diskSpaceTick(db, { statfs: disk(30) }), "ok");
assert.equal(await runner.diskSpaceTick(db, { statfs: disk(10), now: new Date("2026-11-26T10:00:00Z") }), "alerted");
assert.equal(await runner.diskSpaceTick(db, { statfs: disk(9) }), "low");
assert.equal(await runner.diskSpaceTick(db, { statfs: disk(16) }), "ok"); // above the threshold, inside the margin
assert.equal(await runner.diskSpaceTick(db, { statfs: disk(12) }), "low");
const one = await sent();
assert.equal(one.length, 1);
assert.match(one[0]!, /свободно 10%/);
assert.equal(await runner.diskSpaceTick(db, { statfs: disk(30) }), "ok");
assert.equal(await runner.diskSpaceTick(db, { statfs: disk(10), now: new Date("2026-11-26T12:00:00Z") }), "alerted");
assert.equal((await sent()).length, 2, "a new episode — a new message");
});
});
describe("PEP-287: образы платформы", () => {
const lib = join(ROOT, "scripts/lib/platform-images.sh");
const toRemove = (lines: string[], cur: string, prev = "") =>
execFileSync("bash", ["-c", `. "${lib}"; platform_images_to_remove "$1" "$2"`, "_", cur, prev], { input: lines.join("\n") + "\n" })
.toString()
.split("\n")
.filter(Boolean);
test("Пять выкаток подряд — три образа", () => {
let images: { at: string; tag: string }[] = [{ at: "2026-11-20 08:00:00 +0000 UTC", tag: "latest" }];
let prev = "";
for (let i = 1; i <= 5; i++) {
const tag = `a${i}b2c3d4e5f6`;
images.push({ at: `2026-11-2${i} 10:00:00 +0000 UTC`, tag });
const gone = toRemove(images.map((x) => `${x.at}\t${x.tag}`), tag, prev);
images = images.filter((x) => !gone.includes(x.tag));
prev = tag;
}
assert.deepEqual(images.map((x) => x.tag).sort(), ["a3b2c3d4e5f6", "a4b2c3d4e5f6", "a5b2c3d4e5f6", "latest"].sort(), "three platform images; other tags untouched");
});
test("Тег отката остаётся, даже если он старый", () => {
const lines = ["2026-11-21 10:00:00 +0000 UTC\taaa111", "2026-11-22 10:00:00 +0000 UTC\tbbb222", "2026-11-23 10:00:00 +0000 UTC\tccc333", "2026-11-24 10:00:00 +0000 UTC\tddd444", "2026-11-24 10:00:00 +0000 UTC\t<none>"];
assert.deepEqual(toRemove(lines, "ddd444", "aaa111").sort(), ["bbb222"]);
});
test("Выкатка зовёт уборку после удачи и убирает временную строку cron", () => {
const deploy = readFileSync(join(ROOT, "scripts/platform-deploy.sh"), "utf8");
execFileSync("bash", ["-n", join(ROOT, "scripts/platform-deploy.sh")]);
const ok = deploy.indexOf('echo "$SHORT" >"$PREV_FILE"');
assert.ok(ok > 0 && deploy.indexOf("prune_platform_images ||") > ok, "images are pruned only after a successful deploy");
assert.match(deploy, /docker rmi "peppa\/platform:\$t"/);
assert.doesNotMatch(deploy, /docker rmi -f/);
assert.match(deploy, /grep -v peppa-build-cache-prune \| crontab -/);
});
});

View File

@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { core, db, runner, teardown, waitFor } from "./helpers.ts";
import { MockTelegram } from "../src/mock-telegram.ts";
import { feedback, tasks, telegramOutbox, users } from "@peppa/db";
import { feedback, telegramOutbox, users } from "@peppa/db";
import { eq, like } from "drizzle-orm";
import type { Bot } from "@peppa/bot";
@ -163,10 +163,7 @@ describe("Разбор агентом обратной связи", () => {
test("Scenario: Разбор с тремя вариантами", async () => {
await db.delete(feedback);
await db.delete(telegramOutbox);
const tasksBefore = (await db.select({ id: tasks.id }).from(tasks)).length;
const f = await analysed("Кнопка „Принять“ не нажимается", [PNG]);
// PEP-295: the feedback agent only analyses — a story appears only by the superadmin's decision.
assert.equal((await db.select({ id: tasks.id }).from(tasks)).length, tasksBefore, "the feedback agent files no story");
assert.equal(f.status, "analyzed");
assert.equal(f.analysis?.kind, "bug");
assert.equal(f.analysis?.options.length, 3);

View File

@ -43,7 +43,6 @@ Object.assign(process.env, {
// domain-guard.test.ts turns it on with mock-docker.
PEPPA_DOMAIN_GUARD: "off",
PEPPA_ORPHAN_CONTAINERS: "off",
PEPPA_DISK_CLEANUP: "off",
// PEP-222: agents run in containers by default; suites run mock agents directly in tmux unless they ask for a container.
PEPPA_DEFAULT_ISOLATION: "none",
// PEP-153: the message classifier never reaches a real CLI from a test.

View File

@ -94,7 +94,7 @@ interface Connected {
}
/** A fresh project connected to (mock) Bugsink, alerts pointed at FORGE, with this policy. */
async function connected(patch: Parameters<typeof core.updateIncidentSettings>[2] = {}, opts: { webhook?: boolean; direct?: boolean } = {}): Promise<Connected> {
async function connected(patch: Parameters<typeof core.updateIncidentSettings>[2] = {}, opts: { webhook?: boolean } = {}): Promise<Connected> {
const p = await project({ turns: [[{ say: "смотрю ошибку" }]] });
const proj = await core.getProject(db, p.key);
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
@ -106,8 +106,6 @@ async function connected(patch: Parameters<typeof core.updateIncidentSettings>[2
bugsink.setWebhook(api, r.webhookUrl);
}
if (Object.keys(patch).length) await core.updateIncidentSettings(db, proj.id, patch);
// PEP-295: the owner's exception — errors go to work without «Делать».
if (opts.direct) await core.setDirectOrigins(db, proj.id, ["incident"]);
return { key: p.key, proj, web, api, secret: r.settings.hookSecret };
}
@ -230,7 +228,7 @@ describe("Политика инцидентов проекта", () => {
assert.equal(buttons(m).length, 0);
});
test("backlog: задача-баг под «Стабильностью» со стеком и ссылкой в «Предложено», PM получает сообщение с «Делать» (PEP-295)", async () => {
test("backlog: задача-баг под «Стабильностью» со стеком и ссылкой, PM получает сообщение со ссылкой", async () => {
const c = await connected({ policy: "backlog" });
await bugsink.capture(c.api, AMOUNT);
const i = await waitIncident(c, "TypeError: amount is undefined", (x) => x.status === "task");
@ -242,26 +240,13 @@ describe("Политика инцидентов проекта", () => {
assert.match(t.description!, /billing\/charge\.ts:42 in charge/);
assert.ok(t.description!.includes(i.url!));
assert.match(t.description!, /Условия готовности/);
assert.equal(t.proposed, true, "not decided by a person — waits for «Делать»");
const m = await waitPm("TypeError: amount is undefined", (x) => x.text.includes(t.key));
assert.match(m.text, /Задача ждёт вашего решения в «Предложено»/);
assert.match(m.text, /Задача в бэклоге/);
assert.ok(m.text.includes(`http://peppa.test/t/${t.key}`));
assert.deepEqual(buttons(m).map((b) => b.callback_data), [`p:${t.id}:do`, `p:${t.id}:no`]);
});
test("start без исключения владельца: задача в «Предложено», агент не запускается (PEP-295)", async () => {
test("start: задача сразу в работе, раннер запущен, PM знает", async () => {
const c = await connected({ policy: "start" });
await bugsink.capture(c.api, { ...AMOUNT, value: "start proposed" });
const i = await waitIncident(c, "TypeError: start proposed", (x) => x.status === "task");
await waitPm("TypeError: start proposed", (m) => /Предложено/.test(m.text));
const t = (await tasksOf(c)).find((x) => x.id === i.taskId)!;
assert.equal(t.status, "backlog");
assert.equal(t.proposed, true);
assert.equal((await core.listSessions(db, { taskId: t.id })).length, 0);
});
test("start с исключением «Ошибки продукта брать в работу сразу»: задача сразу в работе, раннер запущен, PM знает", async () => {
const c = await connected({ policy: "start" }, { direct: true });
await bugsink.capture(c.api, { ...AMOUNT, value: "start now" });
const i = await waitIncident(c, "TypeError: start now", (x) => x.status === "task");
// The incident points at its task before the task is moved to work.
@ -321,7 +306,7 @@ describe("Политика инцидентов проекта", () => {
test("triage, триажёр уверен: задача в работе, обоснование в задаче и в сообщении", async () => {
const prompt = "падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси";
triage({ rules: [{ match: "PaymentError", action: "start", confidence: 0.92, reason: "падает оплата — по правилам сразу в работу" }] });
const c = await connected({ policy: "triage", triagePrompt: prompt }, { direct: true });
const c = await connected({ policy: "triage", triagePrompt: prompt });
await bugsink.capture(c.api, { type: "PaymentError", value: "card declined handler crashed", environment: "prod", release: "a1b2c3", frames: [{ filename: "billing/pay.ts", function: "pay", lineno: 3 }] });
await waitIncident(c, "PaymentError: card declined handler crashed", (x) => x.status === "task");
// The message is the last step of the decision: after it the incident and the task are final.
@ -393,9 +378,6 @@ describe("Политика инцидентов проекта", () => {
// The PM's own decision isn't capped.
const r = await runner.decideIncident(db, i.id, "backlog", "mock-pm");
assert.equal(r.task?.task.status, "backlog");
// PEP-295: a person decided — not a proposal, and the shared daily limit is not spent.
assert.equal(r.task?.task.proposed, false);
assert.equal(await core.proposalsToday(db, c.proj.id), 5);
});
test("Смена политики: после выбора triage новые ошибки разбирает триажёр по промпту", async () => {
@ -469,7 +451,6 @@ describe("Проект-образец SBX: ошибка → инцидент →
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
for (const s of r.sources) bugsink.setWebhook(s.bugsinkProjectId, r.webhookUrl);
await core.updateIncidentSettings(db, proj.id, { policy: "start" });
await core.setDirectOrigins(db, proj.id, ["incident"]);
const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId;
await bugsink.capture(web, { type: "TypeError", value: "Cannot read properties of undefined (reading 'total')", environment: "prod", release: "sbx001", frames: [{ filename: "app/checkout/page.tsx", function: "Checkout", lineno: 21 }] });
const entry = await p.waitLog("agent read the bug task", (e) => e.ev === "mcp" && e.tool === "get_task");

View File

@ -40,7 +40,9 @@ describe("Потерянный разговор — новый запуск, а
await tickAt(new Date(t0.getTime() + MIN + 1000));
const resumed = await p.waitLog("resume refused", (e) => e.ev === "exit" && e.reason === "no_conversation");
assert.equal(resumed.gen, "2");
assert.equal((await sess(sid)).watchState?.restarts?.length, 1);
// PEP-268: a vanished tmux session is the platform's failure — no automatic restart spent.
assert.equal((await sess(sid)).watchState?.restarts?.length ?? 0, 0);
assert.equal((await sess(sid)).watchState?.platformFails?.length, 1);
// …Claude no longer has it: the conversation is forgotten, a new one starts at once.
const t1 = new Date(t0.getTime() + MIN + 5000);
@ -53,7 +55,7 @@ describe("Потерянный разговор — новый запуск, а
const start = await p.waitLog("fresh start", (e) => e.ev === "start" && e.gen === "3");
assert.equal(start.resume, null, "no --resume");
assert.ok((start.argv as string[]).some((a) => a.includes("сверься с peppa.get_task и tasks.md") || a.includes("Сверься с peppa.get_task и tasks.md")), "the prompt sends the agent to get_task and tasks.md");
assert.equal((await sess(sid)).watchState?.restarts?.length, 1, "no automatic restart spent");
assert.equal((await sess(sid)).watchState?.restarts?.length ?? 0, 0, "no automatic restart spent");
assert.equal((await eventsOf(sid, "conversation_restarted")).length, 1);
await runner.stopSession(db, sid);
});

View File

@ -0,0 +1,121 @@
// PEP-268: failures of the platform itself (a vanished tmux session, a hang before the agent CLI
// started, a launch on a host or tmux server that is down) keep their own count — the story keeps
// every automatic restart, waits and goes on by itself; the superadmin hears once, on the third.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { after, afterEach, describe, test } from "node:test";
import { and, eq } from "drizzle-orm";
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
import { core, db, project, runner, superadmin, teardown, waitFor } from "./helpers.ts";
const { events } = await import("@peppa/db");
after(teardown);
afterEach(() => runner.setWatchdogSettings(db, ["reset"]));
const MIN = 60_000;
const sess = (id: number) => core.getSession(db, id);
const tickAt = (now: Date, stallMs = 3_600_000) => runner.tick(db, { intervalMs: 0, stallMs, now });
const eventsOf = async (sid: number, type: string) => db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, type)));
const killTmux = async (sid: number) => execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await sess(sid)).tmuxName}`]);
async function storyAtWork(scenario: Parameters<typeof project>[0]) {
const p = await project(scenario);
const ref = await core.resolveTask(db, p.taskKey);
await core.updateTask(db, ref, { status: "in_progress" });
return p;
}
describe("Сбои платформы не списывают попытки задачи", () => {
test("Три сбоя платформы — весь запас попыток", async () => {
const sent = await superadmin();
const p = await storyAtWork({ turns: [[{ say: "Жду." }]], resumeTurns: [[{ say: "Вернулся." }], [{ say: "Ещё раз." }], [{ say: "И снова." }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
let t = Date.now();
const pauses = runner.PLATFORM_RETRY_MIN;
for (let n = 1; n <= 3; n++) {
await killTmux(sid);
await tickAt(new Date(t));
const s = await sess(sid);
assert.equal(s.watchState?.restartReason, "platform:gone");
assert.equal(s.watchState?.platformFails?.length, n);
assert.ok(Math.abs(s.watchState!.restartAt! - (t + pauses[n - 1]! * MIN)) < 1000, `pause ${pauses[n - 1]} min`);
assert.equal((await sent()).length, n < 3 ? 0 : 1, n < 3 ? "quiet before the third" : "the third failure — one message");
t += pauses[n - 1]! * MIN + 1000;
await tickAt(new Date(t));
await p.waitLog(`relaunched ${n}`, (e) => e.ev === "start" && e.gen === String(n + 1));
await p.waitLog(`turn after ${n}`, (e) => e.ev === "prompt" && e.gen === String(n + 1)).catch(() => null);
}
const s = await sess(sid);
assert.deepEqual(s.watchState?.restarts ?? [], [], "no automatic restart of the story spent");
assert.equal((await eventsOf(sid, "auto_restarted")).length, 0);
assert.equal((await eventsOf(sid, "platform_retried")).length, 3);
assert.match((await sent())[0]!, /сбой платформы \(№3 подряд\)/);
assert.equal((await p.pending(sid)).length, 0, "nothing for the owner");
await runner.stopSession(db, sid);
});
test("Падение агента по-прежнему тратит попытку", async () => {
const p = await storyAtWork({ turns: [[{ crash: 1 }]], resumeTurns: [[{ say: "Поднялся." }]] });
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
const t0 = new Date();
await waitFor("restart planned", async () => (await tickAt(t0), (await sess(sid)).watchState?.restartAt));
assert.equal((await sess(sid)).watchState?.restartReason, "crash");
await tickAt(new Date(t0.getTime() + MIN + 1000));
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
assert.equal((await sess(sid)).watchState?.restarts?.length, 1);
assert.equal((await sess(sid)).watchState?.platformFails, undefined);
await runner.stopSession(db, sid);
});
test("Перезапуск не состоялся — сервер агентов недоступен", async () => {
const p = await storyAtWork({ turns: [[{ crash: 1 }]], resumeTurns: [[{ say: "Поднялся." }]] });
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
const t0 = Date.now();
await waitFor("restart planned", async () => (await tickAt(new Date(t0)), (await sess(sid)).watchState?.restartAt));
const socket = process.env.PEPPA_TMUX_SOCKET;
process.env.PEPPA_TMUX_EXTERNAL = "1";
process.env.PEPPA_TMUX_SOCKET = `${socket}-down`;
const t1 = t0 + MIN + 1000;
try {
await runner.restartTick(db, { now: new Date(t1), cfg: await runner.getWatchdogSettings(db), log: () => {} });
} finally {
delete process.env.PEPPA_TMUX_EXTERNAL;
process.env.PEPPA_TMUX_SOCKET = socket;
}
const s = await sess(sid);
assert.deepEqual(s.watchState?.restarts ?? [], [], "the attempt is given back");
assert.equal(s.watchState?.restartReason, "platform:launch");
assert.equal(s.watchState?.platformFails?.length, 1);
assert.ok(Math.abs(s.watchState!.restartAt! - (t1 + MIN)) < 1000, "next try on the platform's schedule");
assert.equal(await core.taskDelayLine(db, (await p.task()).id, { now: new Date(t1) }).then((l) => /^Сбой на нашей стороне, чиним — задача продолжится сама\. Следующая попытка в \d\d:\d\d$/.test(l ?? "")), true);
await runner.restartTick(db, { now: new Date(t1 + MIN + 1000), cfg: await runner.getWatchdogSettings(db), log: () => {} });
// The failed launch took generation 2.
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "3");
assert.deepEqual((await sess(sid)).watchState?.restarts ?? [], []);
assert.equal((await eventsOf(sid, "platform_retried")).length, 1);
await runner.stopSession(db, sid);
});
test("Зависание на старте — сбой платформы, а не попытка задачи", async () => {
const p = await storyAtWork({ turns: [[{ say: "Работаю." }]], hangAtStart: true });
const sid = await p.start();
await p.waitLog("hung", (e) => e.ev === "hang_at_start");
await new Promise((r) => setTimeout(r, 500));
const t0 = Date.now();
await tickAt(new Date(t0)); // remembers the screen
await tickAt(new Date(t0 + 10 * MIN), 5 * MIN); // stalled → alert
assert.equal((await sess(sid)).status, "stalled");
await tickAt(new Date(t0 + 75 * MIN), 5 * MIN); // the alert went unanswered
const s = await sess(sid);
assert.equal(s.watchState?.restartReason, "platform:stall");
assert.deepEqual(s.watchState?.restarts ?? [], []);
await tickAt(new Date(t0 + 77 * MIN), 5 * MIN);
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
assert.deepEqual((await sess(sid)).watchState?.restarts ?? [], [], "still the whole stock");
await runner.stopSession(db, sid);
});
});

View File

@ -405,7 +405,7 @@ const asked = (projectId: number) => core.createTask(db, { projectId, title: "П
const byTitle = async (projectId: number, title: string) => (await core.listTasks(db, { projectId, includeArchived: true })).find((t) => t.title === title);
describe("PEP-197: приёмка предлагает, а не запускает", () => {
test("Scenario: Агент приёмки находит улучшение — задача в «Предложено», диспетчер её не берёт; поломка — тоже в «Предложено» с пометкой (PEP-295)", async () => {
test("Scenario: Агент приёмки находит улучшение — задача в «Предложено», диспетчер её не берёт; поломка — в бэклоге с пометкой", async () => {
page = REAL_PAGE;
const p = await proj();
await asked(p.id);
@ -414,10 +414,8 @@ describe("PEP-197: приёмка предлагает, а не запускае
const idea = (await byTitle(p.id, "Подписать кнопку «Подобрать»"))!;
assert.deepEqual([idea.origin, idea.proposed, idea.severity, idea.status], ["acceptance", true, "important", "backlog"]);
const broken = (await byTitle(p.id, "Страница не открывается без токена"))!;
assert.deepEqual([broken.origin, broken.proposed, broken.severity, broken.status], ["acceptance", true, "breakage", "backlog"], "a breakage waits for «Делать» too, marked");
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [], "the dispatcher sees none of them");
await core.resolveProposals(db, [idea.id, broken.id], "important");
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id).sort(), [idea.id, broken.id].sort(), "«Делать важные» takes both");
assert.deepEqual([broken.origin, broken.proposed, broken.severity, broken.status], ["acceptance", false, "breakage", "backlog"], "a breakage goes to the backlog at once, marked");
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [broken.id], "the dispatcher sees the breakage only");
});
test("Scenario: Повтор открытой задачи не создаётся — к ней дописано замечание; похожая сделанная — в «Предложено» с пометкой", async () => {
@ -454,11 +452,10 @@ describe("PEP-197: приёмка предлагает, а не запускае
const msg = (await core.discussionMessages(db, (await core.ensureProjectChat(db, p.id)).id))[0]!;
const offer = (await core.chatOffers(db, [msg.id])).get(msg.id)!;
assert.equal(offer.kind, "proposals");
assert.deepEqual(offer.items!.map((i) => [i.title, i.open]), [["Починить вход", true], ["Убрать слово «ID» с экрана", true], ["Выровнять отступы в шапке", true]], "PEP-295: a breakage waits for «Делать» too");
assert.deepEqual(offer.items!.map((i) => [i.title, i.open]), [["Починить вход", false], ["Убрать слово «ID» с экрана", true], ["Выровнять отступы в шапке", true]]);
const idea = (await byTitle(p.id, "Убрать слово «ID» с экрана"))!;
const minor = (await byTitle(p.id, "Выровнять отступы в шапке"))!;
await runner.decideProposals(db, pm, [(await byTitle(p.id, "Починить вход"))!.id], "do");
await runner.decideProposals(db, pm, [idea.id], "do");
assert.equal((await byTitle(p.id, idea.title))!.proposed, false, "«Делать» moves it to the backlog");
await runner.decideProposals(db, pm, [minor.id], "no");

View File

@ -56,11 +56,7 @@ describe("PEP-145: системная задача при отсутствии
const backlog = await core.listTasks(db, { projectId: p.id, statuses: ["backlog"] });
assert.equal(backlog[0]!.title, "Продукт должен открываться по ссылке", "first in the backlog");
assert.match(backlog[0]!.description ?? "", /принято задач: 2/);
// PEP-295: a system story waits for «Делать» like any story not from a person.
assert.equal(backlog[0]!.proposed, true);
assert.ok(!(await runner.readyBacklog(db, p.id)).some((t) => t.id === backlog[0]!.id), "the dispatcher does not take it alone");
await core.approveProposal(db, backlog[0]!.id);
assert.equal((await runner.readyBacklog(db, p.id))[0]!.id, backlog[0]!.id, "after «Делать» it goes before the rest");
assert.equal((await runner.readyBacklog(db, p.id))[0]!.id, backlog[0]!.id, "the dispatcher takes it before the rest");
assert.ok(backlog.some((t) => t.id === waiting.task.id));
});

View File

@ -54,7 +54,7 @@ describe("PEP-270: предложения агентов", () => {
assert.ok(ready2.some((x) => x.id === t.id));
});
test("Шестая задача агента за сутки не создаётся, агент получает объяснение; предел общий для всех путей (PEP-295)", async () => {
test("Шестая задача агента за сутки не создаётся, агент получает объяснение; ошибка продукта предел не тратит", async () => {
const tp = await project({ turns: [] });
const p = await core.getProject(db, tp.key);
const call = await agent(tp.key);
@ -67,11 +67,11 @@ describe("PEP-270: предложения агентов", () => {
assert.equal(await byTitle(p.id, "Идея номер 6"), undefined);
assert.equal((await limited(p.id)).length, 1);
// PEP-295: an error of the product and a part of a split count too; a person's story does not.
// An error of the product's users and a part of a person's story don't spend the limit.
await core.createTask(db, { projectId: p.id, title: "Ошибка: TypeError", origin: "incident", severity: "breakage" });
await core.createTask(db, { projectId: p.id, title: "Часть задачи человека", origin: "analyst" });
await core.createTask(db, { projectId: p.id, title: "Задача человека" });
assert.equal(await core.proposalsToday(db, p.id), 7);
assert.equal(await core.proposalsToday(db, p.id), 5);
// The window slides: in 24 hours the room is back.
assert.equal((await core.proposalRoom(db, p.id, new Date(Date.now() + 86_400_000 + 1000))).room, 5);

View File

@ -1,181 +0,0 @@
// PEP-295: one rule for every story not from a person — it is created in «Предложено» and goes to
// work only after «Делать» of the owner or a member; the only exception is the owner's explicit
// choice per project; the limit of 5 a day is shared by every path. Paths covered here: the
// developing agent (MCP), the acceptance agent (a breakage too), errors of the product, the split of
// the analyst, the system story about the link; the reviewer and the feedback agent file nothing —
// reviewer.test.ts / feedback.test.ts; the policies of errors end to end — incidents.test.ts.
import assert from "node:assert/strict";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, describe, test } from "node:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { events, tasks } from "@peppa/db";
import { and, eq } from "drizzle-orm";
import { core, db, project, runner, teardown } from "./helpers.ts";
// No model for the repeat check: a failing call means «not a repeat».
process.env.PEPPA_INTAKE_BIN = "/nonexistent/mock-intake";
const { createAgentServer } = await import("@peppa/mcp/agent");
after(teardown);
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
async function agent(projectKey: string) {
const [a, b] = InMemoryTransport.createLinkedPair();
await createAgentServer(db, { defaultKey: projectKey }).connect(a);
const client = new Client({ name: "mock-agent", version: "0" });
await client.connect(b);
return async (name: string, args: Record<string, unknown> = {}) => {
const r = await client.callTool({ name, arguments: args });
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
};
}
async function fresh() {
const tp = await project({ turns: [] });
const p = await core.getProject(db, tp.key);
// «Сам берёт»: the dispatcher would take anything ready — the rule must hold anyway.
await core.setAutonomy(db, p.id, { pick: "auto" });
return { tp, p };
}
const byTitle = async (projectId: number, title: string) => (await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.title, title))))[0]!;
const ready = async (projectId: number) => (await runner.readyBacklog(db, projectId)).map((t) => t.id);
describe("PEP-295: задача не от человека — только через «Предложено»", () => {
test("Scenario Outline: каждое происхождение не от человека создаётся в «Предложено»; задача человека — нет", async () => {
const { p } = await fresh();
for (const origin of ["agent", "acceptance", "incident", "analyst"] as const) {
// Even when a caller asks for the backlog, the rule wins.
const ref = await core.createTask(db, { projectId: p.id, title: `от ${origin}`, origin, proposed: false });
assert.equal(ref.task.proposed, true, `${origin}: «Предложено»`);
assert.ok(!(await ready(p.id)).includes(ref.task.id), `${origin}: the dispatcher does not see it`);
}
const mine = await core.createTask(db, { projectId: p.id, title: "от человека" });
assert.equal(mine.task.proposed, false);
});
test("Scenario: решение человека — задача сразу в бэклоге и не тратит предел", async () => {
const { p } = await fresh();
const ref = await core.createTask(db, { projectId: p.id, title: "Ошибка: решил человек", origin: "incident", severity: "breakage", decidedByPerson: true });
assert.equal(ref.task.proposed, false);
});
test("Scenario: исключение владельца — только для своего происхождения и только в своём проекте", async () => {
const { p } = await fresh();
const { p: other } = await fresh();
assert.deepEqual(await core.getDirectOrigins(db, p.id), [], "no exceptions by default");
await core.setDirectOrigins(db, p.id, ["incident"]);
assert.equal((await core.createTask(db, { projectId: p.id, title: "ошибка напрямую", origin: "incident", severity: "breakage" })).task.proposed, false);
assert.equal((await core.createTask(db, { projectId: p.id, title: "находка приёмки", origin: "acceptance", severity: "breakage" })).task.proposed, true, "other origins still wait");
assert.equal((await core.createTask(db, { projectId: other.id, title: "ошибка в другом проекте", origin: "incident" })).task.proposed, true, "other projects still wait");
await assert.rejects(core.setDirectOrigins(db, p.id, ["human"]), /Неизвестное происхождение/);
await core.setDirectOrigins(db, p.id, []);
assert.equal((await core.createTask(db, { projectId: p.id, title: "ошибка снова ждёт", origin: "incident" })).task.proposed, true);
const log = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "direct_origins_changed")));
assert.equal(log.length, 2, "the owner's choice is in the journal");
});
test("Scenario: агент разработки через MCP — в «Предложено»", async () => {
const { tp, p } = await fresh();
const call = await agent(tp.key);
assert.equal((await call("create_task", { title: "Экспорт в CSV" })).isError, false);
const t = await byTitle(p.id, "Экспорт в CSV");
assert.deepEqual([t.origin, t.proposed], ["agent", true]);
assert.ok(!(await ready(p.id)).includes(t.id));
});
test("Scenario: поломка от агента приёмки — в «Предложено» с пометкой, «Делать» отдаёт её в бэклог", async () => {
const { p } = await fresh();
const filed = await runner.fileStories(db, p, [{ title: "Кнопка оплаты не работает", description: "Оплата падает.", severity: "breakage" }], { envLabel: "staging", url: "", ignoreFinish: true });
const t = await byTitle(p.id, "Кнопка оплаты не работает");
assert.deepEqual([t.origin, t.severity, t.proposed, t.status], ["acceptance", "breakage", true, "backlog"]);
assert.equal(filed.created[0]!.proposed, true);
assert.ok(!(await ready(p.id)).includes(t.id));
const buttons = runner.proposalButtons(filed.created, "ru").flat().map((b) => b.callback_data);
assert.ok(buttons.includes(`p:${t.id}:do`), "the owner gets «Делать» for a breakage too");
await core.approveProposal(db, t.id);
assert.ok((await ready(p.id)).includes(t.id));
});
test("Scenario: системная задача о ссылке — в «Предложено»; без места в пределе не заводится", async () => {
const { p } = await fresh();
const done = await core.createTask(db, { projectId: p.id, title: "Каталог" });
await core.updateTask(db, done, { status: "done" });
// The limit is used up: the system story waits for the next tick.
for (let i = 0; i < 5; i++) await core.createTask(db, { projectId: p.id, title: `предложение ${i}`, origin: "agent" });
assert.equal(await runner.ensureProductLinkTask(db, p), null);
// A day later there is room again.
const key = await runner.ensureProductLinkTask(db, p, { now: new Date(Date.now() + 86_400_000 + 1000) });
assert.ok(key);
const t = (await core.resolveTask(db, key)).task;
assert.equal(t.title, core.PRODUCT_LINK_TITLE);
assert.equal(t.proposed, true);
assert.ok(!(await ready(p.id)).includes(t.id));
});
test("Scenario: части разбивки — в «Предложено»; «Подходит» у разбивки отдаёт их в бэклог", async () => {
const { tp, p } = await fresh();
const main = await core.resolveTask(db, tp.taskKey);
const part = await core.createTask(db, { projectId: p.id, title: "Часть 2", origin: "analyst" });
await core.markSplitPart(db, part.task.id, main.task.id);
assert.equal(part.task.proposed, true);
const [d] = await core.setDecisions(db, main.task.id, [], { text: "Разделила на 2 задачи", parts: [part.task.id], deferred: [] });
assert.equal(d!.kind, "split");
await runner.confirmTaskDecision(db, main, d!.id, { login: "mock-pm" });
assert.equal((await core.resolveTask(db, part.key)).task.proposed, false, "«Подходит» is the owner's «Делать»");
});
test("Scenario: предел 5 в сутки — общий для всех путей", async () => {
const { tp, p } = await fresh();
await core.createTask(db, { projectId: p.id, title: "ошибка", origin: "incident" });
await core.createTask(db, { projectId: p.id, title: "часть", origin: "analyst" });
await core.createTask(db, { projectId: p.id, title: "находка", origin: "acceptance" });
await core.createTask(db, { projectId: p.id, title: "ссылка", origin: "acceptance", severity: "breakage" });
await core.createTask(db, { projectId: p.id, title: "задача человека" });
assert.deepEqual(await core.proposalRoom(db, p.id), { room: 1, limit: 5, used: 4 });
const call = await agent(tp.key);
assert.equal((await call("create_task", { title: "пятая" })).isError, false);
const sixth = await call("create_task", { title: "шестая" });
assert.equal(sixth.isError, true, "the developing agent is refused when other paths used the limit");
});
test("Каждый вызов createTask в коде — известный путь (новый путь создания задачи не обойдёт правило незаметно)", () => {
// Path → how the rule holds there. A new call site fails this test until it is classified here.
const KNOWN: Record<string, string> = {
"packages/core/src/feedback.ts": "human — решение суперадмина по обращению",
"packages/core/src/incidents.ts": "incident — «Предложено», кроме решения человека и исключения владельца",
"packages/mcp/src/manager.ts": "human — человек через свой ИИ-клиент",
"packages/mcp/src/agent.ts": "agent — «Предложено»",
"packages/cli/src/index.ts": "human — администратор",
"packages/runner/src/product-link.ts": "acceptance — «Предложено»",
"packages/runner/src/product-review.ts": "acceptance — «Предложено»",
"packages/runner/src/intake.ts": "analyst — «Предложено»",
"packages/runner/src/message-intent.ts": "human — кнопка «Создать» в чате",
"packages/runner/src/runners.ts": "human — «Оформить стори» из свободного раннера",
"packages/runner/src/planner.ts": "human — план эпика применяет человек",
"packages/runner/src/gitea-events.ts": "human — issue владельца или участника",
"apps/web/app/(app)/actions.ts": "human — «+ Задача»",
"apps/bot/src/bot.ts": "human — сообщение в Telegram",
};
const found = new Set<string>();
const walk = (dir: string) => {
for (const name of readdirSync(dir)) {
if (name === "node_modules" || name === ".next" || name === "test") continue;
const path = join(dir, name);
if (statSync(path).isDirectory()) walk(path);
else if (/\.tsx?$/.test(name) && /\bcreateTask\(db,/.test(readFileSync(path, "utf8"))) found.add(relative(ROOT, path));
}
};
for (const dir of ["packages/core/src", "packages/runner/src", "packages/mcp/src", "packages/cli/src", "apps/web", "apps/bot/src"]) walk(join(ROOT, dir));
assert.deepEqual([...found].sort(), Object.keys(KNOWN).sort());
// Paths not from a person pass their origin: the rule in createTask sees them.
for (const [file, why] of Object.entries(KNOWN)) {
if (why.startsWith("human")) continue;
const origin = why.split(" ")[0];
assert.match(readFileSync(join(ROOT, file), "utf8"), new RegExp(`createTask\\(db,[^;]*origin: "${origin}"`, "s"), `${file} passes origin ${origin}`);
}
});
});

View File

@ -117,7 +117,7 @@ describe("Авто-перезапуск упавшего раннера", () =>
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await sess(sid)).tmuxName}`]);
const t0 = new Date();
await tickAt(t0);
assert.equal((await sess(sid)).watchState?.restartReason, "gone");
assert.equal((await sess(sid)).watchState?.restartReason, "platform:gone", "PEP-268: a vanished tmux session is the platform's failure");
await tickAt(new Date(t0.getTime() + MIN + 1000));
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
await runner.stopSession(db, sid);

View File

@ -103,8 +103,6 @@ describe("Агент-ревьюер до ревью PM", () => {
const tool = await t.p.waitLog("update_task answered", (e) => e.ev === "mcp" && e.tool === "update_task");
assert.match(String(tool.text), /reviewer agent is checking/);
await t.p.waitLog("findings delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("деление на ноль возвращает Infinity") && String(e.prompt).includes("src/divide.ts:1"));
// PEP-295: the reviewer's remarks go to the agent; no story is filed.
assert.deepEqual((await core.listTasks(db, { projectId: t.proj.id, includeArchived: true })).map((x) => x.id), [(await t.ref()).task.id], "the reviewer files no story");
const [call] = calls();
assert.equal(call?.story, t.p.taskKey);
assert.ok(call?.diff, "the reviewer got the PR diff");

View File

@ -1,15 +0,0 @@
# PEP-287: какие образы peppa/platform убрать после удачной выкатки (каждый ~4 ГБ, автовыкатка — после
# каждого мержа). Остаются текущий, тег отката и самые новые — всего три. Теги только из hex (SHA);
# прочие (latest, <none>) не трогаем.
# Вход (stdin): строки «CreatedAt<TAB>tag» из `docker image ls --format '{{.CreatedAt}}\t{{.Tag}}' peppa/platform`.
# Выход: теги к удалению, по одному в строке.
platform_images_to_remove() { # <текущий тег> [<тег отката>]
sort -r | awk -F'\t' -v cur="$1" -v prev="${2:-}" -v keep="${PEPPA_PLATFORM_IMAGES_KEEP:-3}" '
$2 ~ /^[0-9a-f]+$/ && !seen[$2]++ { tags[n++] = $2 }
END {
kept = 0
for (i = 0; i < n; i++) if (tags[i] == cur || tags[i] == prev) { k[tags[i]] = 1; kept++ }
for (i = 0; i < n && kept < keep; i++) if (!k[tags[i]]) { k[tags[i]] = 1; kept++ }
for (i = 0; i < n; i++) if (!k[tags[i]]) print tags[i]
}'
}

View File

@ -9,9 +9,7 @@
# PEP-256: tmux-сервер агентов (сервис `tmux`, контейнер peppa-tmux) выкатка не пересоздаёт — агенты
# переживают её; если его нет — поднимает (тег образа в $PEPPA_HOME/tmux.tag). Обновить его образ —
# только явно: scripts/platform-deploy.sh --tmux (текущий тег платформы; агенты обрываются один раз);
# 7. PEP-287: после удачной выкатки — три образа peppa/platform (текущий и два для отката), прочие удаляются;
# временная строка cron peppa-build-cache-prune убирается (кэш сборки чистит вачдог).
# 8. PEP-242: шаблон проектов (template/ цели) → репозиторий шаблона в Gitea; сбой — сообщение
# 7. PEP-242: шаблон проектов (template/ цели) → репозиторий шаблона в Gitea; сбой — сообщение
# суперадмину (peppa template push --alert), выкатку не откатывает.
# Usage: scripts/platform-deploy.sh [--wait] [--no-ci] [<sha>] PEPPA_PLATFORM_DRY=1 — только план.
# scripts/platform-deploy.sh --auto — PEP-276: выкатить HEAD main, если прод отстаёт и проверки main
@ -23,7 +21,7 @@
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"
WAIT=0 NOCI=0 TMUX_ONLY=0 AUTO=0 TARGET=""
for a in "$@"; do case "$a" in --wait) WAIT=1;; --no-ci) NOCI=1;; --tmux) TMUX_ONLY=1;; --auto) AUTO=1;; -h|--help) sed -n '2,21p' "$0"; exit 0;; *) TARGET=$a;; esac; done
for a in "$@"; do case "$a" in --wait) WAIT=1;; --no-ci) NOCI=1;; --tmux) TMUX_ONLY=1;; --auto) AUTO=1;; -h|--help) sed -n '2,19p' "$0"; exit 0;; *) TARGET=$a;; esac; done
# PEP-276: раскладка сервера — рабочая копия ~/peppa/src, настройки ~/peppa/.env, данные ~/peppa/home.
# Без этих умолчаний скрипт на сервере падал сразу («.env: No such file»), выкатывали только руками.
# Раскладка сервера важнее ~/.peppa: 24.11 выкатка из cron взяла пустой ~/.peppa (его создал прошлый
@ -175,27 +173,6 @@ done
rm -f "$JAR"
echo "$SHORT" >"$PREV_FILE"
rm -f "$PEPPA_HOME/platform-deploy.failed"
# PEP-287: старые образы платформы (по ~4 ГБ) — остаются текущий и два для отката. Занятый контейнером
# образ (peppa-tmux, остановленные peppa-test-*) docker без -f не удалит — это не ошибка.
. "$ROOT/scripts/lib/platform-images.sh"
prune_platform_images() {
local t gone=0
for t in $(docker image ls --format '{{.CreatedAt}} {{.Tag}}' peppa/platform | platform_images_to_remove "$SHORT" "$PREV"); do
if docker rmi "peppa/platform:$t" >/dev/null 2>&1; then gone=$((gone + 1)); else say "образ peppa/platform:$t занят — оставлен"; fi
done
say "старых образов платформы удалено: $gone"
}
prune_platform_images || say "уборка старых образов не удалась — выкатка не откатывается"
# PEP-287: 26.11 до выкатки этой задачи кэш сборки чистила временная строка cron (~/peppa/bin/disk-prune.sh).
# Теперь это делает вачдог раз в час — строка и скрипт убираются один раз, первой же выкаткой.
remove_temp_prune_cron() {
command -v crontab >/dev/null 2>&1 || return 0
crontab -l 2>/dev/null | grep -q peppa-build-cache-prune || return 0
crontab -l 2>/dev/null | grep -v peppa-build-cache-prune | crontab - || return 1
rm -f "$HOME/peppa/bin/disk-prune.sh"
say "временная чистка кэша сборки (cron peppa-build-cache-prune) убрана — её делает вачдог"
}
remove_temp_prune_cron || say "строку cron peppa-build-cache-prune убрать не удалось — уберите вручную"
# PEP-242: с 15.11 по 23.11 шаблон в Gitea никто не обновлял — агенты брали старые правила. Теперь его
# отправляет каждая выкатка — из уже запущенного watchdog цели (в образе template/, git с помощником бота,
# сеть и .env — как у сервисов).