Compare commits

...

120 Commits

Author SHA1 Message Date
d322f53423 Merge pull request 'PEP-324: кнопки открытой страницы работают после выкатки' (#307) from task/pep-324 into main
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 39с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1748с
peppa-ci / ci (push) Successful in 31m45s
2026-11-27 20:12:11 +00:00
64ce2a1cc0 PEP-324: ревью в браузере — текст возвращается в своё поле, секреты не запоминаются, ошибки страниц доходят до «Ошибок из прода»
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 37с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1854с
peppa-ci / ci (pull_request) Successful in 33m9s
Проверка рабочей сборки настоящим браузером (подмена действия на неизвестное серверу и ответ 500) нашла три изъяна:
- ответ, набранный в карточке одного вопроса, после самообновления возвращался в поле другого: адресом поля было имя, а на Главной у каждой карточки поле «answer». Адрес теперь — собственный id поля, имя — только когда текстовое поле с таким именем на странице одно;
- секрет проекта и ключ сервера вводятся в textarea и попали бы в sessionStorage: поля секретов и кодов по имени не запоминаются;
- ошибка, пойманная новой границей app/error.tsx, не уходила в «Ошибки из прода» (на main уходила): Next печатает её console.error, взятым до обёртки ErrorReporter. Граница сама поднимает её через reportError.

Тесты на каждый изъян падали до правки; спека, design архива, AGENTS.md и память дополнены.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 00:37:49 +05:00
d33ee71c78 PEP-324: казахский перевод шагов ключа действий в ревизии секретов
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 34с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1704с
peppa-ci / ci (pull_request) Successful in 30m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:47:14 +00:00
81fb6215da PEP-324: архив change, память
Some checks failed
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/bundle bundle: success за 0с
peppa/test test: failure за 1721с
peppa-ci / ci (pull_request) Failing after 31m20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:15:13 +00:00
a0979af39b PEP-324: постоянный ключ серверных действий и самообновление страницы при неизвестном действии
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:14:57 +00:00
cd8d797e6c Merge pull request 'PEP-322: папка агента с каталогами без права записи убирается' (#306) from task/pep-322 into main
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 38с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1733с
peppa-ci / ci (push) Successful in 31m24s
2026-11-27 17:55:45 +00:00
5ba612b571 PEP-322: папка агента с каталогами без права записи убирается
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 47с
peppa/build build: success за 33с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1689с
peppa-ci / ci (pull_request) Successful in 30m5s
Go делает каталоги кэша модулей (~/go/pkg/mod) только для чтения, и rmSync в уборке
папок агентов падал на них каждые 10 минут: на живом сервере так осталась папка первой же
задачи на Go (722 МБ, 2776 таких каталогов).

Уборка, получив отказ, возвращает владельцу права на настоящие каталоги внутри папки
(по ссылкам не ходит) и удаляет её повторно. Код отказа не разбирается: на Linux это
EACCES, на macOS — ENOTEMPTY.

Тест: папка с каталогами без права записи и ссылкой наружу. До правки падал.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 22:23:59 +05:00
4e1d981719 Merge pull request 'PEP-320: один демон исполнителя проверок на регистрацию' (#305) from task/pep-320 into main
All checks were successful
peppa/lint lint: success за 4с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 33с
peppa/bundle bundle: success за 1с
peppa/test test: success за 1706с
peppa-ci / ci (push) Successful in 30m51s
2026-11-27 14:30:01 +00:00
e227609a0d Merge pull request 'PEP-321: упавшее задание проверок перезапускается через пару минут' (#304) from task/pep-321 into main
PEP-321 [skip ci]
2026-11-27 14:29:57 +00:00
4ae203e037 PEP-320: один демон исполнителя проверок на регистрацию
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1652с
peppa-ci / ci (pull_request) Successful in 29m39s
supervise.sh пишет в .pid номер самого демона, журнал без буфера sed,
лишних демонов каталога останавливает SIGTERM; register.sh сначала
останавливает прежнего демона. Тест с mock-act-runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:42:33 +00:00
d4dd8f235b PEP-321: упавшее задание проверок перезапускается через пару минут, а не через полчаса
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 34с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1650с
peppa-ci / ci (pull_request) Successful in 29m34s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:39:41 +00:00
12af9b54bf Merge pull request 'PEP-314: Go и PostgreSQL — в песочнице агента, проверках и шаблоне выкладки' (#301) from task/pep-314 into main
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1705с
peppa-ci / ci (push) Successful in 31m21s
2026-11-27 12:36:22 +00:00
b411a65964 Merge pull request 'PEP-319: в сообщении о версии — только задачи, чьи коммиты в неё вошли' (#303) from task/pep-319 into main
PEP-319 [skip ci]
2026-11-27 12:36:18 +00:00
3a195f9980 PEP-314: помощник проверяет, что Go распаковался; тест не привязан к Linux
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 37с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1705с
peppa-ci / ci (pull_request) Successful in 30m46s
Приёмка координатора, полный локальный прогон на macOS: четыре теста «Go для проверок» ждали архив
для Linux, а помощник просит архив своей системы. Заодно нашёлся изъян самого помощника: когда
curl ничего не скачал, tar на macOS считает пустой поток пустым архивом — помощник сообщал об
успехе и ставил в PATH каталог без go. Теперь итог загрузки проверяется по самому файлу go.

Проверено: macOS — 13 из 13 (без правки скрипта «Go не скачался» падает); Linux, образ задания
проверок — обычная загрузка и отказ с кодом 1 при недоступном адресе.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 17:17:10 +05:00
40eda2ea6f Merge branch 'main' into task/pep-314
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1626с
peppa-ci / ci (pull_request) Successful in 29m30s
2026-11-27 12:04:01 +00:00
df565fa515 PEP-319: в сообщении о версии — только задачи, чьи коммиты в неё вошли
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1658с
peppa-ci / ci (pull_request) Successful in 29m48s
Список задач версии собирался из всего текста коммитов между версиями: задача, названная в
описании чужого коммита, попадала в сообщение канала как выпущенная (27.11.2026 — дважды).
Теперь считается только ключ в начале заголовка коммита или названия слитого PR.

Тест: коммит с упоминанием другой задачи в тексте и «Merge branch» — в списке только задачи версии;
до правки падали оба теста.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 16:56:28 +05:00
049b05ca19 Merge pull request 'PEP-318: «Принять всё» отвечает сразу, приёмка идёт в фоне' (#302) from task/pep-318 into main
All checks were successful
peppa/lint lint: success за 5с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 40с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1738с
peppa-ci / ci (push) Successful in 32m25s
2026-11-27 11:45:48 +00:00
700669380a Merge pull request 'PEP-317: страница «Gitea» не ждёт Git-сервер при заходе' (#300) from task/pep-317 into main
PEP-317 [skip ci]
2026-11-27 11:45:44 +00:00
13e5550de9 PEP-314: память — грабли с uid без passwd и *.go в шаблоне
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 54с
peppa/build build: success за 37с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1779с
peppa-ci / ci (pull_request) Successful in 32m3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:31:55 +00:00
b02c41ec80 PEP-314: замечания координатора — база у агента без записи в passwd (nss_wrapper), Dockerfile.golang, адрес базы ${ROUTER}-db, «go 1.27» = последний выпуск, stop без адреса, оценка времени
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1773с
peppa-ci / ci (pull_request) Successful in 32m0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:31:46 +00:00
9052c24c6a PEP-318: вместе с PEP-317 — в тестовом моке Gitea обе задержки ответа (общая и для поиска репозиториев)
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 40с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1739с
peppa-ci / ci (pull_request) Successful in 32m45s
Обе задачи правили одно место мока: ответ с задержкой. Объединено: задержка поиска и общая задержка
работают вместе, берётся большая.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 16:29:43 +05:00
bcee434ed9 PEP-318: недоступная служба запуска — не отказ; на паузе решение выполняется
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1637с
peppa-ci / ci (pull_request) Successful in 29m38s
Замечания координатора: RunnerUnavailableError оставляет задачу в очереди без причины,
веб отпускает аренду, вачдог доводит; проверка паузы убрана из processAcceptQueue
(отложенное по PEP-127 по-прежнему ждёт «Продолжить»). Тесты и спека.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:02:48 +00:00
217d0d44ac PEP-314: временная база под root — пользователь для базы создаётся, если его нет (PEPPA_PG_USER); тесты под root в проверках
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 40с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1656с
peppa-ci / ci (pull_request) Successful in 29m49s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:45:32 +00:00
8dce469bbc PEP-317: казахский перевод пометки «Список загружается»
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 34с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1673с
peppa-ci / ci (pull_request) Successful in 30m38s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:45:25 +00:00
1c3a11db3b PEP-318: «Принять всё» отвечает сразу, приёмка идёт в фоне по одной задаче
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1624с
peppa-ci / ci (pull_request) Successful in 29m7s
Очередь приёмки в settings (accept.queue / accept.run / accept.worker), веб запускает
обработку после ответа, вачдог доводит брошенную. Страница «Приёмка» показывает ход и итог.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:23:33 +00:00
004b9f3cca PEP-314: стандарт 1.1.0 — данные продукта и копии, команды проверок для Go; правила и AGENTS.md шаблона; archive
Some checks failed
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: failure за 1600с
peppa-ci / ci (pull_request) Failing after 28m54s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:15:18 +00:00
ec7345f483 PEP-317: страница «Gitea» не ждёт Git-сервер — список из памяти при любом возрасте, переживает перезапуск
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: failure за 1591с
peppa-ci / ci (pull_request) Failing after 28m44s
Последний список отдаётся сразу (старше минуты — обновление в фоне), хранится в settings
`gitea.overview` и прогревается при старте веба; без списка — «загружается». Ждёт Gitea
только «Получить заново» и «Сделать закрытым».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:13:36 +00:00
6df31deae0 PEP-314: шаблон выкладки Go + PostgreSQL — пароль базы на стенд, копия перед миграцией, тома превью уходят с превью
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:10:45 +00:00
a7f992dae2 PEP-314: помощник шаблона ставит Go и временную PostgreSQL для проверок без docker
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:06:52 +00:00
88d6ce4921 PEP-314: Go и PostgreSQL 18 в образе агента, дымовой тест их проверяет
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:05:34 +00:00
bb474b2a0a Merge pull request 'PEP-316: любая транзакция берёт блокировку записи первой — «database is locked» при записи из другого процесса' (#299) from task/pep-316 into main
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1605с
peppa-ci / ci (push) Successful in 29m9s
2026-11-27 08:21:00 +00:00
ae7400e4f1 PEP-316: любая транзакция берёт блокировку записи первой — «database is locked» при записи из другого процесса
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1639с
peppa-ci / ci (pull_request) Successful in 29m27s
27.11.2026 в 11:27 веб потерял отчёт шага проверки с ошибкой «database is locked»: в этот момент
в базу писал другой процесс. `db.transaction` по умолчанию начиналась как читающая (BEGIN), а
читающей транзакции SQLite не даёт ждать блокировку записи: первая запись получает отказ сразу,
busy_timeout не работает. Утренняя правка результата проверок обернула чтение и запись в такую
транзакцию и гонку не убрала; так же были устроены ещё 15 транзакций ядра (команда агентов,
подписки, чаты, журнал подключений).

- db/client.ts: транзакция всегда начинается с BEGIN IMMEDIATE — ждёт свою очередь и видит то,
  что сохранили другие.
- Тест db-write-lock.test.ts с настоящим вторым процессом (mock-db-writer держит блокировку
  записи): отчёт проверки и транзакция «прочитал — записал» ждут и сохраняются. До исправления
  оба случая падали той же ошибкой, что на проде, сразу и без ожидания.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 13:02:47 +05:00
57191981a2 Merge pull request 'PEP-315: «Дать: чтение» после истёкших полных прав не возвращает запись' (#298) from task/pep-315 into main
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 37с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1579с
peppa-ci / ci (push) Successful in 28m44s
2026-11-27 07:51:46 +00:00
7e84bfd9eb Merge pull request 'PEP-261: «Дать: чтение / полные права» и срок кнопками под запросом доступа агента' (#297) from task/pep-261 into main
Заход приёмки 27.11: PEP-261 перед исправлением PEP-315 [skip ci]
2026-11-27 07:51:42 +00:00
cb604d7a41 PEP-315: «Дать: чтение» после истёкших полных прав не возвращает запись
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 34с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1569с
peppa-ci / ci (pull_request) Successful in 28m8s
Приёмка PEP-261, 27.11.2026: агенту дали полные права на срок, срок вышел; на новый запрос
владелец нажал «Дать: чтение» — проект снова получил чтение и запись, а сообщение говорило
«чтение». `grantFor` расширял права по строке прошлой выдачи и не смотрел, действует ли она.
На живом сервере выдач ещё не было.

- core/access-requests.ts: прошлая выдача расширяет новую, только пока она действует
  (`grantState` = active); права и операции истёкшей или снятой «без дела» не возвращаются.
- Тест access-regrant.test.ts: истёкшие полные права и права, снятые «без дела» → «Дать: чтение»
  даёт только чтение (оба случая падали до исправления: writeMode auto вместо off);
  действующая выдача по-прежнему только расширяется.
- Спека access-hub: уточнение требования и сценарий «Чтение после истёкших полных прав».

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 12:20:45 +05:00
fd0db12629 Merge branch 'main' into task/pep-261
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 33с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1571с
peppa-ci / ci (pull_request) Successful in 28m45s
2026-11-27 07:13:58 +00:00
2bbeeab019 Merge pull request 'PEP-285: аудит стека FORGE относительно Default Stack' (#295) from task/pep-285 into main
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1623с
peppa-ci / ci (push) Successful in 29m15s
2026-11-27 06:34:19 +00:00
6b8e2d2892 Merge pull request 'PEP-284: новые проекты получают FORGE Default Stack в инструкциях агентов' (#294) from task/pep-284 into main
Заход приёмки 27.11: PEP-284 и PEP-285 после зелёных проверок [skip ci]
2026-11-27 06:34:14 +00:00
a1525081ab Заход приёмки 27.11: стыковка PEP-284 и PEP-285, пустые строки в двух спеках [skip ci]
- PEP-285 правит строку стандарта, PEP-284 требует, чтобы копия в шаблоне совпадала с ним:
  вместе тест «Копия стандарта в шаблоне отстала» падал. Ссылка на аудит записана путём
  в репозитории платформы (в копии проекта относительная ссылка вела бы в никуда), копия
  в template/ обновлена.
- Мой разборщик конфликтов слияния в блоках «обе стороны добавили» выбрасывал строки,
  уже встречавшиеся у другой стороны, в том числе пустые: в спеках gitea-integration
  (заход из 20 задач, PEP-281 и PEP-282) и engineering-standards (PEP-285) пропало 13 пустых
  строк. Возвращены, блоки требований сверены с текстом агентов. Других потерь нет:
  повтор всех 21 слияния показал только пустые строки.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 11:33:53 +05:00
b0674c1c2e Заход приёмки 27.11: PEP-285 поверх main и PEP-284 [skip ci] 2026-11-27 11:33:53 +05:00
5191f1e5fe Merge branch 'main' into task/pep-285
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 37с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1629с
peppa-ci / ci (pull_request) Successful in 29m20s
2026-11-27 06:25:17 +00:00
3bef77100e Merge branch 'main' into task/pep-284
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1632с
peppa-ci / ci (pull_request) Successful in 29m21s
2026-11-27 06:25:16 +00:00
92e7c6f85f PEP-261: тест кнопок выдачи, AGENTS.md, память, archive change
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1586с
peppa-ci / ci (pull_request) Successful in 28m31s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 06:15:39 +00:00
69cebe9b22 Merge pull request 'PEP-313: результат проверки пишется одной транзакцией — отчёт шага и опрос статусов не ломают друг друга' (#296) from task/pep-313 into main
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1643с
peppa-ci / ci (push) Successful in 30m7s
2026-11-27 05:59:55 +00:00
079df65255 PEP-261: кнопки «Дать: чтение / полные права» и срок под запросом доступа агента
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 05:55:51 +00:00
3785562d51 PEP-285: аудит стека FORGE относительно Default Stack
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1647с
peppa-ci / ci (pull_request) Successful in 29m33s
Отчёт docs/standards/forge-stack-audit.md (слои, статусы, DDD-Lite, PostgreSQL/UUIDv7,
Bugsink, Gitea/Forgejo, Docker, roadmap, решения владельцу), ссылка из стандарта, тест структуры.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 05:55:17 +00:00
73b4653e1f PEP-284: память проекта
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 37с
peppa/bundle bundle: success за 1с
peppa/test test: success за 1649с
peppa-ci / ci (pull_request) Successful in 29m38s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 05:55:05 +00:00
8052413375 PEP-284: стандарт стека в шаблоне новых проектов (AGENTS.md, RULES.md, копия стандарта, e2e через шаблон Gitea)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 05:54:56 +00:00
978ccfdd3e PEP-313: результат проверки пишется одной транзакцией — отчёт шага и опрос статусов не ломают друг друга
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 41с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1644с
peppa-ci / ci (pull_request) Successful in 29m56s
27.11.2026 в 02:32 веб ответил 500 на отчёт шага проверки: «UNIQUE constraint failed:
check_runs.project_id, check_runs.sha, check_runs.check». Отчёт шага (веб) и опрос статусов
(вачдог) писали одну проверку одного коммита одновременно: чтение шло отдельно от записи, оба не
видели строки, вторая вставка падала, отчёт с журналом терялся.

- core/ci.ts: `upsertCheckRun` — чтение и запись в одной синхронной транзакции (блокировка записи
  берётся первой); второй писатель видит строку первого, журнал отчёта сохраняется, «изменилось» —
  один раз.
- Тест project-tabs.test.ts: два одновременных отчёта — одна запись; до исправления падал той же
  ошибкой, что на проде.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 10:41:55 +05:00
b664e6ad7c Merge pull request 'PEP-304: подписки в лимите — не «нет подписки»; время людям — в поясе платформы' (#292) from task/pep-304 into main
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 54с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa-ci / ci (push) Has been cancelled
2026-11-27 05:31:19 +00:00
d5bcec2f95 Merge pull request 'PEP-298: ложный «конфликт» сразу после обновления ветки не зовёт агента' (#291) from task/pep-298 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:31:14 +00:00
690d0d59a2 Merge pull request 'PEP-294: хвосты после переезда — суперадмины по id, уборка токенов, сообщения фабрики закрываются сами, capacity_wait один раз' (#290) from task/pep-294 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:31:09 +00:00
59ac4ddb28 Merge pull request 'PEP-293: вход через eGov при сбоях сервиса подписи' (#289) from task/pep-293 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:31:05 +00:00
e9d1c68897 Merge pull request 'PEP-292: сообщение о новой версии FORGE без git в контейнере' (#288) from task/pep-292 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:31:00 +00:00
37cf2933c9 Merge pull request 'PEP-291: журналы сервисов переживают выкатку' (#287) from task/pep-291 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:54 +00:00
e712ecbaff Merge pull request 'PEP-283: FORGE Default Stack и принципы DDD-Lite' (#286) from task/pep-283 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:49 +00:00
efa7e4308c Merge pull request 'PEP-282: случайные падения проверок — таймаут к Gitea не съедает пауза процесса; список упавших тестов в отчёте; повтор тестов main' (#285) from task/pep-282 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:48 +00:00
ad6dd0a178 Merge pull request 'PEP-274: «Готовим ссылку» со сроком, поле чата на телефоне, свои заголовки вкладок' (#283) from task/pep-274 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:47 +00:00
8a6e9234b8 Merge pull request 'PEP-273: /gitea из кэша и по 50 строк, ссылки веба без предзагрузки' (#281) from task/pep-273 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:42 +00:00
664c9ef5e9 Merge pull request 'PEP-272: /api/health анониму — только ok; без X-Powered-By, script-src в CSP, аватар по https' (#282) from task/pep-272 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:40 +00:00
375ad25cd8 Merge pull request 'PEP-303: сторожа экрана не реагируют на текст в выводе агента' (#274) from task/pep-303 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:39 +00:00
98eddf376b Merge pull request 'PEP-302: отложенные находки приёмки видны и не теряются, поломки — в «Предложено» сразу' (#272) from task/pep-302 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:34 +00:00
eaca63aa0f Merge pull request 'PEP-281: старый Git — сверка 16 PR и 57 веток, ссылки на него убраны из платформы' (#276) from task/pep-281 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:32 +00:00
43176fc15d Merge pull request 'PEP-280: новые проекты закрытые по умолчанию; суперадмин закрывает публичные' (#273) from task/pep-280 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:31 +00:00
650d4e649e Merge pull request 'PEP-279: старые вопросы закрываются вариантом по умолчанию, «Принять» — одна сводка в день' (#271) from task/pep-279 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:26 +00:00
265c1d6052 Merge pull request 'PEP-260: Access Hub — агенту только текст, ключ bearer/header латиницей' (#250) from task/pep-260 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:25 +00:00
564c7a0217 Merge pull request 'PEP-250: Access Hub — агент сам просит доступ к сервису, владелец подключает ключ один раз' (#240) from task/pep-250 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:19 +00:00
7d0b3bcee8 Merge pull request 'PEP-217: Web Vitals пользователей и проверка веса JS в CI' (#206) from task/pep-217 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:30:17 +00:00
d6d5044e61 Merge pull request 'PEP-306: память проекта — файл на задачу, без конфликтов и красного теста размера' (#293) from task/pep-306 into main
Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
2026-11-27 05:29:58 +00:00
bc14e5824c Заход приёмки 27.11: стыковка задач между собой [skip ci]
Двадцать задач слиты одним заходом; три правила одной задачи ломались кодом другой:

- PEP-273 × PEP-250, PEP-279: три новых файла веба брали `next/link` напрямую — переведены на
  `@/components/Link` (сторож no-prefetch.test.ts).
- PEP-281 × PEP-272: адрес аватара в health-anon.test.ts и спеке web-auth — на git.vibe42.kz
  (сторож old-git-cleanup.test.ts не пускает старый адрес в репозиторий).
- PEP-217 × PEP-281: в observe.db миграции стали подряд (web_vitals — версия 4, монитор «Интернет» —
  версия 5); тест PEP-281 возвращал файл «к версии 3» и повторял чужую миграцию. Версия берётся по
  самой миграции (`observeMigrationIndex`).

Стыки, решённые при слиянии: страница /gitea и мок `/repos/search` (PEP-273 × PEP-280; после
«Сделать закрытым» страница берёт свежий список мимо кэша), импорты (PEP-250 × PEP-302,
PEP-279 × PEP-291, PEP-273 × PEP-304), память — файл на задачу по раскладке PEP-306.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 10:11:36 +05:00
d2124d8008 Заход приёмки 27.11: PEP-304 поверх main и принятых перед ней [skip ci] 2026-11-27 10:09:21 +05:00
787cde39f2 Заход приёмки 27.11: PEP-298 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:55 +05:00
f9881ea43f Заход приёмки 27.11: PEP-294 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:55 +05:00
c44f2db3f4 Заход приёмки 27.11: PEP-293 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:54 +05:00
5302e74fc8 Заход приёмки 27.11: PEP-292 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:54 +05:00
1c5fc6e072 Заход приёмки 27.11: PEP-291 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:54 +05:00
899570acf1 Заход приёмки 27.11: PEP-283 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:40 +05:00
d8b1fcfd5f Заход приёмки 27.11: PEP-282 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:39 +05:00
9a87f92d87 Заход приёмки 27.11: PEP-274 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:39 +05:00
4a15bcf551 Заход приёмки 27.11: PEP-273 поверх main и принятых перед ней [skip ci] 2026-11-27 10:08:39 +05:00
7373ad013d Заход приёмки 27.11: PEP-272 поверх main и принятых перед ней [skip ci] 2026-11-27 10:07:39 +05:00
22136ea160 Заход приёмки 27.11: PEP-303 поверх main и принятых перед ней [skip ci] 2026-11-27 10:06:37 +05:00
9b38dab378 Заход приёмки 27.11: PEP-302 поверх main и принятых перед ней [skip ci] 2026-11-27 10:06:36 +05:00
b52ccb4651 PEP-304: архив change, память проекта
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 35с
peppa/test test: success за 1489с
peppa-ci / ci (pull_request) Successful in 26m54s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:56:21 +00:00
020886eb1c PEP-304: подписки в лимите — не «нет подписки»; время людям — в поясе платформы
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:55:49 +00:00
d38719e213 PEP-298: ложный «конфликт» сразу после обновления ветки не зовёт агента; карточка считает проверки по списку версии
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 35с
peppa/test test: success за 1513с
peppa-ci / ci (pull_request) Successful in 27m19s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:34:13 +00:00
2a2405f588 PEP-294: archive change
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1512с
peppa-ci / ci (pull_request) Successful in 27m19s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:24:19 +00:00
ac17f79cc4 PEP-294: память — суперадмины по id
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:23:44 +00:00
f870bc7b67 PEP-294: суперадмины по id учётки, уборка токенов MCP, сообщения фабрики закрываются сами, capacity_wait один раз
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:22:28 +00:00
e30b3371f9 PEP-293: archive change
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 36с
peppa/test test: success за 1522с
peppa-ci / ci (pull_request) Successful in 27m26s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:19:02 +00:00
206083d127 PEP-294: proposal — хвосты после переезда на сервер
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:17:23 +00:00
c52ff4a4f1 PEP-293: вход через eGov — липкий запасной DNS, понятная фраза при недоступном сервисе подписи
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:17:02 +00:00
e2b06b5e80 PEP-292: версия FORGE для канала — из коммита выкатки и истории main в Gitea, без git в контейнере
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 35с
peppa/test test: success за 1527с
peppa-ci / ci (pull_request) Successful in 27m32s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:16:00 +00:00
8746d80ab3 Merge branch 'main' into task/pep-282
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 35с
peppa/test test: success за 1523с
peppa-ci / ci (pull_request) Successful in 27m33s
2026-11-26 21:49:14 +00:00
11261e4483 PEP-291: archive change, память проекта
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 35с
peppa/test test: success за 1521с
peppa-ci / ci (pull_request) Successful in 27m29s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:48:05 +00:00
eac871eac4 PEP-291: журналы сервисов в $PEPPA_HOME/logs с ротацией, путь в peppa status
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:47:39 +00:00
71cac58cf9 Merge branch 'main' into task/pep-272
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 36с
peppa/test test: success за 1538с
peppa-ci / ci (pull_request) Successful in 27m43s
2026-11-26 21:42:54 +00:00
c3f552b500 Merge branch 'main' into task/pep-273
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/test test: success за 1546с
peppa-ci / ci (pull_request) Successful in 27m51s
2026-11-26 21:41:33 +00:00
af218f76f5 PEP-283: archive change, память проекта
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1559с
peppa-ci / ci (pull_request) Successful in 28m3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:31:25 +00:00
8065c1936c PEP-283: FORGE Default Stack и принципы DDD-Lite
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:30:54 +00:00
0d539146ac Merge branch 'main' into task/pep-274
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 37с
peppa/test test: success за 1558с
peppa-ci / ci (pull_request) Successful in 28m5s
2026-11-26 21:26:33 +00:00
1341d61a05 PEP-272: тест зависшего раннера ждёт, пока экран устоится, вместо паузы 1,5 с
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 38с
peppa/test test: success за 1580с
peppa-ci / ci (pull_request) Successful in 28m35s
Под нагрузкой CI ответ мок-агента дорисовывался между тиками, вачдог видел активность.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:13:37 +00:00
d743b38f31 PEP-273: тест зависшего раннера ждёт, пока экран успокоится (нестабилен в CI)
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 35с
peppa/test test: success за 1590с
peppa-ci / ci (pull_request) Successful in 28m43s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:12:37 +00:00
227c911baa PEP-282: архив change, память проекта
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/test test: success за 1558с
peppa-ci / ci (pull_request) Successful in 28m7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:11:14 +00:00
d2372c631b PEP-282: отчёт проверки называет упавшие тесты; тесты main повторяются один раз
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:10:38 +00:00
a1717939da PEP-282: таймаут запроса к Gitea по отзывчивому времени — пауза процесса не обрывает готовый ответ
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:08:34 +00:00
76c40f7f40 PEP-274: archive change, память проекта
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 56с
peppa/test test: success за 1713с
peppa-ci / ci (pull_request) Successful in 30m59s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:55:09 +00:00
f117f7fb62 PEP-274: «Готовим ссылку» со сроком, поле чата на телефоне, заголовки вкладок
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:52:14 +00:00
ce03df667c PEP-272: /api/health анониму — только ok; без X-Powered-By, script-src в CSP, аватар по https
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 55с
peppa/build build: success за 35с
peppa/test test: failure за 1720с
peppa-ci / ci (pull_request) Failing after 31m5s
- /api/health без ключа X-Peppa-Health (HMAC от PEPPA_SECRET, принимается и PREVIOUS) отдаёт только {ok};
  ключ шлют сторож адреса, сторож отставания выкатки, healthcheck контейнеров, скрипты выкатки
- poweredByHeader: false; CSP: script-src 'self' 'unsafe-inline' (unsafe-eval только в dev), worker-src 'self'
- httpsAvatar: http → https при записи и показе
- тест health-anon.test.ts, change archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:36:06 +00:00
fdc88d587c PEP-273: архив change, память проекта
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 35с
peppa/test test: failure за 1734с
peppa-ci / ci (pull_request) Failing after 31m14s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:34:48 +00:00
f6ae77efe1 PEP-273: ссылки веба без предзагрузки — обёртка @/components/Link
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:34:02 +00:00
96fa6151ab PEP-273: /gitea — кэш списка, параллельные страницы, 50 строк на страницу
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:31:56 +00:00
bae36b82b7 Merge branch 'main' into task/pep-303
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 54с
peppa/build build: success за 38с
peppa/test test: success за 1843с
peppa-ci / ci (pull_request) Successful in 33m29s
2026-11-26 19:42:49 +00:00
a1dcb10daf Merge branch 'main' into task/pep-302
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 38с
peppa/test test: success за 1861с
peppa-ci / ci (pull_request) Successful in 34m9s
2026-11-26 19:37:44 +00:00
d198818996 PEP-303: память проекта, archive change
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 34с
peppa/test test: success за 1652с
peppa-ci / ci (pull_request) Successful in 29m51s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:10:07 +00:00
63ef12a100 PEP-303: плашка лимита — до двух значков CLI перед фразой; задачи отмечены
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:09:28 +00:00
7d5adcdfe1 PEP-302: архив change, спека agent-task-origin
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/test test: success за 1657с
peppa-ci / ci (pull_request) Successful in 29m57s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:06:58 +00:00
fb7d6e1b62 PEP-302: память — грабли мока проверки на повтор
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:06:46 +00:00
0c50be58f6 PEP-302: отложенные находки приёмки видны и не теряются, поломки — в «Предложено» сразу
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:06:31 +00:00
311aad4c90 PEP-303: сторожа экрана читают только строки CLI, не вывод инструментов агента
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:05:39 +00:00
385 changed files with 11630 additions and 619 deletions

View File

@ -20,7 +20,7 @@ jobs:
# The runner has the host's docker.sock: only branches of this repository, never forks. # 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 if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: peppa-trusted runs-on: peppa-trusted
timeout-minutes: 30 timeout-minutes: 45
env: env:
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source # 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. # for the Postgres → SQLite migration test, which makes and drops its own database.

4
.peppa/memory/pep-261.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-261
## Грабли
- Тесты с агентом-моком (access-requests, bot) в песочнице молча висят по 25 с на Node 22 — нужен Node 26 из tarball и tmux из .deb в PATH/LD_LIBRARY_PATH (PEP-261).

4
.peppa/memory/pep-272.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-272
## Решения
- `/api/health` анониму — только `{ok}` (PEP-272); сводку читать с `healthHeaders()` / `scripts/lib/health-token.sh`.

4
.peppa/memory/pep-273.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-273
## Соглашения
- Ссылки веба — только `Link` из `@/components/Link` (предзагрузка выкл., PEP-273; тест no-prefetch); медленная страница из-за Gitea — кэш в globalThis, как `giteaServerOverview`.

4
.peppa/memory/pep-274.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-274
## Решения
- Заголовок вкладки (PEP-274) — `pageTitle`/`projectTitle`/`taskTitle` (apps/web/lib/title.ts); page.tsx без `generateMetadata` роняет page-titles.test.ts.

4
.peppa/memory/pep-282.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-282
## Грабли
- Таймаут запроса в процессе с моком-сервером: синхронная пауза дольше таймаута обрывает готовый ответ (таймеры libuv раньше сокетов) — `responsiveTimeout` (core, PEP-282), не `AbortSignal.timeout`.

4
.peppa/memory/pep-283.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-283
## Решения
- Стек новых проектов — docs/standards/default-stack.md (PEP-283).

4
.peppa/memory/pep-284.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-284
## Соглашения
- Стандарт стека в шаблоне (PEP-284): template/docs/standards/default-stack.md — побайтная копия docs/standards/default-stack.md (тест template-default-stack); правишь стандарт — копируй в template/.

4
.peppa/memory/pep-285.md Normal file
View File

@ -0,0 +1,4 @@
# Память: 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).

4
.peppa/memory/pep-291.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-291
## Грабли
- Песочница раннера: Node 22.23 тянет одиночные тесты (PEP-291).

4
.peppa/memory/pep-292.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-292
## Грабли
- В образе платформы нет `.git` (PEP-292): `git` в коде службы не звать; коммит — `PEPPA_COMMIT`, история main — Gitea API.

4
.peppa/memory/pep-294.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-294
## Решения
- Суперадмины (PEP-294): `platform.admins` — id учёток (строка = логин без учётки, привязывается при чтении); проверка — `superadminIds`/`platformAdminUsers`, не сравнение логинов.

4
.peppa/memory/pep-298.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-298
## Соглашения
- Конфликт PR с main: первая просьба — после второго наблюдения через 2 мин (PEP-298, в тестах `PEPPA_CONFLICT_SETTLE_MIN=0`).

4
.peppa/memory/pep-302.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-302
## Грабли
- mock-intake `dedup` считает похожие названия («Идея 1»/«Идея 2») повтором — в тестах приёмки бери разные слова.

4
.peppa/memory/pep-303.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-303
## Грабли
- Сторож экрана (PEP-303): строки — через `screen-lines.ts` (`isQuotedLine`/`ownLines`), фразу CLI якорить к началу строки, нажимать только на неизменном экране (`still`). Мок `say` печатает «⏺ » перед текстом.

4
.peppa/memory/pep-304.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-304
## Соглашения
- Время людям (PEP-304) — только `platformTime`/`platformDayTime`/`platformZone` из `@peppa/shared/time`; `toLocale*String` для дат без `timeZone` не писать. Лимит в `claudePrint` — `limited`/`limitedUntil`, не «нет подписки».

7
.peppa/memory/pep-314.md Normal file
View File

@ -0,0 +1,7 @@
# Память: 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).

4
.peppa/memory/pep-315.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-315
## Грабли
- Строка `connection_grants` остаётся после конца срока и после снятия «без дела»: читая «прошлую выдачу», проверяй `grantState(row, now) === "active"`, иначе вернёшь права, которых уже нет (PEP-315: «Дать: чтение» возвращало запись).

5
.peppa/memory/pep-316.md Normal file
View File

@ -0,0 +1,5 @@
# Память: 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).

4
.peppa/memory/pep-317.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-317
## Соглашения
- Список «Gitea» (PEP-317): отдаётся сразу при любом возрасте, хранится в `settings` `gitea.overview`, прогрев — `warmGiteaOverview` в instrumentation.ts; ждёт Gitea только `fresh`. В тестах — `giteaOverviewSettled()`, медленная Gitea — `MockGitea.searchDelayMs`.

7
.peppa/memory/pep-318.md Normal file
View File

@ -0,0 +1,7 @@
# Память: 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).

7
.peppa/memory/pep-319.md Normal file
View File

@ -0,0 +1,7 @@
# Память: PEP-319
## Соглашения
- Состав задач в сообщении о версии (`storiesIn`, runner/platform-build.ts) — только ключ в начале заголовка коммита («PEP-318: …», «PEP-284, PEP-285: …») или названия слитого PR. Упоминание другой задачи в тексте коммита версию не «выпускает».
## Грабли
- 27.11.2026 канал дважды назвал задачи, вышедшие раньше: PEP-281 и PEP-282 (утро), PEP-127 (вечер) — их ключи стояли в тексте коммитов других задач. Сообщение из канала не отозвать.

4
.peppa/memory/pep-320.md Normal file
View File

@ -0,0 +1,4 @@
# Память: 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`.

4
.peppa/memory/pep-321.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-321
## Соглашения
- Упавшее задание проверок (PEP-321): `checksQueueTick` до порога очереди через 2 мин (`EARLY_JOB_MS`) переоткрывает PR (`reopenFailedJob`, общий счётчик `reopened` с поздним путём, ≤2 на коммит, пауза 10 мин) — без `stuck`, задержки, сообщения суперадмину и агенту; `pending` до порога не трогается.

9
.peppa/memory/pep-322.md Normal file
View File

@ -0,0 +1,9 @@
# Память: 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, ему права каталогов не мешают: тест на это падает без правки только у обычного пользователя (локальный прогон).

11
.peppa/memory/pep-324.md Normal file
View File

@ -0,0 +1,11 @@
# Память: 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 не увидели ни чужую карточку, ни пропавшие ошибки.

File diff suppressed because one or more lines are too long

View File

@ -80,8 +80,8 @@ import {
} from "@peppa/core"; } from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db"; import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared"; import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
import { delayAction, denyAccessRequestAndTell, resolveTaskById } from "@peppa/runner"; import { delayAction, denyAccessRequestAndTell, grantAccessRequestByButton, resolveTaskById } from "@peppa/runner";
import { decideIdleGrant, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core"; import { accessButtonTarget, accessRequestKeyboard, decideIdleGrant, GRANT_TERM_TEXT, NO_CONNECTION_TEXT, parseAccessCallback, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner"; import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
import { INTENT_TEXT, statusAnswer } from "@peppa/core"; import { INTENT_TEXT, statusAnswer } from "@peppa/core";
import { AsyncLocalStorage } from "node:async_hooks"; import { AsyncLocalStorage } from "node:async_hooks";
@ -978,6 +978,39 @@ export function createBot(o: BotOptions) {
return "done"; return "done";
} }
/** PEP-261: «Дать: чтение / полные права» → term → grant; «Назад»; «Отказать». The owner only (core: accessRequestForUser). */
async function onAccessButton(user: User, c: TgCallbackQuery): Promise<string> {
const b = parseAccessCallback(c.data ?? "");
if (!b) return tr("Неизвестная кнопка");
const keyboard = (inline_keyboard: unknown[]) =>
c.message ? api.call("editMessageReplyMarkup", { chat_id: c.message.chat.id, message_id: c.message.message_id, reply_markup: { inline_keyboard } }).catch(() => {}) : Promise.resolve();
if (b.action === "no") {
await denyAccessRequestAndTell(db, user.id, b.id, null);
await keyboard([]);
return tr("Отказано. Агент узнает об этом.");
}
if (b.action === "back") {
const canGrant = await accessButtonTarget(db, user.id, b.id).then(
() => true,
(e) => {
if (e instanceof PeppaError && e.message === NO_CONNECTION_TEXT) return false;
throw e;
},
);
await keyboard(accessRequestKeyboard(b.id, { step: "rights", canGrant }));
return tr("Выберите, что дать агенту");
}
if (b.action === "rights") {
await accessButtonTarget(db, user.id, b.id); // not the owner, decided already or no connection → the refusal is the toast
await keyboard(accessRequestKeyboard(b.id, { step: "term", rights: b.rights }));
return tr("Выберите срок");
}
await grantAccessRequestByButton(db, user.id, b.id, { rights: b.rights, term: b.term });
await keyboard([]);
const what = b.rights === "full" ? tr("полные права") : tr("чтение");
return tr("Готово: {what}, {term}. Агент узнает об этом.", { what, term: GRANT_TERM_TEXT[b.term] });
}
async function onDelayButton(user: User, data: string): Promise<string> { async function onDelayButton(user: User, data: string): Promise<string> {
const b = parseDelayCallback(data); const b = parseDelayCallback(data);
if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка"); if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка");
@ -1019,12 +1052,10 @@ export function createBot(o: BotOptions) {
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done"; return "done";
} }
// PEP-250: «Отказать» under an agent's access request: `ar:<id>:no` — only the project's owner (core checks). // PEP-250/261: buttons under an agent's access request — `ar:<id>:no` (refuse), `ar:<id>:r|f` (rights →
// term buttons), `ar:<id>:r|f:<term>` (grant), `ar:<id>:back`. Only the project's owner (core checks).
if (parts[0] === "ar") { if (parts[0] === "ar") {
const toast = await denyAccessRequestAndTell(db, user.id, Number(parts[1]), null).then( const toast = await onAccessButton(user, c).catch((e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
() => tr("Отказано. Агент узнает об этом."),
(e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))),
);
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done"; return "done";
} }

View File

@ -2,7 +2,7 @@
import { createDb } from "@peppa/db"; import { createDb } from "@peppa/db";
import { loadEnv } from "@peppa/shared"; import { loadEnv } from "@peppa/shared";
import { setRunnerClient } from "@peppa/runner"; import { setRunnerClient } from "@peppa/runner";
import { installCrashReporting } from "@peppa/core"; import { installCrashReporting, installServiceLog } from "@peppa/core";
import { createBot } from "./bot.ts"; import { createBot } from "./bot.ts";
import { TelegramApi } from "./telegram.ts"; import { TelegramApi } from "./telegram.ts";
@ -16,6 +16,8 @@ const db = createDb(env.PEPPA_DB);
setRunnerClient(true, db); setRunnerClient(true, db);
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it. // PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
installCrashReporting(db, "bot"); installCrashReporting(db, "bot");
// PEP-291: the log also goes to $PEPPA_HOME/logs/bot.log — it survives a redeploy.
installServiceLog("bot");
const bot = createBot({ const bot = createBot({
db, db,
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL), api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),

View File

@ -1,13 +1,15 @@
// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202. // Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202.
import { createDb } from "@peppa/db"; import { createDb } from "@peppa/db";
import { loadEnv } from "@peppa/shared"; import { loadEnv } from "@peppa/shared";
import { installCrashReporting, setDefaultActor } from "@peppa/core"; import { installCrashReporting, installServiceLog, setDefaultActor } from "@peppa/core";
import { runObserver } from "./observer.ts"; import { runObserver } from "./observer.ts";
const env = loadEnv(); const env = loadEnv();
const db = createDb(env.PEPPA_DB); const db = createDb(env.PEPPA_DB);
setDefaultActor({ kind: "system" }); setDefaultActor({ kind: "system" });
installCrashReporting(db, "observer"); 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(); const ac = new AbortController();
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => (ac.abort(), setTimeout(() => process.exit(0), 200))); 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); await runObserver(db, { log: (m) => console.log(`${new Date().toISOString()} ${m}`) }, ac.signal);

View File

@ -71,12 +71,13 @@ import {
} from "@peppa/core"; } 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 { 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 { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestFromExisting } from "@peppa/runner"; import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestByButton, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
import { bugsinkFromEnv } from "@peppa/bugsink"; import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared"; import { loadEnv } from "@peppa/shared";
import { pauseProject, resumeProject, acceptAll, 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 { 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 { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { after } from "next/server";
import { asWebActor, requireUser, words } from "@/lib/auth"; import { asWebActor, requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
@ -211,8 +212,9 @@ export async function acceptStoryAction(f: FormData) {
} }
/** /**
* PEP-209: «Принять» / «Принять всё» on the acceptance page — one by one, a failure of one doesn't * PEP-209: «Принять» / «Принять всё» on the acceptance page. PEP-318: the decision is queued and
* stop the others; the page shows the result («Принято 6, на доработке 1…»). * 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) { export async function acceptAllAction(f: FormData) {
const user = asWebActor(await requireUser()); const user = asWebActor(await requireUser());
@ -227,8 +229,10 @@ export async function acceptAllAction(f: FormData) {
if (ref.task.status === "review") refs.push(ref); if (ref.task.status === "review") refs.push(ref);
} }
if (!refs.length) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу")); if (!refs.length) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу"));
const r = await acceptAll(db, refs, "web"); startAcceptAll(db, refs, user.id, "web");
return `${base}?ok=${r.accepted.length}&pending=${r.pending.length}&failed=${r.failed.length}`; const projectId = refs[0]!.project.id;
after(() => processAcceptQueue(db, projectId).catch(() => 0));
return base;
}); });
} }
@ -543,6 +547,16 @@ export async function proposalAction(f: FormData) {
}); });
} }
/** 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. */ /** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */
export async function setAcceptOwnAction(f: FormData) { export async function setAcceptOwnAction(f: FormData) {
const user = asWebActor(await requireUser()); const user = asWebActor(await requireUser());
@ -1131,6 +1145,12 @@ export async function setConnectionIdleAction(f: FormData) {
}); });
} }
// 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). // PEP-250: an agent's access request — only its project's owner decides (core checks).
export async function connectAccessRequestAction(f: FormData) { export async function connectAccessRequestAction(f: FormData) {
const user = asWebActor(await requireUser()); const user = asWebActor(await requireUser());
@ -1143,7 +1163,7 @@ export async function connectAccessRequestAction(f: FormData) {
secret: String(f.get("secret") ?? "").trim(), secret: String(f.get("secret") ?? "").trim(),
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer", authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
authHeader: str(f, "authHeader") || null, authHeader: str(f, "authHeader") || null,
}); }, grantChoice(f));
const r = await checkConnection(db, user.id, connection.id).catch(() => null); const r = await checkConnection(db, user.id, connection.id).catch(() => null);
return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`; return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
}); });
@ -1153,7 +1173,17 @@ export async function grantAccessRequestAction(f: FormData) {
const user = asWebActor(await requireUser()); const user = asWebActor(await requireUser());
await attempt(f, async () => { await attempt(f, async () => {
const id = Number(str(f, "requestId")); const id = Number(str(f, "requestId"));
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId"))); 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`; return `/connections/requests/${id}?done=granted`;
}); });
} }

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react"; import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
import { ANALYST_NAME, analystPending, attachmentsByMessage, chatStatusLine, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, splitForDisplay, syncChats, threadTitle, THREAD_KEY, type AttachmentView, type ChatMessageView, type Question } from "@peppa/core"; import { ANALYST_NAME, analystPending, attachmentsByMessage, chatStatusLine, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, splitForDisplay, syncChats, threadTitle, THREAD_KEY, type AttachmentView, type ChatMessageView, type Question } from "@peppa/core";
@ -21,12 +21,13 @@ import { AttachField } from "@/components/AttachField";
import { Workspace } from "@/components/Workspace"; import { Workspace } from "@/components/Workspace";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input"; import { Textarea } from "@/components/ui/input";
import { requireUser, words } from "@/lib/auth"; import { currentUser, requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text"; import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions"; import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
import { pageTitle } from "@/lib/title";
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string }; type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
@ -34,6 +35,16 @@ const CHANNEL = "channel";
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */ /** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
const FEED = "feed"; const FEED = "feed";
// PEP-274: «Чат KEY — FORGE» (the chat list of the viewer — no names of chats they cannot see).
export async function generateMetadata({ params }: { params: Promise<{ chat: string }> }) {
const t = await getT();
const user = await currentUser();
const slug = (await params).chat;
const chat = user ? (await listChats(db, user)).find((c) => c.slug.toLowerCase() === slug.toLowerCase()) : null;
if (!chat) return pageTitle(t, t("Чаты"));
return pageTitle(t, chat.kind === "master" ? t("Все события") : t("Чат {key}", { key: chat.slug.toUpperCase() }));
}
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */ /** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) { export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
const user = await requireUser(); const user = await requireUser();
@ -338,11 +349,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
{writable && ( {writable && (
<form action={postChatAction} data-chat-composer className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-20 -mx-1 flex flex-col gap-1 rounded-lg border bg-card p-2 shadow-md md:bottom-3"> <form action={postChatAction} data-chat-composer className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-20 -mx-1 flex flex-col gap-1 rounded-lg border bg-card p-2 shadow-md md:bottom-3">
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} /> <Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
<div className="flex items-end gap-1.5"> {/* PEP-274 (F-12): on a phone the field takes the whole row (the hint is not cut), the buttons go below, each ≥ 44 px. */}
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-9 flex-1 resize-y py-1.5" /> <div className="flex flex-wrap items-end gap-1.5 md:flex-nowrap">
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" />} <Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-[4.25rem] flex-1 basis-full resize-y py-1.5 [field-sizing:content] md:min-h-9 md:basis-0" data-chat-text />
<Dictate target="chat-text" compact /> {chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" touch />}
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="h-9"> <Dictate target="chat-text" compact touch />
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="ml-auto size-11 md:ml-0 md:h-9 md:w-auto" data-chat-send>
<Send /> <Send />
</Button> </Button>
</div> </div>

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { ArrowRight, MessagesSquare } from "lucide-react"; import { ArrowRight, MessagesSquare } from "lucide-react";
import { chatOverview, isRoleName, syncChats } from "@peppa/core"; import { chatOverview, isRoleName, syncChats } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh"; import { LiveRefresh } from "@/components/LiveRefresh";

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { ExternalLink, PlugZap, Search } from "lucide-react"; import { ExternalLink, PlugZap, Search } from "lucide-react";
import { import {
CATALOG_KIND_TEXT, CATALOG_KIND_TEXT,
@ -18,6 +18,7 @@ import {
listConnections, listConnections,
listUserProjects, listUserProjects,
ownerAccessRequests, ownerAccessRequests,
connectionsForRequest,
oauthOffer, oauthOffer,
scopeLabel, scopeLabel,
searchCatalog, searchCatalog,
@ -652,6 +653,8 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
const t = await getT(); const t = await getT();
const engineer = (await uiMode()) === "engineer"; const engineer = (await uiMode()) === "engineer";
const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]); const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
// PEP-261: «Дать» right in the list — only where a fitting connection exists.
const grantable = new Set((await Promise.all(requests.map(async (r) => ((await connectionsForRequest(db, user.id, r)).fit.length ? r.id : 0)))).filter(Boolean));
const proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined; const proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined;
const chosen = q.service === "custom" ? "custom" : catalogService(q.service); const chosen = q.service === "custom" ? "custom" : catalogService(q.service);
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null; const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
@ -668,7 +671,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
{requests.length > 0 && ( {requests.length > 0 && (
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}> <Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
<AccessRequestList list={requests} t={t} /> <AccessRequestList list={requests} grantable={grantable} t={t} />
</Section> </Section>
)} )}

View File

@ -1,9 +1,9 @@
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { ExternalLink, KeyRound } from "lucide-react"; import { ExternalLink, KeyRound } from "lucide-react";
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core"; import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n"; import type { Translator } from "@peppa/shared/i18n";
import { AccessStatus, accessModeText } from "@/components/AccessRequests"; import { AccessStatus, accessModeText, GrantRightsSelect, GrantTermSelect } from "@/components/AccessRequests";
import { Hidden } from "@/components/cards"; import { Hidden } from "@/components/cards";
import { Flash, Notice, PageHeader, Section } from "@/components/common"; import { Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@ -42,6 +42,17 @@ function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Tran
); );
} }
/** PEP-261: rights and term of the grant (1 day by default). */
function GrantFields({ r, t }: { r: AccessRequestView; t: Translator }) {
return (
<div className="flex flex-wrap items-center gap-2 text-sm">
<GrantRightsSelect r={r} t={t} />
<span className="text-muted-foreground">{t("на срок")}</span>
<GrantTermSelect t={t} />
</div>
);
}
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) { function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
const back = `/connections/requests/${r.id}`; const back = `/connections/requests/${r.id}`;
return ( return (
@ -76,6 +87,7 @@ function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogServic
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} /> <Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
</div> </div>
)} )}
<GrantFields r={r} t={t} />
<Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button> <Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button>
</form> </form>
</li> </li>
@ -97,6 +109,7 @@ function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: Connect
</option> </option>
))} ))}
</select> </select>
<GrantFields r={r} t={t} />
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button> <Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
</form> </form>
); );
@ -155,9 +168,7 @@ export default async function AccessRequestPage({ params, searchParams }: { para
<Card className="p-4"> <Card className="p-4">
<ConnectForm r={r} card={card} t={t} /> <ConnectForm r={r} card={card} t={t} />
<p className="m-0 mt-3 text-xs text-muted-foreground"> <p className="m-0 mt-3 text-xs text-muted-foreground">
{r.mode === "write" {t("Агенты проекта получат выбранный доступ на выбранный срок. Изменить, продлить или отозвать доступ можно в разделе «Подключения».")}
? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
: t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
</p> </p>
</Card> </Card>
</Section> </Section>

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Hourglass } from "lucide-react"; import { Hourglass } from "lucide-react";
import { isSuperadmin, platformDelayOverview } from "@peppa/core"; import { isSuperadmin, platformDelayOverview } from "@peppa/core";

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Gauge } from "lucide-react"; import { Gauge } from "lucide-react";
import { isSuperadmin, platformDashboard, platformDelayCounts, type DashboardCounts } from "@peppa/core"; import { isSuperadmin, platformDashboard, platformDelayCounts, type DashboardCounts } from "@peppa/core";

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { MessageCircleQuestion } from "lucide-react"; import { MessageCircleQuestion } from "lucide-react";
import { isSuperadmin } from "@peppa/core"; import { isSuperadmin } from "@peppa/core";

View File

@ -1,7 +1,8 @@
// PEP-218: the card of one production error, read from Bugsink on the server. The superadmin // PEP-218: the card of one production error, read from Bugsink on the server. The superadmin
// opens any error, a project's owner or member — errors of that project only (else 404). // opens any error, a project's owner or member — errors of that project only (else 404).
// «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink. // «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink.
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Bug, ExternalLink } from "lucide-react"; import { Bug, ExternalLink } from "lucide-react";
import { errorDetail, errorScope } from "@peppa/core"; import { errorDetail, errorScope } from "@peppa/core";
@ -46,8 +47,8 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
<ErrorStateBadge state={r.state} t={t} /> <ErrorStateBadge state={r.state} t={t} />
<span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span> <span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
{d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null} {d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null}
<span className="text-muted-foreground" title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span> <span className="text-muted-foreground" title={r.firstSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
<span className="text-muted-foreground" title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span> <span className="text-muted-foreground" title={r.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
</div> </div>
<div className="text-sm"> <div className="text-sm">
{r.taskKey ? ( {r.taskKey ? (
@ -109,7 +110,7 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm"> <ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{d.events.map((e) => ( {d.events.map((e) => (
<li key={e.id} className="flex gap-3"> <li key={e.id} className="flex gap-3">
<span className="tabular-nums">{e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium" })}</span> <span className="tabular-nums">{e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium", timeZone: platformZone() })}</span>
<span className="font-mono text-xs text-muted-foreground">{e.id.slice(0, 8)}</span> <span className="font-mono text-xs text-muted-foreground">{e.id.slice(0, 8)}</span>
</li> </li>
))} ))}

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { FEEDBACK_ADMIN_STATUS, FEEDBACK_STATUSES, isFeedbackStatus, isSuperadmin, listAllFeedback, listUserFeedback } from "@peppa/core"; import { FEEDBACK_ADMIN_STATUS, FEEDBACK_STATUSES, isFeedbackStatus, isSuperadmin, listAllFeedback, listUserFeedback } from "@peppa/core";
import { AdminFeedbackCard, MyFeedbackCard } from "@/components/Feedback"; import { AdminFeedbackCard, MyFeedbackCard } from "@/components/Feedback";
import { Empty, Flash, PageHeader, Section } from "@/components/common"; import { Empty, Flash, PageHeader, Section } from "@/components/common";
@ -7,11 +7,14 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Обращения"));
}
/**
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
* also sees everybody's, filtered by status, and decides on them.
*/
export default async function FeedbackPage({ searchParams }: { searchParams: Promise<{ error?: string; status?: string; id?: string }> }) { export default async function FeedbackPage({ searchParams }: { searchParams: Promise<{ error?: string; status?: string; id?: string }> }) {
const user = await requireUser(); const user = await requireUser();
const t = await getT(); const t = await getT();
@ -50,3 +53,8 @@ export default async function FeedbackPage({ searchParams }: { searchParams: Pro
</Workspace> </Workspace>
); );
} }
/**
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
* also sees everybody's, filtered by status, and decides on them.
*/

View File

@ -20,6 +20,8 @@ export async function makeRepoPrivateAction(f: FormData) {
await requireSuperadmin(db, user); await requireSuperadmin(db, user);
const r = await makeRepoPrivate(db, user, str(f, "repo")); const r = await makeRepoPrivate(db, user, str(f, "repo"));
back.set("closed", r.fullName); back.set("closed", r.fullName);
// The list is cached (PEP-273): without a fresh one the repository would still show as public for a minute.
back.set("fresh", "1");
} catch (e) { } catch (e) {
const t = await getT(); const t = await getT();
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message }); const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });

View File

@ -1,5 +1,5 @@
// glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here // glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { ExternalLink, GitBranch, Lock } from "lucide-react"; import { ExternalLink, GitBranch, Lock } from "lucide-react";
import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core"; import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core";
@ -20,9 +20,12 @@ export async function generateMetadata() {
return { title: t("Gitea — FORGE") }; return { title: t("Gitea — FORGE") };
} }
type Params = { q?: string; show?: string; closed?: string; error?: string }; type Params = { q?: string; show?: string; closed?: string; error?: string; page?: string; fresh?: string };
type Show = "all" | "linked" | "unlinked" | "public"; type Show = "all" | "linked" | "unlinked" | "public";
/** Rows per page (PEP-273: the whole list made the page over 1 MB). */
const PAGE_SIZE = 50;
function RepoRow({ r, t, q, show }: { r: GiteaServerRepo; t: Translator; q: string; show: Show }) { function RepoRow({ r, t, q, show }: { r: GiteaServerRepo; t: Translator; q: string; show: Show }) {
return ( return (
<li className="flex flex-col gap-1 border-b border-border px-4 py-3 last:border-b-0"> <li className="flex flex-col gap-1 border-b border-border px-4 py-3 last:border-b-0">
@ -75,7 +78,7 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
const t = await getT(); const t = await getT();
if (!(await isSuperadmin(db, user))) notFound(); if (!(await isSuperadmin(db, user))) notFound();
const q = await searchParams; const q = await searchParams;
const o = await giteaServerOverview(db); const o = await giteaServerOverview(db, { fresh: q.fresh === "1" });
const needle = (q.q ?? "").trim().toLowerCase(); const needle = (q.q ?? "").trim().toLowerCase();
const show: Show = q.show === "linked" || q.show === "unlinked" || q.show === "public" ? q.show : "all"; const show: Show = q.show === "linked" || q.show === "unlinked" || q.show === "public" ? q.show : "all";
const repos = o.repos.filter( const repos = o.repos.filter(
@ -84,6 +87,17 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
(show === "all" || (show === "public" ? !r.private : (show === "linked") === !!r.project)), (show === "all" || (show === "public" ? !r.private : (show === "linked") === !!r.project)),
); );
const open = o.repos.filter((r) => !r.private).length; const open = o.repos.filter((r) => !r.private).length;
const pages = Math.max(1, Math.ceil(repos.length / PAGE_SIZE));
const page = Math.min(pages, Math.max(1, Number.parseInt(q.page ?? "1", 10) || 1));
const shown = repos.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
const href = (extra: Record<string, string>) => {
const sp = new URLSearchParams();
if (q.q) sp.set("q", q.q);
if (show !== "all") sp.set("show", show);
for (const [k, v] of Object.entries(extra)) sp.set(k, v);
const s = sp.toString();
return s ? `/gitea?${s}` : "/gitea";
};
const owners = new Map<string, number>(); const owners = new Map<string, number>();
for (const r of o.repos) owners.set(r.owner, (owners.get(r.owner) ?? 0) + 1); for (const r of o.repos) owners.set(r.owner, (owners.get(r.owner) ?? 0) + 1);
const linked = o.repos.filter((r) => r.project).length; const linked = o.repos.filter((r) => r.project).length;
@ -111,6 +125,12 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
{t("Бот")}: <span className="font-mono">{o.bot?.login ?? "—"}</span> {t("Бот")}: <span className="font-mono">{o.bot?.login ?? "—"}</span>
{o.bot && (o.bot.admin ? <Badge variant="ok" className="ml-2">{t("админ сервера — видит все репозитории")}</Badge> : <Badge variant="warn" className="ml-2">{t("не админ — видит публичные и свои репозитории")}</Badge>)} {o.bot && (o.bot.admin ? <Badge variant="ok" className="ml-2">{t("админ сервера — видит все репозитории")}</Badge> : <Badge variant="warn" className="ml-2">{t("не админ — видит публичные и свои репозитории")}</Badge>)}
</div> </div>
{o.fetchedAt && (
<div className="text-muted-foreground">
{t("Список получен {when}", { when: ago(o.fetchedAt, t) })} ·{" "}
<a href={href({ fresh: "1" })}>{t("Получить заново")}</a>
</div>
)}
{o.repos.length > 0 && ( {o.repos.length > 0 && (
<div className="text-muted-foreground"> <div className="text-muted-foreground">
{t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "} {t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "}
@ -132,6 +152,12 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
{q.closed && <Notice>{t("{repo} теперь закрытый: его видят только владелец, участники и бот", { repo: q.closed })}</Notice>} {q.closed && <Notice>{t("{repo} теперь закрытый: его видят только владелец, участники и бот", { repo: q.closed })}</Notice>}
<Flash error={q.error} /> <Flash error={q.error} />
{o.error && <Notice>{t("Gitea не ответила: {error}", { error: o.error })}</Notice>} {o.error && <Notice>{t("Gitea не ответила: {error}", { error: o.error })}</Notice>}
{o.loading && (
// PEP-317: the page does not wait for the Git server — the list is loaded in the background.
<Notice>
{t("Список репозиториев загружается — это может занять несколько секунд.")} <a href={href({})}>{t("Обновить")}</a>
</Notice>
)}
<Section title={t("Репозитории")} count={repos.length}> <Section title={t("Репозитории")} count={repos.length}>
<form className="mb-3 flex flex-wrap items-center gap-2" action="/gitea"> <form className="mb-3 flex flex-wrap items-center gap-2" action="/gitea">
@ -146,17 +172,24 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
{t("Показать")} {t("Показать")}
</Button> </Button>
</form> </form>
{repos.length === 0 ? ( {o.loading ? null : repos.length === 0 ? (
<Empty>{t("Репозиториев не найдено.")}</Empty> <Empty>{t("Репозиториев не найдено.")}</Empty>
) : ( ) : (
<Card className="p-0"> <Card className="p-0">
<ul> <ul>
{repos.map((r) => ( {shown.map((r) => (
<RepoRow key={r.fullName} r={r} t={t} q={q.q ?? ""} show={show} /> <RepoRow key={r.fullName} r={r} t={t} q={q.q ?? ""} show={show} />
))} ))}
</ul> </ul>
</Card> </Card>
)} )}
{pages > 1 && (
<nav className="mt-3 flex items-center gap-3 text-sm">
{page > 1 ? <a href={href({ page: String(page - 1) })}>{t("‹ Назад")}</a> : <span className="text-muted-foreground">{t("‹ Назад")}</span>}
<span className="text-muted-foreground">{t("Страница {page} из {pages}", { page, pages })}</span>
{page < pages ? <a href={href({ page: String(page + 1) })}>{t("Дальше ›")}</a> : <span className="text-muted-foreground">{t("Дальше ›")}</span>}
</nav>
)}
</Section> </Section>
</div> </div>
</Workspace> </Workspace>

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { CONNECT_HELP, featureGateView } from "@peppa/core"; import { CONNECT_HELP, featureGateView } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate"; import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh"; import { LiveRefresh } from "@/components/LiveRefresh";
@ -7,8 +7,14 @@ import { CopyText } from "@/components/CopyText";
import { Workspace } from "@/components/Workspace"; import { Workspace } from "@/components/Workspace";
import { publicOrigin } from "@/lib/auth"; import { publicOrigin } from "@/lib/auth";
import { getLocale, getT } from "@/lib/i18n"; import { getLocale, getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, (CONNECT_HELP[t.locale] ?? CONNECT_HELP.ru).title);
}
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
export default async function ConnectHelp() { export default async function ConnectHelp() {
const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru; const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
const address = `${await publicOrigin()}/mcp`; const address = `${await publicOrigin()}/mcp`;
@ -72,3 +78,5 @@ export default async function ConnectHelp() {
</Workspace> </Workspace>
); );
} }
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core"; import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate"; import { FeatureGate } from "@/components/FeatureGate";
@ -9,6 +9,7 @@ import { publicOrigin, uiMode } from "@/lib/auth";
import { Workspace } from "@/components/Workspace"; import { Workspace } from "@/components/Workspace";
import { voiceStoriesEnabled } from "@peppa/shared"; import { voiceStoriesEnabled } from "@peppa/shared";
import { PageHeader, Section } from "@/components/common"; import { PageHeader, Section } from "@/components/common";
import { pageTitle } from "@/lib/title";
const TOOLS: Array<[string, string]> = [ const TOOLS: Array<[string, string]> = [
["get_started", m("правила работы для ИИ-клиента: вызывается первым, коротко и без кода")], ["get_started", m("правила работы для ИИ-клиента: вызывается первым, коротко и без кода")],
@ -140,6 +141,12 @@ async function ProductHelp() {
); );
} }
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Помощь"));
}
export default async function Help() { export default async function Help() {
if ((await uiMode()) === "product") return <ProductHelp />; if ((await uiMode()) === "product") return <ProductHelp />;
const t = await getT(); const t = await getT();

View File

@ -1,11 +1,17 @@
import Link from "next/link"; import Link from "@/components/Link";
import { ShortcutsList } from "@/components/CommandPalette"; import { ShortcutsList } from "@/components/CommandPalette";
import { PageHeader, Section } from "@/components/common"; import { PageHeader, Section } from "@/components/common";
import { Workspace } from "@/components/Workspace"; import { Workspace } from "@/components/Workspace";
import { PALETTE_KEYS } from "@/lib/shortcuts"; import { PALETTE_KEYS } from "@/lib/shortcuts";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Горячие клавиши"));
}
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
export default async function Shortcuts() { export default async function Shortcuts() {
const t = await getT(); const t = await getT();
return ( return (
@ -26,3 +32,5 @@ export default async function Shortcuts() {
</Workspace> </Workspace>
); );
} }
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */

View File

@ -6,8 +6,14 @@ import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth"; import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Журнал действий"));
}
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */
export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) { export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) {
const me = await requireUser(); const me = await requireUser();
if (!(await isSuperadmin(db, me))) notFound(); if (!(await isSuperadmin(db, me))) notFound();
@ -35,3 +41,5 @@ export default async function Journal({ searchParams }: { searchParams: Promise<
</Workspace> </Workspace>
); );
} }
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */

View File

@ -1,5 +1,5 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin, pendingFeedbackCount } from "@peppa/core"; import { accountUsageForUser, agentsLine, getNotifyPrefs, httpsAvatar, isSuperadmin, pendingFeedbackCount } from "@peppa/core";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { subscriptionRequestOffers } from "@peppa/runner"; import { subscriptionRequestOffers } from "@peppa/runner";
import { requireUser, uiMode } from "@/lib/auth"; import { requireUser, uiMode } from "@/lib/auth";
@ -35,7 +35,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
<WordsProvider mode={mode}> <WordsProvider mode={mode}>
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]"> <div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} /> <AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={{ ...counts, feedback }} superadmin={superadmin} engineer={engineer} /> <Sidebar login={user.login} avatarUrl={httpsAvatar(user.avatarUrl)} counts={{ ...counts, feedback }} superadmin={superadmin} engineer={engineer} />
<div className="flex min-w-0 flex-col pb-16 md:pb-0"> <div className="flex min-w-0 flex-col pb-16 md:pb-0">
<VersionWatch boot={bootId()} /> <VersionWatch boot={bootId()} />
{line ? <AgentsStrip line={line} offers={offers} /> : <UsageStrip accounts={accounts} admin={superadmin} />} {line ? <AgentsStrip line={line} offers={offers} /> : <UsageStrip accounts={accounts} admin={superadmin} />}

View File

@ -1,5 +1,6 @@
// glossary-ignore-file: the section is for the superadmin only. // glossary-ignore-file: the section is for the superadmin only.
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Activity, Pause, Play, Trash2 } from "lucide-react"; import { Activity, Pause, Play, Trash2 } from "lucide-react";
import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core"; import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
@ -15,11 +16,18 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions"; import { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
const PAGE = 100; const PAGE = 100;
const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }); // PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Мониторинг"));
}
const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZone: platformZone() });
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) { export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
const user = await requireUser(); const user = await requireUser();

View File

@ -1,5 +1,6 @@
// glossary-ignore-file: the section is for the superadmin only. // glossary-ignore-file: the section is for the superadmin only.
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Activity, Pause, Play, Plus } from "lucide-react"; import { Activity, Pause, Play, Plus } from "lucide-react";
import { describeTarget, observeRemindMin, PROVIDER_LABEL, smokeStatus, smokeTimeoutMin, type SmokeRun, type SmokeStatus, egovLoginSummary, errorScope, errorsOverview, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary, isBadVital, vitalsSummary, type VitalDevice, type VitalMetric } from "@peppa/core"; import { describeTarget, observeRemindMin, PROVIDER_LABEL, smokeStatus, smokeTimeoutMin, type SmokeRun, type SmokeStatus, egovLoginSummary, errorScope, errorsOverview, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary, isBadVital, vitalsSummary, type VitalDevice, type VitalMetric } from "@peppa/core";
@ -83,7 +84,7 @@ async function SmokeSection({ t }: { t: Awaited<ReturnType<typeof getT>> }) {
skipped: [t("не проверен"), "text-muted-foreground"], skipped: [t("не проверен"), "text-muted-foreground"],
}; };
const TRIGGER = { deploy: t("после выкатки"), hourly: t("плановая"), manual: t("по запросу") } as const; const TRIGGER = { deploy: t("после выкатки"), hourly: t("плановая"), manual: t("по запросу") } as const;
const when = (r: SmokeRun) => new Date(r.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }); const when = (r: SmokeRun) => new Date(r.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
return ( return (
<Section <Section
title={t("Запуск агентов")} title={t("Запуск агентов")}
@ -287,7 +288,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm"> <ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{flog.map((e) => ( {flog.map((e) => (
<li key={e.id} className="flex flex-wrap gap-2"> <li key={e.id} className="flex flex-wrap gap-2">
<span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span> <span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() })}</span>
<span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span> <span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
<span className="font-medium">{t(FEATURES[e.name].label)}</span> <span className="font-medium">{t(FEATURES[e.name].label)}</span>
{e.reason && <span className="text-muted-foreground">{e.reason}</span>} {e.reason && <span className="text-muted-foreground">{e.reason}</span>}

