PEP-224: статус функций из мониторинга (сведено с main после PEP-225)
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 34с
peppa/test test: success за 1325с
peppa-ci / ci (pull_request) Successful in 24m11s

Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP,
отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на
WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и
WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с
`observe`, смена сбрасывает кэш статусов.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-23 05:14:32 +00:00
parent 8ba72b0263
commit acb6e3fb81
37 changed files with 1054 additions and 65 deletions

View File

@ -45,7 +45,7 @@
- Чужой текст в сообщениях (PEP-139/140): слова человека/модели, название задачи/проекта, логин, варианты агента, причину извне подставляй в `m()` как `asIs(…)` (shared/i18n) — перевод их не трогает; фразы самой фабрики (`PeppaError`, причина гейта) не помечай. Вопрос агента = `questionIsFreeText`, текст переводящему читателю — `questionText(q)`; MCP, CLI, агенту и сравнение текста в тестах — `stripAsIs`.
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts; `runner/agent-relay.ts` — это релей песочницы, не путать), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; задачу из очереди ёмкости убирай `moveTask(backlog)`, иначе её подхватит тик соседнего теста. Конец хода агента вопроса не создаёт — жди статус сессии `idle`. Сообщения суперадмина — `superadmin()` из helpers.ts. Текст из `chat_messages` сравнивай через `stripAsIs`.
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб с агентами — runnerCall.
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб с агентами — runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>`, живая область `features` открыта без входа (PEP-224).
- Вопрос ≠ задача (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 — стоп).
@ -59,6 +59,6 @@
- `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: по почте учётки не склеиваем.
- Привязка Google к учётке с другим Google-only пользователем объединяет учётки (core/merge-users.ts `mergeUserInto`); с eGov/Gitea — отказ к админу (PEP-195).
- Речь — свой faster-whisper (`<Dictate>`), не Web Speech API. Google: по почте учётки не склеиваем.
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
- Язык голоса (PEP-131): `transcribeLanguage(cfg, locale)` — язык интерфейса говорящего; новый вызов `transcribe` передаёт его пятым аргументом.

View File

@ -109,6 +109,8 @@
- **Шаблон уходит сам (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`, без сообщений. **Напоминания (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`
- **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`
- **Статус функций из мониторинга (PEP-224)**: `core/feature-status.ts` — функции платформы (`FEATURE_NAMES` в `feature-names.ts`: `egov_login`, `mcp`, `google_login`, `bot`, `voice`, `bugsink`), связка — колонка `monitors.features` в `observe.db` (v2; там же `features` — порог `disable_after_min` и объявленное состояние, `feature_log`). Правило `computeFeatures`: связанный мониторинг не на паузе `down` дольше порога (5 мин) → `unavailable`, `degraded` → пометка, восстановление — по `recover_threshold` мониторинга; тихие сбои тоже выключают. Чтение `featureStatus(name)`/`featureGateView` — кэш 15 с с отпечатком объявленных состояний (`featureFingerprint`), сбой `observe.db` → доступна. `featureTick` в `peppa-observer`: смена → `feature_log`, событие `feature_disabled|feature_enabled` платформенного проекта, сообщение в канал «services» (`mon:ch:feature:…`, без канала — `alertAdmins`), `notify({type:"feature"})`; первое вычисление только запоминает. Встроенные: eGov-мониторинги с `egov_login`, `seedFeatureMonitors` — «MCP-сервер /mcp» (ждёт 401) и «MCP — вход OAuth» для публичного `PEPPA_WEB_URL`. Сервер: `startEgovFlow` → `assertFeatureAvailable` до запроса к relay; `/mcp` — ошибка JSON-RPC (HTTP 200: 5xx подменяет Cloudflare). Веб: `components/FeatureGate.tsx` (серый, `aria-disabled`, подпись, «с ЧЧ:ММ»; новые функции — через него) на входе (Google становится основным), «Настройки → eGov» и подключение ИИ-клиентов, `/mcp-guide`, «Помощь»; живая область `features` открыта без входа (`/api/live`), хаб сверяет её отпечаток сам каждую секунду. `/observability` — «Функции» (порог, журнал), у мониторинга «Что отключать при сбое»; MCP `create_monitor`/`update_monitor` — `features`. Тест `feature-status.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

@ -3,7 +3,8 @@
// 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it
// deletes checks older than the retention (7 days). Monitors are rows in observe.db: the web and
// MCP change them, the service picks the change up on its next pass — no restart.
import { beat, observeTick, pruneObserve, seedMonitors, type ObserveProbes } from "@peppa/core";
import { beat, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, type ObserveProbes } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import type { Db } from "@peppa/db";
export interface ObserverOptions {
@ -16,6 +17,10 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
const log = o.log ?? (() => {});
const made = seedMonitors();
if (made.length) log(`observer: built-in monitors created: ${made.map((m) => m.name).join(", ")}`);
// PEP-224: MCP monitors switch the «mcp» feature off; created once, when the web has a public address.
const mcp = seedFeatureMonitors(loadEnv().PEPPA_WEB_URL);
if (mcp.length) log(`observer: built-in monitors created: ${mcp.map((m) => m.name).join(", ")}`);
let featuresBusy = false;
log("observer started");
let lastBeat = 0;
let lastPrune = 0;
@ -36,6 +41,13 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
}
// Not awaited: a slow check must not hold the others or the heartbeat.
void observeTick(db, { log, probes: o.probes }).catch((e: Error) => log(`observer: tick failed: ${e.message}`));
// PEP-224: features follow their monitors — announce a change (journal, channel, live pages).
if (!featuresBusy) {
featuresBusy = true;
void featureTick(db, { log })
.catch((e: Error) => log(`observer: features failed: ${e.message}`))
.finally(() => (featuresBusy = false));
}
await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000));
}
}

View File

