Compare commits

..

19 Commits

Author SHA1 Message Date
6778b99161 PEP-213: память после rebase — без дублей, в предел
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 35с
peppa/test test: success за 1379с
peppa-ci / ci (pull_request) Successful in 25m19s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:56:43 +00:00
1461fd9ffd PEP-213: замер медленных страниц и SQL, warning в Bugsink, сводка на /observability
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 14:56:43 +00:00
8ba72b0263 Merge pull request 'PEP-242: шаблон проектов уходит в Gitea сам; блок секретов проектам без затирания доработок' (#229) from task/pep-242 into main
Some checks failed
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 44с
peppa/build build: success за 32с
peppa/test test: success за 1418с
peppa-ci / ci (push) Has been cancelled
2026-11-23 14:49:21 +00:00
f8f6d735e6 PEP-242: память проекта в пределе после мержа main (убран пункт, повторяющий AGENTS.md)
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 44с
peppa/build build: success за 32с
peppa/test test: success за 1253с
peppa-ci / ci (pull_request) Successful in 23m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:56:59 +00:00
076e3c42cc Merge branch 'main' into task/pep-242
Some checks failed
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 44с
peppa/build build: success за 31с
peppa/test test: failure за 1250с
peppa-ci / ci (pull_request) Failing after 23m44s
2026-11-23 08:32:22 +00:00
7bedf9d342 PEP-242: якорь блока секретов не зависит от названия платформы (после PEP-243 «из FORGE»)
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 42с
peppa/build build: success за 31с
peppa/test test: success за 1278с
peppa-ci / ci (pull_request) Successful in 23m28s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:08:01 +00:00
44a00668c8 Merge pull request 'PEP-223: напоминание о простое каждые 30 минут' (#212) from task/pep-223 into main
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 45с
peppa/build build: success за 31с
peppa/test test: success за 1250с
peppa-ci / ci (push) Successful in 22m44s
2026-11-23 07:38:14 +00:00
4fa58fa21d Merge branch 'main' into task/pep-242
Some checks failed
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 45с
peppa/build build: success за 31с
peppa/test test: failure за 1244с
peppa-ci / ci (pull_request) Failing after 23m9s
2026-11-23 07:25:57 +00:00
dad7d80f03 PEP-223: AGENTS.md — один абзац Observability
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 47с
peppa/build build: success за 31с
peppa/test test: success за 1268с
peppa-ci / ci (pull_request) Successful in 23m0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 07:07:49 +00:00
073c47bb3e PEP-223: память после rebase — без дублей, в пределе
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 07:07:41 +00:00
66f9de2732 PEP-223: архив change, память и AGENTS.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 07:07:41 +00:00
fea2c4b93a PEP-223: напоминания о затянувшемся сбое мониторинга и сервисов раз в 30 минут
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 07:07:41 +00:00
15668145e7 Merge branch 'main' into task/pep-242
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 33с
peppa/test test: success за 1315с
peppa-ci / ci (pull_request) Successful in 24m41s
2026-11-23 06:47:29 +00:00
c75b7c6f3d PEP-242: purpose спеки project-template
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 31с
peppa/test test: success за 1262с
peppa-ci / ci (pull_request) Successful in 23m0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:07:56 +00:00
f12281fe85 PEP-242: archive change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:07:50 +00:00
2d1b7f755a PEP-242: память проекта — шаблон уходит сам
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:07:45 +00:00
60077e5b2d PEP-242: AGENTS.md и памятка сервера — шаблон уходит сам, блок секретов проектам
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:07:33 +00:00
badad190eb PEP-242: шаблон уходит в Gitea с выкаткой, сверка в вачдоге, ci connect --secrets-only
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:07:20 +00:00
2c01d3330d PEP-242: proposal — шаблон уходит в Gitea сам, блок секретов проектам
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:02:58 +00:00
37 changed files with 1180 additions and 54 deletions

View File

@ -3,7 +3,7 @@
Пишет агент через `remember` (PEP-30); не повторяй AGENTS.md.
## Команды
- Тесты из шелла Claude: `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test --test-reporter=spec test/<file>.test.ts` (иначе node --test и `pnpm run ci` молча ничего не запускают). В свежем worktree сначала `pnpm install --frozen-lockfile`.
- Тесты из шелла Claude: `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test --test-reporter=spec test/<file>.test.ts` (иначе тесты молча не запускаются). В свежем worktree сначала `pnpm install --frozen-lockfile`.
- CLI против живой системы (сервер): `docker exec peppa-watchdog peppa …` (docs/SERVER.md).
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate` (Node < 26 — `node packages/cli/src/index.ts`), `DATABASE_URL=… node apps/web/scripts/mock-ui-seed.ts mock-pm`, в apps/web `node server.ts [--dev] -p <порт>` с тем же env + `PEPPA_WEB_URL=http://localhost:<порт> PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off`; вход — `peppa web login-link mock-pm`; «Инженер» — settings `ui.mode:<userId>` = `"engineer"`.
- Словарь: `pnpm lint`; почистил тексты экрана — `pnpm lint --update` (baseline только уменьшать); новое слово в «Нельзя» — сразу `pnpm lint`, оно может стоять в чужих текстах.
@ -11,14 +11,15 @@
## Грабли
- `resumeSession` у сессии без `conversationId` пишет событие `started`, не `resumed`. Скриншоты staging (PEP-209) — отчёт `screenshots` с `env`.
- `next dev` правит apps/web/AGENTS.md (он в git — `git checkout`, не `rm`) и next-env.d.ts — не коммитить. Открывать `http://localhost:<порт>`, не 127.0.0.1 (allowedDevOrigins — без гидрации кнопки молчат).
- Headless Chrome: playwright-core + `chrome-headless-shell` (Mac: `~/.hermes/hermes-agent/node_modules`), cookie из curl-jar в `ctx.addCookies`; getUserMedia подменяй; обрыв канала — `globalThis.__peppaLive.ws.close()`. Без браузера — WebSocket-клиент Node (`headers: {cookie, origin}`).
- Headless Chrome: playwright-core + `chrome-headless-shell` (Mac: `~/.hermes/hermes-agent/node_modules`), cookie из curl-jar в `ctx.addCookies`; getUserMedia подменяй; обрыв канала — `globalThis.__peppaLive.ws.close()`. Без браузера — WebSocket Node (`headers: {cookie, origin}`).
- CLI из теста с моком в том же процессе — только async execFile. Тест testkit не импортирует apps/web статически (типы Next ломают ProcessEnv) — `import(new URL(…).href)`.
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
- mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`.
- git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент.
- Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
- Скорость: замер `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (копию базы сначала `peppa db migrate`, иначе без индексов PEP-214 в 15 раз медленнее); N+1 по проектам — `workLineIndex`. `liveHub` на globalThis переживает HMR — после правок live.ts перезапусти server.ts. Не `pkill -f next-server` — убьёт живой веб.
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (копию базы сначала `peppa db migrate`: индексы PEP-214); N+1 — `workLineIndex`. `liveHub` на globalThis переживает HMR: правишь live.ts — перезапусти server.ts. Не `pkill -f next-server`.
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
@ -28,7 +29,7 @@
- Продукт на другой docker переносить только с данными (PEP-231): `scripts/server-move/products-move.sh` — тома со сверкой сумм, Postgres дампом, без отчёта о выкладке; `peppa deploy redeploy` поднимает продукт с пустыми томами и шлёт владельцу «новая версия».
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
- Сервер (PEP-230): памятка — docs/SERVER.md. В контейнере агента нет глобального git: автор коммита — `gitRelayEnv` (GIT_AUTHOR_*); на старом образе — `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
- Песочница-контейнер раннера: нет tmux, openspec и Node 26 (есть 22). tmux — `.deb` с deb.debian.org (curl pool/main: tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + обёртка с LD_LIBRARY_PATH в PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; e2e на 22 — локально снизить MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — `.deb` с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; e2e на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
## Соглашения
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
@ -48,7 +49,6 @@
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:<messageId>`, `INTENT_TEXT`).
- Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask).
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
- Чат проекта на месте (PEP-228): новые сообщения — область `chat:<id>` (на зрителя), вид — `apps/web/lib/chat-live.ts` (`setLiveChatView`), рисует `ChatLiveFeed`; меняешь вид сообщения на странице чата — поменяй и там.
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
@ -57,7 +57,7 @@
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.
- Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`.
- После правок `template/` — `scripts/push-template.sh` и `peppa ci connect <KEY>` старым проектам.
- `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect <KEY> [--secrets-only]`.
- Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac.
- Эталон (PEP-184, PM): подписка прогона — наименее загруженная свободная из общего пула; про подписку PM не спрашивать.
- Распознавание речи — свой faster-whisper (`<Dictate>`, MediaRecorder), не Web Speech API. Вход через Google: по почте учётки не склеиваем.

View File

@ -106,8 +106,9 @@
- **Продукты с данными (PEP-231)**: продукт проекта переезжает на другой docker скриптом `scripts/server-move/products-move.sh` (Mac) + `product-up.sh` (сервер): версия — тег образа работающего контейнера, тома — tar со сверкой сумм, Postgres — `pg_dump`/`pg_restore`, отчёт о выкладке в Peppa не уходит; предпроверка не даёт тронуть сервер, где уже есть контейнеры или тома проекта; `rehearse` — репетиция без простоя, `previews`, `runner stop|server|mac`. `peppa deploy redeploy` — только для продуктов без данных. Адрес продукта без контейнера на Mac идёт на сервер правилом `peppa-server-products` (`mac-route.sh routes`, приоритет 2 — выше страниц Gitea, ниже контейнера). Тест `products-move.test.ts`
- **Название FORGE (PEP-243)**: платформа для людей называется «FORGE» (`PRODUCT_NAME` в `@peppa/shared/i18n`, логотип `components/Brand.tsx`, значок `public/icon.svg`; в `docs/glossary.md` «Пеппа», «Peppa», «Peppa FACTORY» — в колонке «Нельзя», `pnpm lint` ловит их в текстах для людей). Агентам в подсказках и `template/RULES.md` платформа тоже названа FORGE. Внутренние имена не менялись: CLI `peppa`, `PEPPA_*`, MCP-сервер `peppa` и его инструменты, контейнеры `peppa-*`, cookie, ключи `PEP-N`, этот документ. Адреса: `forge.telecom.quest` и `peppa.telecom.quest` ведут на один веб (правила Traefik сервера `~/peppa/traefik/dynamic/peppa.yml` и Mac — `mac-route.sh`); веб берёт адрес из запроса (`publicOrigin`), поэтому вход, cookie и `/mcp` работают на обоих; ссылки в сообщениях — `PEPPA_WEB_URL`. Новый адрес платформы = правило в обоих Traefik + адрес возврата в Google Cloud (`<адрес>/auth/google/callback`)
- **Выкатка на сервере и Bugsink (PEP-240)**: `scripts/platform-deploy.sh` на Linux без доступа к сокету docker зовёт `sudo -E docker` сам (весь скрипт под sudo нельзя — сервисы получат uid 0), копию базы без `sqlite3` на хосте делает утилитой из образа цели. Bugsink на сервере с 2026-11-23 (`peppa-bugsink`, том `peppa-bugsink-data`): по имени контейнера отвечает только из-за `ALLOWED_HOSTS` в compose (иначе 400 — принимает лишь хост `BASE_URL` и localhost); вебхуки проектов — `BUGSINK_WEBHOOK_BASE=http://peppa-web:3100` (`host.docker.internal` на Linux не видит порт, слушающий 127.0.0.1 хоста), переписать сохранённые — `scripts/server-move/bugsink-move.sh webhooks` (= `peppa project errors <KEY>` каждому проекту с источниками). Тест `server-deploy.test.ts`
- **Шаблон уходит сам (PEP-242)**: `runner/template-sync.ts` — `syncTemplate({push})` (клон шаблона ботом, содержимое = `template/`, `git add -A`; без `push` — только «отстаёт», коммит «Update Peppa template (<sha>)»), `pushTemplateOrAlert` (сбой — `alertAdmins` `template:push:<commit>`), `templateSyncTick` (вачдог раз в час, `PEPPA_TEMPLATE_SYNC=off`, в тестах выключен; отстаёт — одно сообщение на коммит, `template.drift`). Выкатка (`platform-deploy.sh`, `live-deploy.sh`) в конце зовёт `peppa template push --alert` — отдельный `scripts/push-template.sh` после мержа больше не нужен. CLI `peppa template push|check`. Блок секретов в выкладку существующего проекта — `peppa ci connect <KEY> --secrets-only` (`addSecretsBlock`: блок перед `dc()`, `${override:+-f "$override"}` в строке compose, вызов после `report deploying`; свой `trap … EXIT` или нет якоря — отказ; ветка `peppa/secrets`). Тест `template-sync.test.ts`
- **Адреса без Mac (PEP-231)**: `core/edge-dns.ts` — свой туннель Cloudflare сервера (`peppa edge tunnel <name>`: токен в `$PEPPA_HOME/cloudflared/token`, сервис `cloudflared` профиля `edge` в `infra/docker-compose.yml`, одно правило входа → `PEPPA_EDGE_SERVICE` = Traefik сервера) и сверка DNS (`edgeHosts` → `syncEdge`: нет записи — CNAME на `<tunnel>.cfargotunnel.com`, CNAME на другой туннель — переписать, чужое — не трогать); `edgeDnsTick` (runner/edge-dns.ts) в тике вачдога раз в 5 мин, только при `CLOUDFLARE_API_TOKEN|ACCOUNT_ID|ZONE_ID|TUNNEL_ID`, `PEPPA_EDGE_DNS=off`; CLI `peppa edge sync [--dry-run]`. Перевыкатка продуктов на тех же коммитах — `redeployProject` (runner/deploy.ts; ей же пользуется перезапуск после секретов PEP-112), CLI `peppa deploy redeploy <KEY|--all> [--dry-run]`. Bugsink в compose — в сети `traefik_default` с метками Traefik. Порядок переезда — `docs/SERVER.md`, скрипты `scripts/server-move/{server-products,bugsink-move,server-edge,mac-products-stop}.sh`. Мок — `mock-cloudflare`; тест `server-edge.test.ts`
- **Observability (PEP-202)**: сервис `peppa-observer` (`apps/observer`, launchd `quest.telecom.peppa.observer`, `scripts/install-launchd.sh observer`, лог `~/.peppa/observer.log`) выполняет мониторинги; всё в `core/observe.ts` + `core/observe-checks.ts`: своя база `PEPPA_OBSERVE_DB` (`$PEPPA_HOME/observe.db`, `node:sqlite` напрямую, схема по `user_version`; таблицы `monitors`, `monitor_checks`, `monitor_incidents`, `observe_meta`), виды http (код, текст, задержка, срок сертификата; без ответа — повтор через запасной DNS) / tcp / dns (`probeDns`: системный DNS против `PEPPA_FALLBACK_DNS`, ok · dns · blocked · down; заменил проверку сети PEP-201 в вачдоге) / internet / heartbeat (`/api/observe/hb/<token>`, без входа). `observeTick` (раз в секунду, не ждёт, ≤16 параллельно), `recordCheck` — состояния unknown/up/degraded/down: смена после `fail_threshold` (3) плохих или `recover_threshold` (2) хороших подряд, сбой — `monitor_incidents`; сообщение — `postToChannel(services, mon:ch:obs:<id>:<сбой>:<состояние>)`, без канала — `alertAdmins`; упавшие вместе с интернетом — `quiet`, без сообщений. `pruneObserve` — журнал 7 дней (`PEPPA_OBSERVE_RETENTION_DAYS`). Встроенные (`seedMonitors`, один раз): «Интернет», «eGov relay», «eGov relay — DNS». Веб `/observability` (+ `/[id]`) — только суперадмин; MCP `list_monitors|get_monitor|create_monitor|update_monitor|pause_monitor|delete_monitor` (`packages/mcp/src/monitors.ts`): удалённый — суперадмин, агента — только проект `PEPPA_PLATFORM_KEY`; события `monitor_created|updated|deleted` в журнале платформенного проекта. `serviceStatus` считает `observer` только после первого heartbeat. Тест `observability.test.ts`
- **Observability (PEP-202)**: сервис `peppa-observer` (`apps/observer`, launchd `quest.telecom.peppa.observer`, `scripts/install-launchd.sh observer`, лог `~/.peppa/observer.log`) выполняет мониторинги; всё в `core/observe.ts` + `core/observe-checks.ts`: своя база `PEPPA_OBSERVE_DB` (`$PEPPA_HOME/observe.db`, `node:sqlite` напрямую, схема по `user_version`; таблицы `monitors`, `monitor_checks`, `monitor_incidents`, `observe_meta`), виды http (код, текст, задержка, срок сертификата; без ответа — повтор через запасной DNS) / tcp / dns (`probeDns`: системный DNS против `PEPPA_FALLBACK_DNS`, ok · dns · blocked · down; заменил проверку сети PEP-201 в вачдоге) / internet / heartbeat (`/api/observe/hb/<token>`, без входа). `observeTick` (раз в секунду, не ждёт, ≤16 параллельно), `recordCheck` — состояния unknown/up/degraded/down: смена после `fail_threshold` (3) плохих или `recover_threshold` (2) хороших подряд, сбой — `monitor_incidents`; сообщение — `postToChannel(services, mon:ch:obs:<id>:<сбой>:<состояние>)`, без канала — `alertAdmins`; упавшие вместе с интернетом — `quiet`, без сообщений. **Напоминания (PEP-223)**: пока сбой `down` (или `degraded` при `remind_degraded`) — `remindIncidents` в `observeTick` раз в `monitors.remind_min` (null — `PEPPA_OBSERVE_REMIND_MIN`, 30; 0 — нет), захват по счётчику `monitor_incidents.reminders` (ключ `…:r<N>`, рестарт не дублирует), неотправленное напоминание того же сбоя удаляется перед новым (ночью — одно утреннее); `checkServices` напоминает админам с тем же сроком. `pruneObserve` — журнал 7 дней (`PEPPA_OBSERVE_RETENTION_DAYS`). Встроенные (`seedMonitors`, один раз): «Интернет», «eGov relay», «eGov relay — DNS». Веб `/observability` (+ `/[id]`) — только суперадмин; MCP `list_monitors|get_monitor|create_monitor|update_monitor|pause_monitor|delete_monitor` (`packages/mcp/src/monitors.ts`): удалённый — суперадмин, агента — только проект `PEPPA_PLATFORM_KEY`; события `monitor_created|updated|deleted` в журнале платформенного проекта. `serviceStatus` считает `observer` только после первого heartbeat. Тест `observability.test.ts`
- **Канал платформы и дайджест Пеппы (PEP-60)**: `core/platform-channel.ts`, настройки в `settings` `platform.telegram_channel` (Chat ID, `check` — результат `checkPlatformChannel`: Bot API `getMe`→`getChat`→`getChatMember`, «бот не видит канал — добавьте его администратором» / нет права публикации; события releases/services/digest; `digest.time/timezone/users`, личные чаты по умолчанию выкл). В канал пишет только при `check.ok` (`postToChannel`, outbox; сервисные ключи `mon:ch:*` — вачдог доставит сам, если упал бот); неработающий канал вачдог перепроверяет раз в час (`recheckPlatformChannel`). События: `checkServices` — одно «не отвечает» и одно «снова работает — простой N мин» на простой, «перезапущен» при смене процесса без простоя (`monitor.process:<service>`, heartbeat несёт `commit`); `platformBuildTick` (runner/platform-build.ts) — HEAD корня ≠ `platform.build` и входит в `main` → «🚀 Peppa vX · sha» + стори из коммитов (первый раз только запоминает). `platformDigestTick` (вачдог): «Что нового» (done-стори `PEPPA_PLATFORM_KEY`, сборки) + «Сейчас» (версия, сервисы, раннеры, вопросы, лимиты), пустой не шлётся, в канал и пользователям событием уведомлений `platform`. Веб `/platform` (суперадмин), CLI `peppa platform channel chat=<id> [k=v…]|check`, `peppa platform digest [now]`. Мок — каналы в `mock-telegram` (`addChannel`)
- **Очередь проверок и Codex (PEP-205)**: `checksQueueTick` (порог `checksStuckMin` 30) определяет причину «none» по не-`peppa/*` статусам коммита (`job_failed` → PR переоткрывается через `closePullRequest`+`reopenPullRequest`, ≤2 раз на коммит; `queue`; `no_job`), `checks.queue` `{since, win}` — суперадмину сообщение и повтор раз в 2 ч, пока запись есть (`checksQueueStanding`), `autoPickSlots`/`dispatch` не берут задачи проектов с проверками (`projectHasChecks`) и `requestRebase` молчит (также пока идут проверки головы PR). `actRunnerTick` (runner/act-runner.ts, `PEPPA_ACT_RUNNER_GUARD=off`, контейнер `PEPPA_ACT_RUNNER_CONTAINER`): `docker inspect` → не `running` или очередь стоит без единого задания ≥10 мин → `docker restart`, событие `act_runner_restarted`. Агент не ждёт проверок: MCP `update_task(status: review)` при идущих проверках пишет `review.wanted:<taskId>` (runner/review-wanted-state.ts — лёгкий, грузится хуком; Stop-хук и `wakeOnGreen` молчат), `reviewWantedTick` (вачдог, раз в минуту) на зелёных делает `requestReview`/`review` + `sendReviewCard`, на красных/конфликте снимает отметку. Предел задач на код: `AgentLimits.inRepo` (4; `peppa project agent-limits KEY inRepo=N`) в `startOrWait` → очередь ожидания места. Codex: `LIMIT_SCREEN_RE` принимает `’`; мёртвый pane с лимитом → `recordLimit`; меню «Switch to …?» — `-c notice.hide_rate_limit_model_nudge=true` + сторож (`codex-screen.ts`: цифра «Keep current model»); `account/read failed` → `onLoginFailure` (recovery.ts: `watchState.restartFree`, паузы 1/5/15 мин, 4-й сбой → подписка `auth_error`, `tryRotate(…, "login")`). Моки: `mock-codex` действия `menu`/`loginFail`, `mock-docker restart`, `MockGitea.reopens`. Тесты `platform-delays.test.ts` (PEP-205), `codex-recovery.test.ts`
- **Ночная тишина (PEP-208)**: с 23:00 до 08:00 (`PEPPA_TZ`) никому, включая суперадмина, не уходят новые сообщения Telegram (личные, группы, канал) и push — `core/night-quiet.ts` `inNightQuiet` на выборке очередей: `dueOutbox` и `pendingMonitorMessages` ночью отдают только `editMessageText`, `flushPushOutbox` — ничего; строки ждут `pending` без траты попыток и уходят утром (отвеченные вопросы бот отбрасывает). Прямые ответы бота на сообщение/кнопку человека не через очередь — проходят. Окно — `PEPPA_NIGHT_QUIET` (`HH:MM-HH:MM` | `off`); в тестах и на `peppa-dev` выключено. Новый канал отправки людям — только через эти очереди. Тест `night-quiet.test.ts`