View File

@ -1,6 +1,6 @@
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { acceptAllSummary, acceptScreen, type AcceptItem } from "@peppa/core"; import { acceptAllSummary, acceptRunLine, acceptScreen, type AcceptItem } from "@peppa/core";
import { acceptAllAction, fixStoryAction } from "@/app/(app)/actions"; import { acceptAllAction, fixStoryAction } from "@/app/(app)/actions";
import { Empty, Flash, Key, Notice, PageHeader } from "@/components/common"; import { Empty, Flash, Key, Notice, PageHeader } from "@/components/common";
import { LiveRefresh } from "@/components/LiveRefresh"; import { LiveRefresh } from "@/components/LiveRefresh";
@ -32,7 +32,8 @@ export default async function AcceptPage({ params, searchParams }: { params: Pro
if (!p) notFound(); if (!p) notFound();
const screen = await acceptScreen(db, p); const screen = await acceptScreen(db, p);
const back = `/p/${p.key}/accept`; const back = `/p/${p.key}/accept`;
const all = screen.groups.flatMap((g) => g.items); // PEP-318: stories already queued are not offered again.
const all = screen.groups.flatMap((g) => g.items).filter((it) => !it.queued);
const done = sp.ok != null ? { accepted: Number(sp.ok) || 0, pending: Number(sp.pending) || 0, failed: Number(sp.failed) || 0 } : null; const done = sp.ok != null ? { accepted: Number(sp.ok) || 0, pending: Number(sp.pending) || 0, failed: Number(sp.failed) || 0 } : null;
return ( return (
<Workspace> <Workspace>
@ -42,13 +43,20 @@ export default async function AcceptPage({ params, searchParams }: { params: Pro
{screen.total ? t("Работа, которая ждёт вашего решения: посмотрите и примите или напишите, что поправить.") : t("Принимать пока нечего: агенты пришлют задачи, когда работа будет готова.")} {screen.total ? t("Работа, которая ждёт вашего решения: посмотрите и примите или напишите, что поправить.") : t("Принимать пока нечего: агенты пришлют задачи, когда работа будет готова.")}
</PageHeader> </PageHeader>
{done && ( {screen.run ? (
// PEP-318: «Принять всё» goes on in the background — its progress, then its result.
<Notice> <Notice>
<span data-accept-result>{t.text(acceptAllSummary(done))}</span> <span data-accept-result data-accept-running={screen.run.finishedAt ? undefined : ""}>{t.text(acceptRunLine(screen.run))}</span>
{screen.liveUrl && done.accepted + done.pending > 0 && ( {screen.liveUrl && screen.run.finishedAt && screen.run.accepted.length + screen.run.pending.length > 0 && (
<a href={screen.liveUrl} target="_blank" rel="noreferrer" className="text-primary">{t("Открыть продукт")} →</a> <a href={screen.liveUrl} target="_blank" rel="noreferrer" className="text-primary">{t("Открыть продукт")} →</a>
)} )}
</Notice> </Notice>
) : (
done && (
<Notice>
<span data-accept-result>{t.text(acceptAllSummary(done))}</span>
</Notice>
)
)} )}
{screen.total > 0 && ( {screen.total > 0 && (
@ -58,32 +66,34 @@ export default async function AcceptPage({ params, searchParams }: { params: Pro
{t("Открыть версию для проверки")} {t("Открыть версию для проверки")}
</a> </a>
)} )}
<details className="group w-full rounded-lg border bg-card sm:w-auto" data-accept-all> {all.length > 0 && (
<summary className={`flex cursor-pointer list-none items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground select-none [&::-webkit-details-marker]:hidden ${BIG}`}> <details className="group w-full rounded-lg border bg-card sm:w-auto" data-accept-all>
{t("Принять всё · {n}", { n: all.length })} <summary className={`flex cursor-pointer list-none items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground select-none [&::-webkit-details-marker]:hidden ${BIG}`}>
</summary> {t("Принять всё · {n}", { n: all.length })}
<form action={acceptAllAction} className="flex flex-col gap-2 p-3"> </summary>
<input type="hidden" name="project" value={p.key} /> <form action={acceptAllAction} className="flex flex-col gap-2 p-3">
<input type="hidden" name="back" value={back} /> <input type="hidden" name="project" value={p.key} />
<p className="m-0 text-sm">{t("Будут приняты по очереди:")}</p> <input type="hidden" name="back" value={back} />
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm"> <p className="m-0 text-sm">{t("Будут приняты по очереди:")}</p>
{all.map((it) => ( <ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
<li key={it.key}> {all.map((it) => (
<input type="hidden" name="taskKey" value={it.key} /> <li key={it.key}>
<Key>{it.key}</Key> {it.title} <input type="hidden" name="taskKey" value={it.key} />
</li> <Key>{it.key}</Key> {it.title}
))} </li>
</ul> ))}
<p className="m-0 text-xs text-muted-foreground">{t("Если какая-то не примется, остальные всё равно примутся, а у неё будет написано почему.")}</p> </ul>
<Button variant="default" className={BIG} data-accept-all-confirm> <p className="m-0 text-xs text-muted-foreground">{t("Если какая-то не примется, остальные всё равно примутся, а у неё будет написано почему.")}</p>
{t("Да, принять {n}", { n: all.length })} <Button variant="default" className={BIG} data-accept-all-confirm>
</Button> {t("Да, принять {n}", { n: all.length })}
</form> </Button>
</details> </form>
</details>
)}
</div> </div>
)} )}
{screen.total === 0 && !done && <Empty>{t("Задач на приёмке нет.")}</Empty>} {screen.total === 0 && !done && !screen.run && <Empty>{t("Задач на приёмке нет.")}</Empty>}
{screen.groups.map((g) => ( {screen.groups.map((g) => (
<section key={g.page || "-"} className="mb-8" data-accept-group={g.page || "-"}> <section key={g.page || "-"} className="mb-8" data-accept-group={g.page || "-"}>
@ -115,6 +125,7 @@ async function AcceptCard({ it, back }: { it: AcceptItem; back: string }) {
{t("Не принялась: {reason}", { reason: t.text(it.failed) })} {t("Не принялась: {reason}", { reason: t.text(it.failed) })}
</p> </p>
)} )}
{it.queued && !it.pending && <p className="m-0 mb-3 text-sm text-muted-foreground" data-accept-queued>{t("Принимается — дождитесь, страница обновится сама.")}</p>}
{it.pending && <p className="m-0 mb-3 text-sm text-muted-foreground">{t("Вы уже приняли — изменения обновляются, задача закроется сама.")}</p>} {it.pending && <p className="m-0 mb-3 text-sm text-muted-foreground">{t("Вы уже приняли — изменения обновляются, задача закроется сама.")}</p>}
{it.shots.length > 0 ? ( {it.shots.length > 0 ? (
// Scrolls sideways on a phone: one page per screen, «было» above «стало». // Scrolls sideways on a phone: one page per screen, «было» above «стало».
@ -141,7 +152,7 @@ async function AcceptCard({ it, back }: { it: AcceptItem; back: string }) {
<a href={it.previewUrl} target="_blank" rel="noreferrer" className="inline-flex min-h-11 items-center text-primary">{t("Открыть в версии для проверки")} →</a> <a href={it.previewUrl} target="_blank" rel="noreferrer" className="inline-flex min-h-11 items-center text-primary">{t("Открыть в версии для проверки")} →</a>
</p> </p>
)} )}
{!it.pending && ( {!it.pending && !it.queued && (
<div className="flex flex-col gap-2 sm:flex-row sm:items-start"> <div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<form action={acceptAllAction}> <form action={acceptAllAction}>
<input type="hidden" name="project" value={it.key.slice(0, it.key.lastIndexOf("-"))} /> <input type="hidden" name="project" value={it.key.slice(0, it.key.lastIndexOf("-"))} />

View File

@ -1,4 +1,5 @@
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { Fragment } from "react"; import { Fragment } from "react";
import { ProductCard } from "@/components/ProductCard"; import { ProductCard } from "@/components/ProductCard";
import { PublishPanel } from "@/components/PublishPanel"; import { PublishPanel } from "@/components/PublishPanel";
@ -6,7 +7,7 @@ import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react"; import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner"; import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getDirectOrigins, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getDirectOrigins, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { productNeeds, lastProductReview } from "@peppa/core"; import { productNeeds, lastProductReview, deferredFindings } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh"; import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside"; import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board"; import { Board, type Card } from "@/components/Board";
@ -47,6 +48,7 @@ import { queuePositions, workLine } from "@peppa/core";
import { WorkLine } from "@/components/WorkLine"; import { WorkLine } from "@/components/WorkLine";
import { deleteProjectAction } from "../../actions"; import { deleteProjectAction } from "../../actions";
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete"; import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
import { projectTitle } from "@/lib/title";
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = { const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
deploying: { label: m("выкатывается"), tone: "info" }, deploying: { label: m("выкатывается"), tone: "info" },
@ -70,6 +72,14 @@ const TABS = [
{ id: "journal", label: m("Журнал") }, { id: "journal", label: m("Журнал") },
] as const; ] as const;
// PEP-274: «KEY · вкладка — FORGE».
export async function generateMetadata({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ tab?: string }> }) {
const t = await getT();
const { tab: id } = await searchParams;
const tab = TABS.find((x) => x.id === id) ?? TABS[0]!;
return projectTitle(t, (await params).key, t.text(tab.label));
}
function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) { function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) {
return ( return (
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2"> <div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">
@ -208,7 +218,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null; const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
const product = await projectProduct(db, p.id); const product = await projectProduct(db, p.id);
const publish = await getPublishMode(db, p.id); const publish = await getPublishMode(db, p.id);
const [productNeedList, productReview] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id)]); const [productNeedList, productReview, deferred] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id), tab === "board" ? deferredFindings(db, p.id) : null]);
// The chat belongs to the project's people; a superadmin looking at someone else's project has none. // The chat belongs to the project's people; a superadmin looking at someone else's project has none.
const canChat = (await userProjectIds(db, user.id)).includes(p.id); const canChat = (await userProjectIds(db, user.id)).includes(p.id);
const sharedReq = await sharedRequest(db, p.id); const sharedReq = await sharedRequest(db, p.id);
@ -700,7 +710,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</nav> </nav>
)} )}
{work && <WorkLine line={work} className="mb-2" />} {work && <WorkLine line={work} className="mb-2" />}
<Board cards={cards} back={back} /> <Board cards={cards} back={back} projectId={p.id} deferred={(deferred?.items ?? []).map((d) => ({ title: d.title, severity: d.severity }))} />
</> </>
)} )}
@ -769,7 +779,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
))} ))}
</td> </td>
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground"> <td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" })} {r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() })}
</td> </td>
</tr> </tr>
))} ))}

