Compare commits
No commits in common. "main" and "task/pep-130" have entirely different histories.
main
...
task/pep-1
18
.env.example
18
.env.example
@ -3,12 +3,12 @@
|
||||
# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36)
|
||||
# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
||||
|
||||
# Gitea (git.vibe42.kz) — token of peppa-bot with repo scope
|
||||
GITEA_URL=https://git.vibe42.kz
|
||||
# Gitea (git.telecom.quest) — token with repo + org scope
|
||||
GITEA_URL=https://git.telecom.quest
|
||||
GITEA_TOKEN=
|
||||
GITEA_TEMPLATE_REPO=peppa-bot/template
|
||||
GITEA_TEMPLATE_REPO=peppa/template
|
||||
# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
|
||||
# GITEA_PLATFORM_REPO=peppa-bot/peppa
|
||||
# GITEA_PLATFORM_REPO=peppa/peppa
|
||||
|
||||
# Where project repos are cloned and sessions run
|
||||
PEPPA_WORKSPACES=~/peppa/workspaces
|
||||
@ -32,13 +32,3 @@ GITEA_OAUTH_CLIENT_SECRET=
|
||||
# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI <PEPPA_WEB_URL>/auth/google/callback
|
||||
# GOOGLE_CLIENT_ID=
|
||||
# GOOGLE_CLIENT_SECRET=
|
||||
|
||||
# Распознавание речи (PEP-45/108): стори голосом в своём Telegram-боте и кнопка «Голосом» в вебе.
|
||||
# Свой сервис Пеппы — infra/whisper (faster-whisper, 127.0.0.1:8178, без ключа); облако — OpenAI/Groq с ключом.
|
||||
# PEPPA_TRANSCRIBE_URL=http://127.0.0.1:8178/v1
|
||||
# Язык записи — язык интерфейса говорящего (kk / en, PEP-131); для русского интерфейса — этот.
|
||||
# auto — язык не передаётся никому, сервис определяет сам.
|
||||
# PEPPA_TRANSCRIBE_LANG=ru
|
||||
# PEPPA_TRANSCRIBE_KEY=
|
||||
# PEPPA_TRANSCRIBE_MODEL=whisper-1
|
||||
# PEPPA_TRANSCRIBE_TIMEOUT_SEC=300
|
||||
|
||||
@ -20,7 +20,7 @@ jobs:
|
||||
# The runner has the host's docker.sock: only branches of this repository, never forks.
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: peppa-trusted
|
||||
timeout-minutes: 45
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
|
||||
# for the Postgres → SQLite migration test, which makes and drops its own database.
|
||||
@ -34,13 +34,7 @@ jobs:
|
||||
node-version: "26"
|
||||
- name: tools
|
||||
run: |
|
||||
# PEP-271: a mirror mid-sync fails `apt-get update`; with `&&` the install was skipped silently
|
||||
# and every e2e test died later on «spawn tmux ENOENT». Retry, then fail here if tmux is missing.
|
||||
for i in 1 2 3; do
|
||||
{ apt-get update -qq && apt-get install -y -qq tmux >/dev/null; } && break
|
||||
echo "apt: attempt $i failed, retrying"; sleep $((i * 15))
|
||||
done
|
||||
command -v tmux >/dev/null || { echo "::error::tmux was not installed (apt mirror unavailable)"; exit 1; }
|
||||
apt-get update -qq && apt-get install -y -qq tmux >/dev/null
|
||||
# Job-local prefix: the node toolcache is shared between jobs running at the same time
|
||||
# (PR + push of one commit), and two global installs into it collide (ENOTEMPTY/EEXIST).
|
||||
npm install -g --prefix "$RUNNER_TEMP/tools" pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null
|
||||
@ -55,14 +49,9 @@ jobs:
|
||||
- name: typecheck
|
||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh typecheck
|
||||
- id: build
|
||||
name: build
|
||||
- name: build
|
||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh build
|
||||
# PEP-217: weight of the first-load JS of every route against docs/bundle-baseline.json (+10 % fails).
|
||||
- name: bundle
|
||||
if: (success() || failure()) && steps.install.outcome == 'success' && steps.build.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh bundle
|
||||
- name: test
|
||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh test
|
||||
|
||||
34
.peppa/memory.md
Normal file
34
.peppa/memory.md
Normal file
@ -0,0 +1,34 @@
|
||||
# Память проекта
|
||||
|
||||
Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.
|
||||
|
||||
## Грабли
|
||||
- Браузер chrome-devtools MCP может быть занят другой сессией («browser is already running») — UI проверять на временной базе: свой seed + `next dev -p <порт>` из worktree с `PEPPA_DB`/`PEPPA_HOME`, вход `peppa web login-link`, страницу читать `curl -b jar`.
|
||||
- peppa-bot не может создавать организации в Gitea (403, флаг пользователя) — организацию создаёт админ Gitea и добавляет бота в Owners; после переноса раннер уровня peppa-bot репо не покрывает, нужен свой (`setupCi` / `peppa ci connect`).
|
||||
- Общая рабочая копия может стоять на чужой ветке — работай в `git worktree`; CLI из worktree против живой системы: `set -a; . /Users/telecom/Dev/Peppa/.env; set +a` и `<worktree>/packages/cli/bin/peppa …`.
|
||||
- Один файл e2e: `env -u NODE_TEST_CONTEXT node --test --test-reporter=spec test/<file>.test.ts` (внутри сессии Claude без этого вывод бинарный); CLI из теста с моком в том же процессе — только async execFile, execFileSync вешает мок.
|
||||
- node --test из шелла Claude Code молча ничего не запускает («run() is being called recursively») — в env висит NODE_TEST_CONTEXT; запускать `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test …`
|
||||
- Gitea 1.22 `GET /compare/<base>...<head>` принимает только имена веток — SHA даёт 404 (PEP-101); mock-gitea ведёт себя так же. Сравнение — подсказка, не гейт: при ошибке мержить обычным путём.
|
||||
- `pnpm run ci` из шелла Claude пишет «all green», но e2e не запускается (NODE_TEST_CONTEXT, «e2e 1/1 (0s)») — запускать `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID pnpm run ci`; `next dev` создаёт apps/web/AGENTS.md — не коммитить.
|
||||
- В свежем worktree нет node_modules — тесты падают «Cannot find package '@peppa/db'»; сначала `pnpm install --frozen-lockfile` (секунды).
|
||||
- Сверка экранов без браузера (chrome-devtools занят соседней сессией): стенд — `PEPPA_HOME`/`PEPPA_DB` во временный каталог, `peppa db migrate`, `DATABASE_URL=<тот же файл> node apps/web/scripts/mock-ui-seed.ts mock-pm`, `peppa web login-link mock-pm`, `next dev -p 3199`; страницы забирать curl с cookie и искать слова из колонки «Нельзя» в тексте без `<script>`; вид «Инженер» — строка settings `ui.mode:<userId>` = `"engineer"`.
|
||||
|
||||
## Решения
|
||||
- Продукт по-настоящему (PEP-112): секреты проекта доходят до выкатки сами (хук `deploy-env` → override в `peppa-deploy.sh`), не через secrets Actions; `ANTHROPIC_*/CLAUDE_*/OPENCODE_*` — только продукту; нужное от владельца — `product.needs:<id>` (MCP `declare_needs`); приёмка — `productReviewTick` (при ролях PEP-84). После мержа правок `template/` — `scripts/push-template.sh` и `peppa ci connect <KEY>` старым проектам.
|
||||
- Репозитории платформы — в организации Gitea `peppa` (PEP-4): `peppa/peppa`, `peppa/template`; старые адреса `peppa-bot/…` живут редиректом — не создавать `peppa-bot/peppa|template` заново. Проект переносит `peppa project transfer <KEY> <owner>`.
|
||||
- Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents.
|
||||
- tmux-сервер по умолчанию: newSession чистит его глобальное окружение от GITEA_*/PEPPA_*/MOCK_*/DATABASE_URL (PEP-69; при PEPPA_TMUX_SOCKET не трогает); агенту нужное — только через new-session -e.
|
||||
- Вход через Google (PEP-90): идентичность — google_sub, по почте учётки не склеиваем; без GOOGLE_CLIENT_ID/SECRET кнопки нет; в тестах эндпоинты подменяет GOOGLE_OAUTH_BASE (mock-google). `pnpm typecheck` в apps/web может падать на устаревших .next/types (auth/callback, auth/start) — не от правок.
|
||||
- Подписки без остановок (PEP-107): ротация claude↔codex, когда нет того же провайдера (PEPPA_ROTATE_CROSS=off выключает, OpenCode не участвует); займы суперадмина и отметки предупреждений — строки settings (`subscription.loan:<pool>:<sub>`, `subscription.warned:<sub>:<pool>`), без миграций; картина пула — `poolOverview` в core/subscription-care.ts.
|
||||
- Группы чатов (PEP-109) связываются через свой бот пользователя: `chats.tg_bot_user_id` (null — общий бот, только суперадмин без своего бота); код связки привязан к боту и чужим ботом не сжигается; новые исходящие в группу маршрутизируются по chat_id через `ownByChat` (`chatGroupBots`) — отдельный outbox не нужен.
|
||||
- Новый пользователь (PEP-113): `announceNewUser` (core/new-users.ts) зовётся внутри функций создания учётки, событие уведомлений `users` только суперадминам; новый способ регистрации — добавить вызов; новое событие в NOTIFY_EVENTS требует строки в PUSH_TITLE бота и скрытых полей в настройках для не-админа.
|
||||
- Слова по режиму (PEP-123): в вебе «стори»/«раннер» не пишем строкой — `w.task("acc")`, `w.runner()` из `await words()` (сервер) или `useWords()` (клиент), только-инженерное — под `w.engineer`; тексты без читателя (EVENT_TEXT чатов, вопросы PM из runner, Telegram, push, подписи core) — всегда «задача», «агент», «Peppa FACTORY», «вы»; промпты агентам, MCP и CLI не трогаем.
|
||||
- Комментарий к стори в бэклоге (PEP-115) разбирает аналитик в тике вачдога (`storyRefineTick`), а не server action; курсор `refine.task:<taskId>` в settings, старше 60 мин не трогает, работает и при выключенных ролях PEP-84 (`PEPPA_STORY_REFINE=off` выключает). Новая роль модели = ветка в `mock-intake` по тексту промпта.
|
||||
- Имена подписок (PEP-121) видят только суперадмин и автор: любое новое место показа подписки — через `visibleSubscriptionName`/`publicSubscriptionName` (core/subscription-names.ts), в вебе у сессий — `<SubscriptionName>`; сообщения участникам проекта — без имени. Экраны на демо-данных без браузера: `PEPPA_DB=<tmp> peppa db migrate`, `DATABASE_URL=<tmp> node apps/web/scripts/mock-ui-seed.ts`, `next dev -p <порт>`, `peppa web login-link mock-pm` + curl с cookie.
|
||||
|
||||
## Соглашения
|
||||
- Тексты экранов вида «Продакт» — в файлах переводов core (`core/help-texts.ts`, PEP-122: объект ru/kk/en одной формы, страница берёт ru, пока нет языка интерфейса); тест сверяет ru с колонкой «Нельзя» docs/glossary.md — новые экраны делать так же.
|
||||
|
||||
## Команды
|
||||
- Глазами проверить веб из worktree без живых данных: свои PEPPA_HOME/PEPPA_DB/DATABASE_URL (один файл) + PEPPA_SECRET + PEPPA_WEB_URL=http://localhost:3222 → `peppa db migrate`, `node apps/web/scripts/mock-ui-seed.ts mock-pm`, `next dev -p 3222` в apps/web, `peppa web login-link mock-pm`; chrome-devtools MCP бывает занят другой сессией — снимки делает headless Chrome со своим --user-data-dir (сначала открыть ссылку входа, потом --screenshot).
|
||||
- Проверка словаря (PEP-124): `pnpm lint` падает, когда в файле экрана слова из «Нельзя» docs/glossary.md стало больше, чем в docs/glossary-baseline.json; чистишь тексты — `pnpm lint --update` (список только уменьшать, руками не дописывать); текст режима «Инженер» или слово в бытовом значении — комментарий `glossary-ignore: <почему>`. Ветка, начатая до PEP-124, может покраснеть на lint после rebase — править слова, не baseline.
|
||||
@ -1,2 +0,0 @@
|
||||
## Грабли
|
||||
- Время продолжения после лимита — `sessions.resume_at`, а не `retryAt` задержки `limit` (это расписание проверок FORGE 1/5/15/60 мин). Строка владельцу — `limitWaitLine` (core/platform-delay.ts), её зовут `taskDelayLine` и страница задачи.
|
||||
@ -1,34 +0,0 @@
|
||||
# Память проекта
|
||||
|
||||
Пишет агент через MCP `remember` (PEP-30); файл на задачу — `.peppa/memory/<ключ>.md` (PEP-306).
|
||||
|
||||
## Команды
|
||||
- Тесты из шелла Claude: `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test --test-reporter=spec test/<file>.test.ts` (иначе тесты молчат). В свежем worktree сначала `pnpm install --frozen-lockfile`.
|
||||
- CLI против живой системы (сервер): `docker exec peppa-watchdog peppa …` (docs/SERVER.md).
|
||||
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate` (Node < 26 — `node packages/cli/src/index.ts`), `DATABASE_URL=… node apps/web/scripts/mock-ui-seed.ts mock-pm`, в apps/web `node server.ts [--dev] -p <порт>` с тем же env + `PEPPA_WEB_URL=http://localhost:<порт> PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off`; вход — `peppa web login-link mock-pm`; «Инженер» — settings `ui.mode:<userId>` = `"engineer"`.
|
||||
- Словарь: `pnpm lint`; почистил тексты экрана — `pnpm lint --update` (baseline только уменьшать); новое слово в «Нельзя» — сразу `pnpm lint`, оно может стоять в чужих текстах.
|
||||
|
||||
## Грабли
|
||||
- `resumeSession` без `conversationId` пишет `started`, не `resumed`.
|
||||
- `next dev` правит apps/web/AGENTS.md (`git checkout`, не `rm`) и next-env.d.ts — не коммитить; открывать `localhost`, не 127.0.0.1. В песочнице dev перезагружает страницы по кругу — экраны смотри на `next build` + `node server.ts -p`.
|
||||
- Headless Chrome: playwright-core + `chrome-headless-shell` (песочница: `npx playwright-core install chromium-headless-shell`; библиотеки — .deb bookworm из Packages.gz → `dpkg-deb -x` + LD_LIBRARY_PATH, шрифты fonts-dejavu-core + FONTCONFIG_PATH); вход — `peppa web login-link`; обрыв канала — `globalThis.__peppaLive.ws.close()`.
|
||||
- CLI из теста с моком в том же процессе — только async execFile. Тест не импортирует apps/web статически — `import(new URL(…).href)`.
|
||||
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
||||
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
||||
- mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`.
|
||||
- git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент.
|
||||
- Новая фраза Claude о лимите — в `parseResetTime` и limits.test.ts. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts`; правишь live.ts — перезапусти server.ts, не `pkill -f next-server`.
|
||||
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes.
|
||||
- Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать.
|
||||
- Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
- Песочница раннера: нет tmux и Node 26 — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp; tmux — .deb (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, sandbox-hosts.test.ts (нет ssh).
|
||||
- Пропал `.git/worktrees/s<id>`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`.
|
||||
- Зависимость с build-скриптом (ssh2, cpu-features) роняет `pnpm install --frozen-lockfile` (ERR_PNPM_IGNORED_BUILDS): реши в `allowBuilds` pnpm-workspace.yaml.
|
||||
|
||||
## Соглашения
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
||||
|
||||
## Решения
|
||||
- Речь — свой faster-whisper (`<Dictate>`). Google: по почте учётки не склеиваем.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-129
|
||||
|
||||
## Соглашения
|
||||
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` проверяет литералы в `m()/tr()/t()` packages/core|runner|mcp; подсказку агенту в `m()` не оборачивать; запрещённое слово — переписать (ключ и в `i18n/en|kk`, тестах) или `glossary-ignore: <почему>` строкой выше; человеку мимо переводов — `glossary-user: <почему>`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-135
|
||||
|
||||
## Соглашения
|
||||
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-154
|
||||
|
||||
## Соглашения
|
||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `userText` (core/user-text.ts); исключение владельцу не слать — `platformFailure` (строка только для PeppaError).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-158
|
||||
|
||||
## Соглашения
|
||||
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-183
|
||||
|
||||
## Соглашения
|
||||
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-195
|
||||
|
||||
## Решения
|
||||
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-198
|
||||
|
||||
## Соглашения
|
||||
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-208
|
||||
|
||||
## Решения
|
||||
- Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-209
|
||||
|
||||
## Решения
|
||||
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-210
|
||||
|
||||
## Решения
|
||||
- Внешний сервис за Cloudflare-челленджем (claude.ai/code → 403 роботам) мониторим по его Statuspage: `https://status.claude.com/api/v2/components/<id>.json` + `contains: "status":"operational"` (у `page` поля status нет). Новый встроенный мониторинг — своя отметка `observe_meta` (`seeded:<имя>`), `seeded` на живой уже стоит.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-212
|
||||
|
||||
## Грабли
|
||||
- QuickJS (PEP-212): строки из хост-функции читай до await; все хэндлы и deferred dispose-ить.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-213
|
||||
|
||||
## Решения
|
||||
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-217
|
||||
|
||||
## Решения
|
||||
- Вес JS: `bundle-check.mjs --update`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-218
|
||||
|
||||
## Соглашения
|
||||
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-221
|
||||
|
||||
## Решения
|
||||
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-222
|
||||
|
||||
## Решения
|
||||
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-223
|
||||
|
||||
## Грабли
|
||||
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-224
|
||||
|
||||
## Соглашения
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
||||
@ -1,7 +0,0 @@
|
||||
# Память: PEP-230
|
||||
|
||||
## Грабли
|
||||
- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287).
|
||||
|
||||
## Решения
|
||||
- Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac.
|
||||
@ -1,5 +0,0 @@
|
||||
# Память: PEP-231
|
||||
|
||||
## Грабли
|
||||
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами.
|
||||
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-233
|
||||
|
||||
## Соглашения
|
||||
- act_runner (PEP-233/248): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь; `not_taken` — pending, а другие проекты отчитываются.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-234
|
||||
|
||||
## Грабли
|
||||
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-235
|
||||
|
||||
## Соглашения
|
||||
- Режим `ask` в Access Hub (PEP-235): новый путь вызова подключения — только через шлюз (`callConnection`/`useConnection`), он сам ставит подтверждение (`approvalGate`); выполнить разрешённое — `runApproval` (захват approved→running), не звать шлюз с `approved` напрямую. В тестах вызов не ждёт владельца (`PEPPA_APPROVAL_WAIT_SEC=0` в helpers.ts); проверка ожидания — `approvalWaitMs`.
|
||||
@ -1,7 +0,0 @@
|
||||
# Память: PEP-236
|
||||
|
||||
## Соглашения
|
||||
- MCP-подключение (protocol mcp, PEP-236): вызов — только `useConnection` (operation = точное имя инструмента), режим инструмента — `mcpToolMode` (свой режим `connection_grants.tools` важнее класса readOnlyHint; подозрительный без явного режима — off); инструменты у агента — `agentMcpTools` → `createAgentServer({connectionTools})`, в тестах транспорт сервера — `core.setMcpFetch(new MockMcpServer(...).fetch)` (testkit/src/mock-mcp-server.ts).
|
||||
|
||||
## Грабли
|
||||
- Песочница агента без tmux и Node 26: тесты, запускающие агента (access-requests, agent-messages, codex-*), падают «spawn tmux ENOENT» и на main — это среда, не код. `code-mode` поддерживает вложенные пространства (`api: {ns: "mcp.slug"}`, `apiOnly`).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-241
|
||||
|
||||
## Грабли
|
||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-242
|
||||
|
||||
## Решения
|
||||
- `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect <KEY> [--secrets-only]`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-245
|
||||
|
||||
## Грабли
|
||||
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-246
|
||||
|
||||
## Грабли
|
||||
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-249
|
||||
|
||||
## Соглашения
|
||||
- Access Hub (PEP-249): новый HTTP-сервис — карточка в `core/connection-catalog.ts` (тест сверяет каждую); меняет данные через GET (Slack) — чтение по методам. Новый не-HTTP вид (PEP-251) — операция в `PROTOCOL_OPERATIONS`, драйвер `GatewayDrivers` (берёт проверенный `address`, DNS не разрешает) и мок в testkit/mock-access.ts. Ответ сервиса агенту (PEP-258) — только через `connectionKeyForms`+`maskConnectionKey`; новый способ ключа — в тест-ловушку access-hub.test.ts.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-250
|
||||
|
||||
## Соглашения
|
||||
- Access Hub (PEP-250): сервис агенту — `request_access`; форму отказа `callConnection` не менять, автозапрос — `refusedCallService`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-252
|
||||
|
||||
## Грабли
|
||||
- Шлюз Access Hub (PEP-252): `cleanPath` не пускает голое «:» в пути — Google-диапазоны и методы (`A1:B2`, `:batchUpdate`) агент шлёт как `%3A`. OAuth-тесты: `MockOAuthService` + `fetch`, переписывающий адрес сервиса на мок (`toMock`).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-253
|
||||
|
||||
## Решения
|
||||
- Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-254
|
||||
|
||||
## Решения
|
||||
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-255
|
||||
|
||||
## Грабли
|
||||
- Очередь проверок (PEP-255): `checks.queue` — `projects` (своя зависшая голова) и `lanes` (`ciLane`); `requestRebase` → false = просьба не ушла.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-256
|
||||
|
||||
## Грабли
|
||||
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-260
|
||||
|
||||
## Решения
|
||||
- Access Hub (PEP-260): агенту — только текст (`isTextResponse`) + `TEXT_TYPES`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-261
|
||||
|
||||
## Грабли
|
||||
- Тесты с агентом-моком (access-requests, bot) в песочнице молча висят по 25 с на Node 22 — нужен Node 26 из tarball и tmux из .deb в PATH/LD_LIBRARY_PATH (PEP-261).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-265
|
||||
|
||||
## Грабли
|
||||
- Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-266
|
||||
|
||||
## Решения
|
||||
- Проверка запуска (PEP-266) идёт в платформенном проекте, не в отдельной строке проекта: тики обходят все проекты и шлют ложные сбои.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-267
|
||||
|
||||
## Грабли
|
||||
- Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <cli> <версия>` (json + оба Dockerfile), откат `--rollback`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-268
|
||||
|
||||
## Соглашения
|
||||
- Сбой платформы — `planPlatformRetry` (PEP-268), `restarts` не трогать; мок `hangAtStart`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-269
|
||||
|
||||
## Соглашения
|
||||
- Конфликт PR с main (PEP-269) — только `conflictStep` (runner/conflict-step.ts), не `requestRebase` напрямую; сироты — `orphanConflictTick` (PEP-301).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-272
|
||||
|
||||
## Решения
|
||||
- `/api/health` анониму — только `{ok}` (PEP-272); сводку читать с `healthHeaders()` / `scripts/lib/health-token.sh`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-273
|
||||
|
||||
## Соглашения
|
||||
- Ссылки веба — только `Link` из `@/components/Link` (предзагрузка выкл., PEP-273; тест no-prefetch); медленная страница из-за Gitea — кэш в globalThis, как `giteaServerOverview`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-274
|
||||
|
||||
## Решения
|
||||
- Заголовок вкладки (PEP-274) — `pageTitle`/`projectTitle`/`taskTitle` (apps/web/lib/title.ts); page.tsx без `generateMetadata` роняет page-titles.test.ts.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-278
|
||||
|
||||
## Соглашения
|
||||
- «Готово» после выкатки (PEP-278): статус `done` не трогаем — поверх него отметка `rollout.wait:<taskId>` (core/rollout.ts), экран — псевдостатус `rollout` в `TASK_STATUS`; снимает `rolloutTick`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-279
|
||||
|
||||
## Решения
|
||||
- Старые вопросы (PEP-279) закрываются только `default_option`; без него — без выбора: варианты фабрики (бюджет, подписка) за человека не выбираем.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-281
|
||||
|
||||
## Грабли
|
||||
- Git — только git.vibe42.kz; старый адрес в репо ловит old-git-cleanup.test.ts (PEP-281).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-282
|
||||
|
||||
## Грабли
|
||||
- Таймаут запроса в процессе с моком-сервером: синхронная пауза дольше таймаута обрывает готовый ответ (таймеры libuv раньше сокетов) — `responsiveTimeout` (core, PEP-282), не `AbortSignal.timeout`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-283
|
||||
|
||||
## Решения
|
||||
- Стек новых проектов — docs/standards/default-stack.md (PEP-283).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-284
|
||||
|
||||
## Соглашения
|
||||
- Стандарт стека в шаблоне (PEP-284): template/docs/standards/default-stack.md — побайтная копия docs/standards/default-stack.md (тест template-default-stack); правишь стандарт — копируй в template/.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-285
|
||||
|
||||
## Решения
|
||||
- Аудит стека (PEP-285): docs/standards/forge-stack-audit.md — основа FORGE (TS/Node 26, Next.js, SQLite, Drizzle, целые id) сохраняется как обоснованное отклонение; условия пересмотра PostgreSQL — там же. Новый слой в default-stack.md = строка и раздел в аудите (тест stack-audit-doc).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-291
|
||||
|
||||
## Грабли
|
||||
- Песочница раннера: Node 22.23 тянет одиночные тесты (PEP-291).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-292
|
||||
|
||||
## Грабли
|
||||
- В образе платформы нет `.git` (PEP-292): `git` в коде службы не звать; коммит — `PEPPA_COMMIT`, история main — Gitea API.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-294
|
||||
|
||||
## Решения
|
||||
- Суперадмины (PEP-294): `platform.admins` — id учёток (строка = логин без учётки, привязывается при чтении); проверка — `superadminIds`/`platformAdminUsers`, не сравнение логинов.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-295
|
||||
|
||||
## Соглашения
|
||||
- Задача не от человека — `createTask` с origin сама в «Предложено» (PEP-295), путь — проверить `proposalRoom` до создания; новый вызов `createTask` — в список `proposals-only.test.ts`; автомерж — autonomy.acceptOwn.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-298
|
||||
|
||||
## Соглашения
|
||||
- Конфликт PR с main: первая просьба — после второго наблюдения через 2 мин (PEP-298, в тестах `PEPPA_CONFLICT_SETTLE_MIN=0`).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-299
|
||||
|
||||
## Грабли
|
||||
- `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-302
|
||||
|
||||
## Грабли
|
||||
- mock-intake `dedup` считает похожие названия («Идея 1»/«Идея 2») повтором — в тестах приёмки бери разные слова.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-303
|
||||
|
||||
## Грабли
|
||||
- Сторож экрана (PEP-303): строки — через `screen-lines.ts` (`isQuotedLine`/`ownLines`), фразу CLI якорить к началу строки, нажимать только на неизменном экране (`still`). Мок `say` печатает «⏺ » перед текстом.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-304
|
||||
|
||||
## Соглашения
|
||||
- Время людям (PEP-304) — только `platformTime`/`platformDayTime`/`platformZone` из `@peppa/shared/time`; `toLocale*String` для дат без `timeZone` не писать. Лимит в `claudePrint` — `limited`/`limitedUntil`, не «нет подписки».
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-306
|
||||
|
||||
## Грабли
|
||||
- Память (PEP-306): пункт — только в `.peppa/memory/<ключ задачи>.md` своей задачи; MCP `remember` до выкатки PEP-306 пишет в старый `.peppa/memory.md` — тогда правь файл задачи руками (тест project-memory-size запрещает старый файл).
|
||||
@ -1,7 +0,0 @@
|
||||
# Память: PEP-314
|
||||
|
||||
## Соглашения
|
||||
- Go/PostgreSQL проектов (PEP-314): в проверках — только `source .gitea/peppa-tools.sh go postgres` шаблона (образ задания общий с платформой, не трогать); база стенда — `deploy.database` + `deploy/compose.postgres.yml`, пароль в томе базы, без `deploy.database` `peppa-deploy.sh` обязан вести себя как раньше (тест «Проект без базы — как раньше»).
|
||||
|
||||
## Грабли
|
||||
- Агент в контейнере идёт от --user <uid> без записи в /etc/passwd: initdb и всё, что ищет пользователя, падает — нужен libnss-wrapper (LD_PRELOAD + NSS_WRAPPER_PASSWD). Файл шаблона *.go, который не код Go, ломает go vet/build у проекта — заготовка называется Dockerfile.golang (тест в stack-tools).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-315
|
||||
|
||||
## Грабли
|
||||
- Строка `connection_grants` остаётся после конца срока и после снятия «без дела»: читая «прошлую выдачу», проверяй `grantState(row, now) === "active"`, иначе вернёшь права, которых уже нет (PEP-315: «Дать: чтение» возвращало запись).
|
||||
@ -1,5 +0,0 @@
|
||||
# Память: PEP-316
|
||||
|
||||
## Грабли
|
||||
- Гонку двух процессов за базу тест в одном процессе не ловит: `node:sqlite` синхронный, два вызова идут по очереди. Нужен настоящий второй процесс — `packages/testkit/src/mock-db-writer.ts` держит блокировку записи (PEP-313 «починил» гонку тестом в одном процессе, на проде она осталась).
|
||||
- Транзакция, начатая как читающая (`BEGIN`), получает «database is locked» на первой записи сразу, без ожидания `busy_timeout`. Поэтому `db.transaction` всегда `BEGIN IMMEDIATE` (PEP-316).
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-317
|
||||
|
||||
## Соглашения
|
||||
- Список «Gitea» (PEP-317): отдаётся сразу при любом возрасте, хранится в `settings` `gitea.overview`, прогрев — `warmGiteaOverview` в instrumentation.ts; ждёт Gitea только `fresh`. В тестах — `giteaOverviewSettled()`, медленная Gitea — `MockGitea.searchDelayMs`.
|
||||
@ -1,7 +0,0 @@
|
||||
# Память: PEP-318
|
||||
|
||||
## Соглашения
|
||||
- «Принять всё» (PEP-318) — только очередь: `startAcceptAll` + `processAcceptQueue` (runner/accept-queue.ts; `accept.queue:<taskId>`, ход `accept.run:<projectId>`, аренда `accept.worker:<projectId>` 3 мин), веб — через `after()`, вачдог — `acceptQueueTick`. Синхронный `acceptAll` в вебе не звать. Медленный Gitea в тесте — `MockGitea.delayMs`.
|
||||
|
||||
## Грабли
|
||||
- В песочнице без tmux тесты приёмки падают «spawn tmux ENOENT», а на Node 22 висят по 25 с: нужны оба — tmux из .deb bookworm и Node 26 (`nodejs.org/dist/index.json` → tarball в /tmp).
|
||||
@ -1,7 +0,0 @@
|
||||
# Память: PEP-319
|
||||
|
||||
## Соглашения
|
||||
- Состав задач в сообщении о версии (`storiesIn`, runner/platform-build.ts) — только ключ в начале заголовка коммита («PEP-318: …», «PEP-284, PEP-285: …») или названия слитого PR. Упоминание другой задачи в тексте коммита версию не «выпускает».
|
||||
|
||||
## Грабли
|
||||
- 27.11.2026 канал дважды назвал задачи, вышедшие раньше: PEP-281 и PEP-282 (утро), PEP-127 (вечер) — их ключи стояли в тексте коммитов других задач. Сообщение из канала не отозвать.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-320
|
||||
|
||||
## Грабли
|
||||
- Сценарии infra/act-runner — busybox ash (в песочнице только dash): проверять тест act-runner-supervise с PATH на каталог апплетов статического busybox (busybox.net/downloads/binaries/1.35.0-x86_64-linux-musl). Новый supervise.sh действует только после `docker restart peppa-act-runner`.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-321
|
||||
|
||||
## Соглашения
|
||||
- Упавшее задание проверок (PEP-321): `checksQueueTick` до порога очереди через 2 мин (`EARLY_JOB_MS`) переоткрывает PR (`reopenFailedJob`, общий счётчик `reopened` с поздним путём, ≤2 на коммит, пауза 10 мин) — без `stuck`, задержки, сообщения суперадмину и агенту; `pending` до порога не трогается.
|
||||
@ -1,9 +0,0 @@
|
||||
# Память: PEP-322
|
||||
|
||||
## Соглашения
|
||||
- Папку, которую писал агент, удаляй через `removeSandbox` (runner/disk-cleanup.ts): обычный `rmSync` не берёт дерево с каталогами без права записи. Права возвращаются только настоящим каталогам внутри папки, по ссылкам не ходим.
|
||||
|
||||
## Грабли
|
||||
- Go делает каталоги кэша модулей (`~/go/pkg/mod`) только для чтения. 27.11.2026, в день выхода PEP-314, папка агента первой же задачи на Go (722 МБ, 2776 таких каталогов) не убралась: уборка падала каждые 10 минут.
|
||||
- Один и тот же отказ `rmSync` читается по-разному: на Linux — `EACCES`, на macOS — `ENOTEMPTY`. Ветвиться по коду ошибки нельзя.
|
||||
- Проверки в CI идут от root, ему права каталогов не мешают: тест на это падает без правки только у обычного пользователя (локальный прогон).
|
||||
@ -1,11 +0,0 @@
|
||||
# Память: PEP-324
|
||||
|
||||
## Грабли
|
||||
- Id серверных действий Next (и Turbopack) — хэш с солью NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: без постоянного ключа каждая сборка образа ломает кнопки открытых вкладок (Bugsink #23). Ключ — в .env сервера, в сборку — секретом BuildKit next_actions_key; проверка на деле: две `next build` с одним ключом → одинаковые ключи server-reference-manifest.json.
|
||||
- Next печатает ошибку, пойманную своей границей (`app/error.tsx`), тем `console.error`, который взял при старте, — обёртка `ErrorReporter` её не слышит. Граница сама поднимает такую ошибку через `reportError` (`reportCaughtError`), иначе ошибки страниц не доходят до «Ошибок из прода».
|
||||
- На одной странице много полей с одним `name` (карточки вопросов — «answer», «Что поправить» — «text»): возвращать сохранённый текст по имени нельзя — он попадёт в чужую карточку. Адрес поля — его `id`, имя годится, только когда оно одно на странице.
|
||||
- Секреты вводятся и в `textarea` (секрет проекта, ключ сервера): правило «не пароль» их не отсекает — отсекать по имени поля.
|
||||
|
||||
## Соглашения
|
||||
- apps/web/lib/* для node-тестов — без импорта `next/navigation` (в ESM без exports-карты node его не находит): проверку Next передавать параметром из клиентского компонента, как `isStaleAction(err, unstable_isUnrecognizedActionError)`.
|
||||
- Поведение страницы в браузере проверять на рабочей сборке настоящим браузером (подмена заголовка `next-action` даёт «такого действия нет»): тесты на моках DOM не увидели ни чужую карточку, ни пропавшие ошибки.
|
||||
@ -1,15 +0,0 @@
|
||||
# Память: PEP-326
|
||||
|
||||
## Соглашения
|
||||
- Сайт запускается только через свой сервер веба: `node server.ts` (`apps/web/server.ts`) — и в `infra/docker-compose.yml`, и в launchd, и в `pnpm start`. Он принимает постоянное соединение страниц `/api/ws`.
|
||||
- После смены способа запуска сайта проверяй соединение, а не только страницы: `. scripts/lib/ws-check.sh; ws_answers http://127.0.0.1:3100` (0 — соединение принято). Выкатка делает это сама и откатывает версию без ответа.
|
||||
|
||||
## Грабли
|
||||
- Голый `next start` на запрос WebSocket не отвечает и не отказывает. Браузер ждёт, пока запрос не оборвёт Cloudflare (524, около 125 секунд). Страницы и `/api/health` при этом в порядке, поэтому проверки выкатки ничего не замечали.
|
||||
- С 21 по 28.11.2026 свежая вкладка около шести минут показывала «подключение…» и не обновлялась сама: три попытки по 125 секунд, потом запасной поток. Заметили по экрану «Приёмка»: «Принимается…» висело, хотя сервер принял задачу за секунду.
|
||||
- Две задачи одного дня могут не встретиться: PEP-222 завёл compose с `next start`, PEP-225 через полтора часа поменял запуск сайта в launchd и `package.json`. В compose его никто не внёс.
|
||||
- Тест проверки на подставном сервере прошёл бы и с неверным ключом запроса: настоящий сервер соединений отклоняет ключ не из 16 байт (так и было в первой версии `ws-check.sh`, выкатка откатывалась бы каждый раз). Проверку живого сервера тестируй настоящим `createLiveWs`.
|
||||
|
||||
## Решения
|
||||
- Клиент не ждёт зависший запрос соединения дольше 4 секунд (`WS_OPEN_TIMEOUT_MS` в `apps/web/lib/live.ts`) и сразу идёт на запасной поток `/api/live`; WebSocket пробуется раз в минуту. Отклонённый запрос — по-прежнему три попытки.
|
||||
- Проверка по внешнему адресу версию не откатывает: путь до сайта (Cloudflare, край) от версии не зависит, страницы при нём работают через запасной поток.
|
||||
@ -1,14 +0,0 @@
|
||||
# Память: PEP-329
|
||||
|
||||
## Соглашения
|
||||
- Клиент пользователя для Git-сервера берётся через `userGitea` (core/users.ts): он отдаёт клиент, только когда сервер отвечает ему на `me()`. Нет рабочего доступа — действуем клиентом бота в пространстве `peppa-bot` (`projectNamespace`), человеку об этом ошибку не показываем.
|
||||
- Страница не зовёт `giteaForUser` сама: место для кода нового проекта — `newProjectSpaces` (runner/provision.ts).
|
||||
|
||||
## Грабли
|
||||
- С 21 по 29.11.2026 учётка, когда-то входившая через Gitea (`gitea_id > 0`), не могла создать проект: «Доступ к коду проекта истёк — войдите заново». Вход через Gitea убран в PEP-71, Git-сервер 21.11 заменён, учётки на новом сервере нет — продлить доступ нечем. На живой таких учёток три, рабочая одна: владелец платформы.
|
||||
- Совет «войдите заново» в тексте ошибки пережил сам способ входа. Убираешь способ входа — пройди по текстам, которые к нему отсылают.
|
||||
- В проверке страницы браузером текст под свёрнутым «Дополнительно» не попадает в `innerText`: читай `textContent`.
|
||||
|
||||
## Решения
|
||||
- Сохранённые старые доступы из базы не удаляем: ими просто не пользуются.
|
||||
- Выбранное в форме пространство при нерабочем доступе не берётся: создавать в нём нечем.
|
||||
@ -1,15 +0,0 @@
|
||||
# Память: PEP-330
|
||||
|
||||
## Соглашения
|
||||
- Когда человек действует клиентом бота, ответ Git-сервера «есть права администратора» говорит о боте. Права человека проверяй отдельно: в общем пространстве кода (`sharedSpace`) не суперадмин берёт только репозиторий без кода.
|
||||
- Шаблон проектов (`GITEA_TEMPLATE_REPO`) проектом не становится: `provisionProject` отклоняет это у всех, и в CLI.
|
||||
- Сбой подготовки проекта пользователя идёт через `platformFailure`: причина — в учёт ошибок и суперадмину, человеку — фраза без вывода команды.
|
||||
|
||||
## Грабли
|
||||
- До 29.11.2026 любой пользователь мог подключить как свой проект шаблон проектов или репозиторий удалённого проекта («У меня уже есть код», MCP `create_project` с `existing`): в основную ветку уходил коммит, а из шаблона берутся правила всех агентов. В тесте подключённый шаблон сразу испортил следующие проекты: в него попал `openspec/changes`.
|
||||
- Сбой после создания репозитория оставлял пустой репозиторий, и название было занято навсегда: 22.11.2026 в образе не было openspec, один пользователь сделал четыре попытки за шесть минут, никто об этом не узнал.
|
||||
- Пустой репозиторий берётся заново только в общем пространстве: в своём пространстве на Git-сервере и в CLI человек может сам выбрать «существующий», там по-прежнему отказ.
|
||||
|
||||
## Решения
|
||||
- Пустые репозитории от неудачных попыток не удаляем: следующая попытка с тем же названием берёт их заново с выбранной видимостью.
|
||||
- Репозиторий с кодом, не занятый проектом, человеку отвечает «Адрес кода занят», а не «подключите как существующий».
|
||||
@ -1,11 +0,0 @@
|
||||
# Память: PEP-333
|
||||
|
||||
## Соглашения
|
||||
- «Агенты не запустятся» у проекта решает `projectAgentWarning`. Условие «без набора подписок» повторяет `startRunner`: агент в контейнере или на отдельной машине без подписки не запускается, право владельца на вход машины тут ничего не даёт.
|
||||
|
||||
## Грабли
|
||||
- Новый проект получает набор подписок сам, только если у владельца есть свой набор (`ownPool`). Набор, назначенный общим набором платформы, своим не считается: новый проект суперадмина создаётся без набора.
|
||||
- До 30.11.2026 такой проект молчал: ни выбора подписки на странице, ни плашки, а диспетчер получал отказ запуска и слал суперадмину сообщение о сбое платформы.
|
||||
|
||||
## Решения
|
||||
- Набор новому проекту суперадмина сам не назначается: выбор остаётся за человеком, страница проекта показывает кнопку «Работать на подписке FORGE».
|
||||
@ -1,12 +0,0 @@
|
||||
# Память: PEP-334
|
||||
|
||||
## Соглашения
|
||||
- Набор подписок нового проекта — `defaultPoolFor(db, ownerId)`: свой набор владельца (`ownPool`), иначе общий набор платформы, если владелец его создал. `ownPool` для этого не годится: общий набор он намеренно не считает своим, чтобы личная подписка не попала в общий набор.
|
||||
- Отказ, который читает владелец, говорит, что сделать и где, со ссылкой. «Подключите подписку» и «выберите подписку для проекта» — разные действия.
|
||||
|
||||
## Грабли
|
||||
- 01.12.2026 владелец создал проект и перевёл задачу «в работу» через MCP. Страницу проекта с выбором подписки (PEP-333) он не видел, а текст отказа «подключите её в настройках проекта» понял как «подключите подписку»: подключил заново на общей странице «Подписки». Проект остался без набора, задача — «в работе» без агента.
|
||||
- `moveTask` сначала ставит задаче «в работе», потом запускает агента. При отказе запуска задача остаётся «в работе» без агента; через 30 минут её поднимает `stuckTaskTick`.
|
||||
|
||||
## Решения
|
||||
- Другим суперадминам общий набор сам не назначается: одним нажатием они и так могут его выбрать, но выбор между своей подпиской и общей остаётся за человеком.
|
||||
@ -1,4 +0,0 @@
|
||||
# Память: PEP-98
|
||||
|
||||
## Соглашения
|
||||
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en|kk/<раздел>.ts` (иначе падают i18n-check/i18n-kk). «Peppa FACTORY» не склоняется (kk: Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем.
|
||||
@ -8,7 +8,6 @@
|
||||
"lint": "pnpm lint",
|
||||
"typecheck": "pnpm -r typecheck",
|
||||
"build": "pnpm --filter @peppa/web build",
|
||||
"bundle": "node scripts/bundle-check.mjs",
|
||||
"test": "pnpm --filter @peppa/testkit test"
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" },
|
||||
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" },
|
||||
"bin": { "peppa-bot": "./bin/peppa-bot" },
|
||||
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
||||
"dependencies": {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,11 +1,10 @@
|
||||
// Stories from a message to the bot (PEP-45): a draft waits for the project/epic buttons, so
|
||||
// a stray message never creates a story by itself. Drafts live in `settings` for a day.
|
||||
import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core";
|
||||
|
||||
export { splitStory, TITLE_MAX } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
|
||||
export const DRAFT_TTL_MS = 24 * 3600_000;
|
||||
export const TITLE_MAX = 120;
|
||||
|
||||
export interface Draft {
|
||||
id: number;
|
||||
@ -14,12 +13,6 @@ export interface Draft {
|
||||
text: string;
|
||||
projectId: number | null;
|
||||
voice: boolean;
|
||||
/** PEP-153: not a story yet — a message the bot answered or asked about («Завести как задачу»). */
|
||||
offer?: boolean;
|
||||
/** PEP-153: the bot asked «Ответить или завести задачу?» and the person has not picked yet. */
|
||||
asked?: boolean;
|
||||
/** PEP-153: the answer at hand for «Ответить» (null — answer from the platform's data). */
|
||||
answer?: string | null;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
@ -53,16 +46,29 @@ export async function dropDraft(db: Db, id: number): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…" and
|
||||
* "в проекте Pay экспорт…" (how whisper writes it down, PEP-108).
|
||||
* "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…".
|
||||
* The key counts only if it is one of the user's projects; otherwise the whole text is the story.
|
||||
*/
|
||||
export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } {
|
||||
const t = text.trim();
|
||||
const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null;
|
||||
const withSep = /^(?:(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
|
||||
const withSep = /^(?:(?:в|во|для|in|to)\s+)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
|
||||
if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() };
|
||||
const spoken = /^(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
|
||||
const spoken = /^(?:в|во|для|in|to)\s+([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
|
||||
if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() };
|
||||
return { project: null, body: t };
|
||||
}
|
||||
|
||||
/** Title (first line, at most TITLE_MAX chars, cut at a word) and the rest as description. */
|
||||
export function splitStory(body: string): { title: string; rest: string } {
|
||||
const [first = "", ...lines] = body.trim().split("\n");
|
||||
let title = first.trim();
|
||||
let rest = lines.join("\n").trim();
|
||||
if (title.length > TITLE_MAX) {
|
||||
const cut = title.lastIndexOf(" ", TITLE_MAX - 1);
|
||||
const at = cut > TITLE_MAX / 2 ? cut : TITLE_MAX - 1;
|
||||
rest = `${title}${rest ? `\n\n${rest}` : ""}`;
|
||||
title = `${title.slice(0, at).trim()}…`;
|
||||
}
|
||||
return { title, rest };
|
||||
}
|
||||
|
||||
@ -1,44 +0,0 @@
|
||||
// PEP-143: «Сообщить о проблеме» in the bot. `/problem` opens a short window in which the next
|
||||
// message (text, a photo with a caption, a voice note) becomes a report; photos sent right after
|
||||
// it join the same report. A superadmin's «Не исправлять» waits for the reason the same way.
|
||||
import { deleteSetting, getSetting, setSetting } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
|
||||
/** How long `/problem` waits for the message. */
|
||||
export const FEEDBACK_MODE_TTL_MS = 15 * 60_000;
|
||||
/** How long after the report more photos still join it (an album arrives message by message). */
|
||||
export const FEEDBACK_MORE_TTL_MS = 2 * 60_000;
|
||||
/** How long «Не исправлять» waits for the reason. */
|
||||
export const REJECT_TTL_MS = 10 * 60_000;
|
||||
|
||||
export interface FeedbackMode {
|
||||
/** Set once the report exists: further photos are attached to it. */
|
||||
feedbackId?: number;
|
||||
until: number;
|
||||
}
|
||||
|
||||
const modeKey = (userId: number) => `bot.feedback:${userId}`;
|
||||
const rejectKey = (userId: number) => `bot.feedback.reject:${userId}`;
|
||||
|
||||
export async function feedbackMode(db: Db, userId: number, now = Date.now()): Promise<FeedbackMode | null> {
|
||||
const m = await getSetting<FeedbackMode>(db, modeKey(userId));
|
||||
if (!m) return null;
|
||||
if (m.until > now) return m;
|
||||
await deleteSetting(db, modeKey(userId));
|
||||
return null;
|
||||
}
|
||||
|
||||
export const openFeedbackMode = (db: Db, userId: number, now = Date.now()) => setSetting(db, modeKey(userId), { until: now + FEEDBACK_MODE_TTL_MS } satisfies FeedbackMode);
|
||||
export const keepFeedbackMode = (db: Db, userId: number, feedbackId: number, now = Date.now()) => setSetting(db, modeKey(userId), { feedbackId, until: now + FEEDBACK_MORE_TTL_MS } satisfies FeedbackMode);
|
||||
export const closeFeedbackMode = (db: Db, userId: number) => deleteSetting(db, modeKey(userId));
|
||||
|
||||
/** The report a superadmin is about to decline: the next message is the reason. */
|
||||
export async function pendingReject(db: Db, userId: number, now = Date.now()): Promise<number | null> {
|
||||
const r = await getSetting<{ feedbackId: number; until: number }>(db, rejectKey(userId));
|
||||
if (!r) return null;
|
||||
if (r.until > now) return r.feedbackId;
|
||||
await deleteSetting(db, rejectKey(userId));
|
||||
return null;
|
||||
}
|
||||
export const askRejectReason = (db: Db, userId: number, feedbackId: number, now = Date.now()) => setSetting(db, rejectKey(userId), { feedbackId, until: now + REJECT_TTL_MS });
|
||||
export const clearReject = (db: Db, userId: number) => deleteSetting(db, rejectKey(userId));
|
||||
@ -2,7 +2,7 @@
|
||||
import { createDb } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { setRunnerClient } from "@peppa/runner";
|
||||
import { installCrashReporting, installServiceLog } from "@peppa/core";
|
||||
import { installCrashReporting } from "@peppa/core";
|
||||
import { createBot } from "./bot.ts";
|
||||
import { TelegramApi } from "./telegram.ts";
|
||||
|
||||
@ -16,8 +16,6 @@ const db = createDb(env.PEPPA_DB);
|
||||
setRunnerClient(true, db);
|
||||
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
||||
installCrashReporting(db, "bot");
|
||||
// PEP-291: the log also goes to $PEPPA_HOME/logs/bot.log — it survives a redeploy.
|
||||
installServiceLog("bot");
|
||||
const bot = createBot({
|
||||
db,
|
||||
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
||||
|
||||
@ -1,104 +1,79 @@
|
||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||
import { agentSignature, questionIsFreeText, questionText, questionType, splitForDisplay, stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core";
|
||||
import type { Question, SessionView } from "@peppa/core";
|
||||
import type { InlineButton } from "./telegram.ts";
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const italic = (s: string) => `<i>${s}</i>`;
|
||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
|
||||
const KIND: Record<Question["kind"], string> = {
|
||||
approval: tr("📝 Нужно одобрение плана"),
|
||||
question: tr("❓ Вопрос"),
|
||||
permission: tr("🔐 Нужно разрешение"),
|
||||
attention: tr("👀 Сообщение"),
|
||||
approval: "📝 Нужно одобрение плана",
|
||||
question: "❓ Вопрос",
|
||||
permission: "🔐 Нужно разрешение",
|
||||
attention: "👀 Сообщение от фабрики",
|
||||
};
|
||||
|
||||
/** PEP-198: the name the owner sees on every message of the factory. */
|
||||
export const VOICE = tr("🔎 Аналитик");
|
||||
|
||||
export interface Rendered {
|
||||
text: string;
|
||||
buttons: InlineButton[][];
|
||||
}
|
||||
|
||||
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" (resume|stop|ask) or "i:<incidentId>:<decision>" (core/incidents.ts)
|
||||
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" or "i:<incidentId>:<decision>" (core/incidents.ts)
|
||||
export function renderQuestion(
|
||||
q: Question,
|
||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean; /** PEP-152: the message has technical details (kept on the site). */ details?: boolean; /** PEP-156: nickname of the agent whose own words these are. */ agent?: string | null },
|
||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
|
||||
): Rendered {
|
||||
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${asIs(esc(clip(ctx.taskTitle, 80)))}</i>` : null]
|
||||
const head = [`<b>${esc(ctx.taskKey ?? (q.sessionId ? `Агент №${q.sessionId}` : "Обновления продукта"))}</b>`, ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
// PEP-154: no service text in the message (a permission request keeps its command, whole).
|
||||
// PEP-152: the main text only — at most five lines; the rest and the details open on the site.
|
||||
// PEP-139: what the agent wrote itself is free text (marked) — only the factory's phrases are translated.
|
||||
const free = questionIsFreeText(q);
|
||||
const shown = q.kind === "permission" ? { main: q.text, more: null } : splitForDisplay(questionText({ ...q, text: userText(q.text) || q.text }));
|
||||
const text = esc(clip(shown.main, 3300));
|
||||
const said = free ? asIs(text) : text;
|
||||
// PEP-156: «🤖 Шустрик: …» — the agent's own words; the factory's messages carry no name.
|
||||
const body = `${ctx.agent ? `<b>${asIs(esc(agentSignature(ctx.agent)))}</b>: ` : ""}${said}`;
|
||||
const lines = [head, q.kind === "attention" && ctx.agent ? tr("💬 Сообщение агента") : KIND[q.kind], "", body];
|
||||
const body = esc(clip(q.text, 3300));
|
||||
const lines = [head, KIND[q.kind], "", body];
|
||||
|
||||
const buttons: InlineButton[][] = [];
|
||||
const type = questionType(q, ctx.taskStatus);
|
||||
if (q.kind === "approval") {
|
||||
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
|
||||
lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием.")));
|
||||
buttons.push([{ text: "✅ Одобрить", callback_data: `q:${q.id}:approve` }]);
|
||||
lines.push("", "<i>Чтобы вернуть на доработку — ответьте на это сообщение комментарием.</i>");
|
||||
} else if (q.kind === "permission") {
|
||||
buttons.push([
|
||||
{ text: tr("✅ Разрешить"), callback_data: `q:${q.id}:allow` },
|
||||
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
|
||||
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
|
||||
{ text: "✅ Разрешить", callback_data: `q:${q.id}:allow` },
|
||||
{ text: "♾ Всегда", callback_data: `q:${q.id}:always` },
|
||||
{ text: "⛔ Запретить", callback_data: `q:${q.id}:deny` },
|
||||
]);
|
||||
} else if (type === "question") {
|
||||
// PEP-149: a question always comes with answers to tap; the default goes first.
|
||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: free ? asIs(clip(o, 60)) : clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||
if (q.kind === "attention") lines[1] = KIND.question;
|
||||
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
|
||||
if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
|
||||
} else if (type === "done") {
|
||||
lines[1] = tr("✅ Готово к ревью");
|
||||
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
|
||||
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
|
||||
} else if (q.kind === "question") {
|
||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||
lines.push("", "<i>Выберите вариант или ответьте на это сообщение своим текстом.</i>");
|
||||
} else if (ctx.taskStatus === "review") {
|
||||
lines[1] = "✅ Готово к ревью";
|
||||
buttons.push([{ text: "✅ Принять", callback_data: `q:${q.id}:accept` }]);
|
||||
lines.push("", "<i>Есть замечания — ответьте на это сообщение, агент доработает.</i>");
|
||||
} else {
|
||||
// A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button.
|
||||
const s = ctx.session;
|
||||
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
||||
buttons.push([
|
||||
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
|
||||
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
|
||||
{ text: "🔁 Перезапустить", callback_data: `s:${s.id}:resume` },
|
||||
{ text: "⏹ Остановить", callback_data: `s:${s.id}:stop` },
|
||||
]);
|
||||
// PEP-186: agents stand on a limit of their subscription — ask the superadmin for one.
|
||||
if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]);
|
||||
} else {
|
||||
buttons.push([{ text: "▶️ Продолжай", callback_data: `q:${q.id}:cont` }]);
|
||||
lines.push("", "<i>Или ответьте на это сообщение — текст уйдёт агенту.</i>");
|
||||
}
|
||||
}
|
||||
lines[1] = `${VOICE} · ${lines[1]}`;
|
||||
if (ctx.session && ctx.engineer) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||
const web = ctx.webUrl.replace(/\/$/, "");
|
||||
if ((ctx.details || shown.more) && ctx.taskKey && /^https?:\/\//.test(web)) buttons.push([{ text: tr("Подробнее"), url: `${web}/t/${ctx.taskKey}?more=1` }]);
|
||||
if (ctx.session) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||
return { text: lines.join("\n"), buttons };
|
||||
}
|
||||
|
||||
/** Text after the question is closed: original + who answered what, no buttons. */
|
||||
export function renderAnswered(original: string, q: Question): string {
|
||||
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
||||
const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"];
|
||||
// PEP-154: service blocks are nobody's answer.
|
||||
const answer = stripServiceBlocks(q.answer ?? "");
|
||||
// A person's answer is free text; a button of a factory question (and a system answer) is a phrase.
|
||||
const own = q.answeredVia !== "system" && !(q.options ?? []).includes(q.answer ?? "") ? asIs : (x: string) => x;
|
||||
const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: <b>{answer}</b>", { via, answer: own(esc(clip(answer, 500))) });
|
||||
return `${original}\n\n${mark} ${said}`;
|
||||
const via = { telegram: "в Telegram", web: "в вебе", terminal: "в терминале", system: "" }[q.answeredVia ?? "telegram"];
|
||||
return `${original}\n\n${mark} ${q.answeredVia === "system" ? esc(q.answer ?? "") : `Ответ ${via}: <b>${esc(clip(q.answer ?? "", 500))}</b>`}`;
|
||||
}
|
||||
|
||||
/** The answer text a button stands for. */
|
||||
export function choiceToAnswer(q: Question, choice: string): string | null {
|
||||
if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent
|
||||
if (q.kind === "approval" && choice === "approve") return "ок";
|
||||
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
|
||||
// PEP-149: the «continue» button is gone — an old one on an earlier message answers nothing.
|
||||
if (q.kind === "attention" && choice === "cont") return "Продолжай.";
|
||||
const m = /^o(\d+)$/.exec(choice);
|
||||
if (m) return q.options?.[Number(m[1])] ?? null;
|
||||
if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at
|
||||
// mock-telegram (packages/testkit).
|
||||
|
||||
@ -18,13 +17,6 @@ export interface TgMessage {
|
||||
/** PEP-45: voice notes and audio files become stories after transcription. */
|
||||
voice?: TgFileRef;
|
||||
audio?: TgFileRef;
|
||||
/** PEP-143: a photo comes as several sizes (the last is the largest); its text is the caption. */
|
||||
photo?: TgFileRef[];
|
||||
/** An image sent «as a file». */
|
||||
document?: TgFileRef & { file_name?: string };
|
||||
caption?: string;
|
||||
/** Messages of one album share it. */
|
||||
media_group_id?: string;
|
||||
}
|
||||
export interface TgFileRef {
|
||||
file_id: string;
|
||||
@ -49,18 +41,6 @@ export interface InlineButton {
|
||||
url?: string;
|
||||
}
|
||||
|
||||
const TG_TEXT_MAX = 4096;
|
||||
const TG_CLIP_NOTE_TEXT = tr("(полностью — на сайте FORGE)");
|
||||
const TG_CLIP_NOTE = "\n\n… " + TG_CLIP_NOTE_TEXT;
|
||||
|
||||
/** PEP-180: a text that fits Telegram — cut at the last line break before the limit. */
|
||||
export function clipForTelegram(text: string): string {
|
||||
if (text.length <= TG_TEXT_MAX) return text;
|
||||
const room = TG_TEXT_MAX - TG_CLIP_NOTE.length;
|
||||
const cut = text.lastIndexOf("\n", room);
|
||||
return `${text.slice(0, cut > room / 2 ? cut : room)}${TG_CLIP_NOTE}`;
|
||||
}
|
||||
|
||||
export class TelegramError extends Error {
|
||||
readonly method: string;
|
||||
readonly code: number;
|
||||
@ -84,11 +64,6 @@ export class TelegramApi {
|
||||
}
|
||||
|
||||
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
|
||||
// PEP-180: Telegram refuses texts over 4096 characters — a long message goes shortened (cut at a
|
||||
// line break, so no HTML tag is left open), with a note that the whole text is on the site.
|
||||
if ((method === "sendMessage" || method === "editMessageText") && typeof params.text === "string" && params.text.length > TG_TEXT_MAX) {
|
||||
params = { ...params, text: clipForTelegram(params.text) };
|
||||
}
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
|
||||
@ -143,23 +118,6 @@ export class TelegramApi {
|
||||
return Buffer.from(await res.arrayBuffer());
|
||||
}
|
||||
|
||||
/** PEP-143: a photo uploaded from memory (multipart/form-data, as the Bot API wants for new files). */
|
||||
async sendPhoto(chatId: number, photo: { data: Uint8Array; filename: string; mime: string }, extra: Record<string, unknown> = {}): Promise<TgMessage> {
|
||||
const form = new FormData();
|
||||
form.set("chat_id", String(chatId));
|
||||
for (const [k, v] of Object.entries(extra)) if (v != null && k !== "chat_id") form.set(k, typeof v === "string" ? v : JSON.stringify(v));
|
||||
form.set("photo", new Blob([photo.data as BlobPart], { type: photo.mime }), photo.filename);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${this.baseUrl}/bot${this.token}/sendPhoto`, { method: "POST", body: form, signal: AbortSignal.timeout(60_000) });
|
||||
} catch (e) {
|
||||
throw new TelegramError("sendPhoto", 0, (e as Error).message);
|
||||
}
|
||||
const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: TgMessage; description?: string; error_code?: number; parameters?: { retry_after?: number } };
|
||||
if (!body.ok) throw new TelegramError("sendPhoto", body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after);
|
||||
return body.result as TgMessage;
|
||||
}
|
||||
|
||||
sendMessage(chatId: number, text: string, extra: Record<string, unknown> = {}) {
|
||||
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
|
||||
}
|
||||
|
||||
52
apps/bot/src/transcribe.ts
Normal file
52
apps/bot/src/transcribe.ts
Normal file
@ -0,0 +1,52 @@
|
||||
// Speech to text for voice notes (PEP-45): any OpenAI-compatible audio API —
|
||||
// POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions (multipart: file, model, language,
|
||||
// response_format=json) with "Authorization: Bearer $PEPPA_TRANSCRIBE_KEY" → {"text": "…"}.
|
||||
// OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1,
|
||||
// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use
|
||||
// mock-transcribe (packages/testkit).
|
||||
|
||||
export interface TranscribeConfig {
|
||||
url: string;
|
||||
key: string | null;
|
||||
model: string;
|
||||
language: string | null;
|
||||
}
|
||||
|
||||
/** From env; null when voice is not set up (the bot asks for text then). */
|
||||
export function transcribeConfig(env: NodeJS.ProcessEnv = process.env): TranscribeConfig | null {
|
||||
const url = env.PEPPA_TRANSCRIBE_URL?.trim();
|
||||
if (!url) return null;
|
||||
return {
|
||||
url: url.replace(/\/$/, ""),
|
||||
key: env.PEPPA_TRANSCRIBE_KEY?.trim() || null,
|
||||
model: env.PEPPA_TRANSCRIBE_MODEL?.trim() || "whisper-1",
|
||||
language: env.PEPPA_TRANSCRIBE_LANG === "" ? null : (env.PEPPA_TRANSCRIBE_LANG?.trim() || "ru"),
|
||||
};
|
||||
}
|
||||
|
||||
export class TranscribeError extends Error {}
|
||||
|
||||
export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename = "voice.ogg", mime = "audio/ogg"): Promise<string> {
|
||||
const form = new FormData();
|
||||
form.set("file", new Blob([new Uint8Array(audio)], { type: mime }), filename);
|
||||
form.set("model", cfg.model);
|
||||
form.set("response_format", "json");
|
||||
if (cfg.language) form.set("language", cfg.language);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${cfg.url}/audio/transcriptions`, {
|
||||
method: "POST",
|
||||
headers: cfg.key ? { Authorization: `Bearer ${cfg.key}` } : {},
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`);
|
||||
}
|
||||
const body = (await res.json().catch(() => ({}))) as { text?: string; error?: { message?: string } | string };
|
||||
if (!res.ok) {
|
||||
const msg = typeof body.error === "string" ? body.error : body.error?.message;
|
||||
throw new TranscribeError(`расшифровка не удалась: ${res.status}${msg ? ` ${msg}` : ""}`);
|
||||
}
|
||||
return (body.text ?? "").trim();
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch
|
||||
# through ~/peppa/current keeps that path in hooks and git config instead of the release dir.
|
||||
_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; }
|
||||
PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l
|
||||
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
||||
exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/observer/src/index.ts" "$@"
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "@peppa/observer",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": { ".": "./src/observer.ts" },
|
||||
"bin": { "peppa-observer": "./bin/peppa-observer" },
|
||||
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
||||
"dependencies": {
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*"
|
||||
}
|
||||
}
|
||||
@ -1,15 +0,0 @@
|
||||
// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202.
|
||||
import { createDb } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { installCrashReporting, installServiceLog, setDefaultActor } from "@peppa/core";
|
||||
import { runObserver } from "./observer.ts";
|
||||
|
||||
const env = loadEnv();
|
||||
const db = createDb(env.PEPPA_DB);
|
||||
setDefaultActor({ kind: "system" });
|
||||
installCrashReporting(db, "observer");
|
||||
// PEP-291: the log also goes to $PEPPA_HOME/logs/observer.log — it survives a redeploy.
|
||||
installServiceLog("observer");
|
||||
const ac = new AbortController();
|
||||
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => (ac.abort(), setTimeout(() => process.exit(0), 200)));
|
||||
await runObserver(db, { log: (m) => console.log(`${new Date().toISOString()} ${m}`) }, ac.signal);
|
||||
@ -1,62 +0,0 @@
|
||||
// PEP-202: the `peppa-observer` service — runs the monitors of Observability. Every second it
|
||||
// starts the checks that are due (they run in the background, each with its own timeout), every
|
||||
// 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, seedClaudeMonitors, seedFeatureMonitors, seedMonitors, vitalsAlertTick, type ObserveProbes } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import type { Db } from "@peppa/db";
|
||||
|
||||
export interface ObserverOptions {
|
||||
log?: (m: string) => void;
|
||||
tickMs?: number;
|
||||
probes?: ObserveProbes;
|
||||
}
|
||||
|
||||
export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: AbortSignal): Promise<void> {
|
||||
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(", ")}`);
|
||||
// PEP-210: Claude Code (Remote Control) by the official status page.
|
||||
const claude = seedClaudeMonitors();
|
||||
if (claude.length) log(`observer: built-in monitors created: ${claude.map((m) => m.name).join(", ")}`);
|
||||
let featuresBusy = false;
|
||||
log("observer started");
|
||||
let lastBeat = 0;
|
||||
let lastPrune = 0;
|
||||
let lastVitals = 0;
|
||||
while (!signal?.aborted) {
|
||||
const now = Date.now();
|
||||
if (now - lastBeat >= 30_000) {
|
||||
lastBeat = now;
|
||||
await beat(db, "observer").catch((e: Error) => log(`observer: heartbeat failed: ${e.message}`));
|
||||
}
|
||||
if (now - lastPrune >= 3_600_000) {
|
||||
lastPrune = now;
|
||||
try {
|
||||
const n = pruneObserve();
|
||||
if (n) log(`observer: ${n} old checks deleted`);
|
||||
} catch (e) {
|
||||
log(`observer: prune failed: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
// PEP-217: slow pages (p75 of real users) → one warning per route and day in Bugsink.
|
||||
if (now - lastVitals >= 600_000) {
|
||||
lastVitals = now;
|
||||
void vitalsAlertTick(db).catch((e: Error) => log(`observer: vitals failed: ${e.message}`));
|
||||
}
|
||||
// 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 +0,0 @@
|
||||
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src"] }
|
||||
@ -15,6 +15,7 @@ import {
|
||||
resolveTask,
|
||||
revokeApp,
|
||||
createPairingCode,
|
||||
getSetting,
|
||||
unpairTelegram,
|
||||
getIncident,
|
||||
getProject as getProjectByKey,
|
||||
@ -26,11 +27,7 @@ import {
|
||||
type IncidentPolicy,
|
||||
getUser,
|
||||
isSuperadmin,
|
||||
getDirectOrigins,
|
||||
setDirectOrigins,
|
||||
setUserDisabled,
|
||||
setSuperadmin,
|
||||
mergeAccounts,
|
||||
NOTIFY_EVENTS,
|
||||
defaultPrefs,
|
||||
deletePushSubscription,
|
||||
@ -51,15 +48,10 @@ import {
|
||||
setTaskAgentSettings,
|
||||
cleanBudget,
|
||||
logEvent,
|
||||
setPublishMode,
|
||||
type PublishMode,
|
||||
setProjectBudget,
|
||||
setTaskBudget,
|
||||
type Budget,
|
||||
setProjectSecret,
|
||||
setSecretAudience,
|
||||
secretToConnection,
|
||||
setAgentSecretsEnabled,
|
||||
setNeedDone,
|
||||
removeNeed,
|
||||
deleteProjectSecret,
|
||||
@ -69,19 +61,13 @@ import {
|
||||
checkGiteaBotToken,
|
||||
setUiMode,
|
||||
} from "@peppa/core";
|
||||
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
||||
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
||||
import { deleteProject, decideConnectionApproval, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestByButton, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { pauseProject, resumeProject, startAcceptAll, processAcceptQueue, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
||||
import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { after } from "next/server";
|
||||
import { asWebActor, requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const back = (f: FormData) => str(f, "back") || "/";
|
||||
@ -92,9 +78,7 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
||||
try {
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const t = await getT();
|
||||
// PEP-98: core errors are rendered Russian text — translate them for the reader.
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
@ -122,8 +106,8 @@ export async function answerQuestion(f: FormData) {
|
||||
const q = await getQuestion(db, Number(str(f, "questionId")));
|
||||
await projectForUser(db, user.id, q.projectId);
|
||||
const answer = str(f, "choice") || str(f, "answer");
|
||||
if (!answer) throw new PeppaError(m("Пустой ответ"));
|
||||
if (q.answeredAt) throw new PeppaError(q.answeredVia === "system" ? m("Уже отвечено: {answer}", { answer: q.answer }) : m("Уже отвечено ({via}): {answer}", { via: q.answeredVia, answer: q.answer }));
|
||||
if (!answer) throw new PeppaError("Пустой ответ");
|
||||
if (q.answeredAt) throw new PeppaError(`Уже отвечено${q.answeredVia === "system" ? "" : ` (${q.answeredVia})`}: ${q.answer}`);
|
||||
if (answer === "__accept") {
|
||||
await acceptTask(db, q.id, "web");
|
||||
return;
|
||||
@ -136,11 +120,9 @@ export async function addTask(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (!str(f, "title")) throw new PeppaError(m("Нужно название задачи"));
|
||||
if (!str(f, "title")) throw new PeppaError("Нужно название задачи");
|
||||
const epic = Number(str(f, "epicId")) || undefined;
|
||||
const ids = parseAttachmentIds(f.getAll("attachment"));
|
||||
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
|
||||
await linkAttachments(db, user, p.id, ids, { taskId: ref.task.id });
|
||||
return `/t/${ref.key}`;
|
||||
});
|
||||
}
|
||||
@ -150,7 +132,7 @@ export async function addEpic(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика"));
|
||||
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
|
||||
await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
|
||||
});
|
||||
}
|
||||
@ -164,7 +146,7 @@ export async function editEpic(f: FormData) {
|
||||
await updateEpic(db, p.id, id, { status: "archived" });
|
||||
return;
|
||||
}
|
||||
if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика"));
|
||||
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
|
||||
await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
|
||||
});
|
||||
}
|
||||
@ -176,7 +158,7 @@ export async function editStoryAction(f: FormData) {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const title = str(f, "title");
|
||||
if (title.length < 2) throw new PeppaError(m("Нужно название задачи"));
|
||||
if (title.length < 2) throw new PeppaError("Нужно название задачи");
|
||||
const epic = str(f, "epicId");
|
||||
await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login);
|
||||
});
|
||||
@ -188,15 +170,11 @@ export async function commentStoryAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const ids = parseAttachmentIds(f.getAll("attachment"));
|
||||
const body = String(f.get("text") ?? "").trim() || (await attachmentLabel(db, ids));
|
||||
const c = await addStoryComment(db, ref, user, body);
|
||||
await linkAttachments(db, user, ref.project.id, ids, { taskId: ref.task.id, eventId: c.id });
|
||||
const c = await addStoryComment(db, ref, user, String(f.get("text") ?? ""));
|
||||
if (str(f, "toAgent")) {
|
||||
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
|
||||
if (!live) throw new PeppaError(m("Комментарий сохранён, но агент сейчас не работает — увидит его, когда вернётся к задаче"));
|
||||
// i18n-ignore — text for the agent
|
||||
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}${await syncSessionAttachments(db, live.id)}`, { person: true });
|
||||
if (!live) throw new PeppaError("Комментарий сохранён, но агент сейчас не работает — увидит его, когда вернётся к задаче");
|
||||
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -211,61 +189,11 @@ export async function acceptStoryAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-209: «Принять» / «Принять всё» on the acceptance page. PEP-318: the decision is queued and
|
||||
* the page answers at once; the stories are accepted one by one in the background (after the
|
||||
* answer here, else by the watchdog), the page shows the progress and the result.
|
||||
*/
|
||||
export async function acceptAllAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
const key = str(f, "project");
|
||||
const base = `/p/${encodeURIComponent(key)}/accept`;
|
||||
await attempt(f, async () => {
|
||||
const refs = [];
|
||||
for (const k of f.getAll("taskKey").map(String)) {
|
||||
const ref = await resolveTask(db, k).catch(() => null);
|
||||
if (!ref || ref.project.key !== key) continue;
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
if (ref.task.status === "review") refs.push(ref);
|
||||
}
|
||||
if (!refs.length) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу"));
|
||||
startAcceptAll(db, refs, user.id, "web");
|
||||
const projectId = refs[0]!.project.id;
|
||||
after(() => processAcceptQueue(db, projectId).catch(() => 0));
|
||||
return base;
|
||||
});
|
||||
}
|
||||
|
||||
/** «Поправить» on the story page in «Продакт» mode (PEP-120): the remark goes to the agent, the story — back to work. */
|
||||
export async function fixStoryAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
await fixStory(db, ref, user, String(f.get("text") ?? ""));
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-198: «Подходит» / «Нужно иначе» / «Не делить» on a decision of «Фабрика решила за вас». */
|
||||
export async function decisionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const id = Number(str(f, "id"));
|
||||
const choice = str(f, "choice");
|
||||
if (choice === "confirm") await confirmTaskDecision(db, ref, id, user);
|
||||
else if (choice === "unsplit") await undoSplit(db, ref, id, user);
|
||||
else if (choice === "change") await changeTaskDecision(db, ref, id, String(f.get("how") ?? ""), user);
|
||||
else throw new PeppaError(m("Эта кнопка уже не работает. Обновите страницу."));
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-67: a superadmin may pick a pool or tick subscriptions; otherwise the project's pool. */
|
||||
async function launchChoice(f: FormData, user: Awaited<ReturnType<typeof requireUser>>) {
|
||||
const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : "";
|
||||
const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined;
|
||||
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError(m("Отметьте хотя бы одну подписку"));
|
||||
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError("Отметьте хотя бы одну подписку");
|
||||
const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined;
|
||||
const provider = str(f, "provider") as Provider | "";
|
||||
return { provider: provider || undefined, subscriptionIds, poolId };
|
||||
@ -381,22 +309,21 @@ export async function messageSession(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||
if (!str(f, "text")) throw new PeppaError(m("Пустое сообщение"));
|
||||
await sendToSession(db, s.id, str(f, "text"), { person: true });
|
||||
if (!str(f, "text")) throw new PeppaError("Пустое сообщение");
|
||||
await sendToSession(db, s.id, str(f, "text"));
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProjectAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
// PEP-142: the same form sent twice (a second click, another tab) opens the one project.
|
||||
const p = await provisionProjectOnce(db, {
|
||||
const p = await provisionProject(db, {
|
||||
...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot
|
||||
slug: str(f, "slug").toLowerCase(),
|
||||
key: str(f, "key"),
|
||||
name: str(f, "name"),
|
||||
existing: str(f, "mode") === "existing",
|
||||
visibility: str(f, "visibility") === "public" ? "public" : "private", // PEP-280: closed unless chosen
|
||||
visibility: str(f, "visibility") === "private" ? "private" : "public",
|
||||
ownerId: user.id,
|
||||
});
|
||||
return `/p/${p.key}?created=1`;
|
||||
@ -411,43 +338,13 @@ export async function deployProdAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-145: «Показывать всем: сам / по кнопке» (owner or member). */
|
||||
export async function setPublishModeAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const mode = await setPublishMode(db, p.id, str(f, "mode") as PublishMode);
|
||||
await logEvent(db, { projectId: p.id, type: "publish_mode_set", payload: { mode, login: user.login } });
|
||||
// «Сам» chosen with an accepted version waiting: it goes to everyone right away.
|
||||
if (mode === "auto") await autoPublish(db, p).catch(() => false);
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-174: «Поставить на паузу» — owner, member or superadmin. Agents stop, nothing is sent. */
|
||||
export async function pauseProjectAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await pauseProject(db, p.id, user.id);
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-174: «Продолжить» — the agents stopped by the pause continue, the dispatcher takes stories again. */
|
||||
export async function resumeProjectAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await resumeProject(db, p.id);
|
||||
});
|
||||
}
|
||||
|
||||
export async function moveTaskCard(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const to = str(f, "to") as BoardColumn;
|
||||
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError(m("Неизвестная колонка"));
|
||||
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError("Неизвестная колонка");
|
||||
await moveTask(db, ref, to);
|
||||
});
|
||||
}
|
||||
@ -465,7 +362,7 @@ export async function addProjectMember(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const r = await shareProject(db, user, p, str(f, "login"));
|
||||
if (!r.repoAccess) throw new PeppaError((await words()).engineer ? m("{login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную", { login: r.login }) : m("{login} добавлен, но доступ к коду проекта выдать не удалось. Напишите в поддержку FORGE.", { login: r.login }));
|
||||
if (!r.repoAccess) throw new PeppaError((await words()).engineer ? `${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную` : `${r.login} добавлен, но доступ к коду проекта выдать не удалось. Напишите в поддержку Peppa FACTORY.`);
|
||||
});
|
||||
}
|
||||
|
||||
@ -474,24 +371,7 @@ export async function grantRepoAccessToMembers(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const r = await grantRepoAccess(db, user, p);
|
||||
if (r.failed.length) throw new PeppaError(m("Не удалось выдать доступ к репозиторию: {logins} — нет прав администратора в Gitea, добавьте соавторов вручную", { logins: r.failed.join(", ") }));
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-163: the owner deletes the project; it stays with the superadmin for a week. */
|
||||
export async function deleteProjectAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
if (str(f, "confirm") !== "yes") throw new PeppaError(m("Отметьте, что хотите удалить проект"));
|
||||
await deleteProject(db, user.id, Number(str(f, "projectId")));
|
||||
return "/projects";
|
||||
});
|
||||
}
|
||||
|
||||
export async function restoreProjectAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await restoreProject(db, Number(str(f, "projectId")), user.id);
|
||||
if (r.failed.length) throw new PeppaError(`Не удалось выдать доступ к репозиторию: ${r.failed.join(", ")} — нет прав администратора в Gitea, добавьте соавторов вручную`);
|
||||
});
|
||||
}
|
||||
|
||||
@ -522,7 +402,6 @@ export async function setAutonomyAction(f: FormData) {
|
||||
merge: str(f, "merge") as AutonomySettings["merge"],
|
||||
close: str(f, "close") as AutonomySettings["close"],
|
||||
closeAfterHours: Number(str(f, "closeAfterHours")),
|
||||
acceptOwn: (str(f, "acceptOwn") || undefined) as AutonomySettings["acceptOwn"],
|
||||
idlePush: f.get("idlePush") === "on",
|
||||
idlePushHours: Number(str(f, "idlePushHours")),
|
||||
quietFrom: quiet ? hour("quietFrom") : null,
|
||||
@ -531,41 +410,6 @@ export async function setAutonomyAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-197: «Делать» / «Не надо» on a suggested story (board, chat). */
|
||||
export async function proposalAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const choice = str(f, "choice");
|
||||
// PEP-209: «Объединить в одну» — the ticked proposals become one story.
|
||||
if (choice === "merge") {
|
||||
await mergeProposals(db, user, f.getAll("pick").map(Number).filter((n) => Number.isInteger(n) && n > 0));
|
||||
return;
|
||||
}
|
||||
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") throw new PeppaError(m("Эта кнопка уже не работает."));
|
||||
const ids = str(f, "ids").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||||
await decideProposals(db, user, ids, choice);
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-302: «Делать» / «Не надо» at a finding put aside until the weekly digest. */
|
||||
export async function deferredAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const choice = str(f, "choice");
|
||||
if (choice !== "do" && choice !== "no") throw new PeppaError(m("Эта кнопка уже не работает."));
|
||||
await decideDeferred(db, user, Number(str(f, "projectId")), str(f, "title"), choice);
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */
|
||||
export async function setAcceptOwnAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await setAutonomy(db, p.id, { acceptOwn: str(f, "acceptOwn") as AutonomySettings["acceptOwn"] });
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeProjectMember(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
@ -583,9 +427,8 @@ export async function pairingLinkAction(): Promise<{ url?: string; error?: strin
|
||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||
// Every user has their own bot: no pairing link through the shared one.
|
||||
const username = user.telegramBotUsername;
|
||||
const t = await getT();
|
||||
if (!username) return { error: t("Сначала подключите своего бота (шаги 1–2)") };
|
||||
if (!token) return { error: t("Telegram сейчас недоступен. Попробуйте через минуту.") };
|
||||
if (!username) return { error: "Сначала подключите своего бота (шаги 1–2)" };
|
||||
if (!token) return { error: "Telegram сейчас недоступен. Попробуйте через минуту." };
|
||||
return { url: `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}` };
|
||||
}
|
||||
|
||||
@ -595,8 +438,8 @@ export async function pairTelegram(f: FormData) {
|
||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||
// Every user has their own bot (PEP-85/100): the platform's bot is never offered to users.
|
||||
const username = user.telegramBotUsername;
|
||||
if (!username) throw new PeppaError(m("Сначала подключите своего Telegram-бота"));
|
||||
if (!token) throw new PeppaError(m("Telegram сейчас недоступен. Попробуйте через минуту."));
|
||||
if (!username) throw new PeppaError("Сначала подключите своего Telegram-бота");
|
||||
if (!token) throw new PeppaError("Telegram сейчас недоступен. Попробуйте через минуту.");
|
||||
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
|
||||
});
|
||||
}
|
||||
@ -635,7 +478,7 @@ export async function saveNotifyPrefsAction(f: FormData) {
|
||||
const events = { ...d.events };
|
||||
for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" };
|
||||
const tz = str(f, "timezone") || cur.timezone;
|
||||
if (!isValidTimezone(tz)) throw new PeppaError(m("Неизвестная таймзона: {tz}", { tz }));
|
||||
if (!isValidTimezone(tz)) throw new PeppaError(`Неизвестная таймзона: ${tz}`);
|
||||
const shown = f.getAll("projectShown").map(Number);
|
||||
const enabled = new Set(f.getAll("project").map(Number));
|
||||
// Projects not on the form (no access any more) keep their old state.
|
||||
@ -675,10 +518,9 @@ export async function deletePushSubscriptionAction(endpoint: string) {
|
||||
export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> {
|
||||
const user = asWebActor(await requireUser());
|
||||
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
|
||||
const t = await getT();
|
||||
if (!sub) return { ok: false, error: t("Этот браузер не подписан") };
|
||||
if (!sub) return { ok: false, error: "Этот браузер не подписан" };
|
||||
const prefs = await getNotifyPrefs(db, user.id);
|
||||
const r = await sendWebPush(db, sub, { title: PRODUCT_NAME, body: t("Уведомления в этом браузере работают ✅"), url: "/settings#notifications", tag: "test", sound: prefs.sound });
|
||||
const r = await sendWebPush(db, sub, { title: "Peppa FACTORY", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound });
|
||||
if (r.ok) return { ok: true };
|
||||
if (r.gone) await deletePushSubscription(db, user.id, endpoint);
|
||||
return { ok: false, error: r.error };
|
||||
@ -689,7 +531,7 @@ export async function testPushAction(endpoint: string): Promise<{ ok: boolean; e
|
||||
async function incidentInProject(userId: number, f: FormData) {
|
||||
const p = await projectForUser(db, userId, Number(str(f, "projectId")));
|
||||
const i = await getIncident(db, Number(str(f, "incidentId")));
|
||||
if (i.projectId !== p.id) throw new PeppaError(m("Не найдено"));
|
||||
if (i.projectId !== p.id) throw new PeppaError("Не найдено");
|
||||
return i;
|
||||
}
|
||||
|
||||
@ -697,22 +539,11 @@ export async function connectErrorTrackingAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (!(await managesProject(db, user, p))) throw new PeppaError(m("Подключает владелец проекта"));
|
||||
if (!(await managesProject(db, user, p))) throw new PeppaError("Подключает владелец проекта");
|
||||
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-295: the owner's exception — errors of the product go to work without «Делать». */
|
||||
export async function setDirectIncidentsAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (p.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError(m("Это решает владелец проекта."));
|
||||
const rest = (await getDirectOrigins(db, p.id)).filter((o) => o !== "incident");
|
||||
await setDirectOrigins(db, p.id, str(f, "on") === "yes" ? [...rest, "incident"] : rest);
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveIncidentSettings(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
@ -746,7 +577,7 @@ export async function decideIncidentAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const i = await incidentInProject(user.id, f);
|
||||
const action = str(f, "action");
|
||||
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError(m("Неизвестное решение"));
|
||||
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError("Неизвестное решение");
|
||||
await decideIncident(db, i.id, action, user.login);
|
||||
});
|
||||
}
|
||||
@ -764,7 +595,7 @@ export async function resolveIncidentAction(f: FormData) {
|
||||
/** Superadmin-only actions: everybody else gets "not found", nothing changes. */
|
||||
async function requireSuperadmin() {
|
||||
const user = asWebActor(await requireUser());
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError(m("Не найдено"));
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
|
||||
return user;
|
||||
}
|
||||
|
||||
@ -774,30 +605,12 @@ export async function setUserDisabledAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const admin = await requireSuperadmin();
|
||||
const u = await getUser(db, Number(str(f, "userId")));
|
||||
if (!u) throw new PeppaError(m("Не найдено"));
|
||||
if (u.id === admin.id) throw new PeppaError(m("Нельзя отключить самого себя"));
|
||||
if (!u) throw new PeppaError("Не найдено");
|
||||
if (u.id === admin.id) throw new PeppaError("Нельзя отключить самого себя");
|
||||
await setUserDisabled(db, u.id, str(f, "disabled") === "1");
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-226: appoint or remove a superadmin from «Пользователи». */
|
||||
export async function setSuperadminAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const admin = asWebActor(await requireSuperadmin());
|
||||
await setSuperadmin(db, admin, Number(str(f, "userId")), str(f, "on") === "1");
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-204: merge an old account into the person's main one, after the confirmation screen. */
|
||||
export async function mergeAccountsAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
// The actor is set in this frame: set inside requireSuperadmin it would not reach the journal entry.
|
||||
const admin = asWebActor(await requireSuperadmin());
|
||||
await mergeAccounts(db, admin, Number(str(f, "from")), Number(str(f, "to")), { confirm: str(f, "confirm") === "1", confirmAdmin: str(f, "confirmAdmin") === "1" });
|
||||
return "/users";
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// ── PEP-43: budgets ────────────────────────────────────────────────────────────────
|
||||
const budgetFrom = (f: FormData): Budget => cleanBudget(Object.fromEntries(["minutes", "tokens", "restarts", "costUsd"].map((k) => [k, Number(str(f, k)) || null])));
|
||||
@ -810,7 +623,7 @@ export async function saveTaskBudgetAction(f: FormData) {
|
||||
const mode = str(f, "mode");
|
||||
const budget = mode === "inherit" ? null : mode === "unlimited" ? {} : budgetFrom(f);
|
||||
await setTaskBudget(db, ref.task.id, budget);
|
||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } }); // i18n-ignore — stored value
|
||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } });
|
||||
await budgetChanged(db, ref.task.id);
|
||||
});
|
||||
}
|
||||
@ -831,32 +644,7 @@ export async function saveProjectSecretAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
// The value is taken as is (no trim): keys may legitimately end with spaces/newlines.
|
||||
// PEP-253: «Кому» — only the product by default.
|
||||
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""), { agent: str(f, "audience") === "agent" });
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-253: «только продукту» ⇄ «агенту и продукту».
|
||||
export async function setSecretAudienceAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await setSecretAudience(db, user.id, Number(str(f, "projectId")), str(f, "name"), str(f, "audience") === "agent");
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-253: «Сделать подключением» — a catalog connection with the secret's key, granted to the project.
|
||||
export async function secretToConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await secretToConnection(db, user.id, Number(str(f, "projectId")), str(f, "name"));
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-253: «Агенты получают секреты в окружение».
|
||||
export async function setAgentSecretsAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await setAgentSecretsEnabled(db, user.id, Number(str(f, "projectId")), str(f, "on") === "1");
|
||||
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""));
|
||||
});
|
||||
}
|
||||
|
||||
@ -934,19 +722,11 @@ export async function chooseSharedSubscriptionAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-186: «Попросить подписку у администратора». */
|
||||
export async function requestSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await requestSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), new Date(), { ahead: str(f, "ahead") === "1" });
|
||||
});
|
||||
}
|
||||
|
||||
export async function connectOwnSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const kind = str(f, "kind") as OwnSubscriptionKind;
|
||||
if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError(m("Выберите, что подключить"));
|
||||
if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
|
||||
});
|
||||
@ -957,7 +737,7 @@ export async function finishOwnClaudeLoginAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"), str(f, "account"));
|
||||
await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"));
|
||||
});
|
||||
}
|
||||
|
||||
@ -983,7 +763,7 @@ export async function saveIntakeSettingsAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on" });
|
||||
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
|
||||
});
|
||||
}
|
||||
|
||||
@ -1004,221 +784,3 @@ export async function disconnectOwnBotAction(f: FormData) {
|
||||
return str(f, "back") === "/" ? "/" : "/settings#telegram";
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// ── PEP-143: users' reports about Peppa — the superadmin decides ─────────────────────
|
||||
export async function fixFeedbackAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await fixFeedback(db, user, Number(str(f, "feedbackId")), Number(str(f, "option")));
|
||||
});
|
||||
}
|
||||
|
||||
export async function linkFeedbackAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await linkFeedback(db, user, Number(str(f, "feedbackId")), str(f, "task") || null);
|
||||
});
|
||||
}
|
||||
|
||||
export async function rejectFeedbackAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await rejectFeedback(db, user, Number(str(f, "feedbackId")), str(f, "reason") || null);
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-234 Access Hub: the user's own connections. Every core function checks the owner itself.
|
||||
// PEP-249: catalog cards, a key check right after saving, read / write modes.
|
||||
const checkWord = (r: ConnectionCheckResult | null) => (!r ? "down" : r.reachableOnly ? "reachable" : r.status);
|
||||
const AUTH_KINDS: CatalogAuth[] = ["bearer", "header", "query", "basic"];
|
||||
|
||||
// PEP-251: the form fields of a database / server / storage / mailbox (never the secret).
|
||||
const PROTOCOL_FIELDS = ["host", "port", "database", "user", "tls", "root", "hostKey", "endpoint", "region", "bucket", "prefix", "accessKeyId", "imapHost", "imapPort", "smtpHost", "smtpPort", "from"];
|
||||
|
||||
export async function createConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const protocol = str(f, "protocol");
|
||||
// PEP-236: a remote MCP server — the test (initialize + tools/list) runs on saving.
|
||||
if (protocol === "mcp") {
|
||||
const kind = str(f, "authKind");
|
||||
const c = await createConnection(db, user.id, { protocol: "mcp", name: str(f, "name"), baseUrl: str(f, "baseUrl"), secret: String(f.get("secret") ?? "").trim(), authKind: kind === "header" || kind === "none" ? kind : "bearer", authHeader: str(f, "authHeader") || null });
|
||||
return `/connections?created=${c.id}&check=${c.checkStatus ?? "down"}#c${c.id}`;
|
||||
}
|
||||
if (isGatewayProtocol(protocol)) {
|
||||
const config = Object.fromEntries(PROTOCOL_FIELDS.filter((k) => f.has(k)).map((k) => [k, str(f, k)]));
|
||||
// An SSH key keeps its line breaks; a password is one line.
|
||||
const raw = String(f.get("secret") ?? "");
|
||||
const secret = protocol === "ssh" && raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim();
|
||||
const c = await createConnection(db, user.id, { protocol, name: str(f, "name"), config, secret });
|
||||
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||||
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||||
}
|
||||
const kind = str(f, "authKind") as CatalogAuth;
|
||||
const c = await createConnection(db, user.id, {
|
||||
catalogId: str(f, "catalogId") || null,
|
||||
name: str(f, "name"),
|
||||
baseUrl: str(f, "baseUrl"),
|
||||
secret: String(f.get("secret") ?? "").trim(),
|
||||
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||||
authHeader: str(f, "authHeader") || null,
|
||||
});
|
||||
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||||
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
const r = await checkConnection(db, user.id, id);
|
||||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function replaceConnectionSecretAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
const raw = String(f.get("secret") ?? "");
|
||||
await replaceConnectionSecret(db, user.id, id, raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim());
|
||||
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function resetHostKeyAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
await resetHostKey(db, user.id, id);
|
||||
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function revokeConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
const r = await revokeConnection(db, user.id, id);
|
||||
// PEP-252: the service didn't confirm the revoke of a sign-in — tell the owner to do it there too.
|
||||
if (r.remote === "failed") return `/connections?revoked=${id}&remote=failed#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await deleteConnection(db, user.id, Number(str(f, "connectionId")));
|
||||
return "/connections";
|
||||
});
|
||||
}
|
||||
|
||||
export async function grantConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const agent = str(f, "agentId");
|
||||
const mode = (k: string): GrantMode => (["auto", "ask"].includes(str(f, k)) ? (str(f, k) as GrantMode) : "off");
|
||||
// PEP-236: an MCP server's own mode per tool — fields «tool:<name>»; empty = as reading / writing.
|
||||
const tools: Record<string, GrantMode> = {};
|
||||
for (const [k, v] of f.entries()) if (k.startsWith("tool:") && ["auto", "ask", "off"].includes(String(v))) tools[k.slice(5)] = String(v) as GrantMode;
|
||||
await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? ""), tools, term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM });
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259 «Продлить»: the same term again from now. */
|
||||
export async function extendGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await extendGrant(db, user.id, Number(str(f, "grantId")));
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259: the owner's answer to «агенты давно не пользуются — снять?»: «Снять» / «Оставить». */
|
||||
export async function decideIdleGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await decideIdleGrant(db, user.id, Number(str(f, "grantId")), str(f, "decision") === "revoke" ? "revoke" : "keep");
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259: «Спрашивать о разрешении без дела через …» of one connection ("" — platform default). */
|
||||
export async function setConnectionIdleAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const v = str(f, "idleHours");
|
||||
await setConnectionIdleHours(db, user.id, Number(str(f, "connectionId")), v === "" ? null : Number(v));
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-261: rights and term chosen by the owner («Дать: чтение / полные права», срок — 1 день по умолчанию).
|
||||
function grantChoice(f: FormData): { rights?: "read" | "full"; term: GrantTerm } {
|
||||
const rights = str(f, "rights");
|
||||
return { rights: rights === "full" || rights === "read" ? rights : undefined, term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM };
|
||||
}
|
||||
|
||||
// PEP-250: an agent's access request — only its project's owner decides (core checks).
|
||||
export async function connectAccessRequestAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "requestId"));
|
||||
const kind = str(f, "authKind") as CatalogAuth;
|
||||
const { connection } = await connectAndGrantAccessRequest(db, user.id, id, {
|
||||
name: str(f, "name"),
|
||||
baseUrl: str(f, "baseUrl") || undefined,
|
||||
secret: String(f.get("secret") ?? "").trim(),
|
||||
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||||
authHeader: str(f, "authHeader") || null,
|
||||
}, grantChoice(f));
|
||||
const r = await checkConnection(db, user.id, connection.id).catch(() => null);
|
||||
return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function grantAccessRequestAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "requestId"));
|
||||
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")), grantChoice(f));
|
||||
return `/connections/requests/${id}?done=granted`;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-261: «Дать: чтение / полные права» with a term in «Агенты просят доступ». */
|
||||
export async function grantAccessButtonAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "requestId"));
|
||||
await grantAccessRequestByButton(db, user.id, id, grantChoice(f));
|
||||
return `/connections/requests/${id}?done=granted`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function denyAccessRequestAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "requestId"));
|
||||
await denyAccessRequestAndTell(db, user.id, id, str(f, "reason") || null);
|
||||
return `/connections/requests/${id}?done=denied`;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-235: «Разрешить один раз» / «Отклонить» on a call waiting for the owner's confirmation. */
|
||||
export async function decideApprovalAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const allow = str(f, "decision") === "allow";
|
||||
await decideConnectionApproval(db, user.id, Number(str(f, "approvalId")), allow, { via: "web" });
|
||||
return `/connections?approval=${allow ? "allowed" : "denied"}#approvals`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function revokeGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await revokeGrant(db, user.id, Number(str(f, "grantId")));
|
||||
});
|
||||
}
|
||||
|
||||
@ -8,7 +8,6 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
|
||||
@ -17,7 +16,7 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
||||
try {
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
@ -41,7 +40,7 @@ export async function reorderTaskCard(f: FormData) {
|
||||
const to = str(f, "to");
|
||||
if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to });
|
||||
else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) });
|
||||
else throw new PeppaError(m("Неизвестное место"));
|
||||
else throw new PeppaError("Неизвестное место");
|
||||
});
|
||||
}
|
||||
|
||||
@ -85,7 +84,7 @@ export async function planEpicAction(f: FormData) {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
|
||||
const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login });
|
||||
if (!r.ok) throw new PeppaError(m("Планировщик: {error}", { error: r.error }));
|
||||
if (!r.ok) throw new PeppaError(`Планировщик: ${r.error}`);
|
||||
});
|
||||
}
|
||||
|
||||
@ -98,12 +97,12 @@ export async function applyPlanAction(f: FormData) {
|
||||
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
|
||||
const kept: number[] = [];
|
||||
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
|
||||
if (!kept.length) throw new PeppaError(m("Не выбрано ни одной задачи. Отметьте хотя бы одну."));
|
||||
if (!kept.length) throw new PeppaError("Не выбрано ни одной задачи. Отметьте хотя бы одну.");
|
||||
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
|
||||
const stories: PlannedStory[] = kept.map((i) => {
|
||||
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
|
||||
if (typeof d !== "number") return d;
|
||||
if (!renum.has(d)) throw new PeppaError(m("Задача {i} зависит от №{d}, которую вы сняли. Уберите зависимость или оставьте задачу.", { i, d }));
|
||||
if (!renum.has(d)) throw new PeppaError(`Задача ${i} зависит от №${d}, которую вы сняли. Уберите зависимость или оставьте задачу.`);
|
||||
return renum.get(d)!;
|
||||
});
|
||||
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user