View File

@ -2,11 +2,11 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Trash2 } from "lucide-react";
import { describeTarget, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
import { describeTarget, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Hidden } from "@/components/cards";
import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability";
import { CheckStrip, KIND_LABEL, MonitorFields, OutageLine, pct, StateBadge } from "@/components/Observability";
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@ -58,6 +58,7 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr
<span className="ml-auto"><CheckStrip recent={m.recent} t={t} /></span>
</div>
{m.lastDetail?.reason ? <p className="m-0 text-sm text-destructive">{String(m.lastDetail.reason)}</p> : null}
<p className="m-0 text-sm empty:hidden"><OutageLine m={m} t={t} /></p>
{m.kind === "heartbeat" && (
<p className="m-0 text-xs text-muted-foreground">
{t("Сервис отмечается запросом GET или POST по адресу:")} <code className="break-all">{describeTarget(m, web)}</code>
@ -65,6 +66,8 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr
)}
<p className="m-0 text-xs text-muted-foreground">
{t("Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}", { n: m.intervalSec, f: m.failThreshold, r: m.recoverThreshold, who: m.createdBy })}
{" · "}
{(m.remindMin ?? observeRemindMin()) ? t("напоминание раз в {n} мин", { n: m.remindMin ?? observeRemindMin() }) : t("без напоминаний")}
</p>
<div className="flex flex-wrap gap-2">
<form action={pauseMonitorAction}>
@ -82,7 +85,7 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr
<Disclosure summary={t("Изменить")}>
<form action={updateMonitorAction} className="flex flex-col gap-2">
<Hidden fields={{ id: m.id }} />
<MonitorFields t={t} m={m} kindFixed />
<MonitorFields t={t} m={m} kindFixed remindDefault={observeRemindMin()} />
<Button size="sm" variant="default" className="self-start">{t("Сохранить")}</Button>
</form>
</Disclosure>
@ -99,6 +102,7 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr
<span>{when(i.startedAt)} → {i.endedAt ? when(i.endedAt) : t("сейчас")}</span>
<span className="text-muted-foreground">{i.reason}</span>
{i.quiet && <span className="text-xs text-muted-foreground">{t("(вместе с интернетом, без сообщения)")}</span>}
{i.reminders > 0 && <span className="text-xs text-muted-foreground">{t("напоминаний: {n}", { n: i.reminders })}</span>}
</li>
))}
</ul>

View File

@ -56,6 +56,9 @@ const numbers = (f: FormData) => ({
intervalSec: str(f, "intervalSec") ? Number(str(f, "intervalSec")) : undefined,
failThreshold: str(f, "failThreshold") ? Number(str(f, "failThreshold")) : undefined,
recoverThreshold: str(f, "recoverThreshold") ? Number(str(f, "recoverThreshold")) : undefined,
// PEP-223: empty — the common default; the form always carries the whole state.
remindMin: str(f, "remindMin") ? Number(str(f, "remindMin")) : null,
remindDegraded: f.get("remindDegraded") === "1",
});
export async function createMonitorAction(f: FormData) {

View File

@ -2,11 +2,11 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Plus } from "lucide-react";
import { describeTarget, egovLoginSummary, errorScope, errorsOverview, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
import { describeTarget, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Hidden } from "@/components/cards";
import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability";
import { CheckStrip, KIND_LABEL, MonitorFields, OutageLine, pct, StateBadge } from "@/components/Observability";
import { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown, ErrorsSummary } from "@/components/Errors";
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
@ -19,7 +19,6 @@ import { createMonitorAction, pauseMonitorAction } from "./actions";
export const dynamic = "force-dynamic";
export async function generateMetadata() {
const t = await getT();
return { title: t("Observability — FORGE") };
@ -102,7 +101,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
<div className="max-w-4xl">
<Flash error={error} />
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
{t("Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы. Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.")}
{t("Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы, пока не работает — напоминание раз в 30 минут (настраивается у мониторинга). Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.")}
</PageHeader>
<Tabs tab="monitors" t={t} />
{retention && (
@ -140,6 +139,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
) : null}
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{m.lastDetail?.reason ? <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{String(m.lastDetail.reason)}</span> : null}
<OutageLine m={m} t={t} />
<span>{m.lastCheckAt ? t("проверен {ago}", { ago: ago(new Date(m.lastCheckAt), t) }) : t("ещё не проверялся")}</span>
<form action={pauseMonitorAction} className="ml-auto">
<Hidden fields={{ id: m.id, paused: m.paused ? "0" : "1", back: "/observability" }} />
@ -152,7 +152,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
)}
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Новый мониторинг")}</span>}>
<form action={createMonitorAction} className="flex flex-col gap-2">
<MonitorFields t={t} />
<MonitorFields t={t} remindDefault={observeRemindMin()} />
<Button size="sm" variant="default" className="self-start">{t("Создать")}</Button>
</form>
</Disclosure>

View File