View File

@ -1,5 +1,6 @@
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves. // PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Sparkles } from "lucide-react"; import { Sparkles } from "lucide-react";
import { getEpic, listTasks } from "@peppa/core"; import { getEpic, listTasks } from "@peppa/core";
@ -15,8 +16,15 @@ import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { intlLocale } from "@peppa/shared/i18n"; import { intlLocale } from "@peppa/shared/i18n";
import { projectForUserByKey } from "@/lib/queries"; import { projectForUserByKey } from "@/lib/queries";
import { projectTitle } from "@/lib/title";
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions"; import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata({ params }: { params: Promise<{ key: string }> }) {
const t = await getT();
return projectTitle(t, (await params).key, t("Эпик"));
}
export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) { export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser(); const user = await requireUser();
const { key, epic: epicParam } = await params; const { key, epic: epicParam } = await params;
@ -102,7 +110,7 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button> <Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
</form> </form>
<p className="m-0 text-xs text-muted-foreground"> <p className="m-0 text-xs text-muted-foreground">
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }), author: draft.createdBy })} {t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }), author: draft.createdBy })}
</p> </p>
</> </>
)} )}

View File

@ -1,4 +1,5 @@
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66). // Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
import { platformZone } from "@peppa/shared/time";
import type { Words } from "@peppa/shared/wording"; import type { Words } from "@peppa/shared/wording";
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react"; import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
import type { Epic, SpecSummary } from "@peppa/core"; import type { Epic, SpecSummary } from "@peppa/core";
@ -13,7 +14,7 @@ import { Input, Textarea } from "@/components/ui/input";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { intlLocale, type Translator } from "@peppa/shared/i18n"; import { intlLocale, type Translator } from "@peppa/shared/i18n";
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }) : "—"); const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }) : "—");
export async function CodeTab({ code }: { code: RepoOverview }) { export async function CodeTab({ code }: { code: RepoOverview }) {
const t = await getT(); const t = await getT();

View File

@ -1,6 +1,6 @@
import { Suspense } from "react"; import { Suspense } from "react";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import Link from "next/link"; import Link from "@/components/Link";
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core"; import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
import { AdminFeedbackCard } from "@/components/Feedback"; import { AdminFeedbackCard } from "@/components/Feedback";
import { AgentTaskSummary } from "@/components/AgentTaskSummary"; import { AgentTaskSummary } from "@/components/AgentTaskSummary";
@ -16,6 +16,7 @@ import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { acceptInbox, activeSessions, inbox } from "@/lib/queries"; import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
import { pageTitle } from "@/lib/title";
function BlockSkeleton() { function BlockSkeleton() {
return <div className="h-24 animate-pulse rounded-md bg-muted/40" aria-hidden />; return <div className="h-24 animate-pulse rounded-md bg-muted/40" aria-hidden />;
@ -35,6 +36,12 @@ async function AgentsBlock({ userId, engineer }: { userId: number; engineer: boo
); );
} }
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Главная"));
}
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) { export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser(); const user = await requireUser();
const { error } = await searchParams; const { error } = await searchParams;

View File

@ -10,6 +10,7 @@ import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { createProjectAction } from "../../actions"; import { createProjectAction } from "../../actions";
import { pageTitle } from "@/lib/title";
function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) { function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
return ( return (
@ -20,6 +21,12 @@ function Choice({ name, value, checked, children }: { name: string; value: strin
); );
} }
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Новый проект"));
}
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) { export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser(); const user = await requireUser();
const t = await getT(); const t = await getT();

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { Plus } from "lucide-react"; import { Plus } from "lucide-react";
import { analystLinks, isSuperadmin, listOtherProjects, listUserProjects, projectTrashDays } from "@peppa/core"; import { analystLinks, isSuperadmin, listOtherProjects, listUserProjects, projectTrashDays } from "@peppa/core";
import { ProjectList } from "@/components/cards"; import { ProjectList } from "@/components/cards";
@ -8,6 +8,13 @@ import { Workspace } from "@/components/Workspace";
import { requireUser, words } from "@/lib/auth"; import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Проекты"));
}
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) { export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser(); const user = await requireUser();

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { Search, SquareTerminal } from "lucide-react"; import { Search, SquareTerminal } from "lucide-react";
import { listUserProjects, runnerStories, listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core"; import { listUserProjects, runnerStories, listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh"; import { LiveRefresh } from "@/components/LiveRefresh";
@ -14,6 +14,7 @@ import { inbox, sessionEvents } from "@/lib/queries";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n"; import { m } from "@peppa/shared/i18n";
import { pageTitle } from "@/lib/title";
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [ const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
{ key: undefined, label: m("все") }, { key: undefined, label: m("все") },
@ -28,6 +29,12 @@ const matches = (s: SessionView, q: string) =>
type Params = { error?: string; f?: string; q?: string; id?: string }; type Params = { error?: string; f?: string; q?: string; id?: string };
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Работа агентов"));
}
export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) { export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) {
const user = await requireUser(); const user = await requireUser();
const t = await getT(); const t = await getT();

View File

@ -2,7 +2,7 @@
// «Сессии» (PEP-257): one place for the terminals of all live agent sessions of the user's // «Сессии» (PEP-257): one place for the terminals of all live agent sessions of the user's
// projects. Left — the list, right — the terminal of the chosen one, open right away: the first // projects. Left — the list, right — the terminal of the chosen one, open right away: the first
// of the list without `?id`, the given one with it (a story links here with its session). // of the list without `?id`, the given one with it (a story links here with its session).
import Link from "next/link"; import Link from "@/components/Link";
import { SquareTerminal } from "lucide-react"; import { SquareTerminal } from "lucide-react";
import { FINISHED_SESSION_STATUSES, listUserSessions, PROVIDER_NAMES, type SessionView } from "@peppa/core"; import { FINISHED_SESSION_STATUSES, listUserSessions, PROVIDER_NAMES, type SessionView } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge"; import { AgentBadge } from "@/components/AgentBadge";
@ -17,6 +17,13 @@ import { inbox } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status"; import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Сессии"));
}
export default async function Sessions({ searchParams }: { searchParams: Promise<{ id?: string }> }) { export default async function Sessions({ searchParams }: { searchParams: Promise<{ id?: string }> }) {
const user = await requireUser(); const user = await requireUser();

View File

@ -20,6 +20,7 @@ import { LanguageSwitcher } from "@/components/I18n";
import { getLocale, getT } from "@/lib/i18n"; import { getLocale, getT } from "@/lib/i18n";
import { CopyText } from "@/components/CopyText"; import { CopyText } from "@/components/CopyText";
import { intlLocale } from "@peppa/shared/i18n"; import { intlLocale } from "@peppa/shared/i18n";
import { pageTitle } from "@/lib/title";
const back = { back: "/settings" }; const back = { back: "/settings" };
@ -36,6 +37,12 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?:
); );
} }
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Настройки"));
}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; mode?: string; egov?: string; google?: string; notify?: string; bot?: string }> }) { export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; mode?: string; egov?: string; google?: string; notify?: string; bot?: string }> }) {
const user = await requireUser(); const user = await requireUser();
const { error, egov, google, notify, bot, mode: modeSaved } = await searchParams; const { error, egov, google, notify, bot, mode: modeSaved } = await searchParams;

View File

@ -2,7 +2,7 @@
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33. // OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
import { queuePositions } from "@peppa/core"; import { queuePositions } from "@peppa/core";
import { Markdown } from "@/components/Markdown"; import { Markdown } from "@/components/Markdown";
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Archive, ArchiveRestore, ChevronDown, ChevronRight, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react"; import { Archive, ArchiveRestore, ChevronDown, ChevronRight, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
import { import {
@ -77,9 +77,15 @@ import { BudgetPanel } from "@/components/Accounting";
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs"; import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
import { archiveTaskAction, setDependenciesAction } from "../../board-actions"; import { archiveTaskAction, setDependenciesAction } from "../../board-actions";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { taskTitle } from "@/lib/title";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> }; const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
// PEP-274: «KEY-N · название — FORGE».
export async function generateMetadata({ params }: { params: Promise<{ key: string }> }) {
return taskTitle(await getT(), (await params).key);
}
/** Gitea behind Cloudflare can hang: the merge tab waits at most this long. */ /** Gitea behind Cloudflare can hang: the merge tab waits at most this long. */
async function gateWithTimeout(ref: Parameters<typeof prGate>[0]): Promise<GateResult | null> { async function gateWithTimeout(ref: Parameters<typeof prGate>[0]): Promise<GateResult | null> {
return Promise.race([prGate(ref).catch(() => null), new Promise<null>((r) => setTimeout(() => r(null), 5000))]); return Promise.race([prGate(ref).catch(() => null), new Promise<null>((r) => setTimeout(() => r(null), 5000))]);

View File

@ -1,5 +1,5 @@
// glossary-ignore-file: the page is for the superadmin only (accounts, repositories, Gitea spaces). // glossary-ignore-file: the page is for the superadmin only (accounts, repositories, Gitea spaces).
import Link from "next/link"; import Link from "@/components/Link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { isSuperadmin, maskIin, mergePlan, PeppaError } from "@peppa/core"; import { isSuperadmin, maskIin, mergePlan, PeppaError } from "@peppa/core";
import { Hidden } from "@/components/cards"; import { Hidden } from "@/components/cards";
@ -11,8 +11,14 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { mergeAccountsAction } from "../../actions"; import { mergeAccountsAction } from "../../actions";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Объединить учётки"));
}
/** PEP-204: what moves from the old account to the main one — confirmed before anything changes. Superadmin only. */
export default async function MergeAccounts({ searchParams }: { searchParams: Promise<{ from?: string; to?: string; error?: string }> }) { export default async function MergeAccounts({ searchParams }: { searchParams: Promise<{ from?: string; to?: string; error?: string }> }) {
const me = await requireUser(); const me = await requireUser();
if (!(await isSuperadmin(db, me))) notFound(); if (!(await isSuperadmin(db, me))) notFound();
@ -111,3 +117,5 @@ export default async function MergeAccounts({ searchParams }: { searchParams: Pr
</Workspace> </Workspace>
); );
} }
/** PEP-204: what moves from the old account to the main one — confirmed before anything changes. Superadmin only. */

View File

@ -1,6 +1,6 @@
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import Link from "next/link"; import Link from "@/components/Link";
import { canLogIn, isLocalUser, isSuperadmin, listUsers, maskIin, mergeHints, platformAdmins } from "@peppa/core"; import { canLogIn, isLocalUser, isSuperadmin, listUsers, maskIin, mergeHints, superadminIds } from "@peppa/core";
import { Hidden } from "@/components/cards"; import { Hidden } from "@/components/cards";
import { ago, Flash, PageHeader, Section } from "@/components/common"; import { ago, Flash, PageHeader, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -12,17 +12,23 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { setSuperadminAction, setUserDisabledAction } from "../actions"; import { setSuperadminAction, setUserDisabledAction } from "../actions";
import { pageTitle } from "@/lib/title";
const back = { back: "/users" }; const back = { back: "/users" };
/** Superadmin only (PEP-68/71): who is registered, disable / enable. */ // PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Пользователи"));
}
export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string }> }) { export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const me = await requireUser(); const me = await requireUser();
if (!(await isSuperadmin(db, me))) notFound(); if (!(await isSuperadmin(db, me))) notFound();
const t = await getT(); const t = await getT();
const { error } = await searchParams; const { error } = await searchParams;
const all = await listUsers(db); const all = await listUsers(db);
const admins = new Set(await platformAdmins(db)); const admins = await superadminIds(db);
const hints = await mergeHints(db, all); const hints = await mergeHints(db, all);
const mains = all.filter((u) => !u.disabledAt && canLogIn(u)); const mains = all.filter((u) => !u.disabledAt && canLogIn(u));
return ( return (
@ -40,7 +46,7 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
const local = isLocalUser(u); const local = isLocalUser(u);
const hint = hints.get(u.id); const hint = hints.get(u.id);
const targets = mains.filter((v) => v.id !== u.id); const targets = mains.filter((v) => v.id !== u.id);
const isAdmin = admins.has(u.login.toLowerCase()); const isAdmin = admins.has(u.id);
return ( return (
<Card key={u.id} className="gap-3" data-user={u.login}> <Card key={u.id} className="gap-3" data-user={u.login}>
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
@ -94,3 +100,5 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
</Workspace> </Workspace>
); );
} }
/** Superadmin only (PEP-68/71): who is registered, disable / enable. */

View File

@ -1,5 +1,5 @@
// PEP-92: the welcome page for everyone who signs in — why Peppa, how work goes, where to click. // PEP-92: the welcome page for everyone who signs in — why Peppa, how work goes, where to click.
import Link from "next/link"; import Link from "@/components/Link";
import { ArrowRight, Check } from "lucide-react"; import { ArrowRight, Check } from "lucide-react";
import { Workspace } from "@/components/Workspace"; import { Workspace } from "@/components/Workspace";
import { PageHeader, Section } from "@/components/common"; import { PageHeader, Section } from "@/components/common";
@ -8,6 +8,7 @@ import { requireUser, words } from "@/lib/auth";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { m, type Translator } from "@peppa/shared/i18n"; import { m, type Translator } from "@peppa/shared/i18n";
import type { Words } from "@peppa/shared/wording"; import type { Words } from "@peppa/shared/wording";
import { pageTitle } from "@/lib/title";
const WHY = [ const WHY = [
{ title: m("Программировать не нужно"), text: m("Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты.") }, { title: m("Программировать не нужно"), text: m("Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты.") },
@ -30,6 +31,12 @@ const glossary = (w: Words, t: Translator): Array<[string, string]> => [
[t("Ревью"), t("момент, когда агент закончил, а вы решаете: принять или вернуть")], [t("Ревью"), t("момент, когда агент закончил, а вы решаете: принять или вернуть")],
]; ];
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Добро пожаловать в FORGE"));
}
export default async function Welcome() { export default async function Welcome() {
await requireUser(); await requireUser();
const t = await getT(); const t = await getT();

View File

@ -1,15 +1,20 @@
import { healthReport } from "@peppa/core"; import { HEALTH_HEADER, healthBody, healthReport } from "@peppa/core";
import { bootId } from "@/lib/boot"; import { bootId } from "@/lib/boot";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
/** Public health check (PEP-20): DB, version, service heartbeats. 503 if the DB is down. */ /**
export async function GET() { * Health check (PEP-20): DB, version, service heartbeats. 503 if the DB is down.
* PEP-272: without the internal key (`X-Peppa-Health`) only `{ok}` — no version, commit or services
* for strangers. Deploy scripts, container healthchecks and the watchdog send the key.
*/
export async function GET(req: Request) {
const r = await healthReport(db, { const r = await healthReport(db, {
version: process.env.NEXT_PUBLIC_PEPPA_VERSION, version: process.env.NEXT_PUBLIC_PEPPA_VERSION,
commit: process.env.NEXT_PUBLIC_PEPPA_COMMIT || null, commit: process.env.NEXT_PUBLIC_PEPPA_COMMIT || null,
}); });
// PEP-114: `boot` changes when the web process restarts — open pages compare it with their own. // PEP-114: `boot` changes when the web process restarts — the domain guard recognises FORGE by it.
return Response.json({ ...r, boot: bootId() }, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } }); const body = healthBody({ ...r, boot: bootId() }, req.headers.get(HEALTH_HEADER));
return Response.json(body, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } });
} }

