Compare commits
4 Commits
e7653aad02
...
1e2690ed2a
| Author | SHA1 | Date | |
|---|---|---|---|
| 1e2690ed2a | |||
| a10f9ed564 | |||
| 3a46400070 | |||
| cb144b618b |
@ -20,7 +20,6 @@
|
||||
- Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (копию базы сначала `peppa db migrate`: индексы PEP-214); N+1 — `workLineIndex`. `liveHub` на globalThis переживает HMR: правишь live.ts — перезапусти server.ts. Не `pkill -f next-server`.
|
||||
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
|
||||
- Скорость: замер `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (копию базы сначала `peppa db migrate`); N+1 по проектам — `workLineIndex`. `liveHub` на globalThis переживает HMR — после правок live.ts перезапусти server.ts. Не `pkill -f next-server` — убьёт живой веб.
|
||||
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
|
||||
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
|
||||
@ -30,12 +29,8 @@
|
||||
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
||||
- Продукт на другой docker переносить только с данными (PEP-231): `scripts/server-move/products-move.sh` — тома со сверкой сумм, Postgres дампом, без отчёта о выкладке; `peppa deploy redeploy` поднимает продукт с пустыми томами и шлёт владельцу «новая версия».
|
||||
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||
- Сервер (PEP-230): памятка — docs/SERVER.md. В контейнере агента нет глобального git: автор коммита — `gitRelayEnv` (GIT_AUTHOR_*); на старом образе — `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — `.deb` с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; e2e на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
|
||||
- Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — .deb с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + обёртка с LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; тесты на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить). Без tmux тесты с запуском агента падают молча; чужие проекты агенту PEP не видны.
|
||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — `.deb` с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH (без tmux тесты с запуском агента падают молча); openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`. Чужие проекты (BRM, KD…) агенту PEP не видны — живые данные только у суперадмина.
|
||||
|
||||
## Соглашения
|
||||
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||
@ -44,15 +39,18 @@
|
||||
- Экраны «Продакт» (PEP-120/122): вид — чистая функция в core с текстами в одном объекте (`storyProductView`, `core/help-texts.ts` ru/kk/en), инженерное — под «Подробнее» (`?more=1`); тест сверяет ru с «Нельзя» docs/glossary.md.
|
||||
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
||||
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` проверяет литералы в `m()/tr()/t()` packages/core|runner|mcp; подсказку агенту в `m()` не оборачивать; запрещённое слово — переписать (ключ и в `i18n/en|kk`, тестах) или `glossary-ignore: <почему>` строкой выше; человеку мимо переводов — `glossary-user: <почему>`.
|
||||
- Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`.
|
||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `core/user-text.ts` (`userText`; `stripServiceBlocks` — для слов человека); `raiseSessionQuestion`/`askPm`/`addChatMessage` чистят сами, пусто → PeppaError, исходник — `questionDetails` (инженер/суперадмин). Текст исключения владельцу не слать: `platformFailure` даёт строку только для PeppaError, иначе null (ушло суперадмину и в учёт ошибок).
|
||||
- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`.
|
||||
- Формат сообщения агента (PEP-152): сообщение агента человеку — через `admitAgentMessage` + `renderMain` (core/agent-message.ts): в тексте — основная часть (слова агента в `asIs`), техника — `details` (`messageDetails`), экран режет `splitForDisplay`. Суть с файлом, веткой, командой, «PR #N», статусом из кода, словом «Нельзя» — отказ.
|
||||
- Чужой текст в сообщениях (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()`. Текст чатов — через `stripAsIs`.
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall.
|
||||
- Вопрос ≠ задача (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 — стоп).
|
||||
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/`; экран — `core/bugsink-errors.ts`, действия — `runner/bugsink-errors.ts`.
|
||||
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
||||
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
|
||||
|
||||
## Решения
|
||||
@ -64,6 +62,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>`), не Web Speech API. Google: по почте учётки не склеиваем.
|
||||
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
|
||||
- Распознавание речи — свой faster-whisper (`<Dictate>`, MediaRecorder), не Web Speech API. Вход через Google: по почте учётки не склеиваем.
|
||||
- Привязка Google к учётке с другим Google-only пользователем объединяет учётки (core/merge-users.ts `mergeUserInto`); с eGov/Gitea — отказ к админу (PEP-195).
|
||||
- Язык голоса (PEP-131): `transcribeLanguage(cfg, locale)` — язык интерфейса говорящего; новый вызов `transcribe` передаёт его пятым аргументом.
|
||||
|
||||
@ -109,8 +109,6 @@
|
||||
- **Шаблон уходит сам (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`
|
||||
|
||||
@ -3,8 +3,7 @@
|
||||
// 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, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, type ObserveProbes } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { beat, observeTick, pruneObserve, seedMonitors, type ObserveProbes } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
|
||||
export interface ObserverOptions {
|
||||
@ -17,10 +16,6 @@ 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;
|
||||
@ -41,13 +36,6 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,33 +1,27 @@
|
||||
import Link from "next/link";
|
||||
import { CONNECT_HELP, featureGateView } from "@peppa/core";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { CONNECT_HELP } from "@peppa/core";
|
||||
import { PageHeader } from "@/components/common";
|
||||
import { CopyText } from "@/components/CopyText";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { publicOrigin } from "@/lib/auth";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
import { getLocale } 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>
|
||||
<FeatureGate view={featureGateView("mcp")} title={tr("MCP временно недоступен")}>
|
||||
<CopyText value={address} label={t.copy} done={t.copied} />
|
||||
</FeatureGate>
|
||||
<CopyText value={address} label={t.copy} done={t.copied} />
|
||||
<p className="m-0 text-muted-foreground">{t.addressNote}</p>
|
||||
</section>
|
||||
{t.apps.map((app) => (
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { CONNECT_HELP, PRODUCT_HELP } from "@peppa/core";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
import { publicOrigin, uiMode } from "@/lib/auth";
|
||||
@ -176,11 +174,8 @@ export default async function Help() {
|
||||
</Section>
|
||||
|
||||
<Section title={t("Подключить MCP")}>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Activity, Pause, Play, Trash2 } from "lucide-react";
|
||||
import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
|
||||
import { describeTarget, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Hidden } from "@/components/cards";
|
||||
@ -69,9 +69,6 @@ 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}` }} />
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
// Observability (PEP-202): every action is superadmin-only (others get "not found").
|
||||
|
||||
import { createMonitor, deleteMonitor, resetFeatureCache, setFeatureThreshold, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core";
|
||||
import { createMonitor, deleteMonitor, 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,8 +53,6 @@ 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,
|
||||
@ -100,14 +98,3 @@ 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}` });
|
||||
});
|
||||
}
|
||||
|
||||
@ -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, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
|
||||
import { describeTarget, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Hidden } from "@/components/cards";
|
||||
@ -15,9 +15,7 @@ import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { createMonitorAction, pauseMonitorAction, setFeatureThresholdAction } from "./actions";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { createMonitorAction, pauseMonitorAction } from "./actions";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@ -97,10 +95,6 @@ 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" />
|
||||
@ -164,63 +158,6 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
||||
</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>
|
||||
|
||||
<Section title={t("Скорость страниц")} count={speed.length}>
|
||||
<p className="mb-2 text-sm text-muted-foreground">{t("Страницы и действия за последние 24 часа: сколько раз открывали, как долго отвечали и какая часть времени ушла на базу данных. Медленные запросы приходят в Bugsink сами. Числа считаются с последнего перезапуска сайта.")}</p>
|
||||
{speed.length === 0 ? (
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { CONNECT_HELP, featureGateView, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
|
||||
import { CONNECT_HELP, 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,8 +6,6 @@ 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";
|
||||
@ -52,14 +50,10 @@ 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">
|
||||
@ -152,9 +146,7 @@ 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">
|
||||
<FeatureGate view={egovGate} label={t("Привязать eGov")}>
|
||||
<EgovSign purpose="link" label={t("Привязать eGov")} />
|
||||
</FeatureGate>
|
||||
<EgovSign purpose="link" label={t("Привязать eGov")} />
|
||||
</div>
|
||||
</Card>
|
||||
</Section>
|
||||
@ -317,14 +309,12 @@ 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>
|
||||
<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>
|
||||
<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>
|
||||
</Section>
|
||||
<Section title={t("Подключённые приложения")} id="apps">
|
||||
{apps.length === 0 ? (
|
||||
|
||||
@ -12,14 +12,12 @@ 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, scopes, req.signal, { since });
|
||||
return await liveSse(db, user, parseScopes(q.get("scope")), req.signal, { since });
|
||||
} catch (e) {
|
||||
if (e instanceof LiveError) return fail(e.status, e.message);
|
||||
console.error("live:", e);
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
|
||||
import { featureGateView, googleEnabled } from "@peppa/core";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { googleEnabled } from "@peppa/core";
|
||||
import { currentUser, safeNext } from "@/lib/auth";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { GoogleSignIn } from "@/components/GoogleSignIn";
|
||||
@ -42,11 +40,6 @@ 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" />
|
||||
@ -64,13 +57,8 @@ 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} />
|
||||
<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>}
|
||||
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
|
||||
{googleEnabled() && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} />}
|
||||
<p className="m-0 text-xs text-muted-foreground lg:hidden">{t("Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.")}</p>
|
||||
</aside>
|
||||
|
||||
|
||||
@ -1,6 +1,4 @@
|
||||
import { featureGateView, MCP_GUIDE } from "@peppa/core";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { MCP_GUIDE } from "@peppa/core";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { GuideCopy } from "@/components/GuideCopy";
|
||||
import { getT } from "@/lib/i18n";
|
||||
@ -15,10 +13,7 @@ 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>
|
||||
<LiveRefresh scope="features" indicator={false} />
|
||||
<FeatureGate view={featureGateView("mcp")} title={t("MCP временно недоступен")}>
|
||||
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
|
||||
</FeatureGate>
|
||||
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
import { enterActor, FEATURES, featureStatus, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
|
||||
import { stripAsIs, t as translate } from "@peppa/shared/i18n";
|
||||
import { enterActor, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
|
||||
import { createManagerServer } from "@peppa/mcp/manager";
|
||||
import { publicOrigin } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
@ -21,15 +20,6 @@ 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());
|
||||
|
||||
@ -1,41 +0,0 @@
|
||||
// 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>
|
||||
);
|
||||
}
|
||||
@ -1,12 +1,12 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/** «Войти через Google» / «Привязать Google» (PEP-90): обычная форма, браузер уходит на Google. */
|
||||
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 }) {
|
||||
export function GoogleSignIn({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) {
|
||||
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={primary ? "default" : "outline"} size="lg" className="w-full">
|
||||
<Button type="submit" variant="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" />
|
||||
|
||||
@ -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, FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
|
||||
import { durationText, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
|
||||
import type { Translator } from "@peppa/shared/i18n";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Input, Label, NativeSelect } from "@/components/ui/input";
|
||||
@ -97,17 +97,6 @@ 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>
|
||||
);
|
||||
}
|
||||
|
||||
@ -25,7 +25,5 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,52 +0,0 @@
|
||||
# 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` — для следующих.
|
||||
@ -1,31 +0,0 @@
|
||||
# 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), основная БД не меняется.
|
||||
@ -1,63 +0,0 @@
|
||||
## 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** мониторинг связан с функцией «Отслеживание ошибок»
|
||||
@ -1,16 +0,0 @@
|
||||
## 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, тесты), браузер
|
||||
@ -1,27 +0,0 @@
|
||||
# Design
|
||||
|
||||
## Доверие папке
|
||||
Codex (`resolve_root_git_project_for_trust`) для worktree берёт корень основного репозитория:
|
||||
`.git` worktree — файл `gitdir: <common>/worktrees/<name>`, в нём `commondir` → общий `.git`,
|
||||
его родитель — корень. `codexTrustRoots(cwd)` возвращает `[cwd, корень]` без повторов; команда
|
||||
получает `-c projects."<путь>".trust_level="trusted"` для каждого.
|
||||
|
||||
`-c` в Codex делит ключ по точкам без учёта кавычек, поэтому для путей с точкой (`~/.peppa/…`)
|
||||
он не срабатывает. Надёжный путь — `config.toml` в CODEX_HOME подписки (он смонтирован в
|
||||
контейнер по тому же пути): `trustCodexFolders(home, paths)` дописывает
|
||||
`[projects."<путь>"]\ntrust_level = "trusted"`, если такого пути в файле ещё нет (не
|
||||
переписываем чужие таблицы — дубль таблицы ломает разбор TOML). Только локально (не на
|
||||
отдельном хосте) и только при CODEX_HOME подписки.
|
||||
|
||||
## Сторож
|
||||
`codexTrustPrompt(screen)` — цифра пункта «Trust and continue» / «Yes, continue» при вопросе
|
||||
«Trust this folder?» / «Do you trust the contents of this directory?», и абсолютные пути на
|
||||
экране. Нажимаем, если путей нет или каждый — из разрешённых (`codexTrustRoots` рабочей
|
||||
папки сессии и папки проекта). Иначе — не жмём (чужая папка). Событие `trust_dismissed`;
|
||||
повтор — не чаще раза в 2 минуты (общий `menuAt`).
|
||||
|
||||
## Модель
|
||||
`modelProvider(name)`: Claude-алиасы → claude, gpt/o\d/codex → codex, с «/» → opencode, иное — null.
|
||||
Без `provider` в настройках модель идёт провайдеру `modelProvider(m) ?? "claude"`. Явный
|
||||
`provider` — как раньше (только ему). Усилия (effort) общие — как раньше.
|
||||
Альтернатива «только claude» сломала бы проекты, где без провайдера записана модель Codex.
|
||||
@ -1,24 +0,0 @@
|
||||
# PEP-241: агенты на ChatGPT начинают работу
|
||||
|
||||
## Why
|
||||
На сервере (Codex 0.171, контейнеры) агент на Codex не делает ни шага (QLFW-84, TPTIP-85):
|
||||
1. Codex показывает экран «Folder access — Trust this folder?» и ждёт нажатия. Доверие через
|
||||
`-c projects."<cwd>".trust_level` не помогает: для worktree Codex ищет доверие по корню
|
||||
основного репозитория, а ключ `-c` с точкой в пути он режет по точкам. Сторож экрана такой
|
||||
экран не знает — агент стоит, перезапуск даёт тот же экран.
|
||||
2. `platform.agent = {model: "opus"}` без провайдера: `launchModelFor` отдавала модель любому
|
||||
провайдеру, Codex получал `--model opus` и отклонял первое сообщение.
|
||||
|
||||
## What Changes
|
||||
- Запуск Codex доверяет и рабочей папке, и корню основного репозитория worktree (`-c` и запись
|
||||
в `config.toml` CODEX_HOME подписки).
|
||||
- Сторож Codex узнаёт экран доверия (старый и 0.171) и жмёт «Trust and continue», только если
|
||||
папка на экране — та, что Peppa дала агенту.
|
||||
- Модель без провайдера идёт только «своему» провайдеру: по виду имени (opus/sonnet/haiku/claude-* —
|
||||
Claude, gpt-*/o<N>/codex-* — Codex, `x/y` — OpenCode), непонятное — Claude (провайдер по
|
||||
умолчанию). То же для `escalateModel`. Codex без своей модели — на модели по умолчанию.
|
||||
- mock-codex: действие `trust` (экран 0.171) и отказ на модель Claude.
|
||||
|
||||
## Impact
|
||||
- `packages/core/src/agent-model.ts`, `packages/runner/src/{providers,codex-screen,watchdog,sessions}.ts`
|
||||
- testkit: `mock-agent.ts`, `scenario.ts`, тесты `codex-recovery`, `agent-smarts`.
|
||||
@ -1,17 +0,0 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Модель без провайдера — только своему CLI
|
||||
Если в настройках агента провайдер не задан, модель (и `escalateModel`) SHALL передаваться
|
||||
только провайдеру, которому она принадлежит по имени (opus/sonnet/haiku/claude-* — Claude,
|
||||
gpt-*/o<N>/codex-* — Codex); имя без признаков — провайдеру по умолчанию Claude. Остальные
|
||||
провайдеры запускаются на своей модели по умолчанию.
|
||||
|
||||
#### Scenario: Платформа указала opus, агент на ChatGPT
|
||||
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
|
||||
- **WHEN** агент запускается на Codex
|
||||
- **THEN** команда Codex без `--model`
|
||||
|
||||
#### Scenario: Та же настройка, агент на Claude
|
||||
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
|
||||
- **WHEN** агент запускается на Claude
|
||||
- **THEN** команда Claude содержит `--model opus`
|
||||
@ -1,23 +0,0 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Экран доверия папке не останавливает агента
|
||||
Peppa SHALL запускать Codex с доверием к рабочей папке и к корню основного репозитория worktree
|
||||
(и в команде, и в `config.toml` CODEX_HOME подписки). Если экран «Trust this folder?» всё же
|
||||
появился, сторож SHALL выбрать «Trust and continue» — только когда папка на экране та, что
|
||||
Peppa дала агенту.
|
||||
|
||||
#### Scenario: Экран доверия Codex 0.171
|
||||
- **GIVEN** агент на Codex, на экране «Folder access — Trust this folder?» с рабочей папкой агента
|
||||
- **WHEN** сторож делает проход
|
||||
- **THEN** выбран пункт «Trust and continue», в журнале `trust_dismissed`
|
||||
- **AND** агент выполняет первый ход
|
||||
|
||||
#### Scenario: Чужая папка на экране
|
||||
- **GIVEN** на экране вопрос о доверии папке `/etc`
|
||||
- **WHEN** сторож делает проход
|
||||
- **THEN** ничего не нажато
|
||||
|
||||
#### Scenario: Worktree
|
||||
- **GIVEN** рабочая папка — worktree репозитория `/w/repo`
|
||||
- **WHEN** запускается агент на Codex
|
||||
- **THEN** команда доверяет и папке worktree, и `/w/repo`
|
||||
@ -1,12 +0,0 @@
|
||||
## 1. Модель
|
||||
- [x] 1.1 `modelProvider` и `launchModelFor`: модель без провайдера — только своему провайдеру (и `escalateModel`)
|
||||
- [x] 1.2 Тест в agent-smarts: `{model: opus}` без провайдера — Codex без `--model`, Claude с `--model opus`
|
||||
|
||||
## 2. Доверие папке
|
||||
- [x] 2.1 `codexTrustRoots` + `-c` для каждого пути в `codexCommand`
|
||||
- [x] 2.2 `trustCodexFolders` в CODEX_HOME подписки при запуске
|
||||
- [x] 2.3 `codexTrustPrompt`/`dismissCodexTrust` и вызов в сторожe
|
||||
- [x] 2.4 mock-codex: действие `trust`, отказ на модель Claude; тесты в codex-recovery
|
||||
|
||||
## 3. Завершение
|
||||
- [x] 3.1 typecheck, lint, тесты; память; archive; PR
|
||||
@ -1,33 +0,0 @@
|
||||
## Контекст
|
||||
`sessions.workspace_path` пишется при запуске (worktree, хост). При переезде PEP-230
|
||||
`server-cutover.sh` обнулил его у живых сессий, у `done`/`failed` остались `/Users/…`.
|
||||
Сторож (PEP-209) перезапускает **последнюю** сессию задачи через `resumeSession` → `runnerCwd`.
|
||||
|
||||
## Решения
|
||||
1. **`runnerCwd` пересоздаёт и запоминает.** Путь не существует (локальная сессия) →
|
||||
`ensureWorktree(project, s.id, taskKey)` в `$PEPPA_HOME/worktrees/<slug>/s<id>`,
|
||||
`sessions.workspace_path` = новый путь, событие `worktree_created {recreated, from}`.
|
||||
Раньше функция создавала копию там же, но возвращала `realpathSync(старый путь)` — ENOENT.
|
||||
Пустой путь (общая копия) и хост — без изменений. Ветка стори берётся из origin, если она
|
||||
там есть (`checkoutStory`), — работа агента, запушенная до переезда, не теряется.
|
||||
2. **Почему не было четвёртой попытки.** Живой базы у агента нет, по коду единственный путь
|
||||
«молчать после назревшей попытки» без исключения — `diagnose` → `wait`: конфликт при стоящей
|
||||
очереди проверок (`checksQueueStanding`, PEP-205) или недоступная Gitea; запись
|
||||
`stuck.heal` и карточка при этом не трогались. Очередь проверок 23.11 стояла (переезд
|
||||
act_runner), а результат PEP-217 конфликтует. Исправление:
|
||||
- назревшая попытка, которую держит ожидание, обновляет карточку (`state: waiting`, причина
|
||||
словами, `retryAt` = следующая проверка через 5 мин) — владелец не видит прошедшее время;
|
||||
- ожидание очереди проверок для назревшей попытки — не дольше `STUCK_QUEUE_WAIT_MIN` = 120
|
||||
мин от `nextAt`, затем попытка идёт (один rebase — одна новая проверка в очереди, это
|
||||
дешевле, чем задача, стоящая сутками); Gitea недоступна — ждём без предела (агент без
|
||||
Gitea ничего не сделает), но карточка обновляется;
|
||||
- каждый пропуск назревшей попытки пишется в журнал вачдога с причиной.
|
||||
Сбой самого перезапуска и раньше считался попыткой (`catch` → `action`) — тест это закрепляет.
|
||||
3. **Живая база.** `peppa session paths` (суперадмин на сервере): показывает сессии с
|
||||
несуществующим локальным путём, проекты с несуществующей рабочей копией, строки `settings`
|
||||
со значением, содержащим `/Users/`. `--fix` переписывает путь завершённых сессий на
|
||||
стандартный (`worktreePath`) — их тогда нормально убирает `cleanupWorktree` и не трогает
|
||||
`readChange`; живые сессии и проекты только показываются. Благодаря п.1 без `--fix` тоже всё
|
||||
работает — команда для порядка и диагностики.
|
||||
4. **PEP-217 сдвинется сама**: после выкатки ближайший проход сторожа перезапустит агента в новой
|
||||
копии (или, если очередь проверок держит, — не позже чем через 2 ч).
|
||||
@ -1,22 +0,0 @@
|
||||
## Why
|
||||
PEP-217 стоит «В работе» 64 часа: сторож застрявших задач трижды перезапускал агента и каждый
|
||||
раз получал `ENOENT: lstat '/Users'`. У завершённых сессий после переезда на сервер (PEP-230)
|
||||
остался путь рабочей копии с Mac: `server-cutover.sh` обнулил путь только у живых сессий.
|
||||
`runnerCwd` пересоздаёт пропавший worktree по стандартному пути, но возвращает старый путь —
|
||||
перезапуск падает. После третьей неудачи сторож замолчал: четвёртой попытки нет, карточка
|
||||
задержки висит «повторяем» с прошедшим временем, суперадмину ничего.
|
||||
|
||||
## What Changes
|
||||
- Пропавшая рабочая копия сессии (чужой хост, удалённый worktree) пересоздаётся в стандартном
|
||||
месте, и сессия запоминает новый путь — перезапуск идёт в новой копии.
|
||||
- Сторож застрявших задач: когда попытка подошла, но её держит ожидание (очередь проверок,
|
||||
Gitea недоступна), карточка честно показывает ожидание и следующую проверку; ожидание очереди
|
||||
проверок для назревшей попытки ограничено 2 часами — дальше попытка идёт, счёт доходит до
|
||||
исчерпания и сообщения суперадмину. Причина каждого пропуска назревшей попытки — в журнале вачдога.
|
||||
- CLI `peppa session paths [--fix]`: сессии и проекты с путями, которых нет на этом хосте, и
|
||||
настройки с путями `/Users/…`; `--fix` переписывает путь завершённых сессий на стандартный.
|
||||
|
||||
## Impact
|
||||
- `packages/runner/src/sessions.ts` (`runnerCwd`), `packages/runner/src/stuck-tasks.ts`,
|
||||
`packages/runner/src/workspace-paths.ts` (новый), `packages/cli/src/index.ts`.
|
||||
- Тест `packages/testkit/test/stuck-heal.test.ts`.
|
||||
@ -1,22 +0,0 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Назревшая попытка лечения не теряется
|
||||
Сбой перезапуска агента SHALL считаться попыткой лечения застрявшей задачи. Попытка, срок
|
||||
которой подошёл, но которую держит ожидание (очередь проверок, недоступная Gitea), SHALL
|
||||
обновлять карточку задержки (ожидание и время следующей проверки); ожидание очереди проверок
|
||||
SHALL длиться не дольше 2 часов от срока попытки, после чего попытка SHALL выполняться и счёт
|
||||
SHALL доходить до исчерпания и одного сообщения суперадмину.
|
||||
|
||||
#### Scenario: Перезапуск падает каждый раз
|
||||
- **GIVEN** задача в работе, результат конфликтует, перезапуск агента каждый раз падает
|
||||
- **WHEN** вачдог заходит в 0, +5, +20, +80 и +200 минут
|
||||
- **THEN** попытки считаются 1, 2, 3, 4
|
||||
- **AND** в +200 минут карточка «нужен администратор» и суперадмин получает одно сообщение
|
||||
|
||||
#### Scenario: Попытку держит очередь проверок
|
||||
- **GIVEN** у задачи 3 попытки, срок четвёртой подошёл, результат конфликтует
|
||||
- **AND** очередь проверок стоит
|
||||
- **WHEN** вачдог делает проход
|
||||
- **THEN** агент не перезапускается, карточка показывает ожидание со временем следующей проверки
|
||||
- **WHEN** очередь стоит дольше 2 часов от срока попытки и вачдог делает проход
|
||||
- **THEN** выполняется четвёртая попытка
|
||||
@ -1,18 +0,0 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Пропавшая рабочая копия пересоздаётся
|
||||
Если рабочей копии сессии нет на этом хосте (путь с другой машины, удалённый worktree), перезапуск
|
||||
сессии SHALL создавать новый worktree в стандартном месте `$PEPPA_HOME/worktrees/<slug>/s<id>` на
|
||||
ветке стори, запоминать новый путь у сессии и запускать агента в нём, а не падать.
|
||||
|
||||
#### Scenario: Путь рабочей копии с другой машины
|
||||
- **GIVEN** задача в работе, у её последней сессии путь рабочей копии `/Users/asel/.peppa/worktrees/peppa/s783`
|
||||
- **AND** такого каталога на этом хосте нет
|
||||
- **WHEN** сессию перезапускают
|
||||
- **THEN** агент запускается в `$PEPPA_HOME/worktrees/<slug>/s<id>` на ветке `task/<key>`
|
||||
- **AND** у сессии записан новый путь, событие `worktree_created` с прежним путём
|
||||
|
||||
#### Scenario: Рабочая копия на месте
|
||||
- **GIVEN** worktree сессии существует
|
||||
- **WHEN** сессию перезапускают
|
||||
- **THEN** агент запускается в том же каталоге, путь сессии не меняется
|
||||
@ -1,13 +0,0 @@
|
||||
## 1. Рабочая копия
|
||||
- [x] 1.1 `runnerCwd`: пропавший путь → новый worktree в стандартном месте, путь сессии обновлён, событие с прежним путём
|
||||
|
||||
## 2. Сторож застрявших задач
|
||||
- [x] 2.1 Назревшая попытка при `wait`: карточка `waiting` + следующая проверка, причина в журнал
|
||||
- [x] 2.2 Ожидание очереди проверок для назревшей попытки ≤ 120 мин, потом попытка
|
||||
|
||||
## 3. Живая база
|
||||
- [x] 3.1 `findForeignPaths` / `fixForeignPaths` (runner/workspace-paths.ts) и CLI `peppa session paths [--fix]`
|
||||
|
||||
## 4. Тесты и завершение
|
||||
- [x] 4.1 Тесты: путь с другой машины → перезапуск в новой копии; сбой перезапуска считается до исчерпания; очередь проверок держит ≤ 2 ч; CLI находит и чинит пути
|
||||
- [x] 4.2 Проверки (lint, typecheck, тесты), память, archive, PR
|
||||
@ -40,19 +40,3 @@
|
||||
- **GIVEN** в пуле проекта подписка Claude «лимит до 18:00» и активная Codex, `fallbackProvider: codex`
|
||||
- **WHEN** PM двигает стори в работу
|
||||
- **THEN** раннер стартует на Codex, в журнале `provider_fallback`
|
||||
|
||||
### Requirement: Модель без провайдера — только своему CLI
|
||||
Если в настройках агента провайдер не задан, модель (и `escalateModel`) SHALL передаваться
|
||||
только провайдеру, которому она принадлежит по имени (opus/sonnet/haiku/claude-* — Claude,
|
||||
gpt-*/o<N>/codex-* — Codex); имя без признаков — провайдеру по умолчанию Claude. Остальные
|
||||
провайдеры запускаются на своей модели по умолчанию.
|
||||
|
||||
#### Scenario: Платформа указала opus, агент на ChatGPT
|
||||
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
|
||||
- **WHEN** агент запускается на Codex
|
||||
- **THEN** команда Codex без `--model`
|
||||
|
||||
#### Scenario: Та же настройка, агент на Claude
|
||||
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
|
||||
- **WHEN** агент запускается на Claude
|
||||
- **THEN** команда Claude содержит `--model opus`
|
||||
|
||||
@ -48,25 +48,3 @@ Codex SHALL запускаться с `notice.hide_rate_limit_model_nudge=true`;
|
||||
- **GIVEN** вход в аккаунт падает при каждом запуске
|
||||
- **WHEN** проходят три повтора и четвёртый запуск
|
||||
- **THEN** подписка в статусе `auth_error`, суперадмину одно сообщение, автоперезапуски не потрачены
|
||||
|
||||
### Requirement: Экран доверия папке не останавливает агента
|
||||
Peppa SHALL запускать Codex с доверием к рабочей папке и к корню основного репозитория worktree
|
||||
(и в команде, и в `config.toml` CODEX_HOME подписки). Если экран «Trust this folder?» всё же
|
||||
появился, сторож SHALL выбрать «Trust and continue» — только когда папка на экране та, что
|
||||
Peppa дала агенту.
|
||||
|
||||
#### Scenario: Экран доверия Codex 0.171
|
||||
- **GIVEN** агент на Codex, на экране «Folder access — Trust this folder?» с рабочей папкой агента
|
||||
- **WHEN** сторож делает проход
|
||||
- **THEN** выбран пункт «Trust and continue», в журнале `trust_dismissed`
|
||||
- **AND** агент выполняет первый ход
|
||||
|
||||
#### Scenario: Чужая папка на экране
|
||||
- **GIVEN** на экране вопрос о доверии папке `/etc`
|
||||
- **WHEN** сторож делает проход
|
||||
- **THEN** ничего не нажато
|
||||
|
||||
#### Scenario: Worktree
|
||||
- **GIVEN** рабочая папка — worktree репозитория `/w/repo`
|
||||
- **WHEN** запускается агент на Codex
|
||||
- **THEN** команда доверяет и папке worktree, и `/w/repo`
|
||||
|
||||
@ -1,68 +0,0 @@
|
||||
# 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** мониторинг связан с функцией «Отслеживание ошибок»
|
||||
@ -264,27 +264,6 @@ Telegram об исчерпанной задержке.
|
||||
- **THEN** исполнитель не перезапущен
|
||||
- **BUT** появилась новая голова DEMO-2 без задания дольше 10 минут — перезапуск
|
||||
|
||||
### Requirement: Назревшая попытка лечения не теряется
|
||||
Сбой перезапуска агента SHALL считаться попыткой лечения застрявшей задачи. Попытка, срок
|
||||
которой подошёл, но которую держит ожидание (очередь проверок, недоступная Gitea), SHALL
|
||||
обновлять карточку задержки (ожидание и время следующей проверки); ожидание очереди проверок
|
||||
SHALL длиться не дольше 2 часов от срока попытки, после чего попытка SHALL выполняться и счёт
|
||||
SHALL доходить до исчерпания и одного сообщения суперадмину.
|
||||
|
||||
#### Scenario: Перезапуск падает каждый раз
|
||||
- **GIVEN** задача в работе, результат конфликтует, перезапуск агента каждый раз падает
|
||||
- **WHEN** вачдог заходит в 0, +5, +20, +80 и +200 минут
|
||||
- **THEN** попытки считаются 1, 2, 3, 4
|
||||
- **AND** в +200 минут карточка «нужен администратор» и суперадмин получает одно сообщение
|
||||
|
||||
#### Scenario: Попытку держит очередь проверок
|
||||
- **GIVEN** у задачи 3 попытки, срок четвёртой подошёл, результат конфликтует
|
||||
- **AND** очередь проверок стоит
|
||||
- **WHEN** вачдог делает проход
|
||||
- **THEN** агент не перезапускается, карточка показывает ожидание со временем следующей проверки
|
||||
- **WHEN** очередь стоит дольше 2 часов от срока попытки и вачдог делает проход
|
||||
- **THEN** выполняется четвёртая попытка
|
||||
|
||||
### Requirement: Задача «В работе» без агента не теряется
|
||||
Сторож застрявших задач SHALL рассматривать задачу «В работе», у которой нет ни одной сессии,
|
||||
нет места в очереди раннера и в очереди свободного агента, если она не менялась дольше 30
|
||||
|
||||
@ -28,20 +28,3 @@ Worktree законченного раннера SHALL удаляться, ко
|
||||
- **GIVEN** раннер упал, в его worktree незакоммиченные изменения
|
||||
- **WHEN** вачдог убирает worktree
|
||||
- **THEN** worktree остаётся, событие `worktree_kept`
|
||||
|
||||
### Requirement: Пропавшая рабочая копия пересоздаётся
|
||||
Если рабочей копии сессии нет на этом хосте (путь с другой машины, удалённый worktree), перезапуск
|
||||
сессии SHALL создавать новый worktree в стандартном месте `$PEPPA_HOME/worktrees/<slug>/s<id>` на
|
||||
ветке стори, запоминать новый путь у сессии и запускать агента в нём, а не падать.
|
||||
|
||||
#### Scenario: Путь рабочей копии с другой машины
|
||||
- **GIVEN** задача в работе, у её последней сессии путь рабочей копии `/Users/asel/.peppa/worktrees/peppa/s783`
|
||||
- **AND** такого каталога на этом хосте нет
|
||||
- **WHEN** сессию перезапускают
|
||||
- **THEN** агент запускается в `$PEPPA_HOME/worktrees/<slug>/s<id>` на ветке `task/<key>`
|
||||
- **AND** у сессии записан новый путь, событие `worktree_created` с прежним путём
|
||||
|
||||
#### Scenario: Рабочая копия на месте
|
||||
- **GIVEN** worktree сессии существует
|
||||
- **WHEN** сессию перезапускают
|
||||
- **THEN** агент запускается в том же каталоге, путь сессии не меняется
|
||||
|
||||
@ -76,7 +76,7 @@ import { createEdgeTunnel, edgeConfig, edgeHosts, formatEdgeSync, syncEdge, isPr
|
||||
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
||||
import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner";
|
||||
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits } from "@peppa/core";
|
||||
import { tidyAgentTasks, findForeignPaths, fixForeignPaths } from "@peppa/runner";
|
||||
import { tidyAgentTasks } from "@peppa/runner";
|
||||
import { installCrashReporting } from "@peppa/core";
|
||||
import { pushTemplateOrAlert, syncTemplate } from "@peppa/runner";
|
||||
import { answerAndDeliver, connectCi, importIssues, deployProd, redeployProject, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
@ -126,7 +126,6 @@ const USAGE = `peppa — FORGE software factory CLI
|
||||
peppa session attach <id>
|
||||
peppa session stop <id>
|
||||
peppa session resume <id> [-p <extra prompt>] (new generation, claude --resume)
|
||||
peppa session paths [--fix] (paths this host does not have: sessions from another machine, missing copies; --fix rewrites finished ones)
|
||||
peppa runner new <KEY> [--name <имя>] [-p <промпт>] [--provider …] (free runner without a story, PEP-53)
|
||||
peppa runner rename <id> <имя>
|
||||
peppa runner promote <id> <название стори> [-d <описание>] (the free runner's work becomes a story)
|
||||
@ -186,7 +185,6 @@ const { values: opts, positionals } = parseArgs({
|
||||
status: { type: "string", short: "s" },
|
||||
help: { type: "boolean", short: "h" },
|
||||
"dry-run": { type: "boolean" },
|
||||
fix: { type: "boolean" },
|
||||
prompt: { type: "string", short: "p" },
|
||||
mode: { type: "string" },
|
||||
provider: { type: "string" },
|
||||
@ -617,17 +615,6 @@ async function main(): Promise<void> {
|
||||
console.log(`Session #${s.id} for ${s.taskKey} → tmux attach -t ${s.tmuxName}`);
|
||||
break;
|
||||
}
|
||||
case "session paths": {
|
||||
// PEP-246: paths this host doesn't have (sessions from the Mac after the move, removed worktrees).
|
||||
const found = await findForeignPaths(db);
|
||||
for (const x of found.sessions) console.log(`session #${x.id} (${x.status}): ${x.path}${x.fixTo ? ` → ${x.fixTo}` : " (left: live, the relaunch makes a new copy)"}`);
|
||||
for (const x of found.projects) console.log(`project ${x.key}: working copy ${x.path} is missing`);
|
||||
for (const x of found.settings) console.log(`setting ${x.key}: mentions /Users/`);
|
||||
if (!found.sessions.length && !found.projects.length && !found.settings.length) console.log("no foreign paths");
|
||||
else if (opts.fix) console.log(`rewritten: ${await fixForeignPaths(db, found)} session path(s)`);
|
||||
else if (found.sessions.some((x) => x.fixTo)) console.log("run with --fix to rewrite the finished sessions' paths");
|
||||
break;
|
||||
}
|
||||
case "session list":
|
||||
for (const s of await listSessions(db, { active: !opts.all })) {
|
||||
const ago = s.lastActivityAt ? `${Math.round((Date.now() - s.lastActivityAt.getTime()) / 60000)}m ago` : "-";
|
||||
|
||||
@ -180,37 +180,14 @@ export interface LaunchModel {
|
||||
escalated: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-241: the CLI a model name belongs to — Claude aliases and `claude-*`, OpenAI `gpt-*`/`o<N>`/`codex-*`,
|
||||
* OpenCode `provider/model`; null when the name says nothing.
|
||||
*/
|
||||
export function modelProvider(model: string): AgentProvider | null {
|
||||
const m = model.trim().toLowerCase();
|
||||
if (/^(opus|sonnet|haiku|opusplan|claude)([-\[.:]|$)/.test(m)) return "claude";
|
||||
if (/^(gpt|codex)([-.]|$)|^o\d/.test(m)) return "codex";
|
||||
if (m.includes("/")) return "opencode";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does `model` go to `provider`? With the provider set in the settings — only to it; without one
|
||||
* (PEP-241) — only to the CLI the name belongs to, an unknown name to the default one (Claude):
|
||||
* `-m opus` makes Codex on a ChatGPT account refuse every message.
|
||||
*/
|
||||
function modelFits(model: string | null, provider: AgentProvider, configured: AgentProvider | null): boolean {
|
||||
if (!model) return false;
|
||||
if (configured) return configured === provider;
|
||||
return (modelProvider(model) ?? "claude") === provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Model and effort for one launch on `provider`: the escalation model once the story is
|
||||
* escalated; the fallback model on the fallback provider; the model only on its own provider.
|
||||
*/
|
||||
export function launchModelFor(s: AgentSettings, provider: AgentProvider, escalated: boolean): LaunchModel {
|
||||
const own = s.provider == null || s.provider === provider;
|
||||
if (own && escalated && s.escalateModel && modelFits(s.escalateModel, provider, s.provider)) return { model: s.escalateModel, effort: s.escalateEffort ?? s.effort, escalated: true };
|
||||
if (own) return { model: modelFits(s.model, provider, s.provider) ? s.model : null, effort: s.effort, escalated: false };
|
||||
if (own && escalated && s.escalateModel) return { model: s.escalateModel, effort: s.escalateEffort ?? s.effort, escalated: true };
|
||||
if (own) return { model: s.model, effort: s.effort, escalated: false };
|
||||
if (s.fallbackProvider === provider) return { model: s.fallbackModel, effort: null, escalated: false };
|
||||
return { model: null, effort: null, escalated: false };
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
// 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";
|
||||
@ -194,8 +193,6 @@ 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");
|
||||
|
||||
@ -1,5 +0,0 @@
|
||||
// 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));
|
||||
@ -1,230 +0,0 @@
|
||||
// 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, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
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;
|
||||
}
|
||||
@ -105,7 +105,6 @@ 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";
|
||||
|
||||
@ -11,8 +11,7 @@ export type PeppaNotification =
|
||||
| { type: "progress"; eventId: number }
|
||||
| { type: "session_updated"; sessionId: number }
|
||||
| { type: "incident"; incidentId: number }
|
||||
| { type: "chat_message"; messageId: number }
|
||||
| { type: "feature"; name: string };
|
||||
| { type: "chat_message"; messageId: number };
|
||||
|
||||
/** 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;
|
||||
|
||||
@ -15,7 +15,6 @@ 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";
|
||||
@ -77,8 +76,6 @@ 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 {
|
||||
@ -117,8 +114,6 @@ 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;
|
||||
@ -185,27 +180,6 @@ 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>();
|
||||
@ -278,7 +252,6 @@ 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),
|
||||
};
|
||||
}
|
||||
|
||||
@ -357,14 +330,7 @@ export function normalizeTarget(kind: MonitorKind, t: Record<string, unknown>):
|
||||
}
|
||||
}
|
||||
|
||||
/** 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[] } {
|
||||
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target" | "remindMin">> & { target: MonitorTarget; remindMin: number | null } {
|
||||
const name = String(input.name ?? "").trim();
|
||||
if (!name || name.length > 80) bad("Название: от 1 до 80 символов");
|
||||
if (!MONITOR_KINDS.includes(input.kind)) bad("Неизвестный вид мониторинга: {kind}", { kind: String(input.kind) });
|
||||
@ -379,7 +345,6 @@ 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 ?? []),
|
||||
};
|
||||
}
|
||||
|
||||
@ -404,10 +369,10 @@ export function createMonitor(input: MonitorInput, author: string, now = new Dat
|
||||
const token = n.kind === "heartbeat" ? randomBytes(18).toString("base64url") : null;
|
||||
const r = db
|
||||
.prepare(
|
||||
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, remind_min, remind_degraded, token, created_by, created_at, updated_at, state_since, last_ping_at, features)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
|
||||
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, remind_min, remind_degraded, token, created_by, created_at, updated_at, state_since, last_ping_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
|
||||
)
|
||||
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, n.remindMin, n.remindDegraded ? 1 : 0, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null, JSON.stringify(n.features)) as Row;
|
||||
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, n.remindMin, n.remindDegraded ? 1 : 0, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null) as Row;
|
||||
return toMonitor(r);
|
||||
}
|
||||
|
||||
@ -426,11 +391,10 @@ 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 = ?, 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;
|
||||
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, remind_min = ?, remind_degraded = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`)
|
||||
.get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, n.remindMin, n.remindDegraded ? 1 : 0, now.toISOString(), id) as Row;
|
||||
return toMonitor(r);
|
||||
}
|
||||
|
||||
@ -781,33 +745,10 @@ 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, features: ["egov_login"] }, "system", now),
|
||||
createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300, features: ["egov_login"] }, "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),
|
||||
];
|
||||
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;
|
||||
}
|
||||
|
||||
@ -6,8 +6,6 @@ import {
|
||||
createMonitor,
|
||||
deleteMonitor,
|
||||
describeTarget,
|
||||
FEATURE_NAMES,
|
||||
featureStatuses,
|
||||
getMonitor,
|
||||
getProject,
|
||||
logEvent,
|
||||
@ -56,10 +54,6 @@ 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)}%`);
|
||||
@ -68,7 +62,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.features.length ? ` · switches off: ${m.features.join(", ")}` : ""}`;
|
||||
`- #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)} — ${m.paused ? "paused" : m.state}${m.lastDetail?.reason ? ` (${m.lastDetail.reason})` : ""} · uptime 24h ${pct(m.uptime24h)}, 7d ${pct(m.uptime7d)}${outage(m)}`;
|
||||
|
||||
async function journal(db: Db, type: string, sessionId: number | null | undefined, payload: Record<string, unknown>) {
|
||||
const p = await getProject(db, platformProjectKey()).catch(() => null);
|
||||
@ -81,9 +75,7 @@ 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();
|
||||
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");
|
||||
return list.length ? list.map(line).join("\n") : "No monitors.";
|
||||
});
|
||||
|
||||
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 }) => {
|
||||
@ -110,7 +102,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, features: a.features }, who.author);
|
||||
const m = createMonitor({ name: a.name, kind: a.kind as MonitorKind, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold, remindMin: a.remind_min, remindDegraded: a.remind_degraded }, who.author);
|
||||
await journal(db, "monitor_created", who.sessionId, { id: m.id, name: m.name, kind: m.kind, target: m.target, author: who.author });
|
||||
return `Created #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)}; first check within a few seconds.`;
|
||||
},
|
||||
@ -119,9 +111,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, 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(", ")}` : ""}.`;
|
||||
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}.`;
|
||||
});
|
||||
|
||||
define("pause_monitor", "Observability: pause (no checks, no messages) or resume a monitor.", { id: z.number().int(), paused: z.boolean() }, false, async ({ id, paused }) => {
|
||||
|
||||
@ -25,37 +25,3 @@ export async function dismissCodexMenu(pane: tmux.Pane, screen: string): Promise
|
||||
|
||||
/** The CLI could not read the account at start: a network hiccup on the way to the provider, not the agent's failure. */
|
||||
export const CODEX_LOGIN_FAIL_RE = /account\/read failed|workspace routing discovery timed out/i;
|
||||
|
||||
/** PEP-241: «Trust this folder?» (0.169 «Do you trust the contents of this directory?», 0.171 «Folder access»). */
|
||||
const TRUST_QUESTION_RE = /Trust this folder\?|Do you trust the contents of this directory\?/i;
|
||||
const TRUST_YES_RE = /^\s*(?:›\s*)?(\d)\.\s*(?:Trust and continue|Yes, continue)\b/im;
|
||||
|
||||
export interface CodexTrustPrompt {
|
||||
digit: string;
|
||||
/** Absolute paths shown on the screen (the folder Codex asks about). */
|
||||
paths: string[];
|
||||
}
|
||||
|
||||
/** The trust question on Codex's screen: the digit of «Trust and continue» and the folders it names. */
|
||||
export function codexTrustPrompt(screen: string): CodexTrustPrompt | null {
|
||||
const tail = screen.trimEnd().split("\n").slice(-30).join("\n");
|
||||
if (!TRUST_QUESTION_RE.test(tail)) return null;
|
||||
const digit = TRUST_YES_RE.exec(tail)?.[1];
|
||||
if (!digit) return null;
|
||||
const paths = [...tail.matchAll(/(?:^|[\s(«"'`])(\/[^\s)»"'`]+)/g)].map((m) => m[1]!.replace(/[.,:;]+$/, "").replace(/(.)\/+$/, "$1"));
|
||||
return { digit, paths: [...new Set(paths)] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers «Trust and continue» — only for the folder Peppa gave the agent: every path on the screen
|
||||
* must be one of `allowed` (a screen without a path is about the folder Codex was started in, `--cd`).
|
||||
* Returns "sent", "foreign" (a folder that is not ours — nothing pressed) or null (no such screen).
|
||||
*/
|
||||
export async function dismissCodexTrust(pane: tmux.Pane, screen: string, allowed: string[]): Promise<"sent" | "foreign" | null> {
|
||||
const prompt = codexTrustPrompt(screen);
|
||||
if (!prompt) return null;
|
||||
const ok = new Set(allowed.map((p) => p.replace(/(.)\/+$/, "$1")));
|
||||
if (prompt.paths.some((p) => !ok.has(p))) return "foreign";
|
||||
await tmux.sendKeys(pane, prompt.digit);
|
||||
return "sent";
|
||||
}
|
||||
|
||||
@ -1,48 +0,0 @@
|
||||
// PEP-241: Codex asks «Trust this folder?» for a folder it does not know and waits for a key. It looks
|
||||
// the trust up by the git project root — for a worktree that is the root of the main repository, not
|
||||
// the worktree folder. And its `-c a.b.c=…` override splits the key on every dot, quoted or not, so a
|
||||
// path with a dot (`~/.peppa/…`) never matches through `-c`: the subscription's config.toml does.
|
||||
import { appendFileSync, existsSync, readFileSync, statSync } from "node:fs";
|
||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
||||
|
||||
/** The folders Codex may ask about for `cwd`: the folder itself and, for a worktree, the main repository's root. */
|
||||
export function codexTrustRoots(cwd: string): string[] {
|
||||
const roots = [cwd];
|
||||
try {
|
||||
const dotGit = join(cwd, ".git");
|
||||
if (existsSync(dotGit) && statSync(dotGit).isFile()) {
|
||||
const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
|
||||
if (m) {
|
||||
const gitdir = resolve(cwd, m[1]!.trim());
|
||||
const commonFile = join(gitdir, "commondir");
|
||||
const common = existsSync(commonFile) ? resolve(gitdir, readFileSync(commonFile, "utf8").trim()) : resolve(gitdir, "../..");
|
||||
const root = basename(common) === ".git" ? dirname(common) : common;
|
||||
if (!roots.includes(root)) roots.push(root);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* not a git folder — the folder itself is enough */
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the folders trusted in `<codexHome>/config.toml`. A folder already named in the file is left
|
||||
* alone: a second `[projects."…"]` table would make the whole config unreadable for Codex.
|
||||
*/
|
||||
export function trustCodexFolders(codexHome: string, folders: string[]): string[] {
|
||||
const file = join(codexHome, "config.toml");
|
||||
const text = existsSync(file) ? readFileSync(file, "utf8") : "";
|
||||
const added: string[] = [];
|
||||
for (const f of folders) {
|
||||
if (!isAbsolute(f)) continue;
|
||||
const key = JSON.stringify(f);
|
||||
if (text.includes(key)) continue;
|
||||
added.push(f);
|
||||
}
|
||||
if (added.length) {
|
||||
const block = added.map((f) => `[projects.${JSON.stringify(f)}]\ntrust_level = "trusted"\n`).join("\n");
|
||||
appendFileSync(file, `${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}${block}`, { mode: 0o600 });
|
||||
}
|
||||
return added;
|
||||
}
|
||||
@ -78,6 +78,3 @@ export * from "./review-wanted.ts";
|
||||
export * from "./review-wanted-state.ts";
|
||||
export * from "./delay-actions.ts";
|
||||
export * from "./edge-dns.ts";
|
||||
export * from "./workspace-paths.ts";
|
||||
export * from "./codex-trust.ts";
|
||||
export * from "./codex-screen.ts";
|
||||
|
||||
@ -32,12 +32,11 @@ export class LiveConnection {
|
||||
private input: Promise<void> = Promise.resolve();
|
||||
private closed = false;
|
||||
private db: Db;
|
||||
/** null — a tab without a sign-in (PEP-224): only open scopes (`features`) pass checkScopeAccess. */
|
||||
private user: User | null;
|
||||
private user: User;
|
||||
private out: (msg: Out) => void;
|
||||
private kill: (code: number, reason: string) => void;
|
||||
|
||||
constructor(db: Db, user: User | null, out: (msg: Out) => void, kill: (code: number, reason: string) => void) {
|
||||
constructor(db: Db, user: User, out: (msg: Out) => void, kill: (code: number, reason: string) => void) {
|
||||
this.db = db;
|
||||
this.user = user;
|
||||
this.out = out;
|
||||
@ -83,7 +82,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 ?? 0) });
|
||||
this.send({ t: "ok", scope, v: scope.startsWith("terminal:") ? undefined : liveHub(this.db).versionOf(scope, this.user.id) });
|
||||
} catch (e) {
|
||||
const status = e instanceof LiveError ? e.status : (e as { status?: number }).status ?? 500;
|
||||
if (status === 500) console.error(`live-ws: ${scope}`, e);
|
||||
@ -94,12 +93,11 @@ 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 ?? 0, since: { [scope]: since } });
|
||||
return liveHub(this.db).subscribe([scope], (e) => this.send({ t: "ev", ...e }), { userId: this.user.id, 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);
|
||||
@ -135,7 +133,6 @@ 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) {
|
||||
@ -180,8 +177,6 @@ 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 {
|
||||
@ -218,7 +213,7 @@ export function createLiveWs(opts: LiveWsOptions): LiveWs {
|
||||
}, pingMs);
|
||||
pinger.unref?.();
|
||||
|
||||
wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User | null) => {
|
||||
wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User) => {
|
||||
alive.set(ws, 0);
|
||||
const conn = new LiveConnection(
|
||||
opts.db,
|
||||
@ -246,7 +241,7 @@ export function createLiveWs(opts: LiveWsOptions): LiveWs {
|
||||
opts
|
||||
.authenticate(req)
|
||||
.then((user) => {
|
||||
if (!user && !opts.anonymous) return refuse(socket, 401, "Unauthorized");
|
||||
if (!user) return refuse(socket, 401, "Unauthorized");
|
||||
wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req, user));
|
||||
})
|
||||
.catch((e) => {
|
||||
|
||||
@ -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, featureFingerprint, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, resetFeatureCache, STEP_EVENT, stepView, type AttachmentView, type ChatMessageView, type StepView, type User } from "@peppa/core";
|
||||
import { attachmentsByMessage, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, 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); `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;
|
||||
/** 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;
|
||||
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,12 +87,9 @@ 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); `features` (PEP-224) — anybody,
|
||||
* the login page watches it.
|
||||
* `chat:<id>` the project's people (a master chat — its owner only).
|
||||
*/
|
||||
export async function checkScopeAccess(db: Db, user: User | null, scope: LiveScope): Promise<void> {
|
||||
if (scope === "features") return;
|
||||
if (!user) throw new LiveError(m("Нужен вход"), 401);
|
||||
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
|
||||
const [kind, raw] = scope.split(":") as [string, string?];
|
||||
const id = Number(raw);
|
||||
if (kind === "observe" || kind === "subs") {
|
||||
@ -158,8 +155,6 @@ 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);
|
||||
@ -453,8 +448,7 @@ class LiveHub {
|
||||
this.wake();
|
||||
}
|
||||
const now = Date.now();
|
||||
// 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) {
|
||||
if (this.watches.has("observe") && now - this.lastObserve >= OBSERVE_EVERY_MS) {
|
||||
this.lastObserve = now;
|
||||
this.wake();
|
||||
}
|
||||
@ -563,8 +557,6 @@ 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);
|
||||
@ -629,7 +621,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 | null, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number; since?: Record<string, string> } = {}): Promise<Response> {
|
||||
export async function liveSse(db: Db, user: User, 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 = () => {};
|
||||
@ -661,7 +653,7 @@ export async function liveSse(db: Db, user: User | null, scopes: LiveScope[], si
|
||||
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 ?? 0, since: opts.since });
|
||||
unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`), { userId: user.id, since: opts.since });
|
||||
},
|
||||
cancel() {
|
||||
cleanup();
|
||||
|
||||
@ -3,7 +3,6 @@ import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Session } from "@peppa/core";
|
||||
import { peppaRoot } from "@peppa/shared";
|
||||
import { codexTrustRoots } from "./codex-trust.ts";
|
||||
import { runDir, writeRunRules, writeRunSettings } from "./run-settings.ts";
|
||||
|
||||
/** PEP-17: inside the runner container the launch dir is mounted here (see sandbox.ts). */
|
||||
@ -97,8 +96,8 @@ function codexCommand(c: LaunchContext): string[] {
|
||||
c.cwd,
|
||||
...codexModeArgs(c.permissionMode, process.env.PEPPA_CODEX_MODE),
|
||||
// PEP-188: Codex 0.169 asks «Trust this folder?» on a first run and waits for a key.
|
||||
// PEP-241: for a worktree it asks about the main repository's root — trust both.
|
||||
...codexTrustRoots(c.cwd).flatMap((dir) => ["-c", `projects.${toml(dir)}.trust_level="trusted"`]),
|
||||
"-c",
|
||||
`projects.${toml(c.cwd)}.trust_level="trusted"`,
|
||||
// PEP-205: near the limit Codex asks «Switch to <model>?» and waits for a key — never show it.
|
||||
"-c",
|
||||
"notice.hide_rate_limit_model_nudge=true",
|
||||
|
||||
@ -48,7 +48,6 @@ import { loadEnv } from "@peppa/shared";
|
||||
import { trustWorkspace } from "./claude-config.ts";
|
||||
import { buildCommand, providerEnv, type Provider } from "./providers.ts";
|
||||
import { subscriptionEnv } from "./subscriptions.ts";
|
||||
import { codexTrustRoots, trustCodexFolders } from "./codex-trust.ts";
|
||||
import { runDir } from "./run-settings.ts";
|
||||
import * as tmux from "./tmux.ts";
|
||||
import { onReleaseAnswer } from "./deploy.ts";
|
||||
@ -241,14 +240,8 @@ export async function runnerCwd(db: Db, s: SessionView): Promise<string> {
|
||||
if (s.host) return (await ensureHostWorkspace(db, s, project!)).path;
|
||||
if (!s.workspacePath) return realpathSync(project!.workspacePath);
|
||||
if (!existsSync(s.workspacePath)) {
|
||||
// PEP-246: the copy may be gone (removed worktree) or recorded on another machine (sessions
|
||||
// from the Mac kept `/Users/…` after the move, PEP-230): a new one in the standard place,
|
||||
// and the session remembers it — returning the old path failed with ENOENT.
|
||||
const wt = await ensureWorktree(project!, s.id, s.taskKey);
|
||||
const path = realpathSync(wt.path);
|
||||
if (path !== s.workspacePath) await updateSession(db, s.id, { workspacePath: path });
|
||||
await logSessionEvent(db, s, "worktree_created", { path, branch: wt.branch, note: wt.note, recreated: true, from: s.workspacePath });
|
||||
return path;
|
||||
await logSessionEvent(db, s, "worktree_created", { path: wt.path, branch: wt.branch, note: wt.note, recreated: true });
|
||||
}
|
||||
return realpathSync(s.workspacePath);
|
||||
}
|
||||
@ -409,18 +402,6 @@ async function launch(
|
||||
};
|
||||
script = `#!/bin/bash\n${preamble}exec ${argv.map(shq).join(" ")}\n`;
|
||||
}
|
||||
// PEP-241: Codex trusts folders from its CODEX_HOME config.toml — the `-c` in the command misses
|
||||
// paths with a dot. Only here: on a host (PEP-40) the subscription's dir is the host's.
|
||||
if (s.provider === "codex" && !s.host && sub) {
|
||||
const home = subscriptionEnv(sub).CODEX_HOME;
|
||||
if (home && existsSync(home)) {
|
||||
try {
|
||||
trustCodexFolders(home, codexTrustRoots(cwd));
|
||||
} catch {
|
||||
/* the watchdog answers the trust screen */
|
||||
}
|
||||
}
|
||||
}
|
||||
writeFileSync(launchScript, script);
|
||||
chmodSync(launchScript, 0o700);
|
||||
await updateSession(db, s.id, { generation, status: "starting", endedAt: null });
|
||||
|
||||
@ -60,11 +60,6 @@ export const STUCK_IDLE_MS = 30 * 60_000;
|
||||
export const STUCK_RETRY_MIN = [5, 15, 60, 120];
|
||||
/** Attempts before the superadmin is asked to look. */
|
||||
export const STUCK_MAX_ATTEMPTS = 4;
|
||||
/**
|
||||
* PEP-246: a due attempt waits for the standing checks queue at most this long (min), then the
|
||||
* agent is relaunched anyway — PEP-217 stood for days while the count never moved.
|
||||
*/
|
||||
export const STUCK_QUEUE_WAIT_MIN = 120;
|
||||
|
||||
export interface StuckHeal {
|
||||
attempts: number;
|
||||
@ -83,14 +78,10 @@ export const clearStuckHeal = (db: Db, taskId: number) => deleteSetting(db, heal
|
||||
export type Diagnosis =
|
||||
| { kind: "merged"; pull: GiteaPull }
|
||||
| { kind: "review"; pull: GiteaPull }
|
||||
/**
|
||||
* Not the platform's to heal right now (checks running, Gitea unreachable, the checks queue).
|
||||
* `held`: what the agent would be asked if the wait were over (the checks queue holds a rebase).
|
||||
*/
|
||||
| { kind: "wait"; why: string; held?: AgentDiagnosis }
|
||||
/** Not the platform's to heal right now (checks running, Gitea unreachable, the checks queue). */
|
||||
| { kind: "wait"; why: string }
|
||||
/** Only the agent can do it: `agent` is told exactly what, `reason` is for the superadmin. */
|
||||
| AgentDiagnosis;
|
||||
type AgentDiagnosis = { kind: "agent"; reason: string; agent: string; pull: GiteaPull | null };
|
||||
| { kind: "agent"; reason: string; agent: string; pull: GiteaPull | null };
|
||||
|
||||
const branchRe = (key: string) => new RegExp(`^task/${key.replace(/[^A-Za-z0-9-]/g, "")}(?![0-9])`, "i");
|
||||
|
||||
@ -136,15 +127,14 @@ export async function diagnose(db: Db, ref: TaskRef, gitea: GiteaClient = giteaF
|
||||
};
|
||||
}
|
||||
if (pull.mergeable === false) {
|
||||
const conflict: AgentDiagnosis = {
|
||||
// PEP-205: no rebase while the checks queue stands — every push queues new checks.
|
||||
if (await checksQueueStanding(db)) return { kind: "wait", why: "checks queue" };
|
||||
return {
|
||||
kind: "agent",
|
||||
reason: m("изменения конфликтуют с основной версией кода"),
|
||||
agent: `PR #${pull.number} стори ${ref.key} конфликтует с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок вызови update_task(status: review).`,
|
||||
pull,
|
||||
};
|
||||
// PEP-205: no rebase while the checks queue stands — every push queues new checks.
|
||||
if (await checksQueueStanding(db)) return { kind: "wait", why: "checks queue", held: conflict };
|
||||
return conflict;
|
||||
}
|
||||
return { kind: "wait", why: "checks running" };
|
||||
}
|
||||
@ -237,24 +227,8 @@ async function healOne(db: Db, ref: TaskRef, delays: Awaited<ReturnType<typeof l
|
||||
return false;
|
||||
}
|
||||
if (card?.exhausted) return false; // the superadmin decides (buttons), nothing more by itself
|
||||
let d = await diagnose(db, ref, gitea);
|
||||
if (d.kind === "wait") {
|
||||
if (!heal) return false;
|
||||
// PEP-246: a due attempt is not lost silently. The checks queue holds it for a while, then it goes.
|
||||
if (d.held && now - heal.nextAt >= STUCK_QUEUE_WAIT_MIN * 60_000) {
|
||||
log(`${ref.key}: stuck — the checks queue held the attempt for ${Math.round((now - heal.nextAt) / 60_000)} min, relaunching anyway`);
|
||||
d = d.held;
|
||||
} else {
|
||||
const at = now + STUCK_RETRY_MIN[0]! * 60_000;
|
||||
if (!card || card.state !== "waiting" || card.retryAt == null || card.retryAt <= now) {
|
||||
// glossary-ignore: сообщение суперадмину
|
||||
const details = m("⏳ {key}: попытка {n} ждёт ({why}), проверим снова в ближайшие минуты", { key: ref.key, n: heal.attempts + 1, why: d.why });
|
||||
await platformDelay(db, scope, { reason: "stuck", state: "waiting", quiet: true, attempts: heal.attempts, retryAt: at, details, action: heal.action, now: new Date(now), log });
|
||||
}
|
||||
log(`${ref.key}: stuck — attempt ${heal.attempts + 1} is due but waits (${d.why})`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const d = await diagnose(db, ref, gitea);
|
||||
if (d.kind === "wait") return false;
|
||||
if (d.kind === "merged") {
|
||||
await closeMergedStory(db, ref, d.pull.number, null, gitea);
|
||||
await clearStuckHeal(db, ref.task.id);
|
||||
|
||||
@ -30,9 +30,7 @@ import {
|
||||
subscriptionWarnTick,
|
||||
warnLastSubscription,
|
||||
} from "@peppa/core";
|
||||
import { projects, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { realpathSync } from "node:fs";
|
||||
import type { Db } from "@peppa/db";
|
||||
import * as tmux from "./tmux.ts";
|
||||
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, LIMIT_SCREEN_RE, limitLines, recordLimit } from "./limits.ts";
|
||||
import { limitDelay, limitOver } from "./limit-delay.ts";
|
||||
@ -67,8 +65,7 @@ import { productLinkTick } from "./product-link.ts";
|
||||
import { pickQuestionTick } from "./pick-question.ts";
|
||||
import { budgetTick } from "./budgets.ts";
|
||||
import { getWatchdogSettings, idleStopTick, LOST_CONVERSATION_RE, onConversationLost, onLoginFailure, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
|
||||
import { CODEX_LOGIN_FAIL_RE, codexModelMenu, codexTrustPrompt, dismissCodexMenu, dismissCodexTrust } from "./codex-screen.ts";
|
||||
import { codexTrustRoots } from "./codex-trust.ts";
|
||||
import { CODEX_LOGIN_FAIL_RE, codexModelMenu, dismissCodexMenu } from "./codex-screen.ts";
|
||||
import { claudeCreditsDialog, dismissCreditsDialog } from "./claude-screen.ts";
|
||||
import { serveRunnerCommands, type RunnerService } from "./runner-service.ts";
|
||||
|
||||
@ -294,15 +291,6 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
|
||||
else if (await dismissCodexMenu(tmux.sessionPane(s), screen).catch(() => false)) await logSessionEvent(db, s, "model_menu_dismissed", {});
|
||||
await patchWatch(db, s, { menuAt: now });
|
||||
}
|
||||
// PEP-241: «Trust this folder?» waits for a key before the first turn — answer «Trust and continue»,
|
||||
// only for the folder Peppa gave the agent (its worktree, the project's copy and their repository roots).
|
||||
if (s.provider === "codex" && codexTrustPrompt(screen) && !(s.watchState?.menuAt && now - s.watchState.menuAt < 120_000)) {
|
||||
const allowed = await agentFolders(db, s);
|
||||
const res = await dismissCodexTrust(tmux.sessionPane(s), screen, allowed).catch(() => null);
|
||||
if (res === "sent") await logSessionEvent(db, s, "trust_dismissed", {});
|
||||
else if (res === "foreign") await logSessionEvent(db, s, "trust_foreign", { paths: codexTrustPrompt(screen)?.paths ?? [] });
|
||||
await patchWatch(db, s, { menuAt: now });
|
||||
}
|
||||
// PEP-227: Claude's «<model> now uses usage credits» dialog waits for a choice — pick «Switch to Opus…»;
|
||||
// without such a choice the superadmin hears once per generation.
|
||||
if (s.provider === "claude") {
|
||||
@ -481,20 +469,3 @@ async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: stri
|
||||
await limitOver(db, s);
|
||||
log(`#${s.id} ${s.taskKey ?? ""}: limit reset, ${alive ? "nudged" : "relaunched"}`);
|
||||
}
|
||||
|
||||
/** PEP-241: the folders Peppa gave this agent — its worktree, the project's copy and their repository roots. */
|
||||
async function agentFolders(db: Db, s: SessionView): Promise<string[]> {
|
||||
const [project] = await db.select({ path: projects.workspacePath }).from(projects).where(eq(projects.id, s.projectId));
|
||||
const out = new Set<string>();
|
||||
for (const p of [s.workspacePath, project?.path]) {
|
||||
if (!p) continue;
|
||||
out.add(p);
|
||||
try {
|
||||
const real = realpathSync(p);
|
||||
for (const r of codexTrustRoots(real)) out.add(r);
|
||||
} catch {
|
||||
/* on a host the folder is not here */
|
||||
}
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
@ -1,50 +0,0 @@
|
||||
// PEP-246: after the move to the server (PEP-230) finished sessions kept their working copy paths
|
||||
// from the Mac (`/Users/…`); `server-cutover.sh` cleared only the live ones. A relaunch of such a
|
||||
// session failed with ENOENT. `runnerCwd` now makes a new copy itself; this finds what is left
|
||||
// (CLI `peppa session paths [--fix]`): sessions and projects with a path this host doesn't have,
|
||||
// settings that mention `/Users/`.
|
||||
import { existsSync } from "node:fs";
|
||||
import { FINISHED_SESSION_STATUSES } from "@peppa/core";
|
||||
import { projects, sessions, settings, type Db } from "@peppa/db";
|
||||
import { and, eq, isNotNull, isNull, sql } from "drizzle-orm";
|
||||
import { worktreePath } from "./worktree.ts";
|
||||
|
||||
export interface ForeignPaths {
|
||||
sessions: Array<{ id: number; projectId: number; status: string; path: string; fixTo: string | null }>;
|
||||
projects: Array<{ id: number; key: string; path: string }>;
|
||||
settings: Array<{ key: string }>;
|
||||
}
|
||||
|
||||
/** What still points to a path this host doesn't have. Sessions on a separate host are skipped. */
|
||||
export async function findForeignPaths(db: Db): Promise<ForeignPaths> {
|
||||
const slugs = new Map((await db.select({ id: projects.id, slug: projects.slug }).from(projects)).map((p) => [p.id, p.slug]));
|
||||
const rows = await db
|
||||
.select({ id: sessions.id, projectId: sessions.projectId, status: sessions.status, path: sessions.workspacePath })
|
||||
.from(sessions)
|
||||
.where(and(isNotNull(sessions.workspacePath), isNull(sessions.hostId)));
|
||||
const out: ForeignPaths = { sessions: [], projects: [], settings: [] };
|
||||
for (const r of rows) {
|
||||
if (!r.path || existsSync(r.path)) continue;
|
||||
const slug = slugs.get(r.projectId);
|
||||
// Only finished sessions are rewritten: a live one is the watchdog's (its relaunch makes the copy).
|
||||
const fixTo = slug && FINISHED_SESSION_STATUSES.includes(r.status) ? worktreePath({ slug }, r.id) : null;
|
||||
out.sessions.push({ id: r.id, projectId: r.projectId, status: r.status, path: r.path, fixTo: fixTo !== r.path ? fixTo : null });
|
||||
}
|
||||
for (const p of await db.select({ id: projects.id, key: projects.key, path: projects.workspacePath }).from(projects).where(isNull(projects.deletedAt))) {
|
||||
if (!existsSync(p.path)) out.projects.push(p);
|
||||
}
|
||||
// Values are JSON text: a LIKE over the raw value finds a path anywhere inside (a one-off scan).
|
||||
for (const s of await db.select({ key: settings.key }).from(settings).where(sql`${settings.value} LIKE '%/Users/%'`)) out.settings.push(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Rewrites the paths of finished sessions to the standard place (where `runnerCwd` would make the copy). */
|
||||
export async function fixForeignPaths(db: Db, found: ForeignPaths): Promise<number> {
|
||||
let n = 0;
|
||||
for (const s of found.sessions) {
|
||||
if (!s.fixTo) continue;
|
||||
await db.update(sessions).set({ workspacePath: s.fixTo }).where(eq(sessions.id, s.id));
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@ -86,7 +86,6 @@ export const acceptScreen: Dict = {
|
||||
"📤 Перевести на ревью": "📤 Move to review",
|
||||
"Закрыть": "Close",
|
||||
"⏳ {key}: ждёт, пока освободится общая рабочая копия проекта": "⏳ {key}: waits for the project's shared working copy to be free",
|
||||
"⏳ {key}: попытка {n} ждёт ({why}), проверим снова в ближайшие минуты": "⏳ {key}: attempt {n} waits ({why}), checking again in a few minutes",
|
||||
// PEP-247: in work without an agent for a lawful reason.
|
||||
"Проект на паузе — агент продолжит, когда вы снимете паузу": "The project is paused — the agent will continue once you resume it",
|
||||
"Агент не запущен: у проекта нет рабочей подписки": "The agent hasn't started: the project has no working subscription",
|
||||
|
||||
@ -1,37 +0,0 @@
|
||||
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.",
|
||||
};
|
||||
@ -30,6 +30,5 @@ 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, ...features };
|
||||
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 };
|
||||
|
||||
@ -86,7 +86,6 @@ export const acceptScreen: Dict = {
|
||||
"📤 Перевести на ревью": "📤 Тексеруге беру",
|
||||
"Закрыть": "Жабу",
|
||||
"⏳ {key}: ждёт, пока освободится общая рабочая копия проекта": "⏳ {key}: жобаның ортақ жұмыс көшірмесі босағанын күтуде",
|
||||
"⏳ {key}: попытка {n} ждёт ({why}), проверим снова в ближайшие минуты": "⏳ {key}: {n}-әрекет күтуде ({why}), бірнеше минуттан кейін қайта тексереміз",
|
||||
// PEP-247: in work without an agent for a lawful reason.
|
||||
"Проект на паузе — агент продолжит, когда вы снимете паузу": "Жоба кідірісте — кідірісті алғаныңызда агент жалғастырады",
|
||||
"Агент не запущен: у проекта нет рабочей подписки": "Агент іске қосылмады: жобада жұмыс істейтін жазылым жоқ",
|
||||
|
||||
@ -1,37 +0,0 @@
|
||||
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})",
|
||||
"Функции ещё не отключались.": "Функциялар әлі өшірілмеген.",
|
||||
};
|
||||
@ -30,6 +30,5 @@ 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, ...features };
|
||||
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 };
|
||||
|
||||
@ -95,9 +95,6 @@ if (provider === "codex" && argv[0] !== "exec" && argv[0] !== "login") {
|
||||
}
|
||||
}
|
||||
const args = parseArgs();
|
||||
// PEP-241: Codex on a ChatGPT account refuses a Claude model on the first message.
|
||||
const codexModel = provider === "codex" ? argv.find((a, i) => argv[i - 1] === "--model" || argv[i - 1] === "-m") : undefined;
|
||||
const codexModelRefused = !!codexModel && /^(opus|sonnet|haiku|claude)/i.test(codexModel);
|
||||
if (!codexTrusted) {
|
||||
process.stdout.write("Do you trust the contents of this directory?\n 1. Yes, continue\n 2. No, quit\nTrust this folder? Press enter to continue\n");
|
||||
await new Promise(() => {});
|
||||
@ -361,16 +358,6 @@ async function run(action: Action): Promise<boolean> {
|
||||
log("menu", { key });
|
||||
out(key === "1" ? "• Switched to gpt-6-luna\n" : "• Keeping the current model\n");
|
||||
mode = "busy";
|
||||
} else if ("trust" in action) {
|
||||
const spec = typeof action.trust === "object" ? action.trust : {};
|
||||
out(` Folder access\n\n Trust this folder?\n ${spec.path ?? cwd}\n\n› 1. Trust and continue\n 2. Back to Agent Command Center\n\n enter select · esc back\n`);
|
||||
const key = await dialog();
|
||||
log("trust", { key });
|
||||
if (key !== "1") {
|
||||
log("exit", { code: 0, reason: "trust" });
|
||||
process.exit(0);
|
||||
}
|
||||
mode = "busy";
|
||||
} else if ("loginFail" in action) {
|
||||
out("› Error: account/read failed: account/read failed: workspace routing discovery timed out (code -32603)\n");
|
||||
log("exit", { code: 1, reason: "login" });
|
||||
@ -499,12 +486,6 @@ async function main() {
|
||||
|
||||
let i = 0;
|
||||
const run = async (prompt: string) => {
|
||||
if (codexModelRefused) {
|
||||
out(`■ The ${codexModel} model is not supported when using Codex with a ChatGPT account.\n\n> `);
|
||||
log("model_refused", { model: codexModel });
|
||||
mode = "prompt";
|
||||
return;
|
||||
}
|
||||
let next = await turn(prompt, turns[i++]);
|
||||
while (next) next = await turn(next, turns[i++], true);
|
||||
};
|
||||
|
||||
@ -18,9 +18,6 @@ export type Action =
|
||||
// PEP-205 (codex): the «Switch to <model>?» menu near the limit — waits for a key (1–3, Esc), logs `menu` with it;
|
||||
// `afterLimit` prints the limit line above it like the real screen
|
||||
| { menu: true | { afterLimit?: boolean } }
|
||||
// PEP-241 (codex 0.171): «Folder access — Trust this folder?» about `path` (default: the cwd) — waits
|
||||
// for a key, logs `trust` with it; «2» (back) ends the run
|
||||
| { trust: true | { path?: string } }
|
||||
// PEP-205 (codex): the CLI cannot sign in — «account/read failed … timed out», exit 1
|
||||
| { loginFail: true }
|
||||
| { warn: number } // usage warning banner: "You've used N% of your weekly limit"
|
||||
|
||||
@ -93,31 +93,6 @@ describe("PEP-41: модель и провайдер стори", () => {
|
||||
assert.equal(core.launchModelFor({ ...s, fallbackModel: "gpt-5-codex" }, "codex", false).model, "gpt-5-codex");
|
||||
});
|
||||
|
||||
test("PEP-241: модель без провайдера идёт только своему CLI — Codex на ChatGPT не получает opus", async () => {
|
||||
const free = { ...core.DEFAULT_AGENT_SETTINGS, model: "opus", escalateModel: "opus" };
|
||||
assert.equal(core.launchModelFor(free, "codex", false).model, null);
|
||||
assert.equal(core.launchModelFor(free, "codex", true).model, null);
|
||||
assert.equal(core.launchModelFor(free, "claude", false).model, "opus");
|
||||
assert.equal(core.launchModelFor(free, "claude", true).model, "opus");
|
||||
assert.equal(core.launchModelFor({ ...free, model: "gpt-5-codex" }, "codex", false).model, "gpt-5-codex");
|
||||
assert.equal(core.launchModelFor({ ...free, model: "gpt-5-codex" }, "claude", false).model, null);
|
||||
assert.equal(core.launchModelFor({ ...free, model: "my-model" }, "codex", false).model, null);
|
||||
assert.equal(core.launchModelFor({ ...free, provider: "codex", model: "my-model" }, "codex", false).model, "my-model");
|
||||
|
||||
await core.setSystemAgentSettings(db, { model: "opus" });
|
||||
try {
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
const sid = await p.start({ provider: "codex" });
|
||||
const argv = argvOf(await p.waitLog("started", (e) => e.ev === "start"));
|
||||
assert.equal(flag(argv, "--model"), undefined, argv.join(" "));
|
||||
await p.waitLog("turn finished", (e) => e.ev === "turn_end");
|
||||
assert.equal(p.log().some((e) => e.ev === "model_refused"), false);
|
||||
await runner.stopSession(db, sid);
|
||||
} finally {
|
||||
await core.setSystemAgentSettings(db, {});
|
||||
}
|
||||
});
|
||||
|
||||
test("Codex получает model_reasoning_effort", async () => {
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
const proj = await core.getProject(db, p.key);
|
||||
|
||||
@ -2,11 +2,6 @@
|
||||
// make the watchdog think the agent hung or crashed.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { schema } from "@peppa/db";
|
||||
import { core, db, project, runner, setDefaultOwner, superadmin, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
@ -126,66 +121,6 @@ describe("Меню «Switch to <model>?»", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-241: экран доверия папке", () => {
|
||||
test("Экран Codex 0.171 о рабочей папке агента — сторож жмёт «Trust and continue», агент работает", async () => {
|
||||
const p = await project({ turns: [[{ trust: true }, { say: "Начал работу." }]] });
|
||||
await atWork(p);
|
||||
const sid = await p.start({ provider: "codex" });
|
||||
await waitFor("trust answered", async () => {
|
||||
await tickAt(new Date());
|
||||
return p.log().find((e) => e.ev === "trust");
|
||||
});
|
||||
assert.equal(p.log().find((e) => e.ev === "trust")!.key, "1");
|
||||
await p.waitLog("turn finished", (e) => e.ev === "turn_end");
|
||||
const evs = await db.select().from(schema.events).where(eq(schema.events.sessionId, sid));
|
||||
assert.ok(evs.some((e) => e.type === "trust_dismissed"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("Вопрос о чужой папке — сторож ничего не нажимает", async () => {
|
||||
const p = await project({ turns: [[{ trust: { path: "/etc" } }, { say: "не должно" }]] });
|
||||
await atWork(p);
|
||||
const sid = await p.start({ provider: "codex" });
|
||||
await p.waitLog("trust screen", (e) => e.ev === "dialog");
|
||||
for (let i = 0; i < 3; i++) await tickAt(new Date(Date.now() + i * 3 * MIN));
|
||||
assert.equal(p.log().some((e) => e.ev === "trust"), false);
|
||||
const evs = await db.select().from(schema.events).where(eq(schema.events.sessionId, sid));
|
||||
assert.ok(evs.some((e) => e.type === "trust_foreign"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("Экран узнаётся: старый и новый текст, пути на экране", () => {
|
||||
const { codexTrustPrompt } = runner;
|
||||
assert.deepEqual(codexTrustPrompt(" Folder access\n\n Trust this folder?\n /w/s1\n\n› 1. Trust and continue\n 2. Back to Agent Command Center\n"), { digit: "1", paths: ["/w/s1"] });
|
||||
assert.equal(codexTrustPrompt("Do you trust the contents of this directory?\n 1. Yes, continue\n 2. No, quit\n")!.digit, "1");
|
||||
assert.equal(codexTrustPrompt("• Working on /w/s1"), null);
|
||||
});
|
||||
|
||||
test("Worktree: команда доверяет и папке, и корню основного репозитория; config.toml подписки дописывается один раз", () => {
|
||||
const base = mkdtempSync(join(tmpdir(), "pep241-"));
|
||||
const repo = join(base, "repo");
|
||||
const wt = join(base, ".peppa", "wt");
|
||||
mkdirSync(join(repo, ".git", "worktrees", "wt"), { recursive: true });
|
||||
writeFileSync(join(repo, ".git", "worktrees", "wt", "commondir"), "../..\n");
|
||||
mkdirSync(wt, { recursive: true });
|
||||
writeFileSync(join(wt, ".git"), `gitdir: ${join(repo, ".git", "worktrees", "wt")}\n`);
|
||||
assert.deepEqual(runner.codexTrustRoots(wt), [wt, repo]);
|
||||
const cmd = buildCommand("codex", { sessionId: 1, generation: 1, cwd: wt, prompt: "p", rules: "r" });
|
||||
assert.ok(cmd.includes(`projects.${JSON.stringify(wt)}.trust_level="trusted"`));
|
||||
assert.ok(cmd.includes(`projects.${JSON.stringify(repo)}.trust_level="trusted"`));
|
||||
|
||||
const home = join(base, "codex");
|
||||
mkdirSync(home);
|
||||
writeFileSync(join(home, "config.toml"), 'model = "gpt-5"');
|
||||
assert.deepEqual(runner.trustCodexFolders(home, [wt, repo]), [wt, repo]);
|
||||
assert.deepEqual(runner.trustCodexFolders(home, [wt, repo]), []);
|
||||
const toml = readFileSync(join(home, "config.toml"), "utf8");
|
||||
assert.match(toml, /^model = "gpt-5"\n/);
|
||||
assert.equal(toml.split(`[projects.${JSON.stringify(wt)}]`).length, 2);
|
||||
assert.match(toml, /trust_level = "trusted"/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Сбой входа «account/read failed»", () => {
|
||||
test("Три повтора с растущей паузой без расхода перезапусков; потом подписка помечена, суперадмину одно сообщение", async () => {
|
||||
const sent = await superadmin();
|
||||
|
||||
@ -1,154 +0,0 @@
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
@ -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 | null) {
|
||||
function conn(u: import("@peppa/core").User) {
|
||||
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,18 +47,6 @@ 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: "Соседняя задача" });
|
||||
|
||||
@ -3,8 +3,7 @@
|
||||
// conflict → the agent is relaunched with the reason; retries 5 min / 15 min / 1 h / 2 h; the 4th
|
||||
// failure — one message to the superadmin; stale cards go; the owner sees when the next attempt is.
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
@ -257,80 +256,3 @@ describe("Пустой SET и общая рабочая копия (находк
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-246: рабочая копия с другой машины", () => {
|
||||
const FOREIGN = "/Users/asel/.peppa/worktrees/peppa/s783";
|
||||
const gitInit = (dir: string) => {
|
||||
for (const a of [["init", "-q", "-b", "main"], ["add", "-A"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init"]]) execFileSync("git", a, { cwd: dir });
|
||||
};
|
||||
const foreign = async (t: Awaited<ReturnType<typeof stuck>>) => {
|
||||
t.pull().mergeable = false;
|
||||
await db.update(sessions).set({ workspacePath: FOREIGN }).where(eq(sessions.id, t.sid));
|
||||
};
|
||||
|
||||
test("Scenario: Путь рабочей копии с другой машины — агент перезапускается в новой копии", async () => {
|
||||
const t = await stuck();
|
||||
gitInit(t.tp.dir);
|
||||
await foreign(t);
|
||||
await tick(Date.now());
|
||||
await waitFor("relaunched", async () => ((await core.getSession(db, t.sid)).status !== "starting" ? true : null));
|
||||
await runner.stopSession(db, t.sid).catch(() => {});
|
||||
const s = await core.getSession(db, t.sid);
|
||||
const want = realpathSync(runner.worktreePath(t.proj, t.sid));
|
||||
assert.equal(s.workspacePath, want, "the session remembers the new copy");
|
||||
assert.ok(existsSync(join(want, ".git")));
|
||||
assert.equal(execFileSync("git", ["branch", "--show-current"], { cwd: want }).toString().trim(), `task/${t.tp.taskKey.toLowerCase()}`);
|
||||
const heal = await runner.getStuckHeal(db, t.ref.task.id);
|
||||
assert.equal(heal?.attempts, 1);
|
||||
assert.doesNotMatch(heal!.action, /не перезапустился/, "the relaunch did not fail");
|
||||
const [e] = await db.select().from(events).where(and(eq(events.sessionId, t.sid), eq(events.type, "worktree_created")));
|
||||
assert.equal((e?.payload as { from?: string }).from, FOREIGN);
|
||||
assert.ok((await db.select().from(events).where(and(eq(events.sessionId, t.sid), inArray(events.type, ["started", "resumed"])))).length >= 1, "the agent was relaunched");
|
||||
});
|
||||
|
||||
test("Scenario: Перезапуск падает каждый раз — попытки считаются до исчерпания", async () => {
|
||||
const t = await stuck();
|
||||
await foreign(t); // the project's copy is not a git repository: no new copy can be made
|
||||
const T = Date.now();
|
||||
for (const [at, n] of [[0, 1], [5, 2], [20, 3], [80, 4]] as const) {
|
||||
await tick(T + at * MIN);
|
||||
const h = await runner.getStuckHeal(db, t.ref.task.id);
|
||||
assert.equal(h?.attempts, n, `attempt ${n} at +${at} min`);
|
||||
assert.match(h!.action, /не перезапустился/);
|
||||
}
|
||||
assert.equal((await toAdmin(t.tp.taskKey)).length, 0);
|
||||
await tick(T + 200 * MIN);
|
||||
assert.equal((await core.getPlatformDelay(db, t.scope, "stuck"))?.exhausted, true);
|
||||
assert.equal((await toAdmin(t.tp.taskKey)).length, 1, "one message to the superadmin");
|
||||
});
|
||||
|
||||
test("Scenario: Попытку держит очередь проверок — не дольше 2 часов", async () => {
|
||||
const t = await stuck();
|
||||
await foreign(t);
|
||||
const T = Date.now();
|
||||
await core.setSetting(db, `stuck.heal:${t.ref.task.id}`, { attempts: 3, at: T - 60 * MIN, nextAt: T, action: "x" });
|
||||
await core.setSetting(db, "checks.queue", { since: T - 300 * MIN, win: 0 });
|
||||
try {
|
||||
await tick(T + MIN);
|
||||
assert.equal((await runner.getStuckHeal(db, t.ref.task.id))?.attempts, 3, "the queue holds the attempt");
|
||||
const d = await core.getPlatformDelay(db, t.scope, "stuck");
|
||||
assert.equal(d?.state, "waiting");
|
||||
assert.ok(d!.retryAt! > T + MIN, "the card shows the next check, not a past time");
|
||||
await tick(T + 121 * MIN);
|
||||
assert.equal((await runner.getStuckHeal(db, t.ref.task.id))?.attempts, 4, "after 2 h the attempt goes anyway");
|
||||
} finally {
|
||||
await core.deleteSetting(db, "checks.queue");
|
||||
}
|
||||
});
|
||||
|
||||
test("peppa session paths: находит путь с другой машины и переписывает завершённую сессию", async () => {
|
||||
const t = await stuck();
|
||||
await db.update(sessions).set({ workspacePath: FOREIGN, status: "done" }).where(eq(sessions.id, t.sid));
|
||||
const found = await runner.findForeignPaths(db);
|
||||
const row = found.sessions.find((x) => x.id === t.sid);
|
||||
assert.equal(row?.fixTo, runner.worktreePath(t.proj, t.sid));
|
||||
await runner.fixForeignPaths(db, found);
|
||||
assert.equal((await core.getSession(db, t.sid)).workspacePath, runner.worktreePath(t.proj, t.sid));
|
||||
assert.equal((await runner.findForeignPaths(db)).sessions.some((x) => x.id === t.sid && x.fixTo), false);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user