@ -1,6 +1,6 @@
// Observability (PEP-202): shared pieces of the monitors list and the monitor page.
// glossary-ignore-file: the section is for the superadmin only.
import type { MonitorKind, MonitorState, MonitorView } from "@peppa/core";
import { durationText, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n";
import { Badge } from "@/components/ui/badge";
import { Input, Label, NativeSelect } from "@/components/ui/input";
@ -33,7 +33,7 @@ export function CheckStrip({ recent, t }: { recent: MonitorView["recent"]; t: Tr
}
/** Fields of the create / edit form; `where` is read by the kind (address, host, host:port, hosts). */
export function MonitorFields({ t, m, kindFixed }: { t: Translator; m?: MonitorView; kindFixed?: boolean }) {
export function MonitorFields({ t, m, kindFixed, remindDefault }: { t: Translator; m?: MonitorView; kindFixed?: boolean; remindDefault: number }) {
const tg = (m?.target ?? {}) as Record<string, unknown>;
const where = !m ? "" : m.kind === "http" ? String(tg.url) : m.kind === "tcp" ? `${tg.host}:${tg.port}` : m.kind === "dns" ? String(tg.host) : m.kind === "internet" ? (tg.hosts as string[]).join(", ") : "";
return (
@ -85,6 +85,14 @@ export function MonitorFields({ t, m, kindFixed }: { t: Translator; m?: MonitorV
{t("Удач подряд до «работает»")}
<Input name="recoverThreshold" type="number" min={1} max={20} defaultValue={m?.recoverThreshold ?? 2} className="h-8" />
</Label>
<Label>
{t("Напоминать раз в, мин (0 — не напоминать)")}
<Input name="remindMin" type="number" min={0} max={1440} defaultValue={m?.remindMin != null ? String(m.remindMin) : ""} placeholder={String(remindDefault)} className="h-8" />
</Label>
<label className="flex items-center gap-2 self-end pb-1.5 text-sm">
<input type="checkbox" name="remindDegraded" value="1" defaultChecked={m?.remindDegraded ?? false} />
{t("Напоминать и когда нестабилен")}
</label>
<Label>
{t("Запас heartbeat, с")}
<Input name="graceSec" type="number" min={0} defaultValue={tg.graceSec != null ? String(tg.graceSec) : ""} placeholder="60" className="h-8" />
@ -92,3 +100,18 @@ export function MonitorFields({ t, m, kindFixed }: { t: Translator; m?: MonitorV
</div>
);
}
/** PEP-223: «не работает 1 ч 30 мин · напоминаний: 3 · следующее в 14:30». */
export function OutageLine({ m, t, now = new Date() }: { m: MonitorView; t: Translator; now?: Date }) {
if (!m.outage || m.paused || (m.state !== "down" && m.state !== "degraded")) return null;
const o = m.outage;
const duration = t.text(durationText(now.getTime() - Date.parse(o.startedAt)));
const parts = [
m.state === "down" ? t("не работает {duration}", { duration }) : t("нестабилен {duration}", { duration }),
t("напоминаний: {n}", { n: o.reminders }),
o.nextRemindAt ? t("следующее в {time}", { time: hhmm(o.nextRemindAt) }) : o.quiet ? t("без напоминаний: вместе с интернетом") : t("без напоминаний"),
];
return <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{parts.join(" · ")}</span>;
}
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });

View File

@ -97,6 +97,9 @@ Google Cloud добавлен адрес возврата `https://forge.telecom
```
Скрипт сам собирает образ `peppa/platform:<sha>`, ждёт проверок, делает копию базы и миграции,
перезапускает сервисы и при плохом `/api/health` откатывает на прежний тег.
В конце он отправляет шаблон проектов (`template/`) в Gitea (`docker exec peppa-watchdog peppa template push --alert`,
PEP-242); сбой — сообщение суперадмину, выкатка не откатывается. Вачдог раз в час сверяет шаблон в Gitea с
работающей версией (`peppa template check`) и пишет суперадмину, если тот отстаёт.
4. После работы оставляйте `~/peppa/src` на `main` без незакоммиченных изменений.
## Полезное
@ -109,6 +112,12 @@ Google Cloud добавлен адрес возврата `https://forge.telecom
потеряли доступ к своим файлам. `sqlite3` на хосте нет: копию базы перед миграцией скрипт делает утилитой из образа.
- `~/peppa/src` смотрит на `https://git.vibe42.kz/peppa-bot/peppa.git` (токен бота берётся из
`~/peppa/gitea-vibe42.token` помощником `credential.helper` этой копии, в настройках git его нет).
- Блок секретов в выкладку существующего проекта (PEP-242), не затирая его доработок:
`sudo docker exec peppa-watchdog peppa ci connect <KEY> --secrets-only` — PR из ветки `peppa/secrets`.
Сделать для `dika` и `qazaq-legacy-foundation-web`. **`freetravel` и `executive-ai` не подключать**, пока
владельцы не сверят значения секретов в «⋯ Настройки проекта → Секреты»: у freetravel в `TELEGRAM_BOT_USERNAME`
похожее на ключ бота значение, у executive-ai `GOOGLE_CLIENT_ID` совпадает с `GOOGLE_CLIENT_SECRET` — блок
передал бы продукту неверные значения поверх рабочих.
- Базу не правьте руками на живую: только через `peppa …` или на копии.
## Откат на Mac (неделя после переезда, Mac не трогать)

View File

@ -0,0 +1,11 @@
## Context
observe.db (PEP-202) — своя SQLite с миграциями по `user_version`. Сообщения — `postToChannel` (outbox Telegram) или `alertAdmins` (Telegram + push по настройкам). Ночью (PEP-208) очереди держат новые строки до утра.
## Decisions
- **Миграция observe.db v2**: `monitors.remind_min INTEGER NULL` (null — общий срок `PEPPA_OBSERVE_REMIND_MIN`, по умолчанию 30; 0 — без напоминаний), `monitors.remind_degraded INTEGER 0` (напоминать и в «нестабилен»; по умолчанию нет — как в постановке «0 для degraded»), `monitor_incidents.reminders INTEGER 0`, `monitor_incidents.notified_at TEXT` (время последнего сообщения о сбое: первое, смена down↔degraded, напоминание). Одно поле срока + флаг вместо двух сроков: проще форма, срок в обоих состояниях одинаковый.
- **Когда**: `remindIncidents(db, {now})` в каждом `observeTick` (раз в секунду). Срок — `notified_at + remind_min`. Захват атомарный: `UPDATE monitor_incidents SET reminders = reminders + 1, notified_at = ? WHERE id = ? AND reminders = ?` — параллельные тики и рестарт не дадут двух сообщений, номер N в ключе outbox из счётчика базы.
- **Ночь**: перед постановкой напоминания удаляются ещё `pending` строки напоминаний того же сбоя (`mon:ch:obs:<id>:<сбой>:r%` в `telegram_outbox`, `mon:obs:<id>:<сбой>:r%` в Telegram и push-очередях). Днём бот успевает отправить раньше следующего, ночью остаётся одно — утром одно сообщение. Текст содержит «с ЧЧ:ММ» — начало простоя, поэтому утреннее сообщение не устаревает.
- **Тихий сбой / пауза**: `quiet` сбоя и `paused` мониторинга исключают из выборки; пауза и так закрывает сбой.
- **Длительность**: «N мин» до часа, иначе «H ч M мин» — две строки-шаблона i18n.
- **checkServices**: `remindMs` по умолчанию = `observeRemindMin()` минут (0 — без напоминаний админам). Канал по-прежнему слышит о простое сервиса один раз (PEP-60).
- Время в тексте — `PEPPA_TZ` через `toLocaleTimeString("ru-RU", {timeZone})`.

View File

@ -0,0 +1,19 @@
## Why
Мониторинг observer (PEP-202) пишет одно сообщение при смене состояния. Если его пропустили, про сбой можно не узнать часами: пока сервис лежит, повторов нет. У сервисов платформы (`checkServices`) напоминание раз в час — правило другое.
## What Changes
- Пока мониторинг «не работает» (и «нестабилен», если так настроено), каждые `remind_min` минут (по умолчанию 30, `PEPPA_OBSERVE_REMIND_MIN`) уходит напоминание с длительностью простоя, причиной и временем последней проверки — туда же, куда первое сообщение (канал «services», без канала — суперадминам).
- Ключ outbox `mon:ch:obs:<id>:<сбой>:r<N>`, счётчик напоминаний и время последнего сообщения — в `monitor_incidents`: рестарт observer не дублирует.
- Тихие сбои (вместе с интернетом) и мониторинги на паузе — без напоминаний.
- Ночная тишина: новое напоминание заменяет ещё не отправленное прежнее того же сбоя — утром приходит одно.
- Настройки мониторинга `remind_min` (0 — без напоминаний) и `remind_degraded` — в форме `/observability` и в MCP `create_monitor`/`update_monitor`.
- `checkServices`: напоминание админам с тем же интервалом (30 мин вместо часа).
- `/observability`: у упавшего мониторинга «не работает 1 ч 30 мин · напоминаний: 3 · следующее в ЧЧ:ММ».
## Capabilities
### Modified Capabilities
- `observability`: напоминания о затянувшемся сбое.
- `service-monitoring`: напоминание о молчащем сервисе раз в 30 минут вместо часа.
## Impact
`packages/core/src/observe.ts` (схема observe.db v2, `remindIncidents`), `packages/core/src/monitor.ts` (`remindMs`), `packages/mcp/src/monitors.ts`, веб `/observability`, переводы `i18n/{en,kk}/observe.ts`, тест `observability.test.ts`.

View File

@ -0,0 +1,30 @@
## ADDED Requirements
### Requirement: Напоминание о затянувшемся сбое
Пока мониторинг «не работает» (или «нестабилен» при `remind_degraded`), Peppa SHALL каждые `remind_min` минут (по умолчанию 30; 0 — никогда) отправлять туда же, куда первое сообщение, напоминание с длительностью и началом простоя, причиной и временем последней проверки. Рестарт сервиса SHALL не дублировать напоминание; тихие сбои и паузы SHALL молчать; неотправленное ночью SHALL заменяться следующим. Счётчик и время следующего SHALL быть видны на `/observability`.
#### Scenario: Сбой длиной 95 минут
- **GIVEN** мониторинг «eGov relay» со сроком напоминаний 30 мин
- **WHEN** он не работает 95 минут, потом восстанавливается
- **THEN** ушли «🔴 eGov relay не работает», три напоминания «не работает уже 30 мин», «1 ч», «1 ч 30 мин» и «✅ снова работает»
- **AND** после восстановления напоминаний больше нет
#### Scenario: Рестарт сервиса не дублирует
- **GIVEN** напоминание №1 уже поставлено в очередь
- **WHEN** сервис мониторингов перезапускается и снова проверяет срок в ту же минуту
- **THEN** второго напоминания №1 нет
#### Scenario: Ночью — одно утреннее
- **GIVEN** ночная тишина 23:00–08:00 и мониторинг упал в 02:10
- **WHEN** до 08:00 наступают сроки трёх напоминаний
- **THEN** в очереди одно неотправленное напоминание, с «с 02:10»
#### Scenario: Тихий сбой и выключенные напоминания
- **GIVEN** мониторинг упал вместе с интернетом, либо у него `remind_min` = 0
- **WHEN** проходит 2 часа
- **THEN** напоминаний нет
#### Scenario: Видно на странице
- **GIVEN** мониторинг не работает 1 ч 30 мин, напоминаний 3
- **WHEN** суперадмин открывает `/observability`
- **THEN** у мониторинга «не работает 1 ч 30 мин · напоминаний: 3 · следующее в ЧЧ:ММ»

View File

@ -0,0 +1,24 @@
## MODIFIED Requirements
### Requirement: Без спама
Один сбой сервиса SHALL давать один алерт и напоминания не чаще раза в `PEPPA_OBSERVE_REMIND_MIN` минут (по умолчанию 30, как у мониторингов Observability); о сервисе SHALL уходить не больше одного алерта за 15 минут; две проверки (вачдог и бот) одновременно SHALL ставить одно сообщение.
#### Scenario: Повторные проверки
- **GIVEN** админ получил алерт «бот молчит» в 12:06
- **WHEN** вачдог проверяет сервисы каждые 30 секунд до 12:35
- **THEN** новых сообщений о боте нет
#### Scenario: Напоминание
- **GIVEN** админ получил алерт «бот молчит» в 12:06, бот так и не отметился
- **WHEN** вачдог проверяет сервисы в 12:36
- **THEN** админ получает одно напоминание «бот молчит 36 мин»
#### Scenario: Дребезг
- **GIVEN** админ получил алерт о боте в 12:06 и «снова на связи» в 12:08
- **WHEN** бот снова замолкает и проверка в 12:15 видит сбой
- **THEN** алерта нет до 12:21, а проверка после 12:21 присылает один алерт
#### Scenario: Две проверки одновременно
- **GIVEN** веб молчит дольше 5 минут
- **WHEN** вачдог и бот проверяют сервисы в одну и ту же минуту
- **THEN** в outbox одно сообщение о вебе для каждого админа

View File

@ -0,0 +1,13 @@
## 1. Ядро
- [x] 1.1 Миграция observe.db v2: `remind_min`, `remind_degraded`, `reminders`, `notified_at`; поля в `Monitor`/`MonitorIncident`, `MonitorInput`, нормализация
- [x] 1.2 `remindIncidents` в `observeTick`: срок, атомарный захват, текст, замена неотправленного, ключи `r<N>`
- [x] 1.3 `notified_at` при первом сообщении и смене состояния; `currentIncident`/`nextRemindAt` для вида
- [x] 1.4 `checkServices`: `remindMs` из `observeRemindMin()`
## 2. Интерфейсы
- [x] 2.1 MCP `create_monitor`/`update_monitor`: `remind_min`, `remind_degraded`; `get_monitor` показывает напоминания
- [x] 2.2 Веб: поля формы, строка «не работает … · напоминаний · следующее»; переводы en/kk
## 3. Проверка
- [x] 3.1 Тест: 95 мин — 1+3, восстановление, рестарт без дублей, ночь — одно, тихий/0 — нет
- [x] 3.2 lint, typecheck, тесты observability/monitor/platform-channel/night-quiet

View File

@ -0,0 +1,52 @@
## Context
Шаблон живёт в `template/` репозитория платформы, а агенты и новые проекты читают его из Gitea.
Отправка была ручной (`scripts/push-template.sh`). На сервере (PEP-230) выкатка идёт контейнерами,
у хоста нет Node 26 и `git-credential-peppa`, но в образе платформы есть всё.
## Goals / Non-Goals
**Goals:** шаблон в Gitea равен `template/` выкаченного коммита без участия человека; расхождение видно
суперадмину; существующим проектам — блок секретов без потери их доработок.
**Non-Goals:** автоматически подключать блок всем проектам (у части секреты сомнительные — решает
владелец); менять сам блок секретов.
## Decisions
- **Отправка — код в runner, не bash.** `syncTemplate(root, { push })` (`runner/template-sync.ts`):
клон шаблона ботом (`git` с помощником `peppa`), содержимое заменяется на `template/`, `git add -A`;
нет изменений — `unchanged`; `push: false` — только ответ «отстаёт / нет»; иначе коммит
«Update Peppa template (<commit>)» и push в `main`. Одна функция и для выкатки, и для сверки —
расхождение считается тем же способом, что и отправка (никаких своих хэшей).
Репозитория нет — создаётся (как в `push-template.sh`), только при `push`.
- **Выкатка зовёт образ цели**: `docker run --rm --env-file .env -v $PEPPA_HOME peppa/platform:<sha>
peppa template push --alert` после записи тега. Сбой — `--alert` сам пишет суперадмину
(`alertAdmins`, ключ `template:push:<commit>`); если не запустился и контейнер — строка в журнале
выкатки. Код выхода выкатки — 0: сайт уже работает, откатывать нечего.
- **Сверка в вачдоге** — `templateSyncTick`, раз в час (`template.sync.last`), только когда есть
`template/` в корне платформы и `PEPPA_TEMPLATE_SYNC` ≠ `off` (в тестах выключено в helpers).
Отстаёт → `alertAdmins` один раз на коммит платформы (`template.drift` = `{commit}`); догнал —
отметка стирается. Сам не отправляет: отправка — решение выкатки, а вачдог может работать на старом
коде дольше, чем шаблон в main.
- **Блок секретов «только блок»** — `addSecretsBlock(script, template)` — чистая функция:
1. есть `project_secrets()` — `present`, ничего не меняется;
2. блок (`# PEP-112: …` … конец функции `project_secrets`) берётся из шаблона и вставляется перед
`dc() {`;
3. в строке `docker compose` внутри `dc()` после `-f "$compose"` добавляется
`${override:+-f "$override"}` — одно слово при пустом `override` пропадает;
4. `project_secrets` — строкой после `report deploying`.
Нет якоря (`dc() {`, `-f "$compose"` в `dc`, `report deploying`) или в скрипте уже есть свой
`trap … EXIT` (наш его затёр бы) — `unsupported` с причиной, PR не открывается.
`connectCi(…, { secretsOnly: true })`: без раннера/секрета/вебхука и без остальных файлов шаблона;
ветка `peppa/secrets`, PR «Секреты проекта в выкладке». Скрипт проекта совпадает с шаблоном или его
нет — тот же путь, что и раньше: файл шаблона целиком.
- **freetravel и executive-ai** — не подключаются, пока владельцы не сверят значения; вопрос
владельцам задаёт суперадмин (агент в песочнице не видит живую систему и не пишет владельцам чужих
проектов). Проекты dika и qazaq-legacy-foundation-web — `peppa ci connect <KEY> --secrets-only` на
сервере (шаг для суперадмина).
## Risks / Trade-offs
- Сверка клонирует шаблон раз в час — небольшой репозиторий, приемлемо.
- Скрипт проекта с переписанным `dc()` получит отказ — правится руками; это лучше, чем затереть доработки.

View File

@ -0,0 +1,32 @@
## Why
С 15.11 до 23.11 шаблон проектов в Gitea (`GITEA_TEMPLATE_REPO`) ни разу не обновлялся: шаг
«после мержа — `scripts/push-template.sh`» держался на памяти человека. Агенты неделю брали старый
`RULES.md`, новые проекты получали старую выкладку, а 28 существующих проектов так и не получили
блок секретов проекта (PEP-112) — секреты владельцев не доходили до продуктов (BRM-153).
## What Changes
- Шаблон отправляется в Gitea сам: `scripts/platform-deploy.sh` после успешной выкатки запускает
`peppa template push --alert` образом цели (тот же результат, что `push-template.sh`, токен бота из
`.env`). Сбой — одно сообщение суперадмину, выкатка не откатывается.
- Сверка в вачдоге (`templateSyncTick`, раз в час): шаблон в Gitea отличается от `template/`
выкаченного коммита — одно сообщение суперадмину на каждое новое расхождение.
- `peppa ci connect <KEY> --secrets-only`: добавляет в `.gitea/peppa-deploy.sh` проекта только
недостающий блок секретов (функция, подключение файла к `docker compose`, вызов) и открывает PR;
остальной скрипт проекта не меняется. Скрипт, который не похож на шаблонный, — отказ с причиной.
- CLI `peppa template push|check`.
## Capabilities
### New Capabilities
- `project-template`: доставка шаблона проектов в Gitea и блока секретов в выкладку существующих проектов.
### Modified Capabilities
## Impact
- `packages/runner/src/template-sync.ts` (новый), `packages/runner/src/ci.ts`, `packages/runner/src/watchdog.ts`
- `packages/cli/src/index.ts`, `scripts/platform-deploy.sh`
- Тест `packages/testkit/test/template-sync.test.ts`
- Без миграций (состояние сверки — `settings` `template.drift`).

View File

@ -0,0 +1,58 @@
## ADDED Requirements
### Requirement: Шаблон проектов уходит в Gitea с выкаткой
После успешной выкатки платформы `scripts/platform-deploy.sh` SHALL отправлять `template/` выкаченного
коммита в репозиторий шаблона Gitea (`peppa template push --alert` образом цели). Сбой отправки SHALL
давать одно сообщение суперадмину и НЕ SHALL откатывать выкатку.
#### Scenario: Выкатка с изменённым шаблоном
- **GIVEN** в выкатываемом коммите `template/RULES.md` отличается от шаблона в Gitea
- **WHEN** выкатка проходит проверку здоровья и страниц
- **THEN** в репозитории шаблона появляется коммит «Update Peppa template (<коммит>)» с новым `RULES.md`
#### Scenario: Шаблон не изменился
- **GIVEN** `template/` совпадает с шаблоном в Gitea
- **WHEN** выполняется `peppa template push`
- **THEN** выводится «template unchanged», новых коммитов в шаблоне нет
#### Scenario: Gitea недоступна при отправке
- **GIVEN** Gitea отвечает ошибкой
- **WHEN** выполняется `peppa template push --alert`
- **THEN** суперадмин получает одно сообщение «Шаблон проектов не отправлен…»
- **AND** выкатка завершается как успешная
### Requirement: Сверка шаблона в вачдоге
Вачдог SHALL раз в час сравнивать шаблон в Gitea с `template/` работающего коммита и при расхождении
SHALL писать суперадмину одно сообщение на коммит платформы.
#### Scenario: Шаблон отстаёт
- **GIVEN** шаблон в Gitea не содержит последней правки `template/`
- **WHEN** вачдог выполняет сверку дважды
- **THEN** суперадмин получает ровно одно сообщение «Шаблон проектов в Gitea отстаёт…»
#### Scenario: Шаблон совпадает
- **GIVEN** шаблон в Gitea равен `template/`
- **WHEN** вачдог выполняет сверку
- **THEN** сообщений нет
### Requirement: Блок секретов без затирания доработок
`peppa ci connect <KEY> --secrets-only` SHALL добавлять в `.gitea/peppa-deploy.sh` проекта только
блок секретов проекта (функция `project_secrets`, подключение её файла к `docker compose`, вызов после
`report deploying`) и открывать PR; остальные строки скрипта SHALL оставаться без изменений. Скрипт без
нужных мест или со своим `trap … EXIT` SHALL получать отказ с причиной, без PR.
#### Scenario: Скрипт проекта с доработками
- **GIVEN** в скрипте выкладки проекта есть своя строка `echo "custom step"` и нет блока секретов
- **WHEN** выполняется `peppa ci connect <KEY> --secrets-only`
- **THEN** открыт PR из ветки `peppa/secrets`, в скрипте есть `project_secrets` и строка `echo "custom step"`
- **AND** все строки прежнего скрипта остались на месте
#### Scenario: Блок уже есть
- **GIVEN** в скрипте проекта уже есть функция `project_secrets`
- **WHEN** выполняется `peppa ci connect <KEY> --secrets-only`
- **THEN** PR не открывается, команда сообщает, что блок уже есть
#### Scenario: Скрипт без функции dc
- **GIVEN** скрипт выкладки проекта переписан и в нём нет `dc() {`
- **WHEN** выполняется `peppa ci connect <KEY> --secrets-only`
- **THEN** команда отказывает с причиной, PR не открывается

View File

@ -0,0 +1,16 @@
## 1. Шаблон уходит в Gitea сам
- [x] 1.1 `runner/template-sync.ts`: `syncTemplate` (клон, замена, сравнение, коммит и push; создание репозитория)
- [x] 1.2 CLI `peppa template push [--alert]` и `peppa template check`
- [x] 1.3 `scripts/platform-deploy.sh`: после успешной выкатки — `peppa template push --alert` образом цели, сбой выкатку не откатывает
- [x] 1.4 `templateSyncTick` в вачдоге: отстаёт — одно сообщение суперадмину на коммит
## 2. Блок секретов существующим проектам
- [x] 2.1 `addSecretsBlock` — чистая функция с отказом по причинам
- [x] 2.2 `connectCi(…, { secretsOnly })` + `peppa ci connect <KEY> --secrets-only`
## 3. Тесты и документация
- [x] 3.1 Тест `template-sync.test.ts`: выкатка отправляет шаблон, сверка, «только блок» не трогает остальной скрипт, отказ без якоря
- [x] 3.2 AGENTS.md, docs/SERVER.md: шаблон уходит сам; шаги для dika, qazaq-legacy-foundation-web, freetravel, executive-ai

View File

@ -91,3 +91,32 @@ Peppa SHALL выполнять мониторинги в отдельном пр
- **GIVEN** суперадмин удалил «eGov relay»
- **WHEN** сервис перезапускается
- **THEN** «eGov relay» не создан снова
### Requirement: Напоминание о затянувшемся сбое
Пока мониторинг «не работает» (или «нестабилен» при `remind_degraded`), Peppa SHALL каждые `remind_min` минут (по умолчанию 30; 0 — никогда) отправлять туда же, куда первое сообщение, напоминание с длительностью и началом простоя, причиной и временем последней проверки. Рестарт сервиса SHALL не дублировать напоминание; тихие сбои и паузы SHALL молчать; неотправленное ночью SHALL заменяться следующим. Счётчик и время следующего SHALL быть видны на `/observability`.
#### Scenario: Сбой длиной 95 минут
- **GIVEN** мониторинг «eGov relay» со сроком напоминаний 30 мин
- **WHEN** он не работает 95 минут, потом восстанавливается
- **THEN** ушли «🔴 eGov relay не работает», три напоминания «не работает уже 30 мин», «1 ч», «1 ч 30 мин» и «✅ снова работает»
- **AND** после восстановления напоминаний больше нет
#### Scenario: Рестарт сервиса не дублирует
- **GIVEN** напоминание №1 уже поставлено в очередь
- **WHEN** сервис мониторингов перезапускается и снова проверяет срок в ту же минуту
- **THEN** второго напоминания №1 нет
#### Scenario: Ночью — одно утреннее
- **GIVEN** ночная тишина 23:00–08:00 и мониторинг упал в 02:10
- **WHEN** до 08:00 наступают сроки трёх напоминаний
- **THEN** в очереди одно неотправленное напоминание, с «с 02:10»
#### Scenario: Тихий сбой и выключенные напоминания
- **GIVEN** мониторинг упал вместе с интернетом, либо у него `remind_min` = 0
- **WHEN** проходит 2 часа
- **THEN** напоминаний нет
#### Scenario: Видно на странице
- **GIVEN** мониторинг не работает 1 ч 30 мин, напоминаний 3
- **WHEN** суперадмин открывает `/observability`
- **THEN** у мониторинга «не работает 1 ч 30 мин · напоминаний: 3 · следующее в ЧЧ:ММ»

View File

@ -0,0 +1,64 @@
# project-template Specification
## Purpose
Шаблон проектов (`template/`) доходит до Gitea без участия человека, а существующие проекты получают блок секретов в выкладку, не теряя своих доработок (PEP-242).
## Requirements
### Requirement: Шаблон проектов уходит в Gitea с выкаткой
После успешной выкатки платформы `scripts/platform-deploy.sh` SHALL отправлять `template/` выкаченного
коммита в репозиторий шаблона Gitea (`peppa template push --alert` образом цели). Сбой отправки SHALL
давать одно сообщение суперадмину и НЕ SHALL откатывать выкатку.
#### Scenario: Выкатка с изменённым шаблоном
- **GIVEN** в выкатываемом коммите `template/RULES.md` отличается от шаблона в Gitea
- **WHEN** выкатка проходит проверку здоровья и страниц
- **THEN** в репозитории шаблона появляется коммит «Update Peppa template (<коммит>)» с новым `RULES.md`
#### Scenario: Шаблон не изменился
- **GIVEN** `template/` совпадает с шаблоном в Gitea
- **WHEN** выполняется `peppa template push`
- **THEN** выводится «template unchanged», новых коммитов в шаблоне нет
#### Scenario: Gitea недоступна при отправке
- **GIVEN** Gitea отвечает ошибкой
- **WHEN** выполняется `peppa template push --alert`
- **THEN** суперадмин получает одно сообщение «Шаблон проектов не отправлен…»
- **AND** выкатка завершается как успешная
### Requirement: Сверка шаблона в вачдоге
Вачдог SHALL раз в час сравнивать шаблон в Gitea с `template/` работающего коммита и при расхождении
SHALL писать суперадмину одно сообщение на коммит платформы.
#### Scenario: Шаблон отстаёт
- **GIVEN** шаблон в Gitea не содержит последней правки `template/`
- **WHEN** вачдог выполняет сверку дважды
- **THEN** суперадмин получает ровно одно сообщение «Шаблон проектов в Gitea отстаёт…»
#### Scenario: Шаблон совпадает
- **GIVEN** шаблон в Gitea равен `template/`
- **WHEN** вачдог выполняет сверку
- **THEN** сообщений нет
### Requirement: Блок секретов без затирания доработок
`peppa ci connect <KEY> --secrets-only` SHALL добавлять в `.gitea/peppa-deploy.sh` проекта только
блок секретов проекта (функция `project_secrets`, подключение её файла к `docker compose`, вызов после
`report deploying`) и открывать PR; остальные строки скрипта SHALL оставаться без изменений. Скрипт без
нужных мест или со своим `trap … EXIT` SHALL получать отказ с причиной, без PR.
#### Scenario: Скрипт проекта с доработками
- **GIVEN** в скрипте выкладки проекта есть своя строка `echo "custom step"` и нет блока секретов
- **WHEN** выполняется `peppa ci connect <KEY> --secrets-only`
- **THEN** открыт PR из ветки `peppa/secrets`, в скрипте есть `project_secrets` и строка `echo "custom step"`
- **AND** все строки прежнего скрипта остались на месте
#### Scenario: Блок уже есть
- **GIVEN** в скрипте проекта уже есть функция `project_secrets`
- **WHEN** выполняется `peppa ci connect <KEY> --secrets-only`
- **THEN** PR не открывается, команда сообщает, что блок уже есть
#### Scenario: Скрипт без функции dc
- **GIVEN** скрипт выкладки проекта переписан и в нём нет `dc() {`
- **WHEN** выполняется `peppa ci connect <KEY> --secrets-only`
- **THEN** команда отказывает с причиной, PR не открывается

View File

@ -71,17 +71,17 @@
| [mock-other] | mock-other |
### Requirement: Без спама
Один сбой сервиса SHALL давать один алерт и напоминания не чаще раза в час; о сервисе SHALL уходить не больше одного алерта за 15 минут; две проверки (вачдог и бот) одновременно SHALL ставить одно сообщение.
Один сбой сервиса SHALL давать один алерт и напоминания не чаще раза в `PEPPA_OBSERVE_REMIND_MIN` минут (по умолчанию 30, как у мониторингов Observability); о сервисе SHALL уходить не больше одного алерта за 15 минут; две проверки (вачдог и бот) одновременно SHALL ставить одно сообщение.
#### Scenario: Повторные проверки
- **GIVEN** админ получил алерт «бот молчит» в 12:06
- **WHEN** вачдог проверяет сервисы каждые 30 секунд до 12:40
- **WHEN** вачдог проверяет сервисы каждые 30 секунд до 12:35
- **THEN** новых сообщений о боте нет
#### Scenario: Напоминание
- **GIVEN** админ получил алерт «бот молчит» в 12:06, бот так и не отметился
- **WHEN** вачдог проверяет сервисы в 13:06
- **THEN** админ получает одно напоминание «бот молчит 66 мин»
- **WHEN** вачдог проверяет сервисы в 12:36
- **THEN** админ получает одно напоминание «бот молчит 36 мин»
#### Scenario: Дребезг
- **GIVEN** админ получил алерт о боте в 12:06 и «снова на связи» в 12:08

View File

@ -78,6 +78,7 @@ import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtect
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits } from "@peppa/core";
import { tidyAgentTasks } from "@peppa/runner";
import { installCrashReporting } from "@peppa/core";
import { pushTemplateOrAlert, syncTemplate } from "@peppa/runner";
import { answerAndDeliver, connectCi, importIssues, deployProd, redeployProject, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
import { spawnSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
@ -108,6 +109,9 @@ const USAGE = `peppa — FORGE software factory CLI
peppa release report [KEY] --sha <sha> -s <deploying|healthy|rolled_back|failed> [--previous <sha>] [--reason <text>]
[--log-file <f>] [--commits-file <f>] (prod release step, from scripts/peppa-release.sh)
peppa ci connect [KEY] (runner + secret + PR with the CI workflow from the template)
peppa ci connect [KEY] --secrets-only (PEP-242: PR adding only the project secrets block to the deploy script)
peppa template push [--alert] (PEP-242: template/ → the template repo in Gitea; --alert: failure → superadmin)
peppa template check (does the template in Gitea differ from template/?)
peppa goal add [KEY] <title> [-d <description>]
peppa goal list [KEY]
peppa task add [KEY] <title> [-g <goal-id>] [-d <description>]
@ -196,6 +200,8 @@ const { values: opts, positionals } = parseArgs({
reason: { type: "string" },
"log-file": { type: "string" },
"commits-file": { type: "string" },
"secrets-only": { type: "boolean" },
alert: { type: "boolean" },
},
});
@ -463,8 +469,26 @@ async function main(): Promise<void> {
case "ci connect": {
const [key] = withKey(args, 0);
const p = await getProject(db, key);
const r = await connectCi(db, p, { log: (step) => console.log(`… ${step}`) });
console.log(`${p.key}: runner=${r.runner}, ${r.prUrl ? `PR ${r.prUrl}` : "workflow already on the default branch"}`);
const r = await connectCi(db, p, { log: (step) => console.log(`… ${step}`), secretsOnly: opts["secrets-only"] });
if (opts["secrets-only"]) console.log(`${p.key}: secrets block ${r.secrets}${r.prUrl ? `, PR ${r.prUrl}` : ""}`);
else console.log(`${p.key}: runner=${r.runner}, ${r.prUrl ? `PR ${r.prUrl}` : "workflow already on the default branch"}`);
break;
}
case "template push": {
if (opts.alert) {
const r = await pushTemplateOrAlert(db, { log: (m) => console.error(m) });
if (!r) process.exitCode = 1;
else console.log(r.state === "pushed" ? `pushed template (${r.changed.length} files)` : "template unchanged");
} else {
const r = await syncTemplate({ push: true });
console.log(r.state === "pushed" ? `pushed template (${r.changed.length} files)` : "template unchanged");
}
break;
}
case "template check": {
const r = await syncTemplate({ push: false });
console.log(r.state === "unchanged" ? "template in Gitea is up to date" : `template in Gitea is behind: ${r.changed.join(", ")}`);
if (r.state !== "unchanged") process.exitCode = 1;
break;
}
case "deploy prod": {

View File

@ -58,7 +58,7 @@ export interface MonitorOptions {
now?: Date;
/** Quiet for longer than this = down (default PEPPA_MONITOR_STALE_MIN or 5 min). */
staleMs?: number;
/** Reminder about the same outage (default 60 min). */
/** Reminder about the same outage (default PEPPA_OBSERVE_REMIND_MIN or 30 min, PEP-223). */
remindMs?: number;
/** At most one alert about a service per this period (default 15 min). */
cooldownMs?: number;
@ -192,6 +192,13 @@ export async function setPlatformAdmins(db: Db, logins: string[] | null): Promis
await setSetting(db, ADMINS, [...new Set(logins.map((l) => l.trim().toLowerCase()).filter(Boolean))].sort());
}
/** PEP-223: the common reminder period about an outage, minutes (PEPPA_OBSERVE_REMIND_MIN, default 30; 0 — none). */
export function observeRemindMin(): number {
const v = process.env.PEPPA_OBSERVE_REMIND_MIN;
const n = v == null || v.trim() === "" ? NaN : Number(v);
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 30;
}
/** Admins who paired Telegram: they get service alerts. */
export async function adminRecipients(db: Db): Promise<User[]> {
const logins = await platformAdmins(db);
@ -232,7 +239,8 @@ const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour:
*/
export async function checkServices(db: Db, o: MonitorOptions & { self: Service }): Promise<number> {
const now = o.now ?? new Date();
const remindMs = o.remindMs ?? 60 * MIN;
// PEP-223: one rule with the monitors of Observability (default 30 min; 0 — no reminders).
const remindMs = o.remindMs ?? (observeRemindMin() ? observeRemindMin() * MIN : Infinity);
const cooldownMs = o.cooldownMs ?? 15 * MIN;
const log = o.log ?? (() => {});
let queued = 0;

View File

@ -9,10 +9,11 @@ import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { randomBytes } from "node:crypto";
import { peppaHome } from "@peppa/shared";
import { m as tr } from "@peppa/shared/i18n";
import type { Db } from "@peppa/db";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { pushOutbox, telegramOutbox, type Db } from "@peppa/db";
import { and, eq, like, or } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { alertAdmins } from "./monitor.ts";
import { alertAdmins, observeRemindMin } from "./monitor.ts";
import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { realObserveProbes, runCheck, type CheckResult, type ObserveProbes } from "./observe-checks.ts";
@ -71,6 +72,10 @@ export interface Monitor {
lastPingAt: string | null;
lastDetail: Record<string, unknown> | null;
incidentId: number | null;
/** PEP-223: minutes between reminders about an ongoing outage; null — the common default, 0 — none. */
remindMin: number | null;
/** PEP-223: remind about «degraded» too (by default only «down»). */
remindDegraded: boolean;
}
export interface MonitorCheck {
@ -92,6 +97,10 @@ export interface MonitorIncident {
endedAt: string | null;
/** Fell together with the internet: no message about it. */
quiet: boolean;
/** PEP-223: reminders sent about this incident. */
reminders: number;
/** PEP-223: time of the last message about it (the first one, a state change or a reminder). */
notifiedAt: string | null;
}
export interface MonitorInput {
@ -102,12 +111,16 @@ export interface MonitorInput {
timeoutMs?: number;
failThreshold?: number;
recoverThreshold?: number;
/** PEP-223: null/undefined — the common default, 0 — no reminders. */
remindMin?: number | null;
remindDegraded?: boolean;
}
export const MIN_INTERVAL_SEC = 30;
export const MAX_MONITORS = 200;
export const DEFAULT_INTERVAL_SEC = 60;
export const retentionDays = () => Number(process.env.PEPPA_OBSERVE_RETENTION_DAYS) || 7;
export const MAX_REMIND_MIN = 1440;
// ── the database ───────────────────────────────────────────────────────────────────
@ -158,7 +171,16 @@ const SCHEMA = [
`CREATE TABLE observe_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
];
/** Each entry upgrades the file by one version (PRAGMA user_version). */
const MIGRATIONS: string[][] = [SCHEMA];
const MIGRATIONS: string[][] = [
SCHEMA,
// PEP-223: reminders about an ongoing outage.
[
`ALTER TABLE monitors ADD COLUMN remind_min INTEGER`,
`ALTER TABLE monitors ADD COLUMN remind_degraded INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE monitor_incidents ADD COLUMN reminders INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE monitor_incidents ADD COLUMN notified_at TEXT`,
],
];
const opened = new Map<string, DatabaseSync>();
@ -228,6 +250,8 @@ function toMonitor(r: Row): Monitor {
lastPingAt: (r.last_ping_at as string | null) ?? null,
lastDetail: json(r.last_detail, null),
incidentId: r.incident_id == null ? null : Number(r.incident_id),
remindMin: r.remind_min == null ? null : Number(r.remind_min),
remindDegraded: Number(r.remind_degraded) === 1,
};
}
@ -249,6 +273,8 @@ const toIncident = (r: Row): MonitorIncident => ({
startedAt: String(r.started_at),
endedAt: (r.ended_at as string | null) ?? null,
quiet: Number(r.quiet) === 1,
reminders: Number(r.reminders ?? 0),
notifiedAt: (r.notified_at as string | null) ?? null,
});
// ── validation ─────────────────────────────────────────────────────────────────────
@ -304,7 +330,7 @@ export function normalizeTarget(kind: MonitorKind, t: Record<string, unknown>):
}
}
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target">> & { target: MonitorTarget } {
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target" | "remindMin">> & { target: MonitorTarget; remindMin: number | null } {
const name = String(input.name ?? "").trim();
if (!name || name.length > 80) bad("Название: от 1 до 80 символов");
if (!MONITOR_KINDS.includes(input.kind)) bad("Неизвестный вид мониторинга: {kind}", { kind: String(input.kind) });
@ -317,6 +343,8 @@ function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target">>
timeoutMs: int(input.timeoutMs ?? 10_000, 1_000, 30_000, "timeoutMs"),
failThreshold: int(input.failThreshold ?? 3, 1, 20, "failThreshold"),
recoverThreshold: int(input.recoverThreshold ?? 2, 1, 20, "recoverThreshold"),
remindMin: input.remindMin == null || String(input.remindMin) === "" ? null : int(input.remindMin, 0, MAX_REMIND_MIN, "remindMin"),
remindDegraded: !!input.remindDegraded,
};
}
@ -341,10 +369,10 @@ export function createMonitor(input: MonitorInput, author: string, now = new Dat
const token = n.kind === "heartbeat" ? randomBytes(18).toString("base64url") : null;
const r = db
.prepare(
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, token, created_by, created_at, updated_at, state_since, last_ping_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, remind_min, remind_degraded, token, created_by, created_at, updated_at, state_since, last_ping_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
)
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null) as Row;
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, n.remindMin, n.remindDegraded ? 1 : 0, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null) as Row;
return toMonitor(r);
}
@ -360,10 +388,13 @@ export function updateMonitor(id: number, patch: Partial<MonitorInput>, now = ne
timeoutMs: patch.timeoutMs ?? cur.timeoutMs,
failThreshold: patch.failThreshold ?? cur.failThreshold,
recoverThreshold: patch.recoverThreshold ?? cur.recoverThreshold,
// undefined — keep; null — back to the common default.
remindMin: patch.remindMin === undefined ? cur.remindMin : patch.remindMin,
remindDegraded: patch.remindDegraded ?? cur.remindDegraded,
});
const r = observeDb()
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`)
.get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, now.toISOString(), id) as Row;
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, remind_min = ?, remind_degraded = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`)
.get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, n.remindMin, n.remindDegraded ? 1 : 0, now.toISOString(), id) as Row;
return toMonitor(r);
}
@ -420,17 +451,48 @@ export interface MonitorView extends Monitor {
uptime7d: number | null;
/** The last checks, oldest first. */
recent: Array<{ at: string; ok: boolean; degraded: boolean }>;
/** PEP-223: the open incident with its reminders (null — none or paused). */
outage: { startedAt: string; reminders: number; nextRemindAt: string | null; quiet: boolean } | null;
}
export function monitorView(m: Monitor, now = new Date()): MonitorView {
const recent = (observeDb().prepare("SELECT at, ok, degraded FROM monitor_checks WHERE monitor_id = ? ORDER BY at DESC, id DESC LIMIT 30").all(m.id) as Row[])
.map((r) => ({ at: String(r.at), ok: Number(r.ok) === 1, degraded: Number(r.degraded) === 1 }))
.reverse();
return { ...m, uptime24h: monitorUptime(m.id, 86_400_000, now), uptime7d: monitorUptime(m.id, 7 * 86_400_000, now), recent };
const inc = m.incidentId && !m.paused ? openIncident(m.incidentId) : null;
const outage = inc ? { startedAt: inc.startedAt, reminders: inc.reminders, nextRemindAt: nextRemindAt(m, inc), quiet: inc.quiet } : null;
return { ...m, uptime24h: monitorUptime(m.id, 86_400_000, now), uptime7d: monitorUptime(m.id, 7 * 86_400_000, now), recent, outage };
}
export const listMonitorViews = (now = new Date()) => listMonitors().map((m) => monitorView(m, now));
function openIncident(id: number): MonitorIncident | null {
const r = observeDb().prepare("SELECT * FROM monitor_incidents WHERE id = ? AND ended_at IS NULL").get(id) as Row | undefined;
return r ? toIncident(r) : null;
}
/** PEP-223: the reminder period of a monitor in its current state, minutes (0 — no reminders). */
export function remindPeriodMin(m: Pick<Monitor, "state" | "remindMin" | "remindDegraded">): number {
if (m.state !== "down" && !(m.state === "degraded" && m.remindDegraded)) return 0;
return m.remindMin ?? observeRemindMin();
}
/** PEP-223: when the next reminder about an open incident is due; null — none will come. */
export function nextRemindAt(m: Pick<Monitor, "state" | "paused" | "remindMin" | "remindDegraded">, inc: Pick<MonitorIncident, "quiet" | "notifiedAt" | "startedAt" | "endedAt">): string | null {
const period = remindPeriodMin(m);
if (m.paused || inc.quiet || inc.endedAt || !period) return null;
return new Date(Date.parse(inc.notifiedAt ?? inc.startedAt) + period * 60_000).toISOString();
}
/** «45 мин», «1 ч», «1 ч 30 мин» (PEP-223). */
export function durationText(ms: number): string {
const total = Math.max(1, Math.round(ms / 60_000));
const h = Math.floor(total / 60);
const min = total % 60;
if (!h) return tr("{n} мин", { n: min });
return min ? tr("{h} ч {n} мин", { h, n: min }) : tr("{h} ч", { h });
}
/** One line about where the monitor looks. */
export function describeTarget(m: Pick<Monitor, "kind" | "target" | "token">, webUrl = ""): string {
const t = m.target as Record<string, unknown>;
@ -491,11 +553,11 @@ export function recordCheck(m: Monitor, r: CheckResult, o: { now?: Date; quiet?:
incidentId = null;
} else if (incidentId) {
// down ↔ degraded: the same incident, a new state.
db.prepare("UPDATE monitor_incidents SET state = ?, reason = ? WHERE id = ?").run(to, r.reason, incidentId);
db.prepare("UPDATE monitor_incidents SET state = ?, reason = ?, notified_at = ? WHERE id = ?").run(to, r.reason, iso, incidentId);
incident = toIncident(db.prepare("SELECT * FROM monitor_incidents WHERE id = ?").get(incidentId) as Row);
} else {
incident = toIncident(
db.prepare("INSERT INTO monitor_incidents (monitor_id, state, reason, started_at, quiet) VALUES (?, ?, ?, ?, ?) RETURNING *").get(m.id, to, r.reason, iso, o.quiet ? 1 : 0) as Row,
db.prepare("INSERT INTO monitor_incidents (monitor_id, state, reason, started_at, quiet, notified_at) VALUES (?, ?, ?, ?, ?, ?) RETURNING *").get(m.id, to, r.reason, iso, o.quiet ? 1 : 0, iso) as Row,
);
incidentId = incident.id;
}
@ -529,7 +591,11 @@ const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replac
async function announce(db: Db, m: Monitor, t: Transition, text: string, log: (s: string) => void): Promise<void> {
const inc = t.ended?.id ?? t.incident?.id ?? 0;
const key = `obs:${m.id}:${inc}:${t.to}`;
await send(db, `obs:${m.id}:${inc}:${t.to}`, text, log);
}
/** The platform channel «services», without it — the superadmins (PEP-202). */
async function send(db: Db, key: string, text: string, log: (s: string) => void): Promise<void> {
const channel = await getPlatformChannel(db);
if (await postToChannel(db, "services", `mon:ch:${key}`, esc(text), channel)) {
log(`observe: ${text}`);
@ -538,6 +604,72 @@ async function announce(db: Db, m: Monitor, t: Transition, text: string, log: (s
await alertAdmins(db, `mon:${key}`, text, log);
}
const clock = (iso: string) => {
const d = new Date(iso);
try {
return d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
} catch {
return d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
}
};
/** PEP-223: text of a reminder about an ongoing outage. */
export function reminderText(m: Pick<Monitor, "name" | "state" | "lastCheckAt" | "lastDetail">, inc: Pick<MonitorIncident, "startedAt" | "reason">, now = new Date()): string {
const vars = {
name: m.name,
duration: durationText(now.getTime() - Date.parse(inc.startedAt)),
since: clock(inc.startedAt),
reason: asIs(String(m.lastDetail?.reason ?? inc.reason)),
time: clock(m.lastCheckAt ?? now.toISOString()),
};
return m.state === "down"
? tr("🔴 {name} не работает уже {duration} (с {since}): {reason}. Последняя проверка {time}.", vars)
: tr("🟡 {name} нестабилен уже {duration} (с {since}): {reason}. Последняя проверка {time}.", vars);
}
/**
* PEP-223: the night silence (PEP-208) holds new messages until the morning — an unsent reminder
* about the same incident is replaced by the new one, so the morning brings one, not a pile.
*/
async function dropUnsentReminders(db: Db, monitorId: number, incidentId: number): Promise<void> {
const base = `obs:${monitorId}:${incidentId}:r`;
await db.delete(telegramOutbox).where(and(eq(telegramOutbox.status, "pending"), or(like(telegramOutbox.dedupeKey, `mon:ch:${base}%`), like(telegramOutbox.dedupeKey, `mon:${base}%`))));
await db.delete(pushOutbox).where(and(eq(pushOutbox.status, "pending"), like(pushOutbox.dedupeKey, `mon:${base}%`)));
}
/**
* PEP-223: one reminder per due open incident (down, or degraded when the monitor asks for it),
* every `remind_min` after the last message. The claim is atomic on the incident's counter, so
* parallel ticks and a restarted service never send the same reminder twice. Quiet incidents and
* paused monitors stay silent. Returns the number of reminders sent.
*/
export async function remindIncidents(db: Db, o: { now?: Date; log?: (s: string) => void } = {}): Promise<number> {
const now = o.now ?? new Date();
const log = o.log ?? (() => {});
const odb = observeDb();
let sent = 0;
for (const m of listMonitors()) {
if (m.paused || !m.incidentId) continue;
const inc = openIncident(m.incidentId);
if (!inc) continue;
const due = nextRemindAt(m, inc);
if (!due || Date.parse(due) > now.getTime()) continue;
const claimed = odb
.prepare("UPDATE monitor_incidents SET reminders = reminders + 1, notified_at = ? WHERE id = ? AND reminders = ? AND ended_at IS NULL RETURNING reminders")
.get(now.toISOString(), inc.id, inc.reminders) as Row | undefined;
if (!claimed) continue;
const n = Number(claimed.reminders);
try {
await dropUnsentReminders(db, m.id, inc.id);
await send(db, `obs:${m.id}:${inc.id}:r${n}`, reminderText(m, inc, now), log);
sent++;
} catch (e) {
log(`observe: reminder failed: ${(e as Error).message}`);
}
}
return sent;
}
const inflight = new Set<number>();
const running: Promise<void>[] = [];
@ -584,6 +716,7 @@ export async function observeTick(db: Db, o: ObserveTickOptions = {}): Promise<n
started.push(p);
running.push(p);
}
await remindIncidents(db, { now: o.now, log: o.log }).catch((e: Error) => (o.log ?? (() => {}))(`observe: reminders failed: ${e.message}`));
await Promise.all(started);
return started.length;
}

View File

@ -13,6 +13,7 @@ import {
monitorIncidents,
monitorView,
listMonitorViews,
observeRemindMin,
PeppaError,
platformProjectKey,
setMonitorPaused,
@ -51,11 +52,17 @@ const common = {
timeout_ms: z.number().int().optional().describe("Per check, 1000–30000 (default 10000)"),
fail_threshold: z.number().int().optional().describe("Bad checks in a row before «down» (default 3)"),
recover_threshold: z.number().int().optional().describe("Good checks in a row before «up» again (default 2)"),
remind_min: z.number().int().min(0).max(1440).nullable().optional().describe("Minutes between reminders while it is down (PEP-223); 0 — no reminders, null — the common default (PEPPA_OBSERVE_REMIND_MIN, 30)"),
remind_degraded: z.boolean().optional().describe("Remind while «degraded» too (default false)"),
};
const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`);
const outage = (m: MonitorView) =>
m.outage && (m.state === "down" || m.state === "degraded")
? ` · ${m.state} since ${m.outage.startedAt}, reminders ${m.outage.reminders}${m.outage.nextRemindAt ? `, next ${m.outage.nextRemindAt}` : m.outage.quiet ? " (quiet: with the internet)" : ", no more"}`
: "";
const line = (m: MonitorView) =>
`- #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)} — ${m.paused ? "paused" : m.state}${m.lastDetail?.reason ? ` (${m.lastDetail.reason})` : ""} · uptime 24h ${pct(m.uptime24h)}, 7d ${pct(m.uptime7d)}`;
`- #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)} — ${m.paused ? "paused" : m.state}${m.lastDetail?.reason ? ` (${m.lastDetail.reason})` : ""} · uptime 24h ${pct(m.uptime24h)}, 7d ${pct(m.uptime7d)}${outage(m)}`;
async function journal(db: Db, type: string, sessionId: number | null | undefined, payload: Record<string, unknown>) {
const p = await getProject(db, platformProjectKey()).catch(() => null);
@ -78,10 +85,10 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
const cs = monitorChecks(id, { limit: checks ?? 50 });
return [
line(m),
`interval ${m.intervalSec}s, timeout ${m.timeoutMs}ms, down after ${m.failThreshold} bad, up after ${m.recoverThreshold} good; created by ${m.createdBy}`,
`interval ${m.intervalSec}s, timeout ${m.timeoutMs}ms, down after ${m.failThreshold} bad, up after ${m.recoverThreshold} good; reminders every ${m.remindMin ?? `${observeRemindMin()} (default)`} min${m.remindDegraded ? " (degraded too)" : ""}; created by ${m.createdBy}`,
"",
"Incidents:",
...(inc.length ? inc.map((i) => `- ${i.startedAt} → ${i.endedAt ?? "now"}: ${i.state} — ${i.reason}${i.quiet ? " (with the internet, no message)" : ""}`) : ["- none"]),
...(inc.length ? inc.map((i) => `- ${i.startedAt} → ${i.endedAt ?? "now"}: ${i.state} — ${i.reason}${i.quiet ? " (with the internet, no message)" : ""}${i.reminders ? `, reminders ${i.reminders}` : ""}`) : ["- none"]),
"",
"Last checks:",
...cs.map((c) => `- ${c.at} ${c.ok ? (c.degraded ? "degraded" : "ok") : "FAIL"}${c.latencyMs != null ? ` ${c.latencyMs}ms` : ""}${c.detail.reason ? ` — ${c.detail.reason}` : ""}`),
@ -90,12 +97,12 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
define(
"create_monitor",
"Observability: add a monitor. Kinds: http (url, expectStatus, contains, maxLatencyMs, certDays), tcp (host, port), dns (host — system DNS vs 1.1.1.1), internet (hosts), heartbeat (graceSec; returns the ping address the service must call). State changes go to the platform's Telegram channel.",
"Observability: add a monitor. Kinds: http (url, expectStatus, contains, maxLatencyMs, certDays), tcp (host, port), dns (host — system DNS vs 1.1.1.1), internet (hosts), heartbeat (graceSec; returns the ping address the service must call). State changes go to the platform's Telegram channel; while down, a reminder every remind_min minutes (default 30).",
{ name: z.string().min(1).max(80), kind, target, ...common },
false,
async (a) => {
const who = await access.check();
const m = createMonitor({ name: a.name, kind: a.kind as MonitorKind, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold }, who.author);
const m = createMonitor({ name: a.name, kind: a.kind as MonitorKind, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold, remindMin: a.remind_min, remindDegraded: a.remind_degraded }, who.author);
await journal(db, "monitor_created", who.sessionId, { id: m.id, name: m.name, kind: m.kind, target: m.target, author: who.author });
return `Created #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)}; first check within a few seconds.`;
},
@ -104,7 +111,7 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
define("update_monitor", "Observability: change a monitor (the kind stays). Fields left out stay.", { id: z.number().int(), name: z.string().min(1).max(80).optional(), target: target.optional(), ...common }, false, async (a) => {
const who = await access.check();
found(a.id);
const m = updateMonitor(a.id, { name: a.name, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold });
const m = updateMonitor(a.id, { name: a.name, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold, remindMin: a.remind_min, remindDegraded: a.remind_degraded });
await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, author: who.author });
return `Updated #${m.id} ${m.name}.`;
});

View File

@ -12,12 +12,16 @@ import { loadEnv } from "@peppa/shared";
import { ensureBranchProtection } from "./branch-protection.ts";
import { repoAdmins } from "./share.ts";
import { git, run, templateRepoUrl } from "./git.ts";
import { addSecretsBlock } from "./template-sync.ts";
/** Files of the CI contract, copied from the template into project repos. */
export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh", ".gitea/workflows/deploy.yml", ".gitea/peppa-deploy.sh"];
/** Starting points copied only when the project has none yet (the project owns them after). */
export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "deploy/Dockerfile.python"];
export const CI_BRANCH = "peppa/ci";
/** PEP-242: branch of the «only the secrets block» PR. */
export const SECRETS_BRANCH = "peppa/secrets";
const DEPLOY_SCRIPT = ".gitea/peppa-deploy.sh";
export const CI_SECRET_NAME = "PEPPA_CI_SECRET";
/** Events the project webhook gets: PRs and pushes (PEP-57), issues, comments, reviews (PEP-46). */
@ -78,14 +82,17 @@ export async function setupCi(db: Db, project: Project): Promise<CiSetup> {
export interface ConnectCiResult extends CiSetup {
/** PR with the workflow files; null when the default branch already has them. */
prUrl: string | null;
/** PEP-242, secretsOnly: what happened to the project's deploy script. */
secrets?: "added" | "replaced" | "present";
}
/**
* "Connect CI" for an existing project: runner + secret, then a PR from Peppa that adds the
* workflow files from the template and an empty `checks` in .peppa/project.json.
*/
export async function connectCi(db: Db, project: Project, o: { templateUrl?: string; log?: (s: string) => void } = {}): Promise<ConnectCiResult> {
export async function connectCi(db: Db, project: Project, o: { templateUrl?: string; log?: (s: string) => void; secretsOnly?: boolean } = {}): Promise<ConnectCiResult> {
const log = o.log ?? (() => {});
if (o.secretsOnly) return connectSecretsBlock(project, o);
log("runner + secret");
const setup = await setupCi(db, project);
// PEP-191: the same command also puts the default branch protection back.
@ -142,3 +149,61 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str
rmSync(work, { recursive: true, force: true });
}
}
/**
* PEP-242: `peppa ci connect <KEY> --secrets-only` — the project's deploy script gets only the
* missing secrets block (addSecretsBlock), its own changes stay. A script equal to an older template
* (or none) is not needed here: the plain `ci connect` replaces it whole. No runner, Actions secret or
* webhook changes — those are already in place for a deploying project.
*/
async function connectSecretsBlock(project: Project, o: { templateUrl?: string; log?: (s: string) => void }): Promise<ConnectCiResult> {
const log = o.log ?? (() => {});
const bot = giteaForBot();
const repo = await bot.getRepo(project.giteaOwner, project.giteaRepo);
if (!repo) throw new PeppaError(m("Код проекта {repo} не найден", { repo: `${project.giteaOwner}/${project.giteaRepo}` }));
const base = project.defaultBranch;
const work = mkdtempSync(join(tmpdir(), "peppa-ci-"));
try {
log("clone");
const dest = join(work, "repo");
const tpl = join(work, "tpl");
await git(work, "clone", "-q", repo.clone_url, dest);
await git(work, "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl);
await git(dest, "checkout", "-q", "-B", SECRETS_BRANCH, `origin/${base}`);
const file = join(dest, DEPLOY_SCRIPT);
const template = readFileSync(join(tpl, DEPLOY_SCRIPT), "utf8");
let secrets: "added" | "replaced";
if (!existsSync(file)) {
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, template, { mode: 0o755 });
secrets = "replaced";
} else {
const r = addSecretsBlock(readFileSync(file, "utf8"), template);
if (r.state === "present") return { runner: "bot", prUrl: null, secrets: "present" };
// glossary-ignore: отказ читает администратор платформы в CLI
if (r.state === "unsupported") throw new PeppaError(m("Блок секретов не добавлен в {key}: {reason}. Добавьте его руками по шаблону.", { key: project.key, reason: r.reason }));
writeFileSync(file, r.script);
secrets = "added";
}
await git(dest, "add", "-A");
log("push");
await git(dest, "-c", "user.name=Peppa", "-c", `user.email=${botLogin()}@telecom.quest`, "commit", "-qm", "Секреты проекта в выкладке (PEP-112)");
await git(dest, "push", "-q", "-f", "origin", `HEAD:refs/heads/${SECRETS_BRANCH}`);
const open = await bot.openPullForBranch(project.giteaOwner, project.giteaRepo, SECRETS_BRANCH);
const pr =
open ??
(await bot.createPullRequest(project.giteaOwner, project.giteaRepo, {
head: SECRETS_BRANCH,
base,
title: "Секреты проекта в выкладке",
body: [
"PR от Peppa FACTORY (PEP-242): скрипт выкладки берёт секреты проекта у Peppa FACTORY («⋯ Настройки проекта → Секреты») и передаёт их сервису как переменные окружения (PEP-112).",
"",
`В \`${DEPLOY_SCRIPT}\` добавлен только блок секретов: функция \`project_secrets\`, её файл в \`docker compose\` внутри \`dc()\` и вызов после \`report deploying\`. Остальные строки скрипта не менялись.`,
].join("\n"),
}));
return { runner: "bot", prUrl: pr.html_url, secrets };
} finally {
rmSync(work, { recursive: true, force: true });
}
}

View File

@ -40,6 +40,7 @@ export * from "./ready-digest.ts";
export * from "./stuck-tasks.ts";
export * from "./project-trash.ts";
export * from "./branch-protection.ts";
export * from "./template-sync.ts";
export * from "./story-refine.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";

View File

@ -0,0 +1,162 @@
// PEP-242: the project template reaches Gitea by itself. From 15.11 to 23.11 nobody ran
// scripts/push-template.sh after merges, so agents read a week-old RULES.md and new projects got
// an old deploy script. Now the platform deploy pushes template/ (`peppa template push --alert`),
// and the watchdog compares Gitea's template with template/ of the running commit once an hour.
// Existing projects get only the missing secrets block in their deploy script (addSecretsBlock).
import { m } from "@peppa/shared/i18n";
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { alertAdmins, deleteSetting, getSetting, giteaForBot, peppaCommit, setSetting } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv, peppaRoot } from "@peppa/shared";
import { git, templateRepoUrl } from "./git.ts";
const HOUR_MS = 3600_000;
const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot";
/** template/ of the platform this process runs (the image has it at /app/template). */
export function platformTemplateDir(root?: string): string {
return join(root ?? peppaRoot(resolve(import.meta.dirname, "../../..")), "template");
}
export interface TemplateSyncResult {
/** unchanged — Gitea's template equals template/; behind — differs (check only); pushed — a commit went to main. */
state: "unchanged" | "behind" | "pushed";
/** Paths that differ (git status --porcelain), at most 50. */
changed: string[];
}
/** Creates the template repo when it is missing (the same as push-template.sh). */
async function ensureTemplateRepo(): Promise<void> {
const full = loadEnv().GITEA_TEMPLATE_REPO;
const [owner, name] = full.split("/") as [string, string];
const bot = giteaForBot();
if (await bot.getRepo(owner, name)) return;
await bot.request("POST", owner === botLogin() ? "/user/repos" : `/orgs/${encodeURIComponent(owner)}/repos`, {
name,
description: "Peppa project template",
default_branch: "main",
private: true,
template: true,
});
}
/**
* Compares the template repo with `dir` (template/ of the platform) and, with `push`, makes Gitea's
* main equal to it. The comparison is the push itself without the commit, so "behind" always means
* "a push would change something".
*/
export async function syncTemplate(o: { push: boolean; dir?: string; templateUrl?: string; commit?: string | null }): Promise<TemplateSyncResult> {
const dir = o.dir ?? platformTemplateDir();
if (!existsSync(dir)) throw new Error(`no template dir: ${dir}`);
if (o.push && !o.templateUrl && !process.env.PEPPA_TEMPLATE_URL) await ensureTemplateRepo();
const work = mkdtempSync(join(tmpdir(), "peppa-template-"));
try {
const dest = join(work, "t");
try {
await git(work, "clone", "-q", templateRepoUrl(o.templateUrl), dest);
} catch (e) {
if (!o.push) throw e;
rmSync(dest, { recursive: true, force: true });
await git(work, "init", "-q", "-b", "main", dest);
await git(dest, "remote", "add", "origin", templateRepoUrl(o.templateUrl));
}
for (const f of readdirSync(dest)) if (f !== ".git") rmSync(join(dest, f), { recursive: true, force: true });
cpSync(dir, dest, { recursive: true });
await git(dest, "add", "-A");
const { stdout } = await git(dest, "status", "--porcelain");
const changed = stdout.split("\n").filter(Boolean).map((l) => l.slice(3)).slice(0, 50);
if (!changed.length) return { state: "unchanged", changed };
if (!o.push) return { state: "behind", changed };
const commit = (o.commit ?? peppaCommit() ?? "unknown").slice(0, 7);
await git(dest, "-c", "user.name=Peppa", "-c", `user.email=${botLogin()}@telecom.quest`, "commit", "-qm", `Update Peppa template (${commit})`);
await git(dest, "push", "-q", "origin", "HEAD:main");
return { state: "pushed", changed };
} finally {
rmSync(work, { recursive: true, force: true });
}
}
/** `peppa template push --alert`: a failed push is one message to the superadmin per commit. */
export async function pushTemplateOrAlert(db: Db, o: { dir?: string; templateUrl?: string; log?: (s: string) => void } = {}): Promise<TemplateSyncResult | null> {
const log = o.log ?? (() => {});
try {
return await syncTemplate({ push: true, dir: o.dir, templateUrl: o.templateUrl });
} catch (e) {
const reason = ((e as Error).message ?? String(e)).replace(/\s+/g, " ").slice(0, 300);
const commit = (peppaCommit() ?? "unknown").slice(0, 7);
// glossary-ignore: сообщение читает администратор платформы
await alertAdmins(db, `template:push:${commit}`, m("Шаблон проектов не отправлен в Gitea после выкатки {commit}: {reason}. Агенты получают старые правила; отправить вручную — peppa template push.", { commit, reason }), log);
return null;
}
}
/**
* Watchdog: once an hour Gitea's template is compared with template/ of the running commit. Behind —
* one message to the superadmin per platform commit; equal again — the mark is cleared. It does not
* push by itself: the push belongs to the deploy.
*/
export async function templateSyncTick(db: Db, o: { now?: Date; dir?: string; templateUrl?: string; log?: (s: string) => void } = {}): Promise<TemplateSyncResult | null> {
if (process.env.PEPPA_TEMPLATE_SYNC === "off") return null;
const dir = o.dir ?? platformTemplateDir();
if (!existsSync(dir)) return null;
const now = (o.now ?? new Date()).getTime();
const last = await getSetting<number>(db, "template.sync.last");
if (last != null && now - last < HOUR_MS) return null;
await setSetting(db, "template.sync.last", now);
const r = await syncTemplate({ push: false, dir, templateUrl: o.templateUrl });
if (r.state === "unchanged") {
await deleteSetting(db, "template.drift");
return r;
}
const commit = (peppaCommit() ?? "unknown").slice(0, 7);
const prev = await getSetting<{ commit: string }>(db, "template.drift");
if (prev?.commit === commit) return r;
await setSetting(db, "template.drift", { commit, at: now, changed: r.changed });
const files = r.changed.slice(0, 5).join(", ");
// glossary-ignore: сообщение читает администратор платформы
await alertAdmins(db, `template:drift:${commit}`, m("Шаблон проектов в Gitea отстаёт от работающей версии {commit} (файлы: {files}). Агенты получают старые правила; отправить — peppa template push.", { commit, files }), o.log ?? (() => {}));
return r;
}
// ── the secrets block for existing projects ───────────────────────────────────────────────
export type SecretsBlockResult =
| { state: "added"; script: string }
| { state: "present" }
| { state: "unsupported"; reason: string };
const BLOCK_START = "# PEP-112: секреты проекта из "; // «из Пеппы» before PEP-243, «из FORGE» after
/**
* Adds only the project secrets block (PEP-112) of the template's deploy script to a project's own
* script: the block before `dc() {`, the override file in dc's `docker compose` line, the call after
* `report deploying`. Every other line stays as it was. No anchor, or the script has its own
* `trap … EXIT` (ours would replace it) — unsupported with the reason.
*/
export function addSecretsBlock(script: string, template: string): SecretsBlockResult {
if (/^\s*project_secrets\(\)\s*\{/m.test(script)) return { state: "present" };
const tl = template.split("\n");
const start = tl.findIndex((l) => l.startsWith(BLOCK_START));
const fn = tl.findIndex((l, i) => i > start && /^project_secrets\(\)\s*\{/.test(l));
const end = tl.findIndex((l, i) => i > fn && l === "}");
if (start < 0 || fn < 0 || end < 0) return { state: "unsupported", reason: "в шаблоне нет блока секретов" };
const block = tl.slice(start, end + 1);
if (/^\s*trap\b.*\bEXIT\b/m.test(script)) return { state: "unsupported", reason: "в скрипте свой trap … EXIT — блок его заменил бы" };
const lines = script.split("\n");
const dc = lines.findIndex((l) => /^dc\(\)\s*\{/.test(l));
if (dc < 0) return { state: "unsupported", reason: "в скрипте нет функции dc()" };
const dcEnd = lines.findIndex((l, i) => i > dc && l === "}");
const compose = lines.findIndex((l, i) => i > dc && i < dcEnd && l.includes("docker compose") && l.includes('-f "$compose"'));
if (compose < 0) return { state: "unsupported", reason: 'в dc() нет docker compose … -f "$compose"' };
const call = lines.findIndex((l) => l.trim() === "report deploying");
if (call < 0) return { state: "unsupported", reason: "в скрипте нет строки report deploying" };
const out = [...lines];
out.splice(call + 1, 0, "project_secrets");
out[compose] = out[compose]!.replace('-f "$compose"', '-f "$compose" ${override:+-f "$override"}');
out.splice(dc, 0, ...block, "");
return { state: "added", script: out.join("\n") };
}

View File

@ -4,6 +4,7 @@ import { asIs, m } from "@peppa/shared/i18n";
import { runnerTick } from "./runners.ts";
import { projectTrashTick } from "./project-trash.ts";
import { branchProtectionTick } from "./branch-protection.ts";
import { templateSyncTick } from "./template-sync.ts";
import { createHash } from "node:crypto";
import {
backupDb,
@ -137,6 +138,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
await projectTrashTick(db, { now: opts.now, log }).catch(failed(db, log, "project trash"));
// PEP-191: once a day the protection of every project's default branch is checked.
await branchProtectionTick(db, { now: opts.now, log }).catch(failed(db, log, "branch protection"));
// PEP-242: once an hour the template in Gitea is compared with template/ of the running commit.
await templateSyncTick(db, { now: opts.now, log }).catch(failed(db, log, "template sync"));
await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake"));
// PEP-115: a comment on a backlog story — the analyst reworks the story.
await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine"));

View File

@ -18,7 +18,7 @@ export const observe: Dict = {
"нестабильно": "unstable",
"← новее": "← newer",
"старее →": "older →",
"Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы. Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.": "Monitors of the services FORGE depends on and of the internet on its server. A change of state is one message to the platform's Telegram channel. The check log is kept for 7 days. Monitors can be created here and via MCP; only superadmins see this section.",
"Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы, пока не работает — напоминание раз в 30 минут (настраивается у мониторинга). Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.": "Monitors of the services FORGE depends on and of the internet on its server. A change of state is one message to the platform's Telegram channel; while down, a reminder every 30 minutes (set per monitor). The check log is kept for 7 days. Monitors can be created here and via MCP; only superadmins see this section.",
"Мониторинги": "Monitors",
"не работает: {n} · нестабильно: {m}": "down: {n} · unstable: {m}",
"Мониторингов нет. Сервис мониторингов создаст встроенные при первом запуске.": "No monitors. The monitoring service creates the built-in ones on its first start.",
@ -97,4 +97,18 @@ export const observe: Dict = {
"Входы за сутки: {n}, неудачных {m} ({reasons})": "Logins in 24 h: {n}, failed {m} ({reasons})",
"Входы за сутки: {n}, неудачных нет": "Logins in 24 h: {n}, none failed",
"Уборка журналов: {ago} — удалено строк {n}, база {size} МБ, свободно внутри {free} МБ": "Journal cleanup: {ago} — rows deleted {n}, database {size} MB, free inside {free} MB",
// PEP-223: reminders about an ongoing outage.
"{h} ч {n} мин": "{h} h {n} min",
"{h} ч": "{h} h",
"🔴 {name} не работает уже {duration} (с {since}): {reason}. Последняя проверка {time}.": "🔴 {name} has been down for {duration} (since {since}): {reason}. Last check {time}.",
"🟡 {name} нестабилен уже {duration} (с {since}): {reason}. Последняя проверка {time}.": "🟡 {name} has been unstable for {duration} (since {since}): {reason}. Last check {time}.",
"Напоминать раз в, мин (0 — не напоминать)": "Remind every, min (0 — never)",
"Напоминать и когда нестабилен": "Remind when unstable too",
"не работает {duration}": "down for {duration}",
"нестабилен {duration}": "unstable for {duration}",
"напоминаний: {n}": "reminders: {n}",
"следующее в {time}": "next at {time}",
"без напоминаний: вместе с интернетом": "no reminders: together with the internet",
"без напоминаний": "no reminders",
"напоминание раз в {n} мин": "reminder every {n} min",
};

View File

@ -480,4 +480,7 @@ export const runner: Dict = {
"🔑 Подписка «{name}»: проблема со входом — агент {n} раза подряд не смог войти в аккаунт. Агенты переезжают на другую подписку набора; эту проверьте в «Подписках».": "🔑 Subscription “{name}”: sign-in problem — the agent failed to sign in {n} times in a row. The agents move to another subscription of the set; check this one in “Subscriptions”.",
"{who}: агент не может войти в аккаунт, другой подписки в наборе нет.": "{who}: the agent cannot sign in to the account, and there is no other subscription in the set.",
"на прежней не удался вход": "sign-in failed on the previous one",
"Шаблон проектов не отправлен в Gitea после выкатки {commit}: {reason}. Агенты получают старые правила; отправить вручную — peppa template push.": "The project template was not pushed to Gitea after deploy {commit}: {reason}. Agents get the old rules; to push by hand — peppa template push.",
"Шаблон проектов в Gitea отстаёт от работающей версии {commit} (файлы: {files}). Агенты получают старые правила; отправить — peppa template push.": "The project template in Gitea is behind the running version {commit} (files: {files}). Agents get the old rules; to push — peppa template push.",
"Блок секретов не добавлен в {key}: {reason}. Добавьте его руками по шаблону.": "The secrets block was not added to {key}: {reason}. Add it by hand from the template.",
};

View File

@ -18,7 +18,7 @@ export const observe: Dict = {
"нестабильно": "тұрақсыз",
"← новее": "← жаңарақ",
"старее →": "ескірек →",
"Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы. Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.": "FORGE тәуелді сервистердің және оның серверіндегі интернеттің мониторингтері. Күйдің өзгеруі — платформаның Telegram-арнасына бір хабарлама. Тексерулер журналы 7 күн сақталады. Мониторингтерді осында және MCP арқылы жасауға болады; бөлімді тек суперәкімшілер көреді.",
"Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы, пока не работает — напоминание раз в 30 минут (настраивается у мониторинга). Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.": "FORGE тәуелді сервистердің және оның серверіндегі интернеттің мониторингтері. Күйдің өзгеруі — платформаның Telegram-арнасына бір хабарлама, жұмыс істемей тұрғанда — 30 минут сайын еске салу (мониторингте бапталады). Тексерулер журналы 7 күн сақталады. Мониторингтерді осында және MCP арқылы жасауға болады; бөлімді тек суперәкімшілер көреді.",
"Мониторинги": "Мониторингтер",
"не работает: {n} · нестабильно: {m}": "жұмыс істемейді: {n} · тұрақсыз: {m}",
"Мониторингов нет. Сервис мониторингов создаст встроенные при первом запуске.": "Мониторинг жоқ. Мониторинг сервисі алғаш іске қосылғанда кірістірілгендерін жасайды.",
@ -97,4 +97,18 @@ export const observe: Dict = {
"Входы за сутки: {n}, неудачных {m} ({reasons})": "Тәулікте кіру: {n}, сәтсіз {m} ({reasons})",
"Входы за сутки: {n}, неудачных нет": "Тәулікте кіру: {n}, сәтсізі жоқ",
"Уборка журналов: {ago} — удалено строк {n}, база {size} МБ, свободно внутри {free} МБ": "Журналдарды тазалау: {ago} — өшірілген жолдар {n}, дерекқор {size} МБ, ішіндегі бос {free} МБ",
// PEP-223: reminders about an ongoing outage.
"{h} ч {n} мин": "{h} сағ {n} мин",
"{h} ч": "{h} сағ",
"🔴 {name} не работает уже {duration} (с {since}): {reason}. Последняя проверка {time}.": "🔴 {name} {duration} бойы жұмыс істемейді ({since} бастап): {reason}. Соңғы тексеру {time}.",
"🟡 {name} нестабилен уже {duration} (с {since}): {reason}. Последняя проверка {time}.": "🟡 {name} {duration} бойы тұрақсыз ({since} бастап): {reason}. Соңғы тексеру {time}.",
"Напоминать раз в, мин (0 — не напоминать)": "Еске салу аралығы, мин (0 — еске салмау)",
"Напоминать и когда нестабилен": "Тұрақсыз кезде де еске салу",
"не работает {duration}": "{duration} бойы жұмыс істемейді",
"нестабилен {duration}": "{duration} бойы тұрақсыз",
"напоминаний: {n}": "еске салу: {n}",
"следующее в {time}": "келесісі {time}",
"без напоминаний: вместе с интернетом": "еске салусыз: интернетпен бірге",
"без напоминаний": "еске салусыз",
"напоминание раз в {n} мин": "{n} мин сайын еске салу",
};

View File

@ -388,4 +388,7 @@ export const runner: Dict = {
"🔑 Подписка «{name}»: проблема со входом — агент {n} раза подряд не смог войти в аккаунт. Агенты переезжают на другую подписку набора; эту проверьте в «Подписках».": "🔑 «{name}» жазылымы: кіру мәселесі — агент аккаунтқа қатарынан {n} рет кіре алмады. Агенттер жиынтықтағы басқа жазылымға көшеді; бұны «Жазылымдар» бөлімінде тексеріңіз.",
"{who}: агент не может войти в аккаунт, другой подписки в наборе нет.": "{who}: агент аккаунтқа кіре алмайды, жиынтықта басқа жазылым жоқ.",
"на прежней не удался вход": "алдыңғысында кіру сәтсіз болды",
"Шаблон проектов не отправлен в Gitea после выкатки {commit}: {reason}. Агенты получают старые правила; отправить вручную — peppa template push.": "Жобалар үлгісі {commit} шығарылымынан кейін Gitea-ға жіберілмеді: {reason}. Агенттер ескі ережелерді алады; қолмен жіберу — peppa template push.",
"Шаблон проектов в Gitea отстаёт от работающей версии {commit} (файлы: {files}). Агенты получают старые правила; отправить — peppa template push.": "Gitea-дағы жобалар үлгісі жұмыс істеп тұрған {commit} нұсқасынан қалып қойды (файлдар: {files}). Агенттер ескі ережелерді алады; жіберу — peppa template push.",
"Блок секретов не добавлен в {key}: {reason}. Добавьте его руками по шаблону.": "Құпиялар блогы {key} жобасына қосылмады: {reason}. Оны үлгі бойынша қолмен қосыңыз.",
};

View File

@ -32,6 +32,7 @@ Object.assign(process.env, {
// accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on.
PEPPA_PRODUCT_LINK: "off",
PEPPA_BRANCH_PROTECT: "off",
PEPPA_TEMPLATE_SYNC: "off",
// PEP-185: no «Взять в работу?» questions in other suites; pick-question.test.ts turns it on.
PEPPA_PICK_QUESTION: "off",
// PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.

View File

@ -257,19 +257,20 @@ describe("Алерт админу о молчащем сервисе", () => {
describe("Без спама", () => {
test("Повторные проверки", async () => {
await beatAt("bot", 0);
for (let m = 6; m <= 40; m += 0.5) await check("watchdog", m);
for (let m = 6; m <= 35; m += 0.5) await check("watchdog", m);
assert.equal((await queued(ADMIN.chatId)).length, 1);
});
test("Напоминание", async () => {
await beatAt("bot", 0);
for (let m = 6; m < 66; m += 5) await check("watchdog", m);
// PEP-223: every 30 minutes, the same period as the monitors of Observability.
for (let m = 6; m < 36; m += 5) await check("watchdog", m);
assert.equal((await queued(ADMIN.chatId)).length, 1);
await check("watchdog", 66);
await check("watchdog", 66.5);
await check("watchdog", 36);
await check("watchdog", 36.5);
const msgs = await queued(ADMIN.chatId);
assert.equal(msgs.length, 2);
assert.match(msgs[1]!, /бот молчит 66 мин/);
assert.match(msgs[1]!, /бот молчит 36 мин/);
});
test("Дребезг", async () => {

View File

@ -238,4 +238,108 @@ describe("Observability", () => {
names = (await core.serviceStatus(db)).map((s) => s.service);
assert.ok(names.includes("observer"));
});
// PEP-223: reminders while an outage lasts.
const reminders = async (id: number) =>
(await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `mon:ch:obs:${id}:%:r%`))).map((r) => ({ key: r.dedupeKey, status: r.status, text: stripAsIs(String(r.params.text)) }));
/** The bot in daytime: everything queued goes out. */
const deliverAll = () => db.update(telegramOutbox).set({ status: "sent", sentAt: new Date(clock) }).where(eq(telegramOutbox.status, "pending"));
test("Scenario: a 95-minute outage — the first message and 3 reminders; recovery stops them; a restart does not repeat one", async () => {
process.env.PEPPA_TZ = "UTC";
const url = "https://mock-remind.example/";
const m = core.createMonitor({ name: "mock remind", kind: "http", target: { url }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
await pass();
net.http.set(url, { status: 502, body: "" });
await pass();
const startedAt = clock;
assert.equal(core.getMonitor(m.id)!.state, "down");
for (let i = 0; i < 95; i++) {
await pass();
await deliverAll();
}
const list = await reminders(m.id);
assert.deepEqual(list.map((r) => r.key.split(":").at(-1)), ["r1", "r2", "r3"]);
assert.match(list[0]!.text, /^🔴 mock remind не работает уже 30 мин \(с \d\d:\d\d\): ответ 502\. Последняя проверка \d\d:\d\d\.$/);
assert.match(list[1]!.text, /не работает уже 1 ч \(/);
assert.match(list[2]!.text, /не работает уже 1 ч 30 мин \(/);
const view = core.monitorView(core.getMonitor(m.id)!, new Date(clock));
assert.equal(view.outage!.reminders, 3);
assert.equal(view.outage!.nextRemindAt, new Date(startedAt + 120 * 60_000).toISOString(), "the next — 30 min after the third");
// A restarted service (a second tick at the same moment) does not send the same reminder again.
clock += 25 * 60_000;
const due = new Date(startedAt + 120 * 60_000);
assert.equal(await core.remindIncidents(db, { now: due }), 1);
assert.equal(await core.remindIncidents(db, { now: due }), 0);
assert.equal((await reminders(m.id)).length, 4);
net.http.delete(url);
await pass();
await deliverAll();
for (let i = 0; i < 40; i++) await pass();
assert.equal((await reminders(m.id)).length, 4, "up again — no reminders");
assert.match((await sent("mon:ch:obs:")).at(-1)!.text, /✅ mock remind снова работает/);
assert.equal(core.monitorIncidents(m.id)[0]!.reminders, 4);
core.deleteMonitor(m.id);
});
test("Scenario: at night the reminders do not pile up — one waits for the morning, with the start of the outage", async () => {
process.env.PEPPA_TZ = "UTC";
process.env.PEPPA_NIGHT_QUIET = "23:00-08:00";
try {
clock = Date.parse("2026-11-19T02:09:00Z");
const url = "https://mock-night.example/";
const m = core.createMonitor({ name: "mock night", kind: "http", target: { url }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
net.http.set(url, "timeout");
await pass(); // 02:10 — down
await deliverAll(); // the first message (the test bot sends it; the real one would hold it till 08:00 too)
while (clock < Date.parse("2026-11-19T07:59:00Z")) await pass(10);
const list = await reminders(m.id);
assert.equal(list.length, 1, "one unsent reminder instead of a pile");
assert.equal(list[0]!.status, "pending");
assert.match(list[0]!.text, /не работает уже 5 ч \d+ мин \(с 02:10\)/);
assert.ok(core.monitorIncidents(m.id)[0]!.reminders >= 10, "the counter keeps counting");
const night = await core.pendingMonitorMessages(db, new Date(Date.parse("2026-11-19T07:30:00Z")));
assert.ok(!night.some((r) => r.dedupeKey.startsWith(`mon:ch:obs:${m.id}:`)), "nothing goes out at night");
const morning = await core.pendingMonitorMessages(db, new Date(Date.parse("2026-11-19T08:01:00Z")));
assert.equal(morning.filter((r) => r.dedupeKey.startsWith(`mon:ch:obs:${m.id}:`) && /:r\d+$/.test(r.dedupeKey)).length, 1, "the morning brings one");
core.deleteMonitor(m.id);
} finally {
process.env.PEPPA_NIGHT_QUIET = "off";
}
});
test("Scenario: no reminders for a quiet outage, with remind_min = 0, for «degraded» by default and on pause", async () => {
const off = core.createMonitor({ name: "mock off", kind: "tcp", target: { host: "10.7.0.1", port: 80 }, intervalSec: 60, failThreshold: 1, remindMin: 0 }, "system", new Date(clock));
const paused = core.createMonitor({ name: "mock paused", kind: "tcp", target: { host: "10.7.0.2", port: 80 }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
net.system.set("mock-slow.example", ["10.7.0.9"]);
net.fallback.set("mock-slow.example", ["10.7.0.8"]);
net.up.add("10.7.0.8");
const slow = core.createMonitor({ name: "mock slow", kind: "dns", target: { host: "mock-slow.example" }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
await pass();
assert.equal(core.getMonitor(off.id)!.state, "down");
assert.equal(core.getMonitor(slow.id)!.state, "degraded");
core.setMonitorPaused(paused.id, true, new Date(clock));
for (let i = 0; i < 12; i++) {
await pass(10);
await deliverAll();
}
for (const m of [off, paused, slow]) assert.equal((await reminders(m.id)).length, 0, m.name);
assert.equal(core.monitorView(core.getMonitor(off.id)!).outage!.nextRemindAt, null);
// «degraded» reminds once the monitor asks for it.
core.updateMonitor(slow.id, { remindDegraded: true, remindMin: 30 });
await pass();
assert.match((await reminders(slow.id))[0]!.text, /^🟡 mock slow нестабилен уже 2 ч/);
for (const m of [off, paused, slow]) core.deleteMonitor(m.id);
net.up.delete("10.7.0.8");
});
test("Scenario: the platform services remind every 30 minutes too", async () => {
// The default period is the monitors' one.
assert.equal(core.observeRemindMin(), 30);
process.env.PEPPA_OBSERVE_REMIND_MIN = "0";
assert.equal(core.observeRemindMin(), 0);
delete process.env.PEPPA_OBSERVE_REMIND_MIN;
});
});

View File

@ -0,0 +1,186 @@
// PEP-242: the project template reaches Gitea by itself (deploy + watchdog check), and existing
// projects get only the missing secrets block in their deploy script. Tests are named after the
// scenarios of openspec/changes/pep-242-template-sync/specs/project-template.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { cpSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { like } from "drizzle-orm";
import { telegramOutbox } from "@peppa/db";
import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, runner, superadmin, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-tpl-sync-"));
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_WORKSPACES = join(TMP, "workspaces");
const gitea = new MockGitea(join(TMP, "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-tpl-bot" };
const TEMPLATE = readFileSync(join(ROOT, "template/.gitea/peppa-deploy.sh"), "utf8");
let tplRepo = "";
/** A copy of template/ the tests edit (the real one stays as it is). */
const DIR = join(TMP, "template");
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
tplRepo = gitea.addRepo("peppa-bot", "template", { files: { "RULES.md": "# old rules\n" } }).path;
cpSync(join(ROOT, "template"), DIR, { recursive: true });
await superadmin();
});
after(async () => {
await gitea.stop();
await teardown();
});
const alerts = async (prefix: string) =>
(await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `${prefix}%`))).map((r) => stripAsIs(String(r.params.text)));
const show = (...args: string[]) => execFileSync("git", ["--git-dir", tplRepo, "show", ...args], { encoding: "utf8" });
describe("Шаблон проектов уходит в Gitea с выкаткой", () => {
test("Сценарий: Выкатка с изменённым шаблоном", async () => {
const deploy = readFileSync(join(ROOT, "scripts/platform-deploy.sh"), "utf8");
execFileSync("bash", ["-n", join(ROOT, "scripts/platform-deploy.sh")]);
const push = deploy.indexOf("push_template ||");
assert.match(deploy, /push_template\(\) \{ docker exec peppa-watchdog peppa template push --alert; \}/);
assert.ok(push > deploy.indexOf('echo "$SHORT" >"$PREV_FILE"'), "the template goes after the deploy is checked and recorded");
assert.ok(push < deploy.indexOf('say "ГОТОВО'));
assert.doesNotMatch(deploy.slice(push, deploy.indexOf("\n", push)), /die|rollback/, "a failed push does not roll the deploy back");
const r = await runner.syncTemplate({ push: true, dir: DIR, templateUrl: tplRepo, commit: "abcdef1234" });
assert.equal(r.state, "pushed");
assert.match(show("main", "--format=%s", "--no-patch"), /^Update Peppa template \(abcdef1\)/);
assert.equal(show("main:RULES.md"), readFileSync(join(ROOT, "template/RULES.md"), "utf8"));
assert.equal(show("main:.gitea/peppa-deploy.sh"), TEMPLATE);
});
test("Сценарий: Шаблон не изменился", async () => {
const head = show("main", "--format=%H", "--no-patch");
assert.equal((await runner.syncTemplate({ push: true, dir: DIR, templateUrl: tplRepo })).state, "unchanged");
assert.equal(show("main", "--format=%H", "--no-patch"), head);
});
test("Сценарий: Gitea недоступна при отправке", async () => {
const r = await runner.pushTemplateOrAlert(db, { dir: DIR, templateUrl: join(TMP, "no-such-repo.git") });
assert.equal(r, null);
const sent = await alerts("template:push:");
assert.equal(sent.length, 1);
assert.match(sent[0]!, /Шаблон проектов не отправлен в Gitea/);
});
});
describe("Сверка шаблона в вачдоге", () => {
test("Сценарий: Шаблон совпадает", async () => {
process.env.PEPPA_TEMPLATE_SYNC = "on";
try {
const r = await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T10:00:00Z") });
assert.equal(r?.state, "unchanged");
assert.equal((await alerts("template:drift:")).length, 0);
} finally {
process.env.PEPPA_TEMPLATE_SYNC = "off";
}
});
test("Сценарий: Шаблон отстаёт", async () => {
process.env.PEPPA_TEMPLATE_SYNC = "on";
try {
writeFileSync(join(DIR, "RULES.md"), `${readFileSync(join(DIR, "RULES.md"), "utf8")}\n## Новое правило\n`);
const r = await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T12:00:00Z") });
assert.equal(r?.state, "behind");
assert.deepEqual(r?.changed, ["RULES.md"]);
// An hour later — the same commit, no second message; within the hour — not even checked.
assert.equal(await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T12:30:00Z") }), null);
assert.equal((await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T13:01:00Z") }))?.state, "behind");
const sent = await alerts("template:drift:");
assert.equal(sent.length, 1);
assert.match(sent[0]!, /Шаблон проектов в Gitea отстаёт.*RULES\.md/);
// The check never pushes by itself.
assert.doesNotMatch(show("main:RULES.md"), /Новое правило/);
} finally {
process.env.PEPPA_TEMPLATE_SYNC = "off";
}
});
});
/** The template's deploy script as it was before PEP-112: no block, no override, no call — plus a project's own line. */
function oldProjectScript(): string {
const lines = TEMPLATE.split("\n");
const start = lines.findIndex((l) => l.startsWith("# PEP-112: секреты проекта из "));
const end = lines.findIndex((l, i) => i > start && l === "}");
lines.splice(start, end - start + 2);
const out = lines
.filter((l) => l !== "project_secrets" && !l.includes('local files=(-f "$compose")') && !l.includes('files+=(-f "$override")'))
.map((l) => l.replace('docker compose -p "$project" "${files[@]}" "$@"', 'docker compose -p "$project" -f "$compose" "$@"'));
out.splice(out.indexOf("report deploying"), 0, 'echo "custom step"');
return out.join("\n");
}
describe("Блок секретов без затирания доработок", () => {
test("Сценарий: Скрипт проекта с доработками", async () => {
const old = oldProjectScript();
assert.doesNotMatch(old, /project_secrets|override/);
const r = runner.addSecretsBlock(old, TEMPLATE);
assert.equal(r.state, "added");
if (r.state !== "added") return;
// Every old line stays, in order; the added ones are the block, the call and the override in dc.
const next = r.script.split("\n");
let at = 0;
for (const l of old.split("\n")) {
const found = next.indexOf(l.replace('-f "$compose" "$@"', '-f "$compose" ${override:+-f "$override"} "$@"'), at);
assert.ok(found >= at, `line kept: ${l}`);
at = found + 1;
}
assert.match(r.script, /^project_secrets\(\) \{/m);
assert.match(r.script, /^report deploying\nproject_secrets\n/m);
assert.match(r.script, /echo "custom step"/);
execFileSync("bash", ["-n"], { input: r.script });
// The override word disappears when there are no secrets and becomes `-f <file>` with them.
const args = (override: string) =>
execFileSync("bash", ["-c", `compose=c.yml override=${JSON.stringify(override)}; printf '[%s]' -f "$compose" \${override:+-f "$override"}`], { encoding: "utf8" });
assert.equal(args(""), "[-f][c.yml]");
assert.equal(args("/tmp/p env"), "[-f][c.yml][-f][/tmp/p env]");
});
test("Сценарий: Блок уже есть", () => {
assert.deepEqual(runner.addSecretsBlock(TEMPLATE, TEMPLATE), { state: "present" });
});
test("Сценарий: Скрипт без функции dc", () => {
const r = runner.addSecretsBlock(oldProjectScript().replace("dc() {", "compose_run() {"), TEMPLATE);
assert.equal(r.state, "unsupported");
const trap = runner.addSecretsBlock(`trap 'rm -f x' EXIT\n${oldProjectScript()}`, TEMPLATE);
assert.equal(trap.state, "unsupported", "the project's own EXIT trap would be replaced");
});
test("ci connect --secrets-only: PR только с блоком, остальные файлы не тронуты", async () => {
const old = oldProjectScript();
gitea.addRepo(BOT.login, "tplsec", {
admins: [BOT.login],
files: { "README.md": "# x\n", ".gitea/peppa-deploy.sh": old, ".peppa/project.json": JSON.stringify({ slug: "tplsec", key: "TPS", name: "TPS", peppaUrl: "http://peppa.test" }) },
});
const p = await core.createProject(db, { slug: "tplsec", key: "TPS", name: "TPS", giteaOwner: BOT.login, workspacePath: join(TMP, "ws", "tplsec"), ownerId: null });
const r = await runner.connectCi(db, p, { templateUrl: tplRepo, secretsOnly: true });
assert.equal(r.secrets, "added");
assert.ok(r.prUrl?.endsWith("/pulls/1"));
const repo = gitea.repo(BOT.login, "tplsec");
assert.equal(repo.pulls[0]!.head, runner.SECRETS_BRANCH);
const git = (...a: string[]) => execFileSync("git", ["--git-dir", repo.path, ...a], { encoding: "utf8" });
assert.equal(git("diff", "--name-only", "main", runner.SECRETS_BRANCH).trim(), ".gitea/peppa-deploy.sh");
const script = git("show", `${runner.SECRETS_BRANCH}:.gitea/peppa-deploy.sh`);
assert.match(script, /echo "custom step"/);
assert.match(script, /^project_secrets$/m);
assert.equal(repo.secrets.PEPPA_CI_SECRET, undefined, "secrets-only does not touch CI setup");
// Merged — the block is there, nothing more to add.
await core.giteaForBot().mergePullRequest(BOT.login, "tplsec", 1);
const again = await runner.connectCi(db, p, { templateUrl: tplRepo, secretsOnly: true });
assert.deepEqual([again.secrets, again.prUrl], ["present", null]);
});
});

View File

@ -173,4 +173,6 @@ ERRS=$(tail -n +$((MARK + 1)) "$LOG" 2>/dev/null | grep -E "⨯|ERR_SQLITE|no su
[ -z "$ERRS" ] || rollback "server errors after the restart:
$ERRS"
rm -rf "$WEB/.next.prev"
# PEP-242: the project template goes to Gitea with every deploy; a failure does not roll back.
./packages/cli/bin/peppa template push --alert || say "project template not pushed (superadmin alerted)"
say "DONE — the site runs ${TARGET:0:8} (was ${PREV:0:8}); pages and health checked"

View File

@ -5,7 +5,9 @@
# 3. копия базы и миграции новым образом (одноразовый контейнер);
# 4. docker compose --profile platform up -d новым тегом;
# 5. /api/health с коммитом цели и свежими heartbeat; страницы под mock-pm;
# 6. сбой на любом шаге после 4 — откат на предыдущий тег (файл $PEPPA_HOME/platform.tag).
# 6. сбой на любом шаге после 4 — откат на предыдущий тег (файл $PEPPA_HOME/platform.tag);
# 7. PEP-242: шаблон проектов (template/ цели) → репозиторий шаблона в Gitea; сбой — сообщение
# суперадмину (peppa template push --alert), выкатку не откатывает.
# Usage: scripts/platform-deploy.sh [--wait] [--no-ci] [<sha>] PEPPA_PLATFORM_DRY=1 — только план.
# Переезд с launchd (остановить quest.telecom.peppa.*, переключить Traefik) — по явному разрешению PM:
# см. openspec/changes/pep-222-all-in-docker/design.md.
@ -105,4 +107,9 @@ for p in / /projects /chats /help /settings /team; do
done
rm -f "$JAR"
echo "$SHORT" >"$PREV_FILE"
# PEP-242: с 15.11 по 23.11 шаблон в Gitea никто не обновлял — агенты брали старые правила. Теперь его
# отправляет каждая выкатка — из уже запущенного watchdog цели (в образе template/, git с помощником бота,
# сеть и .env — как у сервисов).
push_template() { docker exec peppa-watchdog peppa template push --alert; }
push_template || say "шаблон проектов не отправлен (суперадмину сообщено) — выкатка не откатывается"
say "ГОТОВО — платформа в контейнерах на $SHORT (была ${PREV:-—})"