33
apps/web/app/error.tsx Normal file
View File

@ -0,0 +1,33 @@
"use client";
import { useEffect } from "react";
import { RefreshCw } from "lucide-react";
import { useT } from "@/components/I18n";
import { isStaleAction, reportStaleAction } from "@/components/StaleActionGuard";
import { reportCaughtError } from "@/lib/stale-action";
/**
* PEP-324: the error boundary of every page. Before it a failed form action (most often a button of a
* page opened before an update) left the person with Next's «Application error». An unknown action is
* handed to StaleActionGuard (keep the text, say FORGE was updated, reload); any other error gets a
* plain screen and is reported to «Ошибки из прода» from here: Next prints a caught error with the
* console.error it took before ErrorReporter wrapped it, so nobody else would report it.
*/
export default function PageError({ error }: { error: Error & { digest?: string } }) {
const t = useT();
const stale = isStaleAction(error);
useEffect(() => {
if (stale) reportStaleAction();
else reportCaughtError(error, window);
}, [stale, error]);
if (stale) return null;
return (
<div role="alert" className="mx-auto flex max-w-lg flex-col items-start gap-3 p-8">
<p className="text-base font-medium">{t("Страница не открылась из-за ошибки.")}</p>
<p className="text-sm text-muted-foreground">{t("Обновите страницу или вернитесь назад.")}</p>
<button type="button" onClick={() => window.location.reload()} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground">
<RefreshCw className="size-3.5" /> {t("Обновить страницу")}
</button>
</div>
);
}