@ -1,27 +1,33 @@
import Link from "next/link";
import { CONNECT_HELP } from "@peppa/core";
import { CONNECT_HELP, featureGateView } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PageHeader } from "@/components/common";
import { CopyText } from "@/components/CopyText";
import { Workspace } from "@/components/Workspace";
import { publicOrigin } from "@/lib/auth";
import { getLocale } from "@/lib/i18n";
import { getLocale, getT } from "@/lib/i18n";
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
export default async function ConnectHelp() {
const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
const address = `${await publicOrigin()}/mcp`;
const tr = await getT();
const card = "flex flex-col gap-2 rounded-lg border bg-card px-4 py-3";
const h2 = "m-0 text-[15px] font-semibold";
return (
<Workspace>
<div className="max-w-2xl text-sm leading-relaxed">
<LiveRefresh scope="features" indicator={false} />
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">{t.back}</Link>} title={t.title}>
{t.lead}
</PageHeader>
<div className="flex flex-col gap-3">
<section className={card}>
<h2 className={h2}>{t.addressTitle}</h2>
<CopyText value={address} label={t.copy} done={t.copied} />
<FeatureGate view={featureGateView("mcp")} title={tr("MCP временно недоступен")}>
<CopyText value={address} label={t.copy} done={t.copied} />
</FeatureGate>
<p className="m-0 text-muted-foreground">{t.addressNote}</p>
</section>
{t.apps.map((app) => (

View File

@ -1,6 +1,8 @@
import Link from "next/link";
import type { ReactNode } from "react";
import { CONNECT_HELP, PRODUCT_HELP } from "@peppa/core";
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { m } from "@peppa/shared/i18n";
import { getLocale, getT } from "@/lib/i18n";
import { publicOrigin, uiMode } from "@/lib/auth";
@ -174,8 +176,11 @@ export default async function Help() {
</Section>
<Section title={t("Подключить MCP")}>
<p className="m-0">{t("Адрес сервера:")}</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
<LiveRefresh scope="features" indicator={false} />
<FeatureGate view={featureGateView("mcp")} title={t("MCP временно недоступен")}>
<p className="m-0">{t("Адрес сервера:")}</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
</FeatureGate>
<ul>
<li>{rich(t("<b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется FORGE — войдите через eGov и нажмите «Разрешить». В чате включите коннектор FORGE."))}</li>
<li>{rich(t("<b>Инструкция для ИИ</b>: первым делом ИИ-клиент вызывает инструмент <m>get_started</m> — памятка менеджера: код пишут только агенты, напрямую в код проекта не лезть, «Готово» — только после «Принять». Те же слова — на открытой странице <a href=\"/mcp-guide\">/mcp-guide</a> (кнопка «Скопировать» — для «Инструкций» проекта ChatGPT или системного сообщения другого ИИ). Первый ответ <m>list_projects</m> и <m>get_task</m> напоминает о ней."))}</li>

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Trash2 } from "lucide-react";
import { describeTarget, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Hidden } from "@/components/cards";
@ -69,6 +69,9 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr
{" · "}
{(m.remindMin ?? observeRemindMin()) ? t("напоминание раз в {n} мин", { n: m.remindMin ?? observeRemindMin() }) : t("без напоминаний")}
</p>
<p className="m-0 text-xs text-muted-foreground">
{t("Что отключать при сбое:")} {m.features.length ? m.features.map((f) => t(FEATURES[f].label)).join(", ") : t("ничего")}
</p>
<div className="flex flex-wrap gap-2">
<form action={pauseMonitorAction}>
<Hidden fields={{ id: m.id, paused: m.paused ? "0" : "1", back: `/observability/${m.id}` }} />

View File

@ -1,7 +1,7 @@
"use server";
// Observability (PEP-202): every action is superadmin-only (others get "not found").
import { createMonitor, deleteMonitor, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core";
import { createMonitor, deleteMonitor, resetFeatureCache, setFeatureThreshold, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core";
import type { Db } from "@peppa/db";
import { m } from "@peppa/shared/i18n";
import { revalidatePath } from "next/cache";
@ -53,6 +53,8 @@ function targetOf(kind: MonitorKind, f: FormData): MonitorTarget {
}
const numbers = (f: FormData) => ({
// PEP-224: «Что отключать при сбое» — the checked features.
features: f.getAll("features").map(String),
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,
@ -98,3 +100,14 @@ export async function deleteMonitorAction(f: FormData) {
return BASE;
});
}
/** PEP-224: how long a linked monitor may be down before the feature turns grey. */
export async function setFeatureThresholdAction(f: FormData) {
await attempt(f, BASE, async (login) => {
const name = str(f, "name");
const minutes = Number(str(f, "disableAfterMin"));
setFeatureThreshold(name, minutes);
resetFeatureCache();
await journal(db, "feature_updated", { feature: name, disableAfterMin: minutes, author: `user:${login}` });
});
}

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Plus } from "lucide-react";
import { describeTarget, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, getLastRetention, isSuperadmin, listErrors, listMonitorViews } from "@peppa/core";
import { describeTarget, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, getLastRetention, isSuperadmin, listErrors, listMonitorViews } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Hidden } from "@/components/cards";
@ -15,7 +15,9 @@ import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { createMonitorAction, pauseMonitorAction } from "./actions";
import { createMonitorAction, pauseMonitorAction, setFeatureThresholdAction } from "./actions";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
@ -93,6 +95,10 @@ export default async function Observability({ searchParams }: { searchParams: Pr
const web = loadEnv().PEPPA_WEB_URL;
const down = monitors.filter((m) => !m.paused && m.state === "down").length;
const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length;
// PEP-224: features follow their monitors.
const features = featureStatuses({ fresh: true });
const flog = featureLog(20);
const FEATURE_STATE = { available: [t("доступна"), "border-ok/40 text-ok"], degraded: [t("с задержками"), "border-warn/40 text-warn"], unavailable: [t("отключена"), "border-destructive/40 text-destructive"] } as const;
return (
<Workspace>
<LiveRefresh scope="observe" />
@ -155,6 +161,63 @@ export default async function Observability({ searchParams }: { searchParams: Pr
</form>
</Disclosure>
</Section>
<Section title={t("Функции")} count={FEATURE_NAMES.length}>
<p className="m-0 text-sm text-muted-foreground">{t("Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.")}</p>
<div className="flex flex-col gap-2">
{FEATURE_NAMES.map((name) => {
const f = features[name];
const [label, cls] = FEATURE_STATE[f.state];
return (
<Card key={name} className="gap-1.5 py-3" data-feature-row={name}>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className={cls}>{label}</Badge>
<span className="font-semibold">{t(FEATURES[name].label)}</span>
<span className="font-mono text-xs text-muted-foreground">{name}</span>
<form action={setFeatureThresholdAction} className="ml-auto flex items-center gap-1.5 text-xs text-muted-foreground">
<Hidden fields={{ name }} />
{t("отключать через, мин")}
<Input name="disableAfterMin" type="number" min={0} max={1440} defaultValue={f.disableAfterMin} className="h-7 w-16" />
<Button size="sm" variant="ghost">{t("Сохранить")}</Button>
</form>
</div>
<div className="text-xs text-muted-foreground">
{f.monitors.length ? (
<>
{t("Мониторинги:")}{" "}
{f.monitors.map((mm, i) => (
<span key={mm.id}>
{i ? ", " : ""}
<Link href={`/observability/${mm.id}`} className="hover:underline">{mm.name}</Link>
</span>
))}
</>
) : (
t("Не связана ни с одним мониторингом — всегда доступна.")
)}
{f.failing.length ? <span className="text-destructive"> · {f.failing.map((x) => `${x.name}${x.reason ? `: ${x.reason}` : ""}`).join("; ")}</span> : null}
</div>
</Card>
);
})}
</div>
<Disclosure summary={t("Журнал включений и выключений ({n})", { n: flog.length })}>
{flog.length === 0 ? (
<Empty>{t("Функции ещё не отключались.")}</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{flog.map((e) => (
<li key={e.id} className="flex flex-wrap gap-2">
<span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span>
<span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
</li>
))}
</ul>
)}
</Disclosure>
</Section>
</div>
</Workspace>
);

View File

@ -1,4 +1,4 @@
import { CONNECT_HELP, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { CONNECT_HELP, featureGateView, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
@ -6,6 +6,8 @@ import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { GoogleSignIn } from "@/components/GoogleSignIn";
import { EgovSign } from "@/components/EgovSign";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { OwnBotSteps } from "@/components/OwnBotSteps";
import { voiceStoriesEnabled } from "@peppa/shared";
import { Workspace } from "@/components/Workspace";
@ -50,10 +52,14 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const vapid = await vapidPublicKey(db);
const t = await getT();
const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
// PEP-224: features whose service is down are grey here (eGov binding, connecting AI clients).
const egovGate = featureGateView("egov_login");
const mcpGate = featureGateView("mcp");
const ownBotSteps = <OwnBotSteps botUsername={user.telegramBotUsername} back="/settings" />;
return (
<Workspace>
<div className="max-w-2xl">
<LiveRefresh scope="features" indicator={false} />
<Flash error={error} />
<PageHeader title={t("Настройки")} />
<Section title={t("Язык интерфейса")} id="language">
@ -146,7 +152,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
<Card>
<p className="m-0 text-sm">{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в FORGE — только через eGov.")}</p>
<div className="max-w-xs">
<EgovSign purpose="link" label={t("Привязать eGov")} />
<FeatureGate view={egovGate} label={t("Привязать eGov")}>
<EgovSign purpose="link" label={t("Привязать eGov")} />
</FeatureGate>
</div>
</Card>
</Section>
@ -309,12 +317,14 @@ export default async function Settings({ searchParams }: { searchParams: Promise
</Section>
<Section title={w.engineer ? t("MCP для ChatGPT и других клиентов") : t("FORGE в вашем Claude или ChatGPT")}>
<p className="m-0 text-sm">{w.engineer ? t("Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране FORGE.") : t("Подключите FORGE к своему чату — и ставьте задачи и отвечайте агентам прямо из него. Понадобится этот адрес; доступ вы подтвердите на экране FORGE.")}</p>
<CopyText value={`${origin}/mcp`} label={connect.copy} done={connect.copied} />
<p className="m-0 text-sm">
<a href="/help/connect" className="font-medium text-primary">{connect.linkLabel} →</a>
{" · "}
<a href="/mcp-guide" className="font-medium text-primary">{t("Инструкция для ИИ")} →</a>
</p>
<FeatureGate view={mcpGate} title={t("MCP временно недоступен")}>
<CopyText value={`${origin}/mcp`} label={connect.copy} done={connect.copied} />
<p className="m-0 text-sm">
<a href="/help/connect" className="font-medium text-primary">{connect.linkLabel} →</a>
{" · "}
<a href="/mcp-guide" className="font-medium text-primary">{t("Инструкция для ИИ")} →</a>
</p>
</FeatureGate>
</Section>
<Section title={t("Подключённые приложения")} id="apps">
{apps.length === 0 ? (

View File

@ -12,12 +12,14 @@ const fail = async (status: number, error: string) => Response.json({ error: (aw
export async function GET(req: Request) {
const user = await currentUser();
if (!user) return fail(401, m("Нужен вход"));
try {
const q = new URL(req.url).searchParams;
const scopes = parseScopes(q.get("scope"));
// PEP-224: only `features` (state of platform features, no user data) is open without a sign-in.
if (!user && scopes.some((s) => s !== "features")) return fail(401, m("Нужен вход"));
// PEP-225: `since.<scope>=<version>` — what the tab saw before a drop (fallback of the WebSocket).
const since = Object.fromEntries([...q].filter(([k]) => k.startsWith("since.")).map(([k, v]) => [k.slice(6), v]));
return await liveSse(db, user, parseScopes(q.get("scope")), req.signal, { since });
return await liveSse(db, user, scopes, req.signal, { since });
} catch (e) {
if (e instanceof LiveError) return fail(e.status, e.message);
console.error("live:", e);

View File

@ -1,6 +1,8 @@
import { redirect } from "next/navigation";
import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
import { googleEnabled } from "@peppa/core";
import { featureGateView, googleEnabled } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { currentUser, safeNext } from "@/lib/auth";
import { Brand } from "@/components/Brand";
import { GoogleSignIn } from "@/components/GoogleSignIn";
@ -40,6 +42,11 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next));
const t = await getT();
// PEP-224: eGov known to be down — a grey button with a caption; Google (if on) becomes the main way in.
const egov = featureGateView("egov_login");
const egovDown = egov.state === "unavailable";
const google = googleEnabled();
const googleButton = google && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} primary={egovDown} />;
return (
<main className="relative mx-auto grid min-h-dvh w-full max-w-6xl content-start items-start gap-x-10 gap-y-8 px-5 py-10 lg:grid-cols-[minmax(0,1fr)_380px] lg:py-16">
<LanguageSwitcher className="absolute top-3 right-5 z-10" />
@ -57,8 +64,13 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
<h2 className="m-0 text-xl font-semibold">{t("Начать — одна минута")}</h2>
<p className="m-0 text-sm text-muted-foreground">{t("Вход через eGov или Google. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.")}</p>
<Flash error={error ? t.text(error) : undefined} />
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
{googleEnabled() && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} />}
<LiveRefresh scope="features" indicator={false} />
{egovDown && googleButton}
<FeatureGate view={egov} label={t("Войти через eGov")}>
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
</FeatureGate>
{!egovDown && googleButton}
{egovDown && !google && <p className="m-0 text-sm text-muted-foreground">{t("Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.")}</p>}
<p className="m-0 text-xs text-muted-foreground lg:hidden">{t("Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.")}</p>
</aside>

View File

@ -1,4 +1,6 @@
import { MCP_GUIDE } from "@peppa/core";
import { featureGateView, MCP_GUIDE } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Brand } from "@/components/Brand";
import { GuideCopy } from "@/components/GuideCopy";
import { getT } from "@/lib/i18n";
@ -13,7 +15,10 @@ export default async function McpGuide() {
<Brand />
<h1 className="m-0 text-xl font-semibold">{t("Инструкция для ИИ")}</h1>
<p className="m-0 text-muted-foreground">{t("Памятка для ИИ, подключённого к FORGE. Вставьте её в «Инструкции» проекта ChatGPT или в системное сообщение другого ИИ.")}</p>
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
<LiveRefresh scope="features" indicator={false} />
<FeatureGate view={featureGateView("mcp")} title={t("MCP временно недоступен")}>
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
</FeatureGate>
</main>
);
}

View File

@ -1,5 +1,6 @@
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { enterActor, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
import { enterActor, FEATURES, featureStatus, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
import { stripAsIs, t as translate } from "@peppa/shared/i18n";
import { createManagerServer } from "@peppa/mcp/manager";
import { publicOrigin } from "@/lib/auth";
import { db } from "@/lib/db";
@ -20,6 +21,15 @@ export async function POST(req: Request) {
const auth = await verifyAccessToken(db, token);
const user = auth && (await getUser(db, auth.userId));
if (!user || !(await isUserAllowed(db, user))) return unauthorized();
// PEP-224: a service MCP depends on is down (Observability) — say so plainly instead of failing midway.
// HTTP 200 with a JSON-RPC error: a 5xx is replaced by Cloudflare's own page (PEP-194).
if (featureStatus("mcp").state === "unavailable") {
const body = (await req.clone().json().catch(() => null)) as { id?: unknown } | Array<{ id?: unknown }> | null;
const id = (Array.isArray(body) ? body[0]?.id : body?.id) ?? null;
const text = FEATURES.mcp.unavailableText;
const message = `${stripAsIs(text)} / ${stripAsIs(translate("en", text))}`;
return json({ jsonrpc: "2.0", id, error: { code: -32001, message } }, 200, { "Access-Control-Allow-Origin": "*", "Retry-After": "300" });
}
// PEP-48: everything this request does is done by the user through this OAuth client.
enterActor({ kind: "user", userId: user.id, channel: "mcp", clientId: auth.clientId });
const server = createManagerServer(db, user, await publicOrigin());

View File

@ -0,0 +1,41 @@
// PEP-224: a feature that depends on a failing service (Observability) — grey, inactive, with a
// plain caption and the time it failed. Available — its children as they are; unstable — the
// children with a note «может работать с задержками». For any new feature: pass `featureGateView`.
import type { ReactNode } from "react";
import { CircleSlash, Clock } from "lucide-react";
import { serverTimezone, type FeatureGateView } from "@peppa/core";
import { getLocale, getT } from "@/lib/i18n";
import { intlLocale } from "@peppa/shared/i18n";
import { cn } from "@/lib/utils";
export async function FeatureGate({ view, label, title, children, className }: { view: FeatureGateView; /** The grey button's text (a button-like control). */ label?: ReactNode; /** A grey status instead (an instruction, a section). */ title?: ReactNode; children: ReactNode; className?: string }) {
if (view.state === "available") return <>{children}</>;
const t = await getT();
if (view.state === "degraded")
return (
<>
{children}
<p className="m-0 flex items-center gap-1.5 text-xs text-warn" data-feature={view.name} data-feature-state="degraded">
<Clock className="size-3.5 shrink-0" /> {t.text(view.text)}
</p>
</>
);
const since = view.since ? new Date(view.since).toLocaleTimeString(intlLocale(await getLocale()), { hour: "2-digit", minute: "2-digit", timeZone: serverTimezone() }) : null;
return (
<div className={cn("flex w-full flex-col gap-1.5", className)} data-feature={view.name} data-feature-state="unavailable">
{label ? (
<button type="button" disabled aria-disabled="true" className="inline-flex h-10 w-full cursor-not-allowed items-center justify-center gap-2 rounded-md border border-dashed bg-muted px-4 text-sm font-medium text-muted-foreground opacity-80">
<CircleSlash className="size-4" /> {label}
</button>
) : (
<div role="status" aria-disabled="true" className="flex items-center gap-2 rounded-lg border border-dashed bg-muted px-4 py-3 text-sm font-medium text-muted-foreground">
<CircleSlash className="size-4 shrink-0" /> {title}
</div>
)}
<p className="m-0 text-xs text-muted-foreground">
{t.text(view.text)}
{since ? " · " + t("с {time}", { time: since }) : ""}
</p>
</div>
);
}

View File

@ -1,12 +1,12 @@
import { Button } from "@/components/ui/button";
/** «Войти через Google» / «Привязать Google» (PEP-90): обычная форма, браузер уходит на Google. */
export function GoogleSignIn({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) {
export function GoogleSignIn({ purpose, next, label, primary = false }: { purpose: "login" | "link"; next?: string; label: string; /** PEP-224: the main way in while eGov is unavailable. */ primary?: boolean }) {
return (
<form method="post" action="/auth/google/start" className="w-full">
<input type="hidden" name="purpose" value={purpose} />
{next && <input type="hidden" name="next" value={next} />}
<Button type="submit" variant="outline" size="lg" className="w-full">
<Button type="submit" variant={primary ? "default" : "outline"} size="lg" className="w-full">
<svg aria-hidden viewBox="0 0 48 48" className="size-4">
<path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.8 2.4 30.3 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.9 6.1C12.4 13.6 17.7 9.5 24 9.5z" />
<path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4.1 7.1-10.1 7.1-17.5z" />

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 { durationText, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
import { durationText, FEATURE_NAMES, FEATURES, 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";
@ -97,6 +97,17 @@ export function MonitorFields({ t, m, kindFixed, remindDefault }: { t: Translato
{t("Запас heartbeat, с")}
<Input name="graceSec" type="number" min={0} defaultValue={tg.graceSec != null ? String(tg.graceSec) : ""} placeholder="60" className="h-8" />
</Label>
<fieldset className="m-0 flex flex-col gap-1 border-0 p-0 sm:col-span-2">
<legend className="mb-1 text-sm font-medium">{t("Что отключать при сбое")}</legend>
<span className="flex flex-wrap gap-x-4 gap-y-1">
{FEATURE_NAMES.map((f) => (
<label key={f} className="flex items-center gap-1.5 text-sm">
<input type="checkbox" name="features" value={f} defaultChecked={m?.features.includes(f)} className="size-4 accent-primary" />
{t(FEATURES[f].label)}
</label>
))}
</span>
</fieldset>
</div>
);
}

View File

@ -25,5 +25,7 @@ export function registerLiveWs(): void {
db,
authenticate: (req) => userFromSessionToken(readCookie(req.headers.cookie, SESSION_COOKIE)),
boot: bootId,
// PEP-224: the login page and /mcp-guide watch `features` before a sign-in.
anonymous: true,
});
}

View File

@ -0,0 +1,52 @@
# Design: PEP-224
## Где хранить связку
Связка «мониторинг → функции» — колонка `monitors.features` (JSON-массив имён) в
`observe.db`: её меняют вместе с мониторингом («Что отключать при сбое» на странице
мониторинга, `features` в MCP `create_monitor`/`update_monitor`). Порог на функцию и
последнее объявленное состояние — таблица `features (name, disable_after_min, state,
since, reason, changed_at)`; журнал — `feature_log`. Основная БД не меняется: всё, что
касается мониторингов, живёт в `observe.db` (PEP-202).
## Правило (чистая функция `computeFeatures`)
Для каждой функции берутся её мониторинги не на паузе:
- `unavailable` — хотя бы один в `down` дольше `disableAfterMin` (от `state_since`);
тихие сбои (весь интернет) тоже считаются — пользователю всё равно недоступно;
- `degraded` — хотя бы один `degraded` (или `down` моложе порога не считается);
- иначе `available`. Восстановление — по состоянию мониторинга, т.е. после его
`recover_threshold` хороших проверок.
`since` — самое раннее `state_since` упавших мониторингов (время, с которого сбой).
## Чтение
`featureStatus(name)` / `featureStatuses()` считают на лету из `observe.db` (одно чтение
таблицы мониторингов) с кэшем 15 с на процесс. Любая ошибка (файла нет, повреждён,
занят) → функция доступна: сбой мониторинга не блокирует вход. Сервер проверяет сам:
`startEgovFlow` при `unavailable` — `PeppaError` до запроса к relay; `/mcp` — ошибка
JSON-RPC с тем же текстом и 503.
## Объявление и живое обновление
`featureTick` в сервисе мониторингов (каждую секунду, после проверок) сравнивает
посчитанное с `features.state`; смена → `feature_log`, событие `feature_disabled` /
`feature_enabled` в журнале платформенного проекта (запись в основную БД будит
`LiveHub` через `data_version`), сообщение в канал «services» (`postToChannel`, без
канала — `alertAdmins`) и `notify()`. Первое вычисление только запоминает состояние
(«доступна» не объявляется). Новая живая область `features` — отпечаток из
`features.state`; `/api/live?scope=features` открыт без входа (только эта область:
в ней нет данных пользователей), страница входа её слушает.
## Тексты
Пользователю — без «relay», «DNS», «OAuth»: «Временно недоступно — технические
неполадки на стороне eGov. Попробуйте позже», «MCP временно недоступен». Сообщения в
канал «services» и `/observability` — для суперадмина, там названия мониторингов как есть.
## Встроенные мониторинги MCP
`seedFeatureMonitors` (один раз, `observe_meta 'seeded:mcp'`): при `PEPPA_WEB_URL` не на
localhost создаёт «MCP-сервер /mcp» (GET `/mcp`, ожидается 401 — без токена сервер
отвечает «нужен вход») и «MCP — вход OAuth» (`/.well-known/oauth-authorization-server`,
текст `token_endpoint`), оба с `features: ["mcp"]`. Миграция v2 проставляет
`egov_login` встроенным «eGov relay» и «eGov relay — DNS».
## Остальные функции
`google_login`, `bot`, `voice`, `bugsink` есть в списке, но без связанных мониторингов
— доступны, пока суперадмин не свяжет мониторинг. Серой в интерфейсе пока делаются только
eGov и MCP; `FeatureGate` — для следующих.

View File

@ -0,0 +1,31 @@
# PEP-224: статус функций из мониторинга
## Why
Мониторинг (PEP-202) знает, что eGov relay или MCP не работает, а интерфейс — нет: человек
сканирует QR, ждёт пять минут и получает ошибку. Функция, зависящая от упавшего сервиса,
должна сама становиться серой с понятной подписью и сама возвращаться после восстановления.
## What Changes
- `core/feature-status.ts`: список функций платформы (`egov_login`, `mcp`, `google_login`,
`bot`, `voice`, `bugsink`), связка «мониторинг → функции» (поле `features` мониторинга),
порог `disableAfterMin` на функцию (по умолчанию 5), чистое правило `computeFeatures`
и дешёвое чтение `featureStatus(name)` (кэш 15 с, сбой `observe.db` → доступна).
- `observe.db` v2: колонка `monitors.features`, таблицы `features` (порог, объявленное
состояние) и `feature_log` (журнал включений/выключений). Встроенные мониторинги eGov
получают `egov_login`; новые встроенные «MCP-сервер /mcp» и «MCP — вход OAuth» — `mcp`.
- Сервис мониторингов: `featureTick` — смена статуса функции → запись в журнал, событие
платформенного проекта, одно сообщение в канал «services» (иначе админам), `notify()`.
- Сервер: `startEgovFlow` при недоступности отказывает `PeppaError` без запроса к relay;
`/mcp` при недоступности отвечает понятной ошибкой JSON-RPC.
- Интерфейс: компонент `FeatureGate`; вход (eGov серый, Google — основной, нет других
способов — подпись), «Настройки → eGov», «Настройки → Peppa FACTORY в вашем Claude или
ChatGPT», `/mcp-guide`, «Помощь → Подключение» — серый статус. Живая область `features`
(доступна и без входа) — кнопка оживает без перезагрузки.
- `/observability`: «Функции» (статус, порог, журнал), у мониторинга «Что отключать при
сбое»; MCP `create_monitor`/`update_monitor` принимают `features`.
## Impact
- Код: `packages/core` (feature-status, observe), `apps/observer`, `packages/mcp`
(monitors), `packages/runner` (live), `apps/web` (вход, настройки, mcp-guide, помощь,
observability, /mcp, /auth/egov/start, /api/live).
- Данные: миграция `observe.db` (user_version 2), основная БД не меняется.

View File

@ -0,0 +1,63 @@
## ADDED Requirements
### Requirement: Статус функции из мониторингов
Peppa SHALL считать функцию платформы недоступной, если связанный с ней мониторинг находится в состоянии «не работает» дольше порога функции (по умолчанию 5 минут), и SHALL снова считать её доступной после восстановления мониторинга. Состояние «нестабильно» SHALL давать только пометку о возможных задержках. Сбой чтения базы мониторингов SHALL оставлять функцию доступной.
#### Scenario: eGov relay лежит дольше порога
- **GIVEN** мониторинг «eGov relay» связан с функцией «Вход через eGov», порог 5 мин
- **AND** мониторинг в состоянии «не работает» 6 минут
- **WHEN** страница входа читает статус функции
- **THEN** функция «Вход через eGov» недоступна с временем начала сбоя
#### Scenario: Сбой короче порога
- **GIVEN** мониторинг «eGov relay» в состоянии «не работает» 2 минуты
- **WHEN** читается статус функции «Вход через eGov»
- **THEN** функция доступна
#### Scenario: Мониторинг восстановился
- **GIVEN** функция «Вход через eGov» недоступна
- **WHEN** мониторинг «eGov relay» после двух удачных проверок снова «работает»
- **THEN** функция доступна
#### Scenario: База мониторингов недоступна
- **GIVEN** файл базы мониторингов не открывается
- **WHEN** читается статус функции «Вход через eGov»
- **THEN** функция доступна
### Requirement: Сервер не начинает недоступное
Начало входа через eGov SHALL отказывать понятным сообщением, не обращаясь к eGov, когда функция «Вход через eGov» недоступна. Удалённый MCP SHALL отвечать клиенту понятной ошибкой, когда функция «MCP» недоступна.
#### Scenario: Отказ без запроса к eGov
- **GIVEN** функция «Вход через eGov» недоступна
- **WHEN** пользователь нажимает «Войти через eGov»
- **THEN** приходит ответ «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже»
- **AND** запроса к eGov не было
### Requirement: Недоступное серое в интерфейсе
Кнопка или инструкция недоступной функции SHALL быть серой и неактивной с подписью «временно недоступно» и временем начала сбоя и SHALL оживать без перезагрузки страницы после восстановления. На странице входа при недоступном eGov другой способ входа SHALL оставаться рабочим и выделенным; если других способов нет, страница SHALL говорить об этом.
#### Scenario: Вход при упавшем eGov
- **GIVEN** функция «Вход через eGov» недоступна
- **AND** вход через Google включён
- **WHEN** человек открывает страницу входа
- **THEN** кнопка «Войти через eGov» серая с подписью «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже»
- **AND** кнопка «Войти через Google» активна и выделена
#### Scenario: MCP недоступен
- **GIVEN** функция «MCP» недоступна
- **WHEN** пользователь открывает «Настройки»
- **THEN** вместо адреса подключения — серый статус «MCP временно недоступен»
### Requirement: Журнал включений и выключений
Смена статуса функции SHALL записываться в журнал на странице Observability и SHALL давать одно сообщение в канал платформы «services». Связку функции с мониторингами SHALL менять суперадмин на странице мониторинга и через MCP.
#### Scenario: Функция отключена и включена
- **GIVEN** канал платформы настроен
- **WHEN** функция «Вход через eGov» становится недоступной, а потом доступной
- **THEN** в канал ушли два сообщения: «отключён для пользователей» и «снова включён»
- **AND** на Observability в журнале функций две записи
#### Scenario: Связка через MCP
- **GIVEN** мониторинг «Bugsink» без связанных функций
- **WHEN** суперадмин вызывает `update_monitor` с `features: ["bugsink"]`
- **THEN** мониторинг связан с функцией «Отслеживание ошибок»

View File

@ -0,0 +1,16 @@
## 1. Ядро
- [x] 1.1 `observe.db` v2: `monitors.features`, `features`, `feature_log`; eGov-мониторингам `egov_login`; `features` в create/update мониторинга
- [x] 1.2 `core/feature-status.ts`: список функций, `computeFeatures`, `featureStatus(es)` с кэшем, `setFeatureThreshold`, `featureTick`, тексты
- [x] 1.3 Встроенные мониторинги MCP (`seedFeatureMonitors`), `featureTick` в сервисе мониторингов
- [x] 1.4 `startEgovFlow` отказывает при недоступности
## 2. Веб и MCP
- [x] 2.1 Живая область `features` (без входа)
- [x] 2.2 `FeatureGate`; вход, «Настройки → eGov», подключение ИИ-клиентов, `/mcp-guide`, помощь
- [x] 2.3 `/mcp` — понятная ошибка при недоступности
- [x] 2.4 `/observability`: «Функции», «Что отключать при сбое»; MCP `features`
- [x] 2.5 Переводы en/kk, словарь
## 3. Проверка
- [x] 3.1 Тест `feature-status.test.ts`
- [x] 3.2 Проверки (lint, typecheck, тесты), браузер

View File

@ -0,0 +1,68 @@
# feature-status Specification
## Purpose
Функции платформы (вход через eGov, MCP и другие) следуют за мониторингами: недоступное серое, после восстановления оживает само.
## Requirements
### Requirement: Статус функции из мониторингов
Peppa SHALL считать функцию платформы недоступной, если связанный с ней мониторинг находится в состоянии «не работает» дольше порога функции (по умолчанию 5 минут), и SHALL снова считать её доступной после восстановления мониторинга. Состояние «нестабильно» SHALL давать только пометку о возможных задержках. Сбой чтения базы мониторингов SHALL оставлять функцию доступной.
#### Scenario: eGov relay лежит дольше порога
- **GIVEN** мониторинг «eGov relay» связан с функцией «Вход через eGov», порог 5 мин
- **AND** мониторинг в состоянии «не работает» 6 минут
- **WHEN** страница входа читает статус функции
- **THEN** функция «Вход через eGov» недоступна с временем начала сбоя
#### Scenario: Сбой короче порога
- **GIVEN** мониторинг «eGov relay» в состоянии «не работает» 2 минуты
- **WHEN** читается статус функции «Вход через eGov»
- **THEN** функция доступна
#### Scenario: Мониторинг восстановился
- **GIVEN** функция «Вход через eGov» недоступна
- **WHEN** мониторинг «eGov relay» после двух удачных проверок снова «работает»
- **THEN** функция доступна
#### Scenario: База мониторингов недоступна
- **GIVEN** файл базы мониторингов не открывается
- **WHEN** читается статус функции «Вход через eGov»
- **THEN** функция доступна
### Requirement: Сервер не начинает недоступное
Начало входа через eGov SHALL отказывать понятным сообщением, не обращаясь к eGov, когда функция «Вход через eGov» недоступна. Удалённый MCP SHALL отвечать клиенту понятной ошибкой, когда функция «MCP» недоступна.
#### Scenario: Отказ без запроса к eGov
- **GIVEN** функция «Вход через eGov» недоступна
- **WHEN** пользователь нажимает «Войти через eGov»
- **THEN** приходит ответ «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже»
- **AND** запроса к eGov не было
### Requirement: Недоступное серое в интерфейсе
Кнопка или инструкция недоступной функции SHALL быть серой и неактивной с подписью «временно недоступно» и временем начала сбоя и SHALL оживать без перезагрузки страницы после восстановления. На странице входа при недоступном eGov другой способ входа SHALL оставаться рабочим и выделенным; если других способов нет, страница SHALL говорить об этом.
#### Scenario: Вход при упавшем eGov
- **GIVEN** функция «Вход через eGov» недоступна
- **AND** вход через Google включён
- **WHEN** человек открывает страницу входа
- **THEN** кнопка «Войти через eGov» серая с подписью «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже»
- **AND** кнопка «Войти через Google» активна и выделена
#### Scenario: MCP недоступен
- **GIVEN** функция «MCP» недоступна
- **WHEN** пользователь открывает «Настройки»
- **THEN** вместо адреса подключения — серый статус «MCP временно недоступен»
### Requirement: Журнал включений и выключений
Смена статуса функции SHALL записываться в журнал на странице Observability и SHALL давать одно сообщение в канал платформы «services». Связку функции с мониторингами SHALL менять суперадмин на странице мониторинга и через MCP.
#### Scenario: Функция отключена и включена
- **GIVEN** канал платформы настроен
- **WHEN** функция «Вход через eGov» становится недоступной, а потом доступной
- **THEN** в канал ушли два сообщения: «отключён для пользователей» и «снова включён»
- **AND** на Observability в журнале функций две записи
#### Scenario: Связка через MCP
- **GIVEN** мониторинг «Bugsink» без связанных функций
- **WHEN** суперадмин вызывает `update_monitor` с `features: ["bugsink"]`
- **THEN** мониторинг связан с функцией «Отслеживание ошибок»

View File

@ -2,6 +2,7 @@
// short-lived <auth><challenge/><nonce/></auth>, reads the signed XML from the relay itself and takes
// the signer's IIN from the certificate. The XMLDSig itself is not verified here — the relay is
// trusted (PM decision, see openspec design); the challenge and nonce never leave the server.
import { assertFeatureAvailable } from "./feature-status.ts";
import { m as tr } from "@peppa/shared/i18n";
import { randomBytes, randomInt, randomUUID } from "node:crypto";
import { and, eq, gte, inArray, sql } from "drizzle-orm";
@ -193,6 +194,8 @@ export async function startEgovFlow(db: Db, purpose: EgovPurpose, userId: number
async function startEgovFlowInner(db: Db, purpose: EgovPurpose, userId: number | null): Promise<EgovStart> {
if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать eGov можно только после входа"));
// PEP-224: eGov is known to be down — say so now instead of a QR that never signs.
assertFeatureAvailable("egov_login");
const env = loadEnv();
const nonce = randomUUID();
const challenge = randomBytes(32).toString("base64url");

View File

@ -0,0 +1,5 @@
// PEP-224: the platform features a monitor can switch off (no imports: observe.ts and
// feature-status.ts both use it).
export const FEATURE_NAMES = ["egov_login", "mcp", "google_login", "bot", "voice", "bugsink"] as const;
export type FeatureName = (typeof FEATURE_NAMES)[number];
export const isFeatureName = (v: unknown): v is FeatureName => (FEATURE_NAMES as readonly string[]).includes(String(v));

View File

@ -0,0 +1,230 @@
// PEP-224: platform features follow their monitors (PEP-202). A feature is `unavailable` while one
// of its monitors has been down longer than the feature's threshold (default 5 min), `degraded`
// while one is unstable, `available` otherwise — recovery follows the monitor's own
// recover_threshold. Reading is cheap (one query of observe.db, cached 15 s per process) and never
// blocks: any trouble with observe.db means «available». The observer announces changes
// (`featureTick`): the journal, one message to the «services» channel, a poke for live pages.
import type { Db } from "@peppa/db";
import { m as tr } from "@peppa/shared/i18n";
import { PeppaError } from "./errors.ts";
import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts";
import { alertAdmins } from "./monitor.ts";
import { notify } from "./notify.ts";
import { listMonitors, observeDb, type Monitor } from "./observe.ts";
import { getPlatformChannel, platformProjectKey, postToChannel } from "./platform-channel.ts";
import { logEvent } from "./audit.ts";
import { getProject } from "./projects.ts";
export { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts";
export type FeatureState = "available" | "degraded" | "unavailable";
export interface FeatureInfo {
/** For people (a key of the translations). */
label: string;
/** What a person sees on a grey button. */
unavailableText: string;
}
const GENERIC = tr("Временно недоступно — технические неполадки. Попробуйте позже");
export const FEATURES: Record<FeatureName, FeatureInfo> = {
egov_login: { label: tr("Вход через eGov"), unavailableText: tr("Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже") },
mcp: { label: tr("Подключение к Claude и ChatGPT"), unavailableText: tr("MCP временно недоступен — технические неполадки. Попробуйте позже") },
google_login: { label: tr("Вход через Google"), unavailableText: tr("Временно недоступно — технические неполадки на стороне Google. Попробуйте позже") },
bot: { label: tr("Telegram-бот"), unavailableText: GENERIC },
voice: { label: tr("Голосовой ввод"), unavailableText: GENERIC },
bugsink: { label: tr("Отслеживание ошибок"), unavailableText: GENERIC },
};
export const DEGRADED_TEXT = tr("Может работать с задержками");
export const DEFAULT_DISABLE_AFTER_MIN = 5;
const CACHE_MS = 15_000;
export interface FeatureStatus {
name: FeatureName;
state: FeatureState;
/** Since when the linked service fails (unavailable / degraded). */
since: string | null;
disableAfterMin: number;
/** Linked monitors (not on pause). */
monitors: Array<Pick<Monitor, "id" | "name" | "state" | "stateSince">>;
/** Monitors that make the state, with their last reason. */
failing: Array<{ id: number; name: string; state: Monitor["state"]; since: string | null; reason: string }>;
}
type MonitorLike = Pick<Monitor, "id" | "name" | "state" | "stateSince" | "paused" | "features" | "lastDetail">;
/** The rule, pure: monitors + thresholds → the state of every feature. */
export function computeFeatures(monitors: MonitorLike[], thresholds: Partial<Record<FeatureName, number>>, now = new Date()): Record<FeatureName, FeatureStatus> {
const out = {} as Record<FeatureName, FeatureStatus>;
for (const name of FEATURE_NAMES) {
const disableAfterMin = thresholds[name] ?? DEFAULT_DISABLE_AFTER_MIN;
const linked = monitors.filter((m) => !m.paused && m.features.includes(name));
const longDown = linked.filter((m) => m.state === "down" && now.getTime() - Date.parse(m.stateSince ?? now.toISOString()) >= disableAfterMin * 60_000);
const shaky = linked.filter((m) => m.state === "degraded");
const state: FeatureState = longDown.length ? "unavailable" : shaky.length ? "degraded" : "available";
const failing = (state === "unavailable" ? longDown : state === "degraded" ? shaky : []).map((m) => ({
id: m.id,
name: m.name,
state: m.state,
since: m.stateSince,
reason: String(m.lastDetail?.reason ?? ""),
}));
const since = failing.map((f) => f.since).filter((s): s is string => !!s).sort()[0] ?? null;
out[name] = { name, state, since, disableAfterMin, monitors: linked.map((m) => ({ id: m.id, name: m.name, state: m.state, stateSince: m.stateSince })), failing };
}
return out;
}
const allAvailable = (): Record<FeatureName, FeatureStatus> => computeFeatures([], {});
/** Per-feature thresholds set by the superadmin (no row = 5 min). */
export function featureThresholds(): Partial<Record<FeatureName, number>> {
const out: Partial<Record<FeatureName, number>> = {};
for (const r of observeDb().prepare("SELECT name, disable_after_min FROM features WHERE disable_after_min IS NOT NULL").all() as Array<{ name: string; disable_after_min: number }>)
if (isFeatureName(r.name)) out[r.name] = Number(r.disable_after_min);
return out;
}
let cache: { at: number; print: string; value: Record<FeatureName, FeatureStatus> } | null = null;
/** Tests and the superadmin's changes: read afresh next time. */
export function resetFeatureCache(): void {
cache = null;
}
/** Every feature's state (cached 15 s); trouble with observe.db = everything available. */
export function featureStatuses(o: { now?: Date; fresh?: boolean } = {}): Record<FeatureName, FeatureStatus> {
const now = o.now ?? new Date();
// The announced states (written by the observer) are part of the key: a change shows at once, even in
// another copy of this module (Next bundles route handlers and pages separately).
const print = o.now ? "" : featureFingerprint();
if (!o.fresh && !o.now && cache && cache.print === print && Date.now() - cache.at < CACHE_MS) return cache.value;
let value: Record<FeatureName, FeatureStatus>;
try {
value = computeFeatures(listMonitors(), featureThresholds(), now);
} catch (e) {
console.error("feature-status: observe.db unavailable, everything counts as available:", (e as Error).message);
value = allAvailable();
}
if (!o.now) cache = { at: Date.now(), print, value };
return value;
}
export const featureStatus = (name: FeatureName, o: { now?: Date; fresh?: boolean } = {}): FeatureStatus => featureStatuses(o)[name];
/** Servers check too: refuses (PeppaError with the person's text) when the feature is unavailable. */
export function assertFeatureAvailable(name: FeatureName, o: { now?: Date } = {}): void {
if (featureStatus(name, o).state === "unavailable") throw new PeppaError(FEATURES[name].unavailableText);
}
/** A grey control's data for the web (kept small: it goes to client components). */
export interface FeatureGateView {
name: FeatureName;
state: FeatureState;
since: string | null;
text: string;
}
export function featureGateView(name: FeatureName, o: { now?: Date } = {}): FeatureGateView {
const s = featureStatus(name, o);
return { name, state: s.state, since: s.since, text: s.state === "unavailable" ? FEATURES[name].unavailableText : s.state === "degraded" ? DEGRADED_TEXT : "" };
}
export function setFeatureThreshold(name: string, minutes: number): void {
if (!isFeatureName(name)) throw new PeppaError(tr("Неизвестная функция: {name}. Есть: {list}", { name, list: FEATURE_NAMES.join(", ") }));
if (!Number.isInteger(minutes) || minutes < 0 || minutes > 1440) throw new PeppaError(tr("{field}: целое число от {min} до {max}", { field: "disableAfterMin", min: 0, max: 1440 }));
observeDb().prepare("INSERT INTO features (name, disable_after_min) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET disable_after_min = excluded.disable_after_min").run(name, minutes);
resetFeatureCache();
}
export interface FeatureLogEntry {
id: number;
name: FeatureName;
state: FeatureState;
reason: string;
at: string;
}
export function featureLog(limit = 50): FeatureLogEntry[] {
return (observeDb().prepare("SELECT * FROM feature_log ORDER BY at DESC, id DESC LIMIT ?").all(limit) as Array<Record<string, unknown>>)
.filter((r) => isFeatureName(r.name))
.map((r) => ({ id: Number(r.id), name: r.name as FeatureName, state: r.state as FeatureState, reason: String(r.reason), at: String(r.at) }));
}
/** Live pages (scope `features`): the announced states; "" when observe.db is unavailable. */
export function featureFingerprint(): string {
try {
return (observeDb().prepare("SELECT coalesce(group_concat(name || ':' || coalesce(state,'') || ':' || coalesce(changed_at,''), ','), '') AS f FROM features").get() as { f: string }).f;
} catch {
return "";
}
}
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
function why(s: FeatureStatus, now: Date): string {
return s.failing
.map((f) => {
const n = Math.max(1, Math.round((now.getTime() - Date.parse(f.since ?? now.toISOString())) / 60_000));
return f.reason ? `${f.name} — ${f.reason}, ${n} мин` : `${f.name}, ${n} мин`;
})
.join("; ");
}
/** Text of the message to the «services» channel (superadmin's: monitor names as they are). */
export function featureChangeText(s: FeatureStatus, now = new Date()): string {
return s.state === "unavailable"
? tr("⛔ «{feature}» отключено для пользователей: не работает {why}", { feature: FEATURES[s.name].label, why: why(s, now) })
: tr("✅ «{feature}» снова включено для пользователей", { feature: FEATURES[s.name].label });
}
export interface FeatureTickOptions {
now?: Date;
log?: (s: string) => void;
}
/**
* The observer, after its checks: compares the computed states with the announced ones. A change
* to/from «unavailable» goes to the feature journal, the platform project's events and the
* «services» channel (no channel — the superadmins); every change pokes live pages. The first
* computation only remembers. Returns the changed features.
*/
export async function featureTick(db: Db, o: FeatureTickOptions = {}): Promise<FeatureName[]> {
const now = o.now ?? new Date();
const log = o.log ?? (() => {});
const iso = now.toISOString();
const odb = observeDb();
const statuses = computeFeatures(listMonitors(), featureThresholds(), now);
const known = new Map((odb.prepare("SELECT name, state FROM features").all() as Array<{ name: string; state: string | null }>).map((r) => [r.name, r.state]));
const changed: FeatureName[] = [];
for (const name of FEATURE_NAMES) {
const s = statuses[name];
const prev = known.get(name) ?? null;
if (prev === s.state) continue;
const reason = s.state === "available" ? "" : why(s, now);
odb
.prepare("INSERT INTO features (name, state, since, reason, changed_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET state = excluded.state, since = excluded.since, reason = excluded.reason, changed_at = excluded.changed_at")
.run(name, s.state, s.since, reason, iso);
changed.push(name);
// The first computation (no state yet) and degraded ↔ available are not announced.
if (prev === null || (prev === "unavailable") === (s.state === "unavailable")) continue;
odb.prepare("INSERT INTO feature_log (name, state, reason, at) VALUES (?, ?, ?, ?)").run(name, s.state === "unavailable" ? "unavailable" : "available", reason, iso);
const text = featureChangeText(s, now);
log(`feature: ${name} ${prev} → ${s.state}${reason ? ` (${reason})` : ""}`);
const p = await getProject(db, platformProjectKey()).catch(() => null);
if (p) await logEvent(db, { projectId: p.id, type: s.state === "unavailable" ? "feature_disabled" : "feature_enabled", payload: { feature: name, reason, since: s.since } }).catch(() => {});
const key = `feature:${name}:${s.state === "unavailable" ? "off" : "on"}:${iso}`;
try {
const channel = await getPlatformChannel(db);
if (!(await postToChannel(db, "services", `mon:ch:${key}`, esc(text), channel))) await alertAdmins(db, `mon:${key}`, text, log);
} catch (e) {
log(`feature: announce failed: ${(e as Error).message}`);
}
}
if (changed.length) {
resetFeatureCache();
for (const name of changed) await notify(db, { type: "feature", name }).catch(() => {});
}
return changed;
}

View File

@ -103,6 +103,7 @@ export * from "./egress.ts";
export * from "./fallback-fetch.ts";
export * from "./observe.ts";
export * from "./observe-checks.ts";
export * from "./feature-status.ts";
export * from "./accept-screen.ts";
export * from "./accept-digest.ts";
export * from "./connections.ts";

View File

@ -11,7 +11,8 @@ export type PeppaNotification =
| { type: "progress"; eventId: number }
| { type: "session_updated"; sessionId: number }
| { type: "incident"; incidentId: number }
| { type: "chat_message"; messageId: number };
| { type: "chat_message"; messageId: number }
| { type: "feature"; name: string };
/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME (web: PEP-37). */
export const SUBSCRIBERS = ["bot", "web"] as const;

View File

@ -15,6 +15,7 @@ import { and, eq, like, or } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { alertAdmins, observeRemindMin } from "./monitor.ts";
import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts";
import { realObserveProbes, runCheck, type CheckResult, type ObserveProbes } from "./observe-checks.ts";
export type MonitorKind = "http" | "tcp" | "dns" | "internet" | "heartbeat";
@ -76,6 +77,8 @@ export interface Monitor {
remindMin: number | null;
/** PEP-223: remind about «degraded» too (by default only «down»). */
remindDegraded: boolean;
/** PEP-224: features switched off while this monitor is down. */
features: FeatureName[];
}
export interface MonitorCheck {
@ -114,6 +117,8 @@ export interface MonitorInput {
/** PEP-223: null/undefined — the common default, 0 — no reminders. */
remindMin?: number | null;
remindDegraded?: boolean;
/** PEP-224: features to switch off while this monitor is down. */
features?: string[];
}
export const MIN_INTERVAL_SEC = 30;
@ -180,6 +185,27 @@ const MIGRATIONS: string[][] = [
`ALTER TABLE monitor_incidents ADD COLUMN reminders INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE monitor_incidents ADD COLUMN notified_at TEXT`,
],
// PEP-224: monitor → features, per-feature threshold and the announced state, their journal.
[
`ALTER TABLE monitors ADD COLUMN features TEXT NOT NULL DEFAULT '[]'`,
`CREATE TABLE features (
name TEXT PRIMARY KEY,
disable_after_min INTEGER,
state TEXT,
since TEXT,
reason TEXT,
changed_at TEXT
)`,
`CREATE TABLE feature_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
state TEXT NOT NULL,
reason TEXT NOT NULL,
at TEXT NOT NULL
)`,
`CREATE INDEX feature_log_at ON feature_log (at)`,
`UPDATE monitors SET features = '["egov_login"]' WHERE name IN ('eGov relay', 'eGov relay — DNS') AND created_by = 'system'`,
],
];
const opened = new Map<string, DatabaseSync>();
@ -252,6 +278,7 @@ function toMonitor(r: Row): Monitor {
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,
features: (json(r.features, []) as unknown[]).filter(isFeatureName),
};
}
@ -330,7 +357,14 @@ export function normalizeTarget(kind: MonitorKind, t: Record<string, unknown>):
}
}
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target" | "remindMin">> & { target: MonitorTarget; remindMin: number | null } {
/** PEP-224: known feature names, without repeats; an unknown one is refused. */
export function normalizeFeatures(v: unknown): FeatureName[] {
const list = (Array.isArray(v) ? v : String(v ?? "").split(/[\s,]+/)).map((x) => String(x).trim()).filter(Boolean);
for (const f of list) if (!isFeatureName(f)) bad("Неизвестная функция: {name}. Есть: {list}", { name: f, list: FEATURE_NAMES.join(", ") });
return [...new Set(list)] as FeatureName[];
}
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target" | "remindMin" | "features">> & { target: MonitorTarget; remindMin: number | null; features: FeatureName[] } {
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) });
@ -345,6 +379,7 @@ function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target" |
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,
features: normalizeFeatures(input.features ?? []),
};
}
@ -369,10 +404,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, remind_min, remind_degraded, 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, features)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
)
.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;
.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, JSON.stringify(n.features)) as Row;
return toMonitor(r);
}
@ -391,10 +426,11 @@ export function updateMonitor(id: number, patch: Partial<MonitorInput>, now = ne
// undefined — keep; null — back to the common default.
remindMin: patch.remindMin === undefined ? cur.remindMin : patch.remindMin,
remindDegraded: patch.remindDegraded ?? cur.remindDegraded,
features: patch.features ?? cur.features,
});
const r = observeDb()
.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;
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, remind_min = ?, remind_degraded = ?, features = ?, 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, JSON.stringify(n.features), now.toISOString(), id) as Row;
return toMonitor(r);
}
@ -745,10 +781,33 @@ export function seedMonitors(now = new Date()): Monitor[] {
if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded'").get()) return [];
const made = [
createMonitor({ name: "Интернет", kind: "internet", target: { hosts: DEFAULT_INTERNET_HOSTS }, intervalSec: 60 }, "system", now),
createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60 }, "system", now),
createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300 }, "system", now),
createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60, features: ["egov_login"] }, "system", now),
createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300, features: ["egov_login"] }, "system", now),
];
db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded', ?)").run(now.toISOString());
return made;
}
/**
* PEP-224: «MCP-сервер /mcp» and «MCP — вход OAuth» (they switch off `mcp`), once, when the web has
* a public address. Without a token /mcp answers 401 — that is the sign it is alive.
*/
export function seedFeatureMonitors(webUrl: string | undefined, now = new Date()): Monitor[] {
const db = observeDb();
if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded:mcp'").get()) return [];
let base: URL;
try {
base = new URL(webUrl ?? "");
} catch {
return [];
}
if (/^(localhost|127\.|\[::1\])/.test(base.hostname)) return [];
const names = new Set(listMonitors().map((m) => m.name));
const made: Monitor[] = [];
if (!names.has("MCP-сервер /mcp")) made.push(createMonitor({ name: "MCP-сервер /mcp", kind: "http", target: { url: new URL("/mcp", base).toString(), expectStatus: [401] }, intervalSec: 60, features: ["mcp"] }, "system", now));
if (!names.has("MCP — вход OAuth"))
made.push(createMonitor({ name: "MCP — вход OAuth", kind: "http", target: { url: new URL("/.well-known/oauth-authorization-server", base).toString(), contains: "token_endpoint" }, intervalSec: 60, features: ["mcp"] }, "system", now));
db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded:mcp', ?)").run(now.toISOString());
return made;
}

View File

@ -6,6 +6,8 @@ import {
createMonitor,
deleteMonitor,
describeTarget,
FEATURE_NAMES,
featureStatuses,
getMonitor,
getProject,
logEvent,
@ -54,6 +56,10 @@ const common = {
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)"),
features: z
.array(z.enum(FEATURE_NAMES))
.optional()
.describe(`PEP-224: platform features to switch off for users (grey, «temporarily unavailable») while this monitor is down longer than the feature's threshold (default 5 min): ${FEATURE_NAMES.join(", ")}. [] — none; left out — unchanged`),
};
const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`);
@ -62,7 +68,7 @@ const outage = (m: MonitorView) =>
? ` · ${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)}${outage(m)}`;
`- #${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)}${m.features.length ? ` · switches off: ${m.features.join(", ")}` : ""}`;
async function journal(db: Db, type: string, sessionId: number | null | undefined, payload: Record<string, unknown>) {
const p = await getProject(db, platformProjectKey()).catch(() => null);
@ -75,7 +81,9 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
define("list_monitors", "Observability (PEP-202): every monitor of the FORGE platform with its state, last reason and uptime for 24 h and 7 days.", {}, true, async () => {
await access.check();
const list = listMonitorViews();
return list.length ? list.map(line).join("\n") : "No monitors.";
const f = Object.values(featureStatuses({ fresh: true }));
const features = ["", "Features (PEP-224):", ...f.map((x) => `- ${x.name}: ${x.state}${x.since ? ` since ${x.since}` : ""} · off after ${x.disableAfterMin} min down · monitors: ${x.monitors.map((mm) => mm.name).join(", ") || "none"}`)];
return [list.length ? list.map(line).join("\n") : "No monitors.", ...features].join("\n");
});
define("get_monitor", "Observability: one monitor — state, uptime, incidents of the week and the last checks.", { id: z.number().int(), checks: z.number().int().min(1).max(500).optional().describe("How many last checks (default 50)") }, true, async ({ id, checks }) => {
@ -102,7 +110,7 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
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, remindMin: a.remind_min, remindDegraded: a.remind_degraded }, 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, features: a.features }, 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.`;
},
@ -111,9 +119,9 @@ 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, 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}.`;
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, features: a.features });
await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, features: m.features, author: who.author });
return `Updated #${m.id} ${m.name}${m.features.length ? `; switches off: ${m.features.join(", ")}` : ""}.`;
});
define("pause_monitor", "Observability: pause (no checks, no messages) or resume a monitor.", { id: z.number().int(), paused: z.boolean() }, false, async ({ id, paused }) => {

View File

@ -32,11 +32,12 @@ export class LiveConnection {
private input: Promise<void> = Promise.resolve();
private closed = false;
private db: Db;
private user: User;
/** null — a tab without a sign-in (PEP-224): only open scopes (`features`) pass checkScopeAccess. */
private user: User | null;
private out: (msg: Out) => void;
private kill: (code: number, reason: string) => void;
constructor(db: Db, user: User, out: (msg: Out) => void, kill: (code: number, reason: string) => void) {
constructor(db: Db, user: User | null, out: (msg: Out) => void, kill: (code: number, reason: string) => void) {
this.db = db;
this.user = user;
this.out = out;
@ -82,7 +83,7 @@ export class LiveConnection {
// Unsubscribed (or closed) while access was checked.
if (!this.pending.has(scope) || this.closed) return stop();
this.subs.set(scope, stop);
this.send({ t: "ok", scope, v: scope.startsWith("terminal:") ? undefined : liveHub(this.db).versionOf(scope, this.user.id) });
this.send({ t: "ok", scope, v: scope.startsWith("terminal:") ? undefined : liveHub(this.db).versionOf(scope, this.user?.id ?? 0) });
} catch (e) {
const status = e instanceof LiveError ? e.status : (e as { status?: number }).status ?? 500;
if (status === 500) console.error(`live-ws: ${scope}`, e);
@ -93,11 +94,12 @@ export class LiveConnection {
}
private watchHub(scope: LiveScope, since: string | number | undefined): () => void {
return liveHub(this.db).subscribe([scope], (e) => this.send({ t: "ev", ...e }), { userId: this.user.id, since: { [scope]: since } });
return liveHub(this.db).subscribe([scope], (e) => this.send({ t: "ev", ...e }), { userId: this.user?.id ?? 0, since: { [scope]: since } });
}
/** The runner terminal (PEP-9): the shared TerminalFeed of the pane, secrets masked, viewers per user limited. */
private async watchTerminal(scope: LiveScope): Promise<() => void> {
if (!this.user) throw new LiveError(m("Нужен вход"), 401);
const s = await terminalSession(this.db, this.user, Number(scope.slice(9)));
const mask = await projectSecretMasker(this.db, s.projectId);
const release = acquireViewer(this.user.id);
@ -133,6 +135,7 @@ export class LiveConnection {
const input = { keys: typeof msg.keys === "string" ? msg.keys : undefined, paste: typeof msg.paste === "string" ? msg.paste : undefined };
const run = async () => {
try {
if (!this.user) throw new LiveError(m("Нужен вход"), 401);
await terminalInput(this.db, this.user, Number(scope.slice(9)), input);
this.send({ t: "ack", id });
} catch (e) {
@ -177,6 +180,8 @@ export interface LiveWsOptions {
/** Boot id of the web process (the client compares it after a reconnect). */
boot?: () => string;
pingMs?: number;
/** PEP-224: let a tab without a sign-in in — it can watch open scopes only (the login page watches `features`). */
anonymous?: boolean;
}
export interface LiveWs {
@ -213,7 +218,7 @@ export function createLiveWs(opts: LiveWsOptions): LiveWs {
}, pingMs);
pinger.unref?.();
wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User) => {
wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User | null) => {
alive.set(ws, 0);
const conn = new LiveConnection(
opts.db,
@ -241,7 +246,7 @@ export function createLiveWs(opts: LiveWsOptions): LiveWs {
opts
.authenticate(req)
.then((user) => {
if (!user) return refuse(socket, 401, "Unauthorized");
if (!user && !opts.anonymous) return refuse(socket, 401, "Unauthorized");
wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req, user));
})
.catch((e) => {

View File

@ -9,15 +9,15 @@ import { m } from "@peppa/shared/i18n";
import { createHash } from "node:crypto";
import { existsSync, statSync } from "node:fs";
import { join } from "node:path";
import { attachmentsByMessage, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, STEP_EVENT, stepView, type AttachmentView, type ChatMessageView, type StepView, type User } from "@peppa/core";
import { attachmentsByMessage, featureFingerprint, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, resetFeatureCache, STEP_EVENT, stepView, type AttachmentView, type ChatMessageView, type StepView, type User } from "@peppa/core";
import { chats, events, sessions, subscriptions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
import { columnOf, type BoardColumn } from "./flow.ts";
import { pollCodexLogin } from "./subscription-login.ts";
import { terminalSession } from "./terminal.ts";
/** Scopes without an id. `attention` and `me` are per user (the hub keys them by the viewer). */
export const LIVE_PLAIN_SCOPES = ["home", "runners", "chats", "team", "attention", "version", "observe", "subs", "me"] as const;
/** Scopes without an id. `attention` and `me` are per user (the hub keys them by the viewer); `features` (PEP-224) is open without a sign-in. */
export const LIVE_PLAIN_SCOPES = ["home", "runners", "chats", "team", "attention", "version", "observe", "subs", "me", "features"] as const;
const ID_KINDS = ["project", "task", "steps", "login", "terminal", "chat"] as const;
type PlainScope = (typeof LIVE_PLAIN_SCOPES)[number];
type IdKind = (typeof ID_KINDS)[number];
@ -87,9 +87,12 @@ const notFound = () => new LiveError(m("Не найдено"), 404);
/**
* Access, the same as the page's: project / story / steps / terminal need the project,
* `observe` and `subs` a superadmin, `login:<id>` the author of that sign-in or a superadmin,
* `chat:<id>` the project's people (a master chat — its owner only).
* `chat:<id>` the project's people (a master chat — its owner only); `features` (PEP-224) — anybody,
* the login page watches it.
*/
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
export async function checkScopeAccess(db: Db, user: User | null, scope: LiveScope): Promise<void> {
if (scope === "features") return;
if (!user) throw new LiveError(m("Нужен вход"), 401);
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
if (kind === "observe" || kind === "subs") {
@ -155,6 +158,8 @@ function tasksMdPath(ws: string, change: string): string | null {
* heartbeats) are left out. Part `t` is covered by the task rows sent along (see taskRows).
*/
function fingerprint(db: Db, scope: LiveScope, userId: number): Parts {
// PEP-224: features follow monitors (observe.db) — no user data, the login page watches it too.
if (scope === "features") return { f: featureFingerprint() };
const c = db.$client;
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
@ -448,7 +453,8 @@ class LiveHub {
this.wake();
}
const now = Date.now();
if (this.watches.has("observe") && now - this.lastObserve >= OBSERVE_EVERY_MS) {
// PEP-224: `features` too — the observer writes observe.db only.
if ((this.watches.has("observe") || this.watches.has("features")) && now - this.lastObserve >= OBSERVE_EVERY_MS) {
this.lastObserve = now;
this.wake();
}
@ -557,6 +563,8 @@ class LiveHub {
if (!changed.length) return;
w.parts = parts;
w.v = liveVersion(JSON.stringify(parts));
// PEP-224: the observer announced a feature change — pages must not read the 15 s cache.
if (scope === "features") resetFeatureCache();
const e: LiveEvent & { type: "change" } = { type: "change", scope, v: w.v, parts: changed };
if (w.rows && (scope.startsWith("project:") || scope.startsWith("task:"))) {
const rows = taskRows(this.db, scope);
@ -621,7 +629,7 @@ export function liveHub(db: Db): LiveHub {
export const liveObservePath = observeDbPath;
/** SSE response for /api/live (the fallback of the tab's WebSocket): `change` / `step` / `data` events, pings for Cloudflare. */
export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number; since?: Record<string, string> } = {}): Promise<Response> {
export async function liveSse(db: Db, user: User | null, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number; since?: Record<string, string> } = {}): Promise<Response> {
for (const s of scopes) await checkScopeAccess(db, user, s);
const enc = new TextEncoder();
let cleanup = () => {};
@ -653,7 +661,7 @@ export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: A
send("retry: 3000\n\n");
send(`event: ready\ndata: ${JSON.stringify({ scopes })}\n\n`);
if (signal.aborted) return close();
unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`), { userId: user.id, since: opts.since });
unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`), { userId: user?.id ?? 0, since: opts.since });
},
cancel() {
cleanup();

View File

@ -0,0 +1,37 @@
import type { Dict } from "../index.ts";
// PEP-224: platform features follow their monitors.
export const features: Dict = {
"Временно недоступно — технические неполадки. Попробуйте позже": "Temporarily unavailable — technical problems. Please try again later",
"Вход через eGov": "Sign-in with eGov",
"Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже": "Temporarily unavailable — technical problems on the eGov side. Please try again later",
"Подключение к Claude и ChatGPT": "Connecting to Claude and ChatGPT",
"MCP временно недоступен — технические неполадки. Попробуйте позже": "MCP is temporarily unavailable — technical problems. Please try again later",
"Вход через Google": "Sign-in with Google",
"Временно недоступно — технические неполадки на стороне Google. Попробуйте позже": "Temporarily unavailable — technical problems on the Google side. Please try again later",
"Telegram-бот": "Telegram bot",
"Голосовой ввод": "Voice input",
"Отслеживание ошибок": "Error tracking",
"Может работать с задержками": "May work with delays",
"Неизвестная функция: {name}. Есть: {list}": "Unknown feature: {name}. Known: {list}",
"⛔ «{feature}» отключено для пользователей: не работает {why}": "⛔ «{feature}» is switched off for users: down — {why}",
"✅ «{feature}» снова включено для пользователей": "✅ «{feature}» is switched on for users again",
"MCP временно недоступен": "MCP is temporarily unavailable",
"Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.": "There is no other way to sign in right now. Open this page later — the button will come back by itself as soon as eGov is available again.",
"с {time}": "since {time}",
"Что отключать при сбое": "What to switch off when it fails",
"Что отключать при сбое:": "Switches off when it fails:",
"ничего": "nothing",
"доступна": "available",
"с задержками": "with delays",
"отключена": "switched off",
"снова включена": "switched on again",
"Функции": "Features",
"Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.":
"A feature turns grey for users when a linked monitor is down longer than the threshold and switches back on by itself after recovery. Link them with «What to switch off when it fails» on a monitor or the features field of MCP update_monitor.",
"отключать через, мин": "switch off after, min",
"Мониторинги:": "Monitors:",
"Не связана ни с одним мониторингом — всегда доступна.": "Not linked to any monitor — always available.",
"Журнал включений и выключений ({n})": "Switch-off log ({n})",
"Функции ещё не отключались.": "No feature has been switched off yet.",
};

View File

@ -30,5 +30,6 @@ import { accountMerge } from "./account-merge.ts";
import { acceptScreen } from "./accept-screen.ts";
import { accessHub } from "./access-hub.ts";
import { errors } from "./errors.ts";
import { features } from "./features.ts";
export const en: Dict = { ...errors, ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub };
export const en: Dict = { ...errors, ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...features };

View File

@ -0,0 +1,37 @@
import type { Dict } from "../index.ts";
// PEP-224: платформа функциялары мониторингтерге қарай қосылады және өшеді.
export const features: Dict = {
"Временно недоступно — технические неполадки. Попробуйте позже": "Уақытша қолжетімсіз — техникалық ақаулар. Кейінірек қайталап көріңіз",
"Вход через eGov": "eGov арқылы кіру",
"Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже": "Уақытша қолжетімсіз — eGov жағында техникалық ақаулар. Кейінірек қайталап көріңіз",
"Подключение к Claude и ChatGPT": "Claude және ChatGPT-ке қосылу",
"MCP временно недоступен — технические неполадки. Попробуйте позже": "MCP уақытша қолжетімсіз — техникалық ақаулар. Кейінірек қайталап көріңіз",
"Вход через Google": "Google арқылы кіру",
"Временно недоступно — технические неполадки на стороне Google. Попробуйте позже": "Уақытша қолжетімсіз — Google жағында техникалық ақаулар. Кейінірек қайталап көріңіз",
"Telegram-бот": "Telegram-бот",
"Голосовой ввод": "Дауыспен енгізу",
"Отслеживание ошибок": "Қателерді бақылау",
"Может работать с задержками": "Кідірістермен жұмыс істеуі мүмкін",
"Неизвестная функция: {name}. Есть: {list}": "Белгісіз функция: {name}. Бар функциялар: {list}",
"⛔ «{feature}» отключено для пользователей: не работает {why}": "⛔ «{feature}» пайдаланушылар үшін өшірілді: жұмыс істемейді — {why}",
"✅ «{feature}» снова включено для пользователей": "✅ «{feature}» пайдаланушылар үшін қайта қосылды",
"MCP временно недоступен": "MCP уақытша қолжетімсіз",
"Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.": "Қазір кірудің басқа жолы жоқ. Бұл бетті кейінірек ашыңыз — eGov қайта қолжетімді болғанда, батырма өзі іске қосылады.",
"с {time}": "{time} бастап",
"Что отключать при сбое": "Ақау кезінде не өшіріледі",
"Что отключать при сбое:": "Ақау кезінде өшіріледі:",
"ничего": "ештеңе",
"доступна": "қолжетімді",
"с задержками": "кідірістермен",
"отключена": "өшірілген",
"снова включена": "қайта қосылды",
"Функции": "Функциялар",
"Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.":
"Байланысты мониторинг шектен ұзақ жұмыс істемесе, функция пайдаланушыларда сұр болады және қалпына келгенде өзі қосылады. Байланыс — мониторингтегі «Ақау кезінде не өшіріледі» немесе MCP update_monitor ішіндегі features өрісі.",
"отключать через, мин": "өшіру уақыты, мин",
"Мониторинги:": "Мониторингтер:",
"Не связана ни с одним мониторингом — всегда доступна.": "Ешбір мониторингпен байланыспаған — әрқашан қолжетімді.",
"Журнал включений и выключений ({n})": "Қосу және өшіру журналы ({n})",
"Функции ещё не отключались.": "Функциялар әлі өшірілмеген.",
};

View File

@ -30,5 +30,6 @@ import { accountMerge } from "./account-merge.ts";
import { acceptScreen } from "./accept-screen.ts";
import { accessHub } from "./access-hub.ts";
import { errors } from "./errors.ts";
import { features } from "./features.ts";
export const kk: Dict = { ...errors, ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub };
export const kk: Dict = { ...errors, ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...features };

View File

@ -0,0 +1,154 @@
// PEP-224, spec feature-status: a platform feature follows its monitors — unavailable after its
// monitor is down longer than the threshold, back after recovery; startEgovFlow refuses without a
// request to the relay; one message per change; trouble with observe.db = available.
import assert from "node:assert/strict";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { after, before, describe, test } from "node:test";
import { events, telegramOutbox, users } from "@peppa/db";
import { and, eq, like } from "drizzle-orm";
import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, project, runner, teardown } from "./helpers.ts";
import { MockKazedsRelay } from "../src/mock-kazeds-relay.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const relay = new MockKazedsRelay({ iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" });
const CHAT = 880_224;
before(async () => {
process.env.KAZEDS_RELAY_BASE = await relay.start();
const u = await core.upsertUserFromGitea(db, { id: CHAT, login: "mock-feature-admin" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: CHAT, telegramUserId: CHAT }).where(eq(users.id, u.id));
await core.setPlatformAdmins(db, ["mock-feature-admin"]);
});
after(async () => {
await relay.stop();
core.closeObserveDb();
await teardown();
});
const min = (n: number) => new Date(Date.now() + n * 60_000);
const bad = { ok: false, degraded: false, reason: "ответ 503", detail: {} };
const good = { ok: true, degraded: false, reason: "", detail: {} };
const sent = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "mon:feature:%"))).map((r) => stripAsIs(String(r.params.text)));
const check = (id: number, r: typeof bad, at: Date) => core.recordCheck(core.getMonitor(id)!, r, { now: at });
describe("Feature status", () => {
test("Scenario: built-in eGov monitors switch off «Вход через eGov»; MCP monitors are made only for a public address", () => {
const made = core.seedMonitors();
assert.deepEqual(made.find((m) => m.name === "eGov relay")!.features, ["egov_login"]);
assert.deepEqual(made.find((m) => m.name === "eGov relay — DNS")!.features, ["egov_login"]);
assert.deepEqual(core.seedFeatureMonitors("http://localhost:3100"), [], "localhost — no MCP monitors");
const mcp = core.seedFeatureMonitors("https://peppa.example");
assert.deepEqual(mcp.map((m) => [m.name, m.features]), [["MCP-сервер /mcp", ["mcp"]], ["MCP — вход OAuth", ["mcp"]]]);
assert.deepEqual((mcp[0]!.target as { expectStatus: number[] }).expectStatus, [401]);
assert.deepEqual(core.seedFeatureMonitors("https://peppa.example"), [], "once");
for (const m of core.listMonitors()) core.deleteMonitor(m.id);
});
test("Scenario: an unknown feature is refused; features can be changed (MCP update_monitor)", () => {
assert.throws(() => core.createMonitor({ name: "x", kind: "dns", target: { host: "a.example" }, features: ["nope"] }, "system"), /Неизвестная функция/);
const m = core.createMonitor({ name: "Bugsink", kind: "dns", target: { host: "bugsink.example" } }, "system");
assert.deepEqual(m.features, []);
assert.deepEqual(core.updateMonitor(m.id, { features: ["bugsink"] }).features, ["bugsink"]);
assert.deepEqual(core.updateMonitor(m.id, { name: "Bugsink 2" }).features, ["bugsink"], "left out — unchanged");
core.deleteMonitor(m.id);
});
test("Scenario: eGov relay down 6 min — unavailable, startEgovFlow refuses without a request; back after 2 good checks", async () => {
const relayMon = core.createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.example/" }, features: ["egov_login"] }, "system", min(-10));
check(relayMon.id, good, min(-10));
assert.deepEqual(await core.featureTick(db), ["egov_login", "mcp", "google_login", "bot", "voice", "bugsink"], "the first computation only remembers");
assert.deepEqual(await sent(), []);
for (const at of [-8, -7, -6]) check(relayMon.id, bad, min(at));
assert.equal(core.getMonitor(relayMon.id)!.state, "down");
assert.equal(core.featureStatus("egov_login", { now: min(-3) }).state, "available", "down 3 min — shorter than 5");
const s = core.featureStatus("egov_login", { now: new Date() });
assert.equal(s.state, "unavailable");
assert.equal(s.since, core.getMonitor(relayMon.id)!.stateSince);
core.resetFeatureCache();
const before = relay.sessions.size;
await assert.rejects(core.startEgovFlow(db, "login"), (e: Error) => e instanceof core.PeppaError && /Временно недоступно — технические неполадки на стороне eGov/.test(e.message));
assert.equal(relay.sessions.size, before, "no request to the relay");
assert.equal(core.featureGateView("egov_login").state, "unavailable");
// Announced once: journal, message, event of the platform project.
const platform = await project({ turns: [[{ say: "ok" }]] });
process.env.PEPPA_PLATFORM_KEY = platform.key;
const platformId = (await core.getProject(db, platform.key)).id;
assert.deepEqual(await core.featureTick(db), ["egov_login"]);
assert.deepEqual(await core.featureTick(db), [], "no repeat");
let msgs = await sent();
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /⛔ «Вход через eGov» отключено для пользователей: не работает eGov relay — ответ 503, 6 мин/);
assert.equal(core.featureLog()[0]!.state, "unavailable");
assert.equal((await db.select().from(events).where(and(eq(events.projectId, platformId), eq(events.type, "feature_disabled")))).length, 1);
assert.notEqual(core.featureFingerprint(), "", "live pages see the change");
check(relayMon.id, good, new Date());
assert.equal(core.featureStatus("egov_login", { fresh: true }).state, "unavailable", "one good check is not enough (recover_threshold 2)");
// The cache follows the announced states: another module copy (a page) sees a change at once.
assert.equal(core.featureStatus("egov_login").state, "unavailable", "cached");
check(relayMon.id, good, new Date());
assert.equal(core.featureStatus("egov_login", { fresh: true }).state, "available");
await core.featureTick(db);
assert.equal(core.featureStatus("egov_login").state, "available", "announced — the cache is dropped by the fingerprint");
msgs = await sent();
assert.equal(msgs.length, 2);
assert.match(msgs[1]!, /✅ «Вход через eGov» снова включено для пользователей/);
assert.equal((await db.select().from(events).where(and(eq(events.projectId, platformId), eq(events.type, "feature_enabled")))).length, 1);
assert.deepEqual(core.featureLog().map((e) => e.state), ["available", "unavailable"]);
core.resetFeatureCache();
const flow = await core.startEgovFlow(db, "login");
assert.ok(flow.qrContent, "eGov works again");
core.deleteMonitor(relayMon.id);
});
test("Scenario: unstable — only a note; a paused monitor and a custom threshold", async () => {
const m = core.createMonitor({ name: "mock mcp", kind: "http", target: { url: "https://mcp.example/" }, features: ["mcp"] }, "system", min(-30));
for (const at of [-20, -19, -18]) check(m.id, { ok: true, degraded: true, reason: "медленно", detail: {} }, min(at));
const v = core.featureGateView("mcp", { now: new Date() });
assert.equal(v.state, "degraded");
assert.match(v.text, /Может работать с задержками/);
for (const at of [-2, -1.5, -1]) check(m.id, bad, min(at));
assert.equal(core.featureStatus("mcp", { now: new Date() }).state, "available", "down 1 min");
core.setFeatureThreshold("mcp", 0);
assert.equal(core.featureStatus("mcp", { now: new Date() }).state, "unavailable", "threshold 0 — at once");
assert.equal(core.featureStatus("mcp", { now: new Date() }).disableAfterMin, 0);
core.setMonitorPaused(m.id, true);
assert.equal(core.featureStatus("mcp", { now: new Date() }).state, "available", "a paused monitor switches nothing off");
assert.throws(() => core.setFeatureThreshold("nope", 5), /Неизвестная функция/);
core.setFeatureThreshold("mcp", 5);
core.deleteMonitor(m.id);
});
test("Scenario: observe.db can not be opened — every feature is available", async () => {
const m = core.createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.example/" }, features: ["egov_login"] }, "system", min(-30));
for (const at of [-20, -19, -18]) check(m.id, bad, min(at));
assert.equal(core.featureStatus("egov_login", { now: new Date() }).state, "unavailable");
const real = process.env.PEPPA_OBSERVE_DB;
const file = join(tmpdir(), `mock-not-a-dir-${process.pid}`);
writeFileSync(file, "x");
process.env.PEPPA_OBSERVE_DB = join(file, "observe.db");
try {
assert.equal(core.featureStatus("egov_login", { now: new Date() }).state, "available");
assert.equal(core.featureFingerprint(), "");
core.resetFeatureCache();
assert.doesNotThrow(() => core.assertFeatureAvailable("egov_login"));
} finally {
if (real === undefined) delete process.env.PEPPA_OBSERVE_DB;
else process.env.PEPPA_OBSERVE_DB = real;
}
core.deleteMonitor(m.id);
});
test("Scenario: the live scope «features» is open without a sign-in, others are not", async () => {
assert.deepEqual(runner.parseScopes("features"), ["features"]);
await runner.checkScopeAccess(db, null, "features");
await assert.rejects(runner.checkScopeAccess(db, null, "home"), (e: Error) => e instanceof runner.LiveError && e.status === 401);
});
});

View File

@ -16,7 +16,7 @@ const user = (login: string) => core.upsertUserFromGitea(db, { id: 9100 + seq++,
type Msg = Record<string, unknown> & { t: string };
/** A connection driven directly: what the server sent and how it closed. */
function conn(u: import("@peppa/core").User) {
function conn(u: import("@peppa/core").User | null) {
const out: Msg[] = [];
const closed: Array<{ code: number; reason: string }> = [];
const c = new LiveConnection(db, u, (m) => out.push(m as Msg), (code, reason) => closed.push({ code, reason }));
@ -47,6 +47,18 @@ describe("tab channel (PEP-225)", () => {
x.c.close();
});
test("Без входа (PEP-224): только область features, остальное — 401", async () => {
const x = conn(null);
await x.send({ t: "sub", scope: "features" });
assert.equal(x.out.at(-1)!.t, "ok");
await x.send({ t: "sub", scope: "home" });
assert.equal(x.out.at(-1)!.status, 401);
await x.send({ t: "sub", scope: "terminal:1" });
assert.equal(x.out.at(-1)!.status, 401);
assert.deepEqual(x.c.scopes, ["features"]);
x.c.close();
});
test("Событие доходит только до своей области — со строкой задачи", async () => {
const a = await ownedStory("ws-owner-2");
const b = await core.createTask(db, { projectId: a.ref.project.id, title: "Соседняя задача" });