View File

@ -7,6 +7,7 @@ import { cn } from "@/lib/utils";
import { THEME_COOKIE } from "@/lib/theme"; import { THEME_COOKIE } from "@/lib/theme";
import { getLocale, getT } from "@/lib/i18n"; import { getLocale, getT } from "@/lib/i18n";
import { ErrorReporter } from "@/components/ErrorReporter"; import { ErrorReporter } from "@/components/ErrorReporter";
import { StaleActionGuard } from "@/components/StaleActionGuard";
import { I18nProvider } from "@/components/I18n"; import { I18nProvider } from "@/components/I18n";
import "./app.css"; import "./app.css";
@ -24,6 +25,8 @@ export default async function RootLayout({ children }: { children: ReactNode })
<body> <body>
<I18nProvider locale={locale} dict={locale === "ru" ? undefined : dictionary(locale)}> <I18nProvider locale={locale} dict={locale === "ru" ? undefined : dictionary(locale)}>
<ErrorReporter /> <ErrorReporter />
{/* PEP-324: a button of a page opened before an update — keep the text and reload. */}
<StaleActionGuard />
{children} {children}
</I18nProvider> </I18nProvider>
</body> </body>

View File

@ -13,6 +13,7 @@ import { PugMascot } from "@/components/PugMascot";
import { LanguageSwitcher } from "@/components/I18n"; import { LanguageSwitcher } from "@/components/I18n";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n"; import { m } from "@peppa/shared/i18n";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
@ -37,7 +38,12 @@ const NEED = [
{ icon: Sparkles, text: m("Платная подписка Claude или ChatGPT — на ней работают агенты") }, { icon: Sparkles, text: m("Платная подписка Claude или ChatGPT — на ней работают агенты") },
]; ];
/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */ // PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Вход"));
}
export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) { export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) {
const { error, next } = await searchParams; const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next)); if (await currentUser()) redirect(safeNext(next));
@ -122,3 +128,5 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
</main> </main>
); );
} }
/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */

View File

@ -4,10 +4,16 @@ import { LiveRefresh } from "@/components/LiveRefresh";
import { Brand } from "@/components/Brand"; import { Brand } from "@/components/Brand";
import { GuideCopy } from "@/components/GuideCopy"; import { GuideCopy } from "@/components/GuideCopy";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
/** PEP-190: public page (no sign-in) with the same guide that the MCP tool get_started returns. */ // PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Инструкция для ИИ"));
}
export default async function McpGuide() { export default async function McpGuide() {
const t = await getT(); const t = await getT();
return ( return (
@ -22,3 +28,5 @@ export default async function McpGuide() {
</main> </main>
); );
} }
/** PEP-190: public page (no sign-in) with the same guide that the MCP tool get_started returns. */

View File

@ -7,12 +7,18 @@ import { Brand } from "@/components/Brand";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
type Params = Record<string, string | undefined>; type Params = Record<string, string | undefined>;
/** OAuth consent screen: who asks, what they get, allow / deny. */ // PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Доступ для приложения"));
}
export default async function Authorize({ searchParams }: { searchParams: Promise<Params> }) { export default async function Authorize({ searchParams }: { searchParams: Promise<Params> }) {
const p = await searchParams; const p = await searchParams;
const user = await currentUser(); const user = await currentUser();
@ -76,3 +82,5 @@ function Hidden({ p }: { p: Params }) {
</> </>
); );
} }
/** OAuth consent screen: who asks, what they get, allow / deny. */

View File

@ -1,11 +1,16 @@
import Link from "next/link"; import Link from "@/components/Link";
import { KeyRound } from "lucide-react"; import { KeyRound } from "lucide-react";
import type { AccessRequestView } from "@peppa/core"; import { DEFAULT_GRANT_TERM, GRANT_TERM_TEXT, GRANT_TERMS, type AccessRequestView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n"; import type { Translator } from "@peppa/shared/i18n";
import { denyAccessRequestAction, grantAccessButtonAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
import { ago } from "@/components/common"; import { ago } from "@/components/common";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
/** «читать» / «читать и менять». */ /** «читать» / «читать и менять». */
export function accessModeText(mode: AccessRequestView["mode"], t: Translator): string { export function accessModeText(mode: AccessRequestView["mode"], t: Translator): string {
return mode === "write" ? t("читать и менять") : t("только читать"); return mode === "write" ? t("читать и менять") : t("только читать");
@ -18,8 +23,31 @@ export function AccessStatus({ r, t }: { r: AccessRequestView; t: Translator })
return <Badge variant="outline">{t("агент отменил запрос")}</Badge>; return <Badge variant="outline">{t("агент отменил запрос")}</Badge>;
} }
/** PEP-250: «Агенты просят доступ» on «Подключения» — the owner's open requests. */ /** PEP-261: the term of a grant — 1 day by default. */
export function AccessRequestList({ list, t }: { list: AccessRequestView[]; t: Translator }) { export function GrantTermSelect({ t }: { t: Translator }) {
return (
<select name="term" defaultValue={DEFAULT_GRANT_TERM} aria-label={t("Срок")} className={SELECT}>
{GRANT_TERMS.map((term) => (
<option key={term} value={term}>
{t.text(GRANT_TERM_TEXT[term])}
</option>
))}
</select>
);
}
/** PEP-261: «чтение» / «полные права» — by default what the agent asked for. */
export function GrantRightsSelect({ r, t }: { r: AccessRequestView; t: Translator }) {
return (
<select name="rights" defaultValue={r.mode === "write" ? "full" : "read"} aria-label={t("Что можно")} className={SELECT}>
<option value="read">{t("Чтение")}</option>
<option value="full">{t("Полные права: чтение и изменения")}</option>
</select>
);
}
/** PEP-250/261: «Агенты просят доступ» on «Подключения» — the owner's open requests with «Дать» buttons. `grantable` — requests with a fitting connection. */
export function AccessRequestList({ list, grantable, t }: { list: AccessRequestView[]; grantable: Set<number>; t: Translator }) {
return ( return (
<ul className="m-0 flex list-none flex-col gap-2 p-0"> <ul className="m-0 flex list-none flex-col gap-2 p-0">
{list.map((r) => ( {list.map((r) => (
@ -36,6 +64,31 @@ export function AccessRequestList({ list, t }: { list: AccessRequestView[]; t: T
<Link href={`/connections/requests/${r.id}`} className="ml-auto text-primary underline-offset-2 hover:underline"> <Link href={`/connections/requests/${r.id}`} className="ml-auto text-primary underline-offset-2 hover:underline">
{t("Посмотреть и решить")} {t("Посмотреть и решить")}
</Link> </Link>
<div className="flex basis-full flex-wrap items-center gap-2 pt-1">
{grantable.has(r.id) ? (
<form action={grantAccessButtonAction} className="flex flex-wrap items-center gap-2">
<Hidden fields={{ back: "/connections#requests", requestId: r.id }} />
<Button size="sm" name="rights" value="read" data-access-grant="read">
{t("Дать: чтение")}
</Button>
<Button size="sm" variant="secondary" name="rights" value="full" data-access-grant="full">
{t("Дать: полные права")}
</Button>
<span className="text-muted-foreground">{t("на срок")}</span>
<GrantTermSelect t={t} />
</form>
) : (
<Button asChild size="sm">
<Link href={`/connections/requests/${r.id}`}>{t("Подключить")}</Link>
</Button>
)}
<form action={denyAccessRequestAction}>
<Hidden fields={{ back: "/connections#requests", requestId: r.id }} />
<Button size="sm" variant="outline">
{t("Отказать")}
</Button>
</form>
</div>
</Card> </Card>
</li> </li>
))} ))}

View File

@ -1,5 +1,6 @@
// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal. // Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { Gauge, Hourglass, Play } from "lucide-react"; import { Gauge, Hourglass, Play } from "lucide-react";
import { import {
@ -74,7 +75,7 @@ function WindowCell({ label, w, t }: { label: string; w: WindowView | null; t: T
function accountTitle(a: AccountUsage, t: Translator): string { function accountTitle(a: AccountUsage, t: Translator): string {
const w = (l: string, v: WindowView | null) => (!v ? t("{label}: нет данных", { label: l }) : v.reset ? t("{label}: сброшено", { label: l }) : `${l}: ${Math.round(v.pct!)}%`); const w = (l: string, v: WindowView | null) => (!v ? t("{label}: нет данных", { label: l }) : v.reset ? t("{label}: сброшено", { label: l }) : `${l}: ${Math.round(v.pct!)}%`);
const limited = a.limitedUntil ? ", " + t("в лимите") : ""; const limited = a.limitedUntil ? ", " + t("в лимите") : "";
const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale)) }) : ""; const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale), { timeZone: platformZone() }) }) : "";
return t.text(a.name) + " — " + w(t("5 ч"), a.fiveHour) + ", " + w(t("7 д"), a.sevenDay) + limited + updated; return t.text(a.name) + " — " + w(t("5 ч"), a.fiveHour) + ", " + w(t("7 д"), a.sevenDay) + limited + updated;
} }

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { ago } from "@/components/common"; import { ago } from "@/components/common";
import { requireUser, words } from "@/lib/auth"; import { requireUser, words } from "@/lib/auth";
import { activeSessions, inbox } from "@/lib/queries"; import { activeSessions, inbox } from "@/lib/queries";

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import type { AgentTaskRow } from "@peppa/core"; import type { AgentTaskRow } from "@peppa/core";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";

View File

@ -26,7 +26,7 @@ const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${Math.round(n
* picture (Ctrl+V). Each file goes up at once (`POST /api/attachments`); the form carries the * picture (Ctrl+V). Each file goes up at once (`POST /api/attachments`); the form carries the
* returned ids as hidden `attachment` fields and the action links them to the message. * returned ids as hidden `attachment` fields and the action links them to the message.
*/ */
export function AttachField({ projectId, target, className }: { projectId: number; /** id of the textarea that takes drops and pastes */ target?: string; className?: string }) { export function AttachField({ projectId, target, className, touch = false }: { projectId: number; /** id of the textarea that takes drops and pastes */ target?: string; className?: string; /** PEP-274: a 44 px target on a phone */ touch?: boolean }) {
const t = useT(); const t = useT();
const inputId = useId(); const inputId = useId();
const picker = useRef<HTMLInputElement>(null); const picker = useRef<HTMLInputElement>(null);
@ -139,7 +139,7 @@ export function AttachField({ projectId, target, className }: { projectId: numbe
<button <button
type="button" type="button"
onClick={() => picker.current?.click()} onClick={() => picker.current?.click()}
className={cn("inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground", over && "border-primary bg-accent text-foreground")} className={cn("inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground", touch && "h-11 min-w-11 justify-center md:h-8 md:min-w-0", over && "border-primary bg-accent text-foreground")}
aria-label={t("Приложить файл")} aria-label={t("Приложить файл")}
title={t("Картинки, PDF, текст, Word, Excel, PowerPoint — до 5 файлов, каждый до 20 МБ. Можно перетащить файл в поле или вставить картинку из буфера.")} title={t("Картинки, PDF, текст, Word, Excel, PowerPoint — до 5 файлов, каждый до 20 МБ. Можно перетащить файл в поле или вставить картинку из буфера.")}
> >

View File

@ -1,12 +1,12 @@
"use client"; "use client";
import { useWords } from "@/components/Words"; import { useWords } from "@/components/Words";
import Link from "next/link"; import Link from "@/components/Link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react"; import { useEffect, useState, useTransition } from "react";
import { useLiveIsland } from "@/lib/live"; import { useLiveIsland } from "@/lib/live";
import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react"; import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react";
import { moveTaskCard, proposalAction } from "@/app/(app)/actions"; import { deferredAction, moveTaskCard, proposalAction } from "@/app/(app)/actions";
import { reorderTaskInline } from "@/app/(app)/board-actions"; import { reorderTaskInline } from "@/app/(app)/board-actions";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -100,7 +100,13 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
* starts/stops agents; drag it onto a card of its own column to change the order (= priority * starts/stops agents; drag it onto a card of its own column to change the order (= priority
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser). * for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
*/ */
export function Board({ cards: server, back }: { cards: Card[]; back: string }) { /** PEP-302: a finding of the acceptance agent put aside until the weekly digest. */
export interface DeferredCard {
title: string;
severity: string;
}
export function Board({ cards: server, back, projectId, deferred = [] }: { cards: Card[]; back: string; projectId?: number; deferred?: DeferredCard[] }) {
// PEP-225: status and title changes from the live channel apply in place — a card moves to the // PEP-225: status and title changes from the live channel apply in place — a card moves to the
// column of its new status at once; fresh server data (a re-render) replaces the patches. // column of its new status at once; fresh server data (a re-render) replaces the patches.
const [patches, setPatches] = useState<Map<number, Pick<Card, "status" | "title" | "column">>>(() => new Map()); const [patches, setPatches] = useState<Map<number, Pick<Card, "status" | "title" | "column">>>(() => new Map());
@ -153,7 +159,7 @@ export function Board({ cards: server, back }: { cards: Card[]; back: string })
}); });
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Proposed cards={cards.filter((x) => x.proposed)} back={back} /> <Proposed cards={cards.filter((x) => x.proposed)} back={back} projectId={projectId} deferred={deferred} />
{error && ( {error && (
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-1.5 text-sm text-destructive"> <p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-1.5 text-sm text-destructive">
{t.text(error)} {t.text(error)}
@ -315,16 +321,16 @@ const SEVERITY: Record<string, { label: string; variant: "danger" | "warn" | "mu
* dispatcher takes nothing from here. «Делать» sends a story to the backlog, «Не надо» archives * dispatcher takes nothing from here. «Делать» sends a story to the backlog, «Не надо» archives
* it and the acceptance agent will not suggest it again. Buttons are at least 44 px for a thumb. * it and the acceptance agent will not suggest it again. Buttons are at least 44 px for a thumb.
*/ */
function Proposed({ cards, back }: { cards: Card[]; back: string }) { function Proposed({ cards, back, projectId, deferred }: { cards: Card[]; back: string; projectId?: number; deferred: DeferredCard[] }) {
const t = useT(); const t = useT();
if (!cards.length) return null; if (!cards.length && !deferred.length) return null;
const ids = cards.map((c) => c.id).join(","); const ids = cards.map((c) => c.id).join(",");
const important = cards.filter((c) => c.severity !== "minor"); const important = cards.filter((c) => c.severity !== "minor");
return ( return (
<details id="proposed" data-proposed className="rounded-lg border border-dashed bg-muted/30 p-2"> <details id="proposed" data-proposed className="rounded-lg border border-dashed bg-muted/30 p-2">
<summary className="flex min-h-11 cursor-pointer items-center gap-2 px-1.5 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase"> <summary className="flex min-h-11 cursor-pointer items-center gap-2 px-1.5 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
{t("Предложено")} {t("Предложено")}
<span className="ml-auto tabular-nums">{cards.length}</span> <span className="ml-auto tabular-nums">{cards.length}{deferred.length > 0 && ` + ${deferred.length}`}</span>
</summary> </summary>
<p className="m-0 px-1.5 pb-2 text-xs text-muted-foreground">{t("Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.")}</p> <p className="m-0 px-1.5 pb-2 text-xs text-muted-foreground">{t("Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.")}</p>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
@ -362,6 +368,7 @@ function Proposed({ cards, back }: { cards: Card[]; back: string }) {
</Button> </Button>
</form> </form>
)} )}
{cards.length > 0 && (
<form action={proposalAction} className="mt-2 flex flex-wrap gap-2"> <form action={proposalAction} className="mt-2 flex flex-wrap gap-2">
<input type="hidden" name="ids" value={ids} /> <input type="hidden" name="ids" value={ids} />
<input type="hidden" name="back" value={back} /> <input type="hidden" name="back" value={back} />
@ -374,6 +381,43 @@ function Proposed({ cards, back }: { cards: Card[]; back: string }) {
{t("Отклонить всё")} {t("Отклонить всё")}
</Button> </Button>
</form> </form>
)}
{deferred.length > 0 && projectId != null && <Deferred items={deferred} projectId={projectId} back={back} />}
</details>
);
}
/**
* PEP-302: «Отложено» — what the acceptance agent found past the daily limit. It waits for the
* weekly message, but the owner sees it now and may send any item to work at once.
*/
function Deferred({ items, projectId, back }: { items: DeferredCard[]; projectId: number; back: string }) {
const t = useT();
return (
<details data-deferred className="mt-2 rounded-md border bg-card/60 p-2">
<summary className="flex min-h-11 cursor-pointer items-center gap-2 px-1.5 text-sm font-medium">
{t("Отложено")}
<span className="ml-auto font-mono text-xs tabular-nums">{items.length}</span>
</summary>
<p className="m-0 px-1.5 pb-2 text-xs text-muted-foreground">{t("Агент приёмки нашёл это сверх дневного предела. Пункты придут раз в неделю одним сообщением — или нажмите «Делать» сейчас.")}</p>
<div className="flex flex-col gap-2">
{items.map((item) => (
<article key={item.title} data-deferred-item className="flex flex-col gap-2 rounded-md border bg-card p-2.5 text-sm">
<span>{item.title}</span>
{SEVERITY[item.severity] && (
<Badge variant={SEVERITY[item.severity]!.variant} className="self-start">
{t(SEVERITY[item.severity]!.label)}
</Badge>
)}
<form action={deferredAction} className="flex flex-wrap gap-2">
<input type="hidden" name="projectId" value={String(projectId)} />
<input type="hidden" name="title" value={item.title} />
<input type="hidden" name="back" value={back} />
<ProposalButtons />
</form>
</article>
))}
</div>
</details> </details>
); );
} }

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { Search, X } from "lucide-react"; import { Search, X } from "lucide-react";
import type { ThreadList, ThreadRow } from "@peppa/core"; import type { ThreadList, ThreadRow } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge"; import { AgentBadge } from "@/components/AgentBadge";

View File

@ -2,6 +2,6 @@
import { voiceStoriesEnabled } from "@peppa/shared"; import { voiceStoriesEnabled } from "@peppa/shared";
import { DictateButton } from "@/components/DictateButton"; import { DictateButton } from "@/components/DictateButton";
export function Dictate(props: { target: string; className?: string; compact?: boolean }) { export function Dictate(props: { target: string; className?: string; compact?: boolean; touch?: boolean }) {
return voiceStoriesEnabled() ? <DictateButton {...props} /> : null; return voiceStoriesEnabled() ? <DictateButton {...props} /> : null;
} }

View File

@ -33,7 +33,7 @@ function pickMime(): string | undefined {
return undefined; return undefined;
} }
export function DictateButton({ target, className, compact = false }: { target: string; className?: string; compact?: boolean }) { export function DictateButton({ target, className, compact = false, touch = false }: { target: string; className?: string; compact?: boolean; /** PEP-274: a 44 px target on a phone */ touch?: boolean }) {
const t = useT(); const t = useT();
const [supported, setSupported] = useState(false); const [supported, setSupported] = useState(false);
const [state, setState] = useState<State>("idle"); const [state, setState] = useState<State>("idle");
@ -103,6 +103,7 @@ export function DictateButton({ target, className, compact = false }: { target:
aria-pressed={state === "recording"} aria-pressed={state === "recording"}
title={state === "recording" ? t("Остановить запись и распознать") : t("Наговорить текст голосом")} title={state === "recording" ? t("Остановить запись и распознать") : t("Наговорить текст голосом")}
data-dictate={target} data-dictate={target}
className={cn(touch && "h-11 min-w-11 md:h-8 md:min-w-0")}
> >
{state === "recording" ? <Square /> : state === "sending" ? <Loader2 className="animate-spin" /> : <Mic />} {state === "recording" ? <Square /> : state === "sending" ? <Loader2 className="animate-spin" /> : <Mic />}
{!compact && label} {!compact && label}

View File

@ -1,6 +1,7 @@
"use client"; "use client";
import { useEffect } from "react"; import { useEffect } from "react";
import { isStaleAction } from "@/lib/stale-action";
const MAX_PER_PAGE = 10; const MAX_PER_PAGE = 10;
@ -37,6 +38,8 @@ export function ErrorReporter() {
let sent = 0; let sent = 0;
const seen = new Set<string>(); const seen = new Set<string>();
const send = (type: string, message: string, stack?: string) => { const send = (type: string, message: string, stack?: string) => {
// PEP-324: a button of a page opened before an update — not a bug; StaleActionGuard reloads the page.
if (type === "UnrecognizedActionError" || isStaleAction(message)) return;
// PEP-143: «Сообщить о проблеме» attaches the page's last errors to the report. // PEP-143: «Сообщить о проблеме» attaches the page's last errors to the report.
if (message) { if (message) {
const w = window as unknown as { __peppaErrors?: Array<{ type: string; message: string; at: string }> }; const w = window as unknown as { __peppaErrors?: Array<{ type: string; message: string; at: string }> };

View File

@ -1,7 +1,8 @@
// PEP-218: production errors read from Bugsink on the server — summary, filters, rows and the // PEP-218: production errors read from Bugsink on the server — summary, filters, rows and the
// error card blocks. «Инженер» and the superadmin (`tech`) also see code places, releases, // error card blocks. «Инженер» and the superadmin (`tech`) also see code places, releases,
// stacks and tags; «Продакт» — the title, how often, when and the bug task. // stacks and tags; «Продакт» — the title, how often, when and the bug task.
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { Bug, TrendingUp } from "lucide-react"; import { Bug, TrendingUp } from "lucide-react";
import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core"; import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core";
import { m, type Translator } from "@peppa/shared/i18n"; import { m, type Translator } from "@peppa/shared/i18n";
@ -16,7 +17,7 @@ import { errorAction } from "@/app/(app)/errors/actions";
const STATE_LABEL: Record<ErrorState, string> = { unresolved: m("не решена"), resolved: m("решена"), muted: m("приглушена") }; const STATE_LABEL: Record<ErrorState, string> = { unresolved: m("не решена"), resolved: m("решена"), muted: m("приглушена") };
const STATE_TONE: Record<ErrorState, "danger" | "ok" | "muted"> = { unresolved: "danger", resolved: "ok", muted: "muted" }; const STATE_TONE: Record<ErrorState, "danger" | "ok" | "muted"> = { unresolved: "danger", resolved: "ok", muted: "muted" };
const hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit" }); const hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
/** Bugsink failed: say so; the data below (if any) is from the cache. */ /** Bugsink failed: say so; the data below (if any) is from the cache. */
export function ErrorsDown({ down, at, tech, t }: { down: boolean; at: Date | null; tech: boolean; t: Translator }) { export function ErrorsDown({ down, at, tech, t }: { down: boolean; at: Date | null; tech: boolean; t: Translator }) {
@ -91,8 +92,8 @@ export function ErrorRows({ rows, tech, from, t, showProject = true }: { rows: E
{tech && r.culprit ? <span className="max-w-full truncate font-mono">{r.culprit}</span> : null} {tech && r.culprit ? <span className="max-w-full truncate font-mono">{r.culprit}</span> : null}
{showProject ? <span>{r.bugsinkName}</span> : null} {showProject ? <span>{r.bugsinkName}</span> : null}
<span className="tabular-nums">{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span> <span className="tabular-nums">{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
<span title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span> <span title={r.firstSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
<span title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span> <span title={r.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
{/* glossary-ignore: the release is shown to «Инженер» and the superadmin only */} {/* glossary-ignore: the release is shown to «Инженер» and the superadmin only */}
{tech && r.release ? <span className="font-mono" title={r.release}>{t("релиз {sha}", { sha: r.release.slice(0, 8) })}</span> : null} {tech && r.release ? <span className="font-mono" title={r.release}>{t("релиз {sha}", { sha: r.release.slice(0, 8) })}</span> : null}
{r.taskKey ? <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key> : null} {r.taskKey ? <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key> : null}

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { FEEDBACK_ADMIN_STATUS, FEEDBACK_KIND, FEEDBACK_SIZE, FEEDBACK_USER_STATUS, feedbackTitle, type FeedbackView } from "@peppa/core"; import { FEEDBACK_ADMIN_STATUS, FEEDBACK_KIND, FEEDBACK_SIZE, FEEDBACK_USER_STATUS, feedbackTitle, type FeedbackView } from "@peppa/core";
import { Hidden } from "@/components/cards"; import { Hidden } from "@/components/cards";
import { ago, Disclosure } from "@/components/common"; import { ago, Disclosure } from "@/components/common";

View File

@ -1,6 +1,6 @@
"use client"; "use client";
import Link from "next/link"; import Link from "@/components/Link";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { CircleCheck, ImagePlus, MessageCircleWarning, X } from "lucide-react"; import { CircleCheck, ImagePlus, MessageCircleWarning, X } from "lucide-react";
@ -35,6 +35,7 @@ export function FeedbackButton() {
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [sent, setSent] = useState(false); const [sent, setSent] = useState(false);
const [over, setOver] = useState(false); const [over, setOver] = useState(false);
const lift = useComposerLift(inChat);
const add = useCallback( const add = useCallback(
(files: Iterable<File>) => { (files: Iterable<File>) => {
@ -124,8 +125,9 @@ export function FeedbackButton() {
// Sits above the «в реальном времени» indicator of LiveRefresh (the same corner). // Sits above the «в реальном времени» indicator of LiveRefresh (the same corner).
title={t("Сообщить о проблеме")} title={t("Сообщить о проблеме")}
aria-label={t("Сообщить о проблеме")} aria-label={t("Сообщить о проблеме")}
style={lift != null ? { bottom: lift } : undefined}
className={cn( className={cn(
"fixed right-3 z-30 flex h-10 cursor-pointer items-center gap-2 rounded-full border bg-card px-3 text-sm text-muted-foreground shadow-md transition-colors hover:text-foreground", "fixed right-3 z-30 flex h-11 min-w-11 justify-center cursor-pointer items-center gap-2 rounded-full border bg-card px-3 text-sm text-muted-foreground shadow-md transition-colors hover:text-foreground",
// PEP-207: in a conversation the message field is pinned to the bottom — the button goes above it, icon only. // PEP-207: in a conversation the message field is pinned to the bottom — the button goes above it, icon only.
inChat ? "bottom-[calc(11rem+env(safe-area-inset-bottom))] md:bottom-32" : "bottom-[calc(6.5rem+env(safe-area-inset-bottom))] md:bottom-12", inChat ? "bottom-[calc(11rem+env(safe-area-inset-bottom))] md:bottom-32" : "bottom-[calc(6.5rem+env(safe-area-inset-bottom))] md:bottom-12",
)} )}
@ -231,3 +233,51 @@ export function FeedbackButton() {
</> </>
); );
} }
/**
* PEP-274 (F-12): in a conversation the button stays above the top edge of the message field,
* however tall the field grew (lines, attached files) — measured, not a fixed height that the
* field outgrows on a phone. `null` — no field on the page, the classes place the button.
*/
function useComposerLift(inChat: boolean): number | null {
const [lift, setLift] = useState<number | null>(null);
useEffect(() => {
if (!inChat) return setLift(null);
let frame = 0;
let observed: Element | null = null;
const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => schedule());
const measure = () => {
frame = 0;
const box = document.querySelector("[data-chat-composer]");
if (box !== observed) {
if (observed) ro?.unobserve(observed);
if (box) ro?.observe(box);
observed = box;
}
if (!box) return setLift(null);
const top = box.getBoundingClientRect().top;
const viewport = window.visualViewport?.height ?? window.innerHeight;
// 8 px above the field; never under the bottom menu if the field scrolled out of view.
setLift(Math.max(Math.round(viewport - top + 8), 72));
};
const schedule = () => {
if (!frame) frame = requestAnimationFrame(measure);
};
schedule();
window.addEventListener("resize", schedule);
window.addEventListener("scroll", schedule, { passive: true, capture: true });
window.visualViewport?.addEventListener("resize", schedule);
// The page re-renders on live updates and may replace the field.
const mo = new MutationObserver(schedule);
mo.observe(document.body, { childList: true, subtree: true });
return () => {
if (frame) cancelAnimationFrame(frame);
ro?.disconnect();
mo.disconnect();
window.removeEventListener("resize", schedule);
window.removeEventListener("scroll", schedule, { capture: true });
window.visualViewport?.removeEventListener("resize", schedule);
};
}, [inChat]);
return lift;
}

View File

@ -0,0 +1,9 @@
// PEP-273: every link of the console goes through here. Next prefetches each visible <Link> in a
// production build; our pages are dynamic, so the home page alone made ~40 server renders per visit.
// Prefetch only where a link asks for it explicitly (`prefetch`).
import NextLink from "next/link";
import type { ComponentProps } from "react";
export default function Link({ prefetch = false, ...props }: ComponentProps<typeof NextLink>) {
return <NextLink prefetch={prefetch} {...props} />;
}

View File

@ -1,5 +1,6 @@
// Observability (PEP-202): shared pieces of the monitors list and the monitor page. // Observability (PEP-202): shared pieces of the monitors list and the monitor page.
// glossary-ignore-file: the section is for the superadmin only. // glossary-ignore-file: the section is for the superadmin only.
import { platformZone } from "@peppa/shared/time";
import { durationText, FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core"; import { durationText, FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n"; import type { Translator } from "@peppa/shared/i18n";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -26,7 +27,7 @@ export function CheckStrip({ recent, t }: { recent: MonitorView["recent"]; t: Tr
<span key={`e${i}`} className="h-full w-1.5 rounded-sm bg-muted" /> <span key={`e${i}`} className="h-full w-1.5 rounded-sm bg-muted" />
))} ))}
{recent.map((c) => ( {recent.map((c) => (
<span key={c.at} title={new Date(c.at).toLocaleString("ru-RU")} className={cn("h-full w-1.5 rounded-sm", !c.ok ? "bg-destructive" : c.degraded ? "bg-warn" : "bg-ok")} /> <span key={c.at} title={new Date(c.at).toLocaleString("ru-RU", { timeZone: platformZone() })} className={cn("h-full w-1.5 rounded-sm", !c.ok ? "bg-destructive" : c.degraded ? "bg-warn" : "bg-ok")} />
))} ))}
</div> </div>
); );
@ -125,4 +126,4 @@ export function OutageLine({ m, t, now = new Date() }: { m: MonitorView; t: Tran
return <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{parts.join(" · ")}</span>; return <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{parts.join(" · ")}</span>;
} }
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined }); const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });

View File

@ -1,4 +1,5 @@
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core"; import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core";
import { delayActionForm } from "@/app/(app)/dashboard/actions"; import { delayActionForm } from "@/app/(app)/dashboard/actions";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -13,7 +14,7 @@ import { getT } from "@/lib/i18n";
*/ */
export async function PlatformDelays({ delays, actions = false }: { delays: DelayView[]; actions?: boolean }) { export async function PlatformDelays({ delays, actions = false }: { delays: DelayView[]; actions?: boolean }) {
const t = await getT(); const t = await getT();
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined }); const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
return ( return (
<ul className="m-0 flex list-none flex-col gap-2 p-0" data-delays> <ul className="m-0 flex list-none flex-col gap-2 p-0" data-delays>
{delays.map((d) => ( {delays.map((d) => (

View File

@ -1,11 +1,12 @@
import { platformZone } from "@peppa/shared/time";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import Link from "next/link"; import Link from "@/components/Link";
import type { PoolOverview, PoolSubscriptionState } from "@peppa/core"; import type { PoolOverview, PoolSubscriptionState } from "@peppa/core";
import { intlLocale, type Locale } from "@peppa/shared/i18n"; import { intlLocale, type Locale } from "@peppa/shared/i18n";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { getT } from "@/lib/i18n"; import { getT } from "@/lib/i18n";
const hhmm = (d: Date, locale: Locale) => d.toLocaleTimeString(intlLocale(locale), { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined }); const hhmm = (d: Date, locale: Locale) => d.toLocaleTimeString(intlLocale(locale), { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
const KIND: Record<PoolSubscriptionState["provider"], string> = { claude: "Claude", codex: "ChatGPT", opencode: "OpenCode" }; const KIND: Record<PoolSubscriptionState["provider"], string> = { claude: "Claude", codex: "ChatGPT", opencode: "OpenCode" };
function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "primary" { function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "primary" {
@ -75,7 +76,7 @@ export async function PoolSwitches({ o }: { o: PoolOverview }) {
<span className="font-medium text-foreground">{t("Переключения")}</span> <span className="font-medium text-foreground">{t("Переключения")}</span>
{o.switches.map((x, i) => ( {o.switches.map((x, i) => (
<span key={i}> <span key={i}>
{x.at.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined })} {x.at.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: platformZone() })}
{" · "} {" · "}
{x.taskKey ? <Link href={`/t/${x.taskKey}`}>{x.taskKey}</Link> : t("агент №{id}", { id: x.sessionId ?? "?" })} {x.taskKey ? <Link href={`/t/${x.taskKey}`}>{x.taskKey}</Link> : t("агент №{id}", { id: x.sessionId ?? "?" })}
{": "} {": "}

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import { ExternalLink, Hourglass, KeyRound, Rocket, Wrench, X } from "lucide-react"; import { ExternalLink, Hourglass, KeyRound, Rocket, Wrench, X } from "lucide-react";
import type { ProductNeedView, ProductReview, ProjectProduct, PublishMode } from "@peppa/core"; import type { ProductNeedView, ProductReview, ProjectProduct, PublishMode } from "@peppa/core";
import { Hidden } from "@/components/cards"; import { Hidden } from "@/components/cards";
@ -56,7 +56,7 @@ export async function ProductCard({
const { task } = wording(engineer ? "engineer" : "product", t.locale); const { task } = wording(engineer ? "engineer" : "product", t.locale);
const { live, check, doneStories } = product; const { live, check, doneStories } = product;
const open = needs.filter((n) => n.open); const open = needs.filter((n) => n.open);
if (!live && !check && doneStories === 0 && !open.length && !product.preparing) return null; if (!live && !check && doneStories === 0 && !open.length && !product.preparing && !product.stalled) return null;
// PEP-145: one big button — the working product, else the version to check. // PEP-145: one big button — the working product, else the version to check.
const link = live ?? check; const link = live ?? check;
const deployed = !!(live || check); const deployed = !!(live || check);
@ -67,7 +67,7 @@ export async function ProductCard({
</p> </p>
); );
return ( return (
<section aria-label={t("Ваш продукт")} className={`mb-5 flex flex-col gap-3 rounded-xl border p-4 ${open.length ? "border-warn/50 bg-warn/5" : link ? "border-ok/40 bg-ok/5" : "border-info/40 bg-info/5"}`}> <section aria-label={t("Ваш продукт")} className={`mb-5 flex flex-col gap-3 rounded-xl border p-4 ${open.length || (!link && product.stalled) ? "border-warn/50 bg-warn/5" : link ? "border-ok/40 bg-ok/5" : "border-info/40 bg-info/5"}`}>
{link ? ( {link ? (
<div className="flex flex-wrap items-center gap-x-4 gap-y-3"> <div className="flex flex-wrap items-center gap-x-4 gap-y-3">
<div className="flex min-w-0 flex-1 basis-full flex-col gap-0.5 sm:basis-0"> <div className="flex min-w-0 flex-1 basis-full flex-col gap-0.5 sm:basis-0">
@ -97,6 +97,24 @@ export async function ProductCard({
</a> </a>
</Button> </Button>
</div> </div>
) : product.stalled ? (
// PEP-274: the wait ran out — an error in two phrases (what happened, what to do), not an endless «готовим».
<div className="flex flex-col gap-0.5" role="alert" data-product-stalled>
<span className="flex items-center gap-2 text-[15px] font-semibold">
<Wrench className="size-4 text-warn" /> {t("Ссылка на продукт пока не открывается")}
</span>
<span className="text-sm text-muted-foreground">
{product.fix ? (
<>
{t("Агент уже чинит это:")} <Link href={`/t/${product.fix.key}`}>{product.fix.key}</Link>. {t("Ссылка появится здесь сама, делать ничего не нужно.")}
</>
) : (
<>
{t("Запустить продукт пока не получилось. Если ссылка нужна срочно —")} <Link href={`/chats/${projectKey}`}>{t("напишите аналитику в чате")}</Link>.
</>
)}
</span>
</div>
) : product.preparing || doneStories > 0 ? ( ) : product.preparing || doneStories > 0 ? (
<div className="flex flex-col gap-0.5" role="status"> <div className="flex flex-col gap-0.5" role="status">
<span className="flex items-center gap-2 text-[15px] font-semibold"> <span className="flex items-center gap-2 text-[15px] font-semibold">

View File

@ -1,4 +1,4 @@
import Link from "next/link"; import Link from "@/components/Link";
import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core"; import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge"; import { AgentBadge } from "@/components/AgentBadge";
import { Empty, Key } from "@/components/common"; import { Empty, Key } from "@/components/common";
@ -58,8 +58,8 @@ function ProjectRow({ p, t, w }: { p: ProjectProgress; t: Translator; w: Words }
{t("Открыть продукт")} ↗ {t("Открыть продукт")} ↗
</a> </a>
) : p.productFix ? ( ) : p.productFix ? (
<Link href={`/t/${p.productFix}`} className="rounded-full border border-info/50 bg-info/10 px-2 text-[11px] font-medium text-foreground hover:no-underline"> <Link href={`/t/${p.productFix}`} className={cn("rounded-full border px-2 text-[11px] font-medium text-foreground hover:no-underline", p.productStalled ? "border-warn/50 bg-warn/12" : "border-info/50 bg-info/10")}>
{t("Готовим ссылку на продукт")} {p.productStalled ? t("Ссылка пока не открывается") : t("Готовим ссылку на продукт")}
</Link> </Link>
) : null} ) : null}
<span className="ml-auto text-xs text-muted-foreground"> <span className="ml-auto text-xs text-muted-foreground">

View File

@ -1,6 +1,6 @@
// PEP-218: the project's tab «Баги» — errors of its own Bugsink projects (`<KEY>-web` / // PEP-218: the project's tab «Баги» — errors of its own Bugsink projects (`<KEY>-web` /
// `<KEY>-api`), read on the server, in the same view as the superadmin's /observability. // `<KEY>-api`), read on the server, in the same view as the superadmin's /observability.
import Link from "next/link"; import Link from "@/components/Link";
import { errorScope, listErrors } from "@peppa/core"; import { errorScope, listErrors } from "@peppa/core";
import { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown } from "@/components/Errors"; import { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown } from "@/components/Errors";
import { Section } from "@/components/common"; import { Section } from "@/components/common";

View File

@ -1,5 +1,5 @@
// Runners console (PEP-38): list rows with status and limit info, and the details panel of the chosen runner. // Runners console (PEP-38): list rows with status and limit info, and the details panel of the chosen runner.
import Link from "next/link"; import Link from "@/components/Link";
import { SquareTerminal, X } from "lucide-react"; import { SquareTerminal, X } from "lucide-react";
import { FINISHED_SESSION_STATUSES, PROVIDER_NAMES, type RunnerTaskView, type SessionView, type StepView } from "@peppa/core"; import { FINISHED_SESSION_STATUSES, PROVIDER_NAMES, type RunnerTaskView, type SessionView, type StepView } from "@peppa/core";
import { RunnerStories } from "@/components/Runners"; import { RunnerStories } from "@/components/Runners";

View File

@ -1,6 +1,6 @@
"use client"; "use client";
import Link from "next/link"; import Link from "@/components/Link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useLive } from "@/lib/live"; import { useLive } from "@/lib/live";

View File

@ -0,0 +1,125 @@
"use client";
import { useEffect, useState } from "react";
import { RefreshCw } from "lucide-react";
import { unstable_isUnrecognizedActionError } from "next/navigation";
import { useT } from "@/components/I18n";
import { DraftTracker, claimReload, isStaleAction as isStaleText, isTextField, restoreDrafts, saveDrafts, takeDrafts, type FieldLike } from "@/lib/stale-action";
/**
* PEP-324: a button of a page opened before an update calls a server action the new server doesn't
* know. The page keeps the typed text, says FORGE was updated and reloads itself (once a minute at
* most — then a button). PEP-114 stays: without such a failed press the page never reloads by itself.
*/
const EVENT = "peppa:stale-action";
const RELOAD_DELAY_MS = 1500;
const tracker = new DraftTracker();
/** The «action not found on the server» error, by Next's own check first. */
export const isStaleAction = (err: unknown) => isStaleText(err, unstable_isUnrecognizedActionError);
/** Called by the error boundary (app/error.tsx) when the caught error is an unknown action. */
export function reportStaleAction() {
if (typeof window !== "undefined") window.dispatchEvent(new Event(EVENT));
}
function setFieldValue(el: FieldLike, value: string) {
const node = el as unknown as HTMLInputElement | HTMLTextAreaElement;
const proto = node instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
// The native setter + an input event: React-controlled fields see the value as typed.
Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(node, value);
node.dispatchEvent(new Event("input", { bubbles: true }));
}
/** Text fields of this name on the page. Text is kept and put back by name only when there is exactly
* one: a card per question means a field per card under the same name, and an answer must not come
* back in another question's field. */
const named = (name: string) =>
Array.from(document.getElementsByName(name)).filter((n): n is HTMLInputElement | HTMLTextAreaElement => (n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement) && isTextField(n));
const alone = (name: string) => named(name).length === 1;
function findField(key: string): FieldLike | null {
if (!key.startsWith("#")) {
const fields = named(key);
return fields.length === 1 ? fields[0]! : null;
}
const el = document.getElementById(key.slice(1));
return el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement ? el : null;
}
const path = () => location.pathname + location.search;
export function StaleActionGuard() {
const t = useT();
const [state, setState] = useState<null | "reloading" | "manual">(null);
useEffect(() => {
// Text saved before the self-reload goes back; parts of the page that mount later get a few tries.
let fields = takeDrafts(sessionStorage, path(), Date.now());
const timers: ReturnType<typeof setTimeout>[] = [];
const place = () => {
if (!fields) return;
const left = restoreDrafts(fields, findField, setFieldValue, alone);
fields = left.length ? Object.fromEntries(left.map((k) => [k, fields![k]])) : null;
};
place();
for (const ms of [300, 1000, 3000]) timers.push(setTimeout(place, ms));
const onInput = (e: Event) => {
const el = e.target;
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) tracker.input(el, alone);
};
const onSubmit = (e: Event) => tracker.submit(e.target, Date.now());
let handled = false;
const handle = () => {
if (handled) return;
handled = true;
saveDrafts(sessionStorage, path(), tracker.snapshot(Date.now()), Date.now());
if (claimReload(sessionStorage, Date.now())) {
setState("reloading");
timers.push(setTimeout(() => window.location.reload(), RELOAD_DELAY_MS));
} else setState("manual");
};
const onRejection = (e: PromiseRejectionEvent) => {
if (!isStaleAction(e.reason)) return;
e.preventDefault(); // not an error for the console or «Ошибки из прода»
handle();
};
const onError = (e: ErrorEvent) => {
if (!isStaleAction(e.error ?? e.message)) return;
e.preventDefault();
handle();
};
document.addEventListener("input", onInput, true);
document.addEventListener("submit", onSubmit, true);
window.addEventListener("unhandledrejection", onRejection);
window.addEventListener("error", onError);
window.addEventListener(EVENT, handle);
return () => {
for (const id of timers) clearTimeout(id);
document.removeEventListener("input", onInput, true);
document.removeEventListener("submit", onSubmit, true);
window.removeEventListener("unhandledrejection", onRejection);
window.removeEventListener("error", onError);
window.removeEventListener(EVENT, handle);
};
}, []);
if (!state) return null;
return (
<div role="alert" className="fixed inset-x-0 top-0 z-50 flex flex-wrap items-center justify-center gap-3 border-b border-primary/50 bg-background/95 px-4 py-2 text-sm shadow">
{state === "reloading" ? (
<span className="inline-flex items-center gap-2">
<RefreshCw className="size-3.5 animate-spin" /> {t("FORGE обновилась. Обновляем страницу — набранный текст сохранится.")}
</span>
) : (
<>
<span>{t("FORGE обновилась. Обновите страницу — набранный текст сохранится.")}</span>
<button type="button" onClick={() => window.location.reload()} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1 font-medium text-primary-foreground">
<RefreshCw className="size-3.5" /> {t("Обновить страницу")}
</button>
</>
)}
</div>
);
}

View File

@ -1,5 +1,6 @@
// Domain cards shared by pages: agent questions, runners, project list. // Domain cards shared by pages: agent questions, runners, project list.
import Link from "next/link"; import { platformZone } from "@peppa/shared/time";
import Link from "@/components/Link";
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
import { pausedProjectIds, messageDetails, questionAuthor, questionDetails, questionIsFreeText, questionState, questionText, questionType, splitForDisplay, trashDaysLeft, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; import { pausedProjectIds, messageDetails, questionAuthor, questionDetails, questionIsFreeText, questionState, questionText, questionType, splitForDisplay, trashDaysLeft, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
@ -358,4 +359,4 @@ export async function ProjectList({ projects, userId, engineer = false, analyst,
); );
} }
const hhmm = (d: Date) => new Date(d).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }); const hhmm = (d: Date) => new Date(d).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });

View File

@ -1,5 +1,5 @@
// Page building blocks of the console (PEP-38): header, sections, empty states, status badges, alerts. // Page building blocks of the console (PEP-38): header, sections, empty states, status badges, alerts.
import Link from "next/link"; import Link from "@/components/Link";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { CircleAlert, CircleCheck } from "lucide-react"; import { CircleAlert, CircleCheck } from "lucide-react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";

View File

@ -2,7 +2,9 @@
// and the runner-client mode (PEP-21): the web enqueues runner commands, the watchdog runs them. // and the runner-client mode (PEP-21): the web enqueues runner commands, the watchdog runs them.
export async function register() { export async function register() {
if (process.env.NEXT_RUNTIME !== "nodejs") return; if (process.env.NEXT_RUNTIME !== "nodejs") return;
const { beat, installCrashReporting } = await import("@peppa/core"); const { beat, installCrashReporting, installServiceLog } = await import("@peppa/core");
// PEP-291: the log also goes to $PEPPA_HOME/logs/web.log — it survives a redeploy.
installServiceLog("web");
const { db } = await import("@/lib/db"); const { db } = await import("@/lib/db");
// PEP-91: a crash of the web goes to Bugsink before launchd restarts it. // PEP-91: a crash of the web goes to Bugsink before launchd restarts it.
installCrashReporting(db, "web"); installCrashReporting(db, "web");
@ -15,6 +17,9 @@ export async function register() {
// PEP-225: the tab's WebSocket (/api/ws) — served by apps/web/server.ts in this process. // PEP-225: the tab's WebSocket (/api/ws) — served by apps/web/server.ts in this process.
const { registerLiveWs } = await import("@/lib/live-server"); const { registerLiveWs } = await import("@/lib/live-server");
registerLiveWs(); registerLiveWs();
// PEP-317: the «Gitea» page's list is ready before the first visit (never waits, never throws).
const { warmGiteaOverview } = await import("@peppa/core");
void warmGiteaOverview(db);
const version = process.env.NEXT_PUBLIC_PEPPA_VERSION; const version = process.env.NEXT_PUBLIC_PEPPA_VERSION;
const tick = () => beat(db, "web", { version }).catch((e) => console.error(`heartbeat: ${(e as Error).message}`)); const tick = () => beat(db, "web", { version }).catch((e) => console.error(`heartbeat: ${(e as Error).message}`));
void tick(); void tick();

View File

@ -0,0 +1,184 @@
// PEP-324: a page opened before an update presses a button whose server action the new server doesn't
// know (renamed, removed, or the actions key changed) — Next throws `UnrecognizedActionError`. Instead
// of «Application error» and lost text, the page says FORGE was updated, keeps what the person typed
// and reloads itself; after the reload the text goes back into the same fields.
// Pure functions over a minimal DOM/storage shape — the browser glue is components/StaleActionGuard.tsx.
const MESSAGE_RE = /Server Action "[^"]*" was not found on the server/;
/** True for the «action not found on the server» error — as an Error, from another module copy, or as text.
* `nextCheck` — `unstable_isUnrecognizedActionError` from `next/navigation` (passed in by the client
* components: this module stays free of Next imports and testable under plain node). */
export function isStaleAction(err: unknown, nextCheck?: (e: unknown) => boolean): boolean {
if (!err) return false;
if (typeof err === "string") return MESSAGE_RE.test(err);
try {
if (nextCheck?.(err)) return true;
} catch {
/* fall through to the name/message check */
}
const e = err as { name?: unknown; message?: unknown };
return e.name === "UnrecognizedActionError" || (typeof e.message === "string" && MESSAGE_RE.test(e.message));
}
export const DRAFTS_KEY = "peppa.stale-drafts";
export const RELOAD_KEY = "peppa.stale-reload";
/** A second self-reload within this window means reloading did not help: show the button instead. */
export const RELOAD_GUARD_MS = 60_000;
/** Fields of a form submitted this recently still go along: it may be the very submit that failed. */
export const SUBMIT_GRACE_MS = 15_000;
/** Saved text older than this is not restored. */
export const DRAFTS_TTL_MS = 5 * 60_000;
export const FIELD_MAX = 20_000;
export interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
/** The parts of an input/textarea the draft logic reads. */
export interface FieldLike {
tagName: string;
type?: string;
name?: string;
id?: string;
value: string;
form?: unknown;
hasAttribute(name: string): boolean;
}
/** An id React generated (`useId`) differs from one page load to the next: not an address to come back to. */
const GENERATED_ID_RE = /^(:|«|_r_|_R_)/;
/** Fields that hold a secret or a one-time code. Their text is never kept, whatever the field's type:
* a project secret or a server key is typed into a textarea, not into a password field. */
const SECRET_NAME_RE = /secret|token|passw|credential|api_?key|^(code|value|key|pin|otp)$/i;
/** A textarea or a text-like input — the fields a draft is kept for (not password, hidden, file…). */
export function isTextField(el: FieldLike): boolean {
const tag = el.tagName.toUpperCase();
if (tag === "TEXTAREA") return true;
return tag === "INPUT" && ["text", "search", "email", "url", "tel", ""].includes((el.type ?? "text").toLowerCase());
}
/**
* Where the text goes back after the reload; null — the text is not kept (password, hidden, file,
* a secret, no address…).
* The field's own lasting id first (`#answer-12`): on a page with a card per question the fields share
* a name, and an answer typed for one question must never come back in another's field. Without such
* an id — the name, but only while it is the only text field of that name on the page (`alone`).
*/
export function fieldKey(el: FieldLike, alone: (name: string) => boolean = () => true): string | null {
if (!isTextField(el)) return null;
if (el.hasAttribute("data-no-draft") || el.hasAttribute("readonly") || el.hasAttribute("disabled")) return null;
if (SECRET_NAME_RE.test(el.name ?? "") || SECRET_NAME_RE.test(el.id ?? "")) return null;
if (el.id && !GENERATED_ID_RE.test(el.id)) return `#${el.id}`;
if (el.name && alone(el.name)) return el.name;
return null;
}
interface Saved {
path: string;
at: number;
fields: Record<string, string>;
}
/** What the person typed on this page, in memory until an unknown action asks to keep it. */
export class DraftTracker {
private typed = new Map<string, { value: string; form: unknown }>();
private sent = new Map<string, { value: string; at: number }>();
/** An `input` event on a field; `alone` — is it the only text field of that name on the page (see fieldKey). */
input(el: FieldLike, alone?: (name: string) => boolean) {
const key = fieldKey(el, alone);
if (!key) return;
this.sent.delete(key);
if (el.value) this.typed.set(key, { value: el.value.slice(0, FIELD_MAX), form: el.form ?? null });
else this.typed.delete(key);
}
/** A `submit` event: the form's fields move to «sent» — after a successful submit the form is
* cleared and that text must not come back on a later reload. */
submit(form: unknown, now: number) {
for (const [key, v] of this.typed) {
if (v.form !== form) continue;
this.sent.set(key, { value: v.value, at: now });
this.typed.delete(key);
}
}
/** Fields to keep across the reload: everything typed plus what was submitted just now. */
snapshot(now: number): Record<string, string> {
const out: Record<string, string> = {};
for (const [key, v] of this.sent) if (now - v.at <= SUBMIT_GRACE_MS) out[key] = v.value;
for (const [key, v] of this.typed) out[key] = v.value;
return out;
}
}
export function saveDrafts(storage: StorageLike, path: string, fields: Record<string, string>, now: number) {
try {
if (Object.keys(fields).length === 0) storage.removeItem(DRAFTS_KEY);
else storage.setItem(DRAFTS_KEY, JSON.stringify({ path, at: now, fields } satisfies Saved));
} catch {
/* storage full or blocked: the reload still helps */
}
}
/** Saved fields for this page (and forgets them); null when none, stale, or from another page. */
export function takeDrafts(storage: StorageLike, path: string, now: number): Record<string, string> | null {
let raw: string | null = null;
try {
raw = storage.getItem(DRAFTS_KEY);
if (raw !== null) storage.removeItem(DRAFTS_KEY);
} catch {
return null;
}
if (!raw) return null;
try {
const saved = JSON.parse(raw) as Saved;
if (saved.path !== path || !(now - saved.at <= DRAFTS_TTL_MS) || !saved.fields) return null;
return saved.fields;
} catch {
return null;
}
}
/** Put saved text back into empty fields; `find` resolves a field key, `set` writes so React sees it,
* `alone` — as in fieldKey: text kept by name goes back only into the single field of that name.
* Returns the keys not placed (their field is not on the page yet, or is not the same field). */
export function restoreDrafts(fields: Record<string, string>, find: (key: string) => FieldLike | null, set: (el: FieldLike, value: string) => void, alone?: (name: string) => boolean): string[] {
const left: string[] = [];
for (const [key, value] of Object.entries(fields)) {
const el = find(key);
if (!el || fieldKey(el, alone) !== key) {
left.push(key);
continue;
}
if (!el.value) set(el, value);
}
return left;
}
/** May the page reload itself now? Records the reload; false when it already did within the guard window. */
export function claimReload(storage: StorageLike, now: number): boolean {
try {
const last = Number(storage.getItem(RELOAD_KEY) ?? 0);
if (last && now - last >= 0 && now - last < RELOAD_GUARD_MS) return false;
storage.setItem(RELOAD_KEY, String(now));
return true;
} catch {
// Without storage we cannot tell a loop from a first time: ask the person instead.
return false;
}
}
/**
* An error caught by the pages' error boundary (app/error.tsx) still has to reach «Ошибки из прода».
* Next prints a caught error with the `console.error` it took at startup — before ErrorReporter
* wrapped it — so the reporter never hears it. Raise it the way the browser raises an uncaught error
* (ErrorReporter listens to those); a browser without `reportError` — through the wrapped console.
*/
export function reportCaughtError(error: unknown, target: { reportError?: (e: unknown) => void; console: { error: (...args: unknown[]) => void } }) {
if (typeof target.reportError === "function") target.reportError(error);
else target.console.error(error);
}

26
apps/web/lib/title.ts Normal file
View File

@ -0,0 +1,26 @@
// PEP-274 (F-13): every browser tab says which page it is — «<страница> — FORGE».
import type { Metadata } from "next";
import { formatTaskKey } from "@peppa/shared";
import { productName, type Translator } from "@peppa/shared/i18n";
import { currentUser } from "@/lib/auth";
import { projectForUserByKey, taskForUser } from "@/lib/queries";
/** «часть · часть — FORGE». Parts are already translated (or are data: keys, names). */
export function pageTitle(t: Translator, ...parts: Array<string | null | undefined | false>): Metadata {
const head = parts.filter((x): x is string => !!x && !!x.trim()).join(" · ");
return { title: head ? `${head} — ${productName(t.locale)}` : productName(t.locale) };
}
/** A project page: «KEY · вкладка — FORGE»; a stranger gets no project name, only the key. */
export async function projectTitle(t: Translator, key: string, ...rest: Array<string | null | undefined | false>): Promise<Metadata> {
const user = await currentUser();
const p = user ? await projectForUserByKey(user.id, decodeURIComponent(key)).catch(() => null) : null;
return pageTitle(t, p?.key ?? null, ...rest);
}
/** A story page: «KEY-N · название — FORGE», only for whoever may see the story. */
export async function taskTitle(t: Translator, key: string): Promise<Metadata> {
const user = await currentUser();
const ref = user ? await taskForUser(user.id, decodeURIComponent(key)).catch(() => null) : null;
return ref ? pageTitle(t, formatTaskKey(ref.project.key, ref.task.number), ref.task.title) : pageTitle(t);
}

View File

@ -31,19 +31,24 @@ const config: NextConfig = {
experimental: { mcpServer: false }, experimental: { mcpServer: false },
// No Next.js badge and no «Issue» pill on the live site: a product manager must not see dev tools. // No Next.js badge and no «Issue» pill on the live site: a product manager must not see dev tools.
devIndicators: false, devIndicators: false,
// PEP-272: no «X-Powered-By: Next.js» — nothing that tells a stranger what the site runs on.
poweredByHeader: false,
// Dev chunks keep their names between edits; Cloudflare turns the dev server's `no-cache` into a // Dev chunks keep their names between edits; Cloudflare turns the dev server's `no-cache` into a
// 4 h browser cache, so a reload ran stale code. `private, no-store` is passed through as is. // 4 h browser cache, so a reload ran stale code. `private, no-store` is passed through as is.
async headers() { async headers() {
// The service worker must not sit in a browser/CDN cache, or fixes to it never arrive (PEP-55). // The service worker must not sit in a browser/CDN cache, or fixes to it never arrive (PEP-55).
const sw = { source: "/sw.js", headers: [{ key: "Cache-Control", value: "private, no-cache, max-age=0" }] }; const sw = { source: "/sw.js", headers: [{ key: "Cache-Control", value: "private, no-cache, max-age=0" }] };
// PEP-133: browser-side hardening on every page. A full script CSP is not set — Next inlines // PEP-133: browser-side hardening on every page. PEP-272: scripts only from our own origin —
// its bootstrap scripts; framing, base tag and plugins are locked instead. // Next inlines its bootstrap scripts (a nonce would need middleware and dynamic rendering of every
// page), so 'unsafe-inline' stays; 'unsafe-eval' only for React Refresh in dev.
const dev = process.env.NODE_ENV === "development";
const scriptSrc = `script-src 'self' 'unsafe-inline'${dev ? " 'unsafe-eval'" : ""}`;
const secure = [ const secure = [
{ key: "X-Content-Type-Options", value: "nosniff" }, { key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-Frame-Options", value: "DENY" }, { key: "X-Frame-Options", value: "DENY" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "Permissions-Policy", value: "camera=(), geolocation=(), payment=(), usb=(), microphone=(self)" }, { key: "Permissions-Policy", value: "camera=(), geolocation=(), payment=(), usb=(), microphone=(self)" },
{ key: "Content-Security-Policy", value: "frame-ancestors 'none'; base-uri 'self'; object-src 'none'" }, { key: "Content-Security-Policy", value: `frame-ancestors 'none'; base-uri 'self'; object-src 'none'; ${scriptSrc}; worker-src 'self'` },
...(process.env.NODE_ENV === "development" ? [] : [{ key: "Strict-Transport-Security", value: "max-age=15552000" }]), ...(process.env.NODE_ENV === "development" ? [] : [{ key: "Strict-Transport-Security", value: "max-age=15552000" }]),
]; ];
const all = { source: "/:path*", headers: secure }; const all = { source: "/:path*", headers: secure };

View File

@ -159,7 +159,11 @@ Claude Code, Codex и OpenCode закреплены в `infra/agent-versions.jso
## Полезное ## Полезное
- Здоровье: `curl -s http://127.0.0.1:3100/api/health` (коммит и сервисы). - Здоровье: `curl -s http://127.0.0.1:3100/api/health` (коммит и сервисы).
- Логи: `docker logs --tail 200 peppa-watchdog` (так же `peppa-web`, `peppa-bot`, `peppa-observer`). - Логи: `docker logs --tail 200 peppa-watchdog` (так же `peppa-web`, `peppa-bot`, `peppa-observer`) — только с
последней выкатки. Журнал, который переживает выкатку (PEP-291): `$PEPPA_HOME/logs/<сервис>.log`
(`web`, `bot`, `watchdog`, `observer`), прошлые дни — `<сервис>.log.<ГГГГ-ММ-ДД>[.N]`, 7 дней и не больше
200 МБ на сервис (`PEPPA_SERVICE_LOG_DAYS`, `PEPPA_SERVICE_LOG_MAX_MB`, выключить — `PEPPA_SERVICE_LOG=off`);
путь и размеры — `docker exec peppa-watchdog peppa status`.
- CLI платформы: `docker exec -it peppa-watchdog peppa status` (любая команда `peppa …`). - CLI платформы: `docker exec -it peppa-watchdog peppa status` (любая команда `peppa …`).
- Терминал агента: `docker exec -it peppa-watchdog peppa session attach <id>` (клиент сокета `peppa-tmux`; - Терминал агента: `docker exec -it peppa-watchdog peppa session attach <id>` (клиент сокета `peppa-tmux`;
выйти — `Ctrl-b d`, не `exit`). Логи tmux-сервера — `docker logs peppa-tmux`. выйти — `Ctrl-b d`, не `exit`). Логи tmux-сервера — `docker logs peppa-tmux`.

View File

@ -0,0 +1,302 @@
# FORGE Default Stack
Версия: 1.1.0 · принят: 2026-11-26 (PEP-283), обновлён: 2026-11-27 (PEP-314) · владелец стандарта: проект FORGE (PEP)
Единственный авторитетный источник предпочтительного технологического стека для проектов,
которые делает FORGE. Изменения — только через задачу FORGE и PR в этот файл (журнал версий внизу).
## Статус и область действия
- **Ориентир для новых проектов.** Агент, который выбирает стек нового проекта или нового
сервиса, берёт его отсюда, если у продукта нет причины поступить иначе.
- **Не требование миграции.** Существующие проекты (и сама FORGE на TypeScript/Node.js/SQLite)
не переписываются под стандарт. Сравнение FORGE со стандартом —
`docs/standards/forge-stack-audit.md` в репозитории платформы (PEP-285).
- **Отклонения разрешены**, если они обоснованы и записаны (раздел «Правило отклонений»).
- Стек проекта, уже записанный в его `AGENTS.md`, `design.md` или памяти проекта, важнее стандарта.
## Сводка
| Слой | Выбор | Применяется |
|---|---|---|
| Бэкенд — язык | Go (актуальная стабильная версия) | любой серверный код продукта |
| Бэкенд — HTTP | Gin | HTTP/JSON API |
| Бэкенд — доступ к данным | Bun (`github.com/uptrace/bun`) | работа с PostgreSQL из Go |
| Бэкенд — конфигурация | Viper | настройки из env и файлов |
| Бэкенд — архитектура | DDD-Lite | любой бэкенд с доменной логикой |
| База данных | PostgreSQL 18 | основное хранилище |
| Идентификаторы | UUIDv7 | первичные ключи новых таблиц |
| Наблюдение за запросами | pg_stat_statements | каждая база PostgreSQL |
| Публичный сайт | Next.js (App Router) | лендинги, контент, SEO |
| Аналитика | GA4 | только публичный сайт |
| CDN | Cloudflare CDN | только публичный сайт и статика |
| Защита форм | Cloudflare Turnstile | только публичные формы |
| Веб-приложение | React + TanStack + Vite | кабинеты, админки, приложения за входом |
| Код и проверки | Gitea или Forgejo (+ Actions) | репозиторий, PR, CI/CD |
| Ошибки | Bugsink (SDK Sentry) | фронт и бэк |
| Логи и метрики | Loki + Grafana | всё, что выкатывается |
| Контейнеры | Docker (+ Docker Compose) | сборка и выкатка |
## Слои
### Бэкенд: Go
- **Назначение:** серверный код продукта — API, фоновые задачи, интеграции.
- **Когда применять:** новый сервис с серверной логикой.
- **Когда не применять:** продукт без бэкенда (статический сайт); нужна библиотека, которой
в Go нет и нет разумной замены (например, ML-инференс — Python); проект уже написан на другом
языке; маленький BFF рядом с Next.js можно оставить в Next.js (Route Handlers / Server Actions).
- **Где запускать:** Go есть в образе агента FORGE; в проверках и где Go нет —
`source .gitea/peppa-tools.sh go` (скачает версию из строки `go` в `go.mod`; «go 1.27» без третьего
числа — последний выпуск ветки, как в образе агента и при сборке стенда). Выкатка —
`deploy/Dockerfile.golang` шаблона (статический бинарь `/app/server` в distroless).
### HTTP: Gin
- **Назначение:** маршрутизация, middleware, привязка и валидация запросов JSON API.
- **Когда применять:** HTTP API на Go.
- **Когда не применять:** gRPC-сервис (берите `grpc-go`), чистый воркер без HTTP (достаточно
`net/http` для `/healthz`).
- Обработчики Gin — тонкий слой: разбор запроса → вызов use-case → ответ. Доменная логика
в обработчиках не живёт и от Gin не зависит.
### Доступ к данным: Bun
- **Назначение:** запросы к PostgreSQL, отображение строк в структуры, миграции (`bun/migrate`).
- **Когда применять:** Go + PostgreSQL.
- **Когда не применять:** сложная аналитика или критичный по скорости запрос — допустим
ручной SQL через `pgx` (в том же репозитории, рядом с репозиторием домена).
- Модели Bun — деталь хранилища: они не протекают в домен, репозиторий переводит их в доменные типы.
### Конфигурация: Viper
- **Назначение:** чтение настроек из переменных окружения (основной путь), файлов и значений
по умолчанию в одну типизированную структуру при старте.
- **Когда применять:** любой Go-сервис.
- **Правила:** секреты — только из окружения (FORGE передаёт их выкатке), не из файлов
в репозитории; конфиг читается один раз в `main` и передаётся явно, без глобального `viper.Get`
по коду; приложение слушает `$PORT` и отвечает 200 на `GET /healthz`.
### База данных: PostgreSQL
- **Назначение:** основное хранилище данных продукта.
- **Когда применять:** любой продукт с постоянными данными.
- **Когда не применять:** встраиваемое или однопользовательское приложение, где отдельный
сервер базы избыточен (SQLite); чистый кэш или очередь (Redis/Valkey) — рядом, а не вместо.
- Версия — PostgreSQL 18 (образ `postgres:18`; в нём есть `uuidv7()`). Тот же сервер есть в
образе агента; временная база для тестов — `source .gitea/peppa-tools.sh postgres`
(`DATABASE_URL`, только 127.0.0.1).
- Стенд — `deploy/compose.postgres.yml` шаблона и `"database": {"service": "db"}` в `deploy`
`.peppa/project.json`: база только во внутренней сети проекта compose, без портов наружу,
пароль свой у каждого стенда (его создаёт выкладка, в репозитории и секретах его нет).
- Миграции — в репозитории, применяются при выкатке (`deploy.migrate`), только вперёд. Для образа
без оболочки — массивом: `"migrate": ["/app/server", "migrate"]`. Откат выкладки возвращает
образ, а не базу: миграция должна работать и с прошлой версией кода (сначала добавить колонку,
убрать старую — в следующей выкатке). Где данные и копии — раздел «Данные продукта и копии».
### Идентификаторы: UUIDv7
- **Назначение:** первичные ключи, сортируемые по времени создания (RFC 9562): нет конфликтов
при генерации в приложении, индекс не фрагментируется, как от UUIDv4.
- **Когда применять:** первичные ключи новых таблиц.
- **Когда не применять:** таблицы-справочники с естественным ключом; связующие таблицы
(составной ключ); там, где время создания по id раскрывать нельзя — UUIDv4.
- Генерация — в приложении (`github.com/google/uuid`, `uuid.NewV7()`) или в базе функцией
`uuidv7()` (PostgreSQL 18+). Тип колонки — `uuid`.
### Наблюдение за запросами: pg_stat_statements
- **Назначение:** статистика по запросам — что медленное и что вызывается чаще всего.
- **Когда применять:** включено в каждой базе PostgreSQL (`shared_preload_libraries`
+ `CREATE EXTENSION pg_stat_statements` в первой миграции).
- **Когда не применять:** управляемая база, где расширение недоступно — отметить в `design.md`.
### Публичный сайт: Next.js App Router
- **Назначение:** страницы, которые должны находиться поиском и быстро открываться:
лендинг, контент, документация продукта.
- **Когда применять:** публичная часть продукта, нужен SEO и серверный рендер.
- **Когда не применять:** приложение целиком за входом — это веб-приложение (React + TanStack + Vite).
- Только App Router (`app/`), не Pages Router. Серверные компоненты по умолчанию, клиентские —
где нужна интерактивность.
### Аналитика: GA4
- **Назначение:** посещаемость и воронки публичного сайта.
- **Когда применять:** публичный сайт, где владельцу нужна статистика.
- **Когда не применять:** внутренние приложения, кабинеты за входом, продукты без согласия
на сбор данных. Подключается с баннером согласия, если этого требуют правила рынка (GDPR и т. п.).
- Идентификатор GA4 — из окружения, без него код аналитики не грузится.
### CDN: Cloudflare CDN
- **Назначение:** кэш статики и страниц у пользователя, TLS, защита от перегрузки.
- **Когда применять:** публичный сайт и его статика (адреса FORGE `*.telecom.quest` уже за Cloudflare).
- **Когда не применять:** API с персональными ответами (кэш выключен заголовками), внутренние сервисы.
- Помнить: Cloudflare превращает `no-cache` в кэш браузера — статике давать неизменяемые имена
файлов, HTML — `private, no-store`, где важна свежесть.
### Защита форм: Cloudflare Turnstile
- **Назначение:** защита публичных форм (регистрация, обратная связь, вход) от ботов без капчи.
- **Когда применять:** форма, доступная без входа.
- **Когда не применять:** формы за входом, API между сервисами.
- Проверка токена — на бэкенде; ключи — из окружения; без ключа — понятный демо-режим, не падение.
### Веб-приложение: React + TanStack + Vite
- **Назначение:** приложения за входом — кабинеты, админки, рабочие экраны.
- **Когда применять:** интерфейс, которому не нужен SEO и серверный рендер.
- **Когда не применять:** публичные страницы (Next.js); простой экран, где хватит HTML с сервера.
- Состав: React + TypeScript; Vite — сборка и dev-сервер; TanStack Router — маршруты;
TanStack Query — данные с сервера (кэш, повторы, инвалидация); TanStack Table и Form — когда
есть таблицы и формы. Глобальное состояние — только если Query и URL не хватает.
### Код и проверки: Gitea или Forgejo
- **Назначение:** репозиторий, PR, ревью, CI/CD (Gitea Actions / Forgejo Actions).
- **Когда применять:** всегда; FORGE ведёт проекты в своей Gitea.
- **Не применять:** GitLab и GitHub как основное место кода проектов FORGE.
- Проверки — `.gitea/workflows/ci.yml` шаблона и `checks` в `.peppa/project.json`. Образ задания
проверок одинаков для всех стеков и Go в нём нет: инструменты ставит `.gitea/peppa-tools.sh`
(каждая команда — своя оболочка, поэтому зовёт его сама; повтор дешёвый). Для Go:
```json
{ "checks": {
"install": "source .gitea/peppa-tools.sh go && go mod download",
"lint": "source .gitea/peppa-tools.sh go && go vet ./... && test -z \"$(gofmt -l .)\"",
"test": "source .gitea/peppa-tools.sh go postgres && go test ./...",
"build": "source .gitea/peppa-tools.sh go && go build ./..." } }
```
Тесты берут базу из `DATABASE_URL`; `golangci-lint` — по желанию проекта. В задании проверок Go
скачивается за секунды, а PostgreSQL ставится пакетом на каждый прогон `test` — это 1–2 минуты;
у агента оба уже в образе.
### Ошибки: Bugsink
- **Назначение:** сбор ошибок фронта и бэка; FORGE превращает их в задачи.
- **Когда применять:** всё, что выкатывается.
- SDK — Sentry (`sentry-go`, `@sentry/react`, `@sentry/nextjs`); DSN, `release`, `environment` —
из окружения, `sendDefaultPii: false`. Sentry SaaS не используется.
### Логи и метрики: Loki + Grafana
- **Назначение:** централизованные логи (Loki) и графики, панели, оповещения (Grafana).
- **Когда применять:** всё, что выкатывается на стенды.
- Приложение пишет структурированные логи (JSON, `log/slog` в Go) в stdout; сбор — агентом
контейнеров (Promtail / Grafana Alloy), не из кода. Секреты и персональные данные в лог не пишутся.
- Если на стенде Loki ещё нет — логи в stdout всё равно в JSON, подключение позже без правок кода.
### Контейнеры: Docker
- **Назначение:** одинаковая сборка и запуск везде — локально, в проверках, на стендах.
- **Когда применять:** всё, что выкатывается.
- `Dockerfile` в корне (многоэтапная сборка; для Go — статический бинарь в `distroless`/`alpine`),
стенд — `deploy/compose.yml` шаблона. Порты и домены — по правилам FORGE (`template/RULES.md`, раздел «CD»).
## Данные продукта и копии
- **Где живут.** База стенда — том `<slug>-<окружение>_db-data` на сервере стендов FORGE
(`staging`, `prod`; превью — `<slug>-pr<N>`). Пароль базы — файл в том же томе: свой у каждого
стенда, переживает повторную выкатку и смену ключей FORGE, удалили том — новый пароль вместе
с новыми данными. Внешняя (управляемая) база вместо своей — секрет проекта `DATABASE_URL`.
- **Превью одноразовые.** Закрыли PR — стенд превью удаляется вместе с томом базы.
- **Кто делает копии.** Выкладка FORGE (`.gitea/peppa-deploy.sh`): перед каждой выкаткой
`staging` и `prod`, если база уже работает, — `pg_dump -Fc` в `backups/` того же тома, хранятся
7 последних. Копия не снялась — выкатка останавливается до миграции.
- **Восстановление** — вручную администратором FORGE на сервере стендов:
`docker compose -p <slug>-prod exec db pg_restore -U app -d app --clean /var/lib/postgresql/backups/<файл>.dump`.
- **Чего нет.** Копий вне сервера стендов и восстановления на точку во времени: копия лежит рядом
с данными и спасает от неудачной миграции, а не от потери сервера. Продукту, которому это нужно
(платежи, персональные данные), — отдельная задача FORGE с записью в `design.md`.
## DDD-Lite
Облегчённый Domain-Driven Design: модель предметной области в центре, но без церемоний, которые
не окупаются в небольшом продукте.
**Берём:**
1. **Пакеты по контекстам**, а не по слоям: `internal/orders`, `internal/billing` — а не
`internal/models`, `internal/services`. Контекст = связанная часть предметной области со своим
словарём (bounded context).
2. **Единый язык.** Имена типов и функций — слова владельца продукта (из `docs/glossary.md`).
3. **Сущности и объекты-значения.** Правила (инварианты) живут в методах типов домена:
нельзя создать заказ с отрицательной суммой — конструктор вернёт ошибку.
4. **Use-case сервисы** (`app`-слой): один сценарий — одна функция; оркестрация, транзакция,
вызовы репозиториев. Обработчики Gin зовут только их.
5. **Репозиторий — интерфейс на границе хранилища**, объявлен в пакете домена, реализован на Bun.
Домен не импортирует Bun, Gin и Viper.
6. **Ошибки домена** — типизированные (`ErrNotFound`, `ErrInvalidState`), HTTP-коды назначает
обработчик.
**Не берём по умолчанию:**
- CQRS, event sourcing, шину событий, саги — только при доказанной нужде, с записью в `design.md`.
- Интерфейс на каждый тип «на всякий случай»; фабрики фабрик; отдельные DTO на каждом слое без причины.
- Агрегаты, растянутые на всю базу: агрегат — то, что меняется одной транзакцией.
Примерная раскладка Go-сервиса:
```
cmd/server/main.go # Viper → зависимости → Gin
internal/<context>/
domain.go # сущности, объекты-значения, ошибки, интерфейс репозитория
service.go # use-cases
repo_bun.go # реализация репозитория на Bun
http.go # обработчики Gin
migrations/ # bun/migrate
```
## Словарь терминов
| Термин | Что значит в этом стандарте |
|---|---|
| **Bun** | Go ORM / query builder `github.com/uptrace/bun` (с драйвером `pgdriver`/`pgx`). **Не** JavaScript-рантайм Bun: JS-код FORGE исполняет на Node.js LTS. |
| **Gin** | HTTP-фреймворк `github.com/gin-gonic/gin`. |
| **Viper** | Библиотека конфигурации `github.com/spf13/viper`. |
| **DDD-Lite** | Облегчённый DDD — раздел выше. |
| **UUIDv7** | UUID версии 7 по RFC 9562: начинается с метки времени в миллисекундах, сортируется по времени создания. |
| **pg_stat_statements** | Расширение PostgreSQL со статистикой выполнения запросов. |
| **App Router** | Маршрутизация Next.js на каталоге `app/` (серверные компоненты), в отличие от Pages Router. |
| **TanStack** | Набор библиотек: Router (маршруты SPA), Query (данные с сервера), Table, Form. «TanStack» без уточнения = Router + Query. |
| **Vite** | Сборщик и dev-сервер фронтенда. |
| **GA4** | Google Analytics 4. |
| **Turnstile** | Защита форм Cloudflare без капчи. |
| **Gitea / Forgejo** | Равноправные варианты: Forgejo — форк Gitea с совместимым API и Actions. FORGE работает на Gitea. |
| **Bugsink** | Самостоятельно размещённый сборщик ошибок, совместимый с SDK Sentry. |
| **Loki + Grafana** | Хранилище логов (Loki) и интерфейс графиков и оповещений (Grafana). |
## Исключения: «только где уместно»
- **GA4, Cloudflare CDN, Turnstile** — только у публичного сайта и публичных форм. Внутренним
приложениям, ботам, API и библиотекам не нужны.
- **Next.js** — только публичная часть; приложение за входом — React + TanStack + Vite.
- **PostgreSQL и pg_stat_statements** — только если у продукта есть постоянные данные.
- **Loki + Grafana, Bugsink, Docker** — только у того, что выкатывается; библиотека или CLI
без стенда обходится проверками.
- Продукт без сайта (бот, библиотека, скрипт) всё равно получает страницу продукта по ссылке —
это правило FORGE (`template/RULES.md`), а не слой стека.
## Правило отклонений
Отклониться от стандарта можно, если это обосновано. Обосновано — значит записано:
1. В `design.md` change: какой слой, что выбрано вместо, **почему** (конкретная причина:
требование продукта, недоступная библиотека, существующий код, ограничение стенда,
стоимость) и что теряем.
2. В память проекта (`remember`, раздел «Решения»), одной строкой — чтобы следующий агент
не возвращался к вопросу.
Не являются причиной: «так привычнее», «так быстрее написать сейчас», «модель лучше знает X».
Отклонение без записи считается несоответствием стандарту. Владельцу продукта технический выбор
не выносится — агент решает сам (правило FORGE «PM — продакт, а не программист»).
## Журнал версий
| Версия | Дата | Задача | Что изменилось |
|---|---|---|---|
| 1.0.0 | 2026-11-26 | PEP-283 | Первая версия: слои, DDD-Lite, словарь, исключения, правило отклонений. |
| 1.1.0 | 2026-11-27 | PEP-314 | PostgreSQL 18; как запускать Go и PostgreSQL у агента, в проверках (`.gitea/peppa-tools.sh`) и на стенде (`deploy/Dockerfile.golang`, `deploy/compose.postgres.yml`); раздел «Данные продукта и копии»; команды `checks` для Go. |
Правило версий: уточнение текста — патч; новый слой или вариант — минорная; замена выбора
в слое — мажорная (с записью, что делать проектам на старом выборе).

Some files were not shown because too many files have changed in this diff Show More