From ec79b0bfaba8a12ca8c5312f9916e68c762f7fc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 14:20:02 +0500 Subject: [PATCH 001/379] PEP-98: proposal pep-98-english-ui Co-Authored-By: Claude Opus 5.5 --- openspec/changes/pep-98-english-ui/design.md | 32 +++++++++++ .../changes/pep-98-english-ui/proposal.md | 28 ++++++++++ .../specs/interface-language/spec.md | 55 +++++++++++++++++++ openspec/changes/pep-98-english-ui/tasks.md | 24 ++++++++ 4 files changed, 139 insertions(+) create mode 100644 openspec/changes/pep-98-english-ui/design.md create mode 100644 openspec/changes/pep-98-english-ui/proposal.md create mode 100644 openspec/changes/pep-98-english-ui/specs/interface-language/spec.md create mode 100644 openspec/changes/pep-98-english-ui/tasks.md diff --git a/openspec/changes/pep-98-english-ui/design.md b/openspec/changes/pep-98-english-ui/design.md new file mode 100644 index 00000000..f40ec49b --- /dev/null +++ b/openspec/changes/pep-98-english-ui/design.md @@ -0,0 +1,32 @@ +# Design: PEP-98 — язык интерфейса + +## Ключи словаря — русские строки +Текстов ~2500, большинство собирается в core/runner и уходит в бот/уведомления/веб уже +строкой. Типизированные ключи (`nav.projects`) потребовали бы переписать каждого +производителя текста и протаскивать язык получателя через все вызовы. Выбрано: +- ключ = русская строка-шаблон (`"Вопрос по {task}"`), русский словарь не нужен; +- `t(locale, key, vars)` — явный перевод (веб); +- `localizeText(locale, text)` — перевод уже собранного текста: шаблоны словаря + компилируются в регэкспы (`{x}` → `(.+?)`), сопоставление построчно (и по сегментам + HTML-разметки Telegram), захваченные значения переводятся рекурсивно (статусы, подписи). + Неизвестная строка остаётся как есть — хуже не станет. +- Производители текста в core/runner помечают шаблоны `m(key, vars)` (возвращает русский + текст как раньше) — это нужно только для проверки покрытия словаря. +- `kk` — пустой словарь с откатом на русский; PEP-99 его заполнит. + +## Где хранится язык +`settings` `user.locale:` (как `notify.prefs:`) — без миграции. Cookie `peppa_lang` +(год, `SameSite=Lax`) — источник для рендера веба; при входе берётся язык пользователя. +Неизвестное значение → `ru`. + +## Где переводим +- Веб, серверные компоненты: `const t = await getT()`; клиентские — `useT()` (словарь + текущего языка передаётся провайдером из layout, только он попадает в бандл страницы). +- Бот: обёртка над `call` клиента Bot API — `text`, `caption`, `reply_markup.inline_keyboard[].text`, + `answerCallbackQuery.text` переводятся по языку пользователя чата (кэш 60 с; группы — + язык владельца связанного проекта, иначе `ru`). +- `deliverToUser`: заголовок и текст push по языку пользователя; Telegram — в боте. +- Чаты в вебе (`chat_messages.text`) — `localizeText` при показе. + +## Название +`ru`: «Пеппа» / «Peppa»; `en`: «Peppa FACTORY» (заголовок страницы, марка входа, бот). diff --git a/openspec/changes/pep-98-english-ui/proposal.md b/openspec/changes/pep-98-english-ui/proposal.md new file mode 100644 index 00000000..2f045e67 --- /dev/null +++ b/openspec/changes/pep-98-english-ui/proposal.md @@ -0,0 +1,28 @@ +# Proposal: PEP-98 — Английская версия интерфейса + +## Why +Пеппой должны пользоваться не только русскоязычные PM. Сейчас все тексты веба, бота и +уведомлений написаны по-русски прямо в коде, языка не выбрать. + +## What Changes +- Языки `ru` (по умолчанию), `en`, `kk` (казахский словарь — PEP-99, пока откат на русский). +- Словарь «русский текст → перевод» (`@peppa/shared/i18n`): ключ — русская строка с + плейсхолдерами `{name}`; `t(locale, key, vars)` для явных текстов и `localizeText(locale, text)` + для уже собранного русского текста (сообщения core/runner, ошибки, уведомления) — + обратное сопоставление по шаблонам словаря, построчно. +- Язык пользователя: cookie `peppa_lang` и настройка `user.locale:` в `settings` + (без миграций). Переключатель RU / EN / KZ — на странице входа (cookie) и в «Настройках» + (cookie + пользователь). При входе язык пользователя переносится в cookie. Без cookie на + странице входа — по `Accept-Language`. +- Веб: серверные страницы — `getT()`, клиентские компоненты — `useT()` из `I18nProvider`; + ``; ошибки server actions — через `localizeText`. +- Бот и уведомления: Telegram-слой бота локализует `text`/`caption` и подписи кнопок по + языку получателя (чат → пользователь); `deliverToUser` локализует push; мастер-чат и чаты + проекта в вебе — при показе. +- Английское название — «Peppa FACTORY» (решение PM). +- Проверка `i18n-check`: каждый ключ `t(…)`/`m(…)` в коде есть в английском словаре; входит в тесты. + +## Impact +- Новое: `packages/shared/src/i18n/*`, `apps/web/lib/i18n*.ts(x)`, переключатель языка. +- Затронуты почти все страницы и компоненты веба (обёртка строк), бот (`api`-слой). +- Без миграций БД и новых зависимостей. diff --git a/openspec/changes/pep-98-english-ui/specs/interface-language/spec.md b/openspec/changes/pep-98-english-ui/specs/interface-language/spec.md new file mode 100644 index 00000000..9ffaa1a5 --- /dev/null +++ b/openspec/changes/pep-98-english-ui/specs/interface-language/spec.md @@ -0,0 +1,55 @@ +## ADDED Requirements + +### Requirement: Выбор языка интерфейса +Пеппа SHALL показывать веб, бота и уведомления на языке пользователя: русский (по +умолчанию), английский, казахский (до PEP-99 — с откатом на русский). Язык выбирается +переключателем RU / EN / KZ на странице входа и в «Настройках» и хранится в cookie +`peppa_lang` и у пользователя. + +#### Scenario: Переключение на английский в настройках +- **GIVEN** пользователь «anna» вошёл в веб, язык не выбран +- **WHEN** она выбирает «EN» в «Настройках» +- **THEN** меню слева показывает «Projects» вместо «Проекты» +- **AND** заголовок вкладки браузера — «Peppa FACTORY» +- **AND** настройка `user.locale:` равна `en` + +#### Scenario: Язык на странице входа +- **GIVEN** гость без cookie `peppa_lang` с браузером на `en-US` +- **WHEN** он открывает `/login` +- **THEN** страница входа показана по-английски +- **AND** выбор «RU» ставит cookie `peppa_lang=ru` и показывает страницу по-русски + +#### Scenario: Неизвестный язык +- **GIVEN** cookie `peppa_lang=de` +- **WHEN** пользователь открывает Главную +- **THEN** интерфейс показан по-русски + +### Requirement: Словарь и перевод собранного текста +Все тексты SHALL переводиться через словарь «русская строка-шаблон → перевод»; текст, +собранный по шаблону (с подставленными значениями), SHALL переводиться обратным +сопоставлением; строка без перевода показывается как есть. Каждый ключ, помеченный в коде, +SHALL иметь английский перевод — иначе падает проверка `i18n-check`. + +#### Scenario: Перевод собранного уведомления +- **GIVEN** шаблон «Стори {key} готова к ревью» с переводом «Story {key} is ready for review» +- **WHEN** пользователю с языком `en` уходит текст «Стори PEP-7 готова к ревью» +- **THEN** он получает «Story PEP-7 is ready for review» + +#### Scenario: Ключ без перевода +- **GIVEN** в коде есть `t("Новая кнопка")`, а в английском словаре такого ключа нет +- **WHEN** запускается `i18n-check` +- **THEN** проверка падает и называет ключ «Новая кнопка» + +### Requirement: Бот и уведомления на языке получателя +Сообщения Telegram-бота (текст и подписи кнопок) и браузерные push SHALL уходить на языке +пользователя-получателя. + +#### Scenario: Вопрос PM по-английски +- **GIVEN** PM с привязанным Telegram и языком `en` +- **WHEN** агент задаёт вопрос по стори +- **THEN** в Telegram приходит сообщение с английскими подписями и кнопками + +#### Scenario: Получатель без выбранного языка +- **GIVEN** PM с привязанным Telegram без настройки языка +- **WHEN** приходит уведомление «готово к ревью» +- **THEN** оно приходит по-русски, как раньше diff --git a/openspec/changes/pep-98-english-ui/tasks.md b/openspec/changes/pep-98-english-ui/tasks.md new file mode 100644 index 00000000..176b4978 --- /dev/null +++ b/openspec/changes/pep-98-english-ui/tasks.md @@ -0,0 +1,24 @@ +# Tasks: PEP-98 + +## 1. Основа +- [ ] 1.1 `@peppa/shared/i18n`: локали, `t`, `localizeText`, `m`, словари `en` (по разделам), `kk` (пустой) +- [ ] 1.2 Язык пользователя: `getUserLocale`/`setUserLocale` (core, `settings`), cookie `peppa_lang` +- [ ] 1.3 Веб: `getLocale`/`getT` (сервер), `I18nProvider`/`useT` (клиент), ``, title «Peppa FACTORY» +- [ ] 1.4 Переключатель RU/EN/KZ: страница входа и «Настройки»; при входе язык пользователя → cookie +- [ ] 1.5 Скрипт и тест `i18n-check` (ключи `t(`/`m(` в коде ↔ `en`) + +## 2. Веб +- [ ] 2.1 Каркас: Sidebar, Workspace, layout, общие компоненты, палитра, вход/велком +- [ ] 2.2 Главная, проекты, доска, страница проекта и вкладки +- [ ] 2.3 Страница стори и её вкладки, раннеры, терминал, шаги +- [ ] 2.4 Настройки, проектные настройки, подписки, админ-разделы, помощь, чаты +- [ ] 2.5 Ошибки server actions и тексты из core на страницах — через `localizeText` + +## 3. Бот и уведомления +- [ ] 3.1 Бот: локализация `text`/`caption`/кнопок/`answerCallbackQuery` по языку чата +- [ ] 3.2 `deliverToUser`: push на языке пользователя +- [ ] 3.3 Шаблоны сообщений core/runner/bot помечены `m(…)` и переведены + +## 4. Завершение +- [ ] 4.1 Тесты (`i18n.test.ts`: t, localizeText, бот по-английски), `pnpm run ci` +- [ ] 4.2 AGENTS.md, память, archive, PR -- 2.45.2 From 9611ab53ed44390cf0f53af15678c0a29d64f929 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 14:21:29 +0500 Subject: [PATCH 002/379] PEP-101: Accept compares by branch name (Gitea 1.22 404s on a SHA) and never blocks on a failed compare Co-Authored-By: Claude Opus 5.5 --- openspec/changes/pep-101-compare-by-branch/proposal.md | 8 ++++++++ .../specs/delivery-pipeline/spec.md | 8 ++++++++ openspec/changes/pep-101-compare-by-branch/tasks.md | 2 ++ packages/runner/src/ci-feedback.ts | 7 +++++-- packages/testkit/src/mock-gitea.ts | 5 ++++- 5 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 openspec/changes/pep-101-compare-by-branch/proposal.md create mode 100644 openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md create mode 100644 openspec/changes/pep-101-compare-by-branch/tasks.md diff --git a/openspec/changes/pep-101-compare-by-branch/proposal.md b/openspec/changes/pep-101-compare-by-branch/proposal.md new file mode 100644 index 00000000..c820d535 --- /dev/null +++ b/openspec/changes/pep-101-compare-by-branch/proposal.md @@ -0,0 +1,8 @@ +# Proposal: PEP-101 — «Принять» с 404 на сравнении + +## Why +PEP-93 сравнивал `main...`; Gitea 1.22 принимает в compare только имена веток и отвечает 404 — «Принять» ломался у всех PR проектов. + +## What Changes +- Сравнение по имени ветки головы PR; ошибка сравнения не блокирует мерж. +- mock-gitea: compare с SHA → 404, как настоящая. diff --git a/openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md b/openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md new file mode 100644 index 00000000..48808605 --- /dev/null +++ b/openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: Сбой проверки «нечего мержить» не блокирует приёмку +«Принять» SHALL мержить PR, даже если сравнение веток в Gitea не удалось. + +#### Scenario: Gitea не сравнила +- **WHEN** запрос сравнения веток вернул ошибку +- **THEN** PR мержится обычным путём diff --git a/openspec/changes/pep-101-compare-by-branch/tasks.md b/openspec/changes/pep-101-compare-by-branch/tasks.md new file mode 100644 index 00000000..6dbcfe68 --- /dev/null +++ b/openspec/changes/pep-101-compare-by-branch/tasks.md @@ -0,0 +1,2 @@ +- [x] 1.1 compare по ветке, ошибка не блокирует +- [x] 1.2 мок как Gitea 1.22 diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 6abdff00..26261f64 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -237,9 +237,12 @@ export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<" * one and was merged first) can't be merged — Gitea answers 405 «Please try again later». Then * the work is in main: close the PR with a note instead. True when merged, false when closed. */ -export async function mergeOrCloseEmpty(ref: TaskRef, pull: { number: number; head: { sha: string }; base: { ref: string } }, gitea: GiteaClient): Promise { +export async function mergeOrCloseEmpty(ref: TaskRef, pull: { number: number; head: { sha: string; ref: string }; base: { ref: string } }, gitea: GiteaClient): Promise { const { giteaOwner: owner, giteaRepo: repo } = ref.project; - if ((await gitea.commitsAhead(owner, repo, pull.base.ref, pull.head.sha)) === 0) { + // PEP-101: Gitea 1.22 compares branch names only (a SHA → 404); a failed compare never blocks + // the merge — Gitea itself refuses what can't be merged. + const ahead = await gitea.commitsAhead(owner, repo, pull.base.ref, pull.head.ref).catch(() => null); + if (ahead === 0) { await gitea.commentIssue(owner, repo, pull.number, `Все коммиты этого PR уже в \`${pull.base.ref}\` (вошли с другим PR) — закрываю без мержа. ${ref.key} принята.`).catch(() => {}); await gitea.closePullRequest(owner, repo, pull.number); return false; diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 5127db9a..16a6235c 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -466,7 +466,10 @@ export class MockGitea { return { status: 201, body: {} }; } if (method === "GET" && (m = sub.match(/^compare\/(.+)\.\.\.(.+)$/))) { - const n = this.ahead(r, decodeURIComponent(m[1]!), decodeURIComponent(m[2]!)); + // Like Gitea 1.22: branch names only — a commit SHA is "not found". + const [base, head] = [decodeURIComponent(m[1]!), decodeURIComponent(m[2]!)]; + if ([base, head].some((x) => /^[0-9a-f]{40}$/.test(x))) return { status: 404, body: { message: "The target couldn't be found." } }; + const n = this.ahead(r, base, head); return { status: 200, body: { total_commits: n, commits: [], files: [] } }; } if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) }; -- 2.45.2 From 2fe9b34344625764cc74d2b3565595ed03261d6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 14:23:08 +0500 Subject: [PATCH 003/379] PEP-101: tests for compare by branch name and the failed-compare fallback; archive change Co-Authored-By: Claude Opus 5.5 --- .../proposal.md | 0 .../specs/delivery-pipeline/spec.md | 15 +++++++++++ .../tasks.md | 3 +++ .../specs/delivery-pipeline/spec.md | 8 ------ .../pep-101-compare-by-branch/tasks.md | 2 -- openspec/specs/delivery-pipeline/spec.md | 14 +++++++++++ packages/testkit/test/ci-feedback.test.ts | 25 +++++++++++++++++++ 7 files changed, 57 insertions(+), 10 deletions(-) rename openspec/changes/{pep-101-compare-by-branch => archive/2026-11-15-pep-101-compare-by-branch}/proposal.md (100%) create mode 100644 openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/specs/delivery-pipeline/spec.md create mode 100644 openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/tasks.md delete mode 100644 openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md delete mode 100644 openspec/changes/pep-101-compare-by-branch/tasks.md diff --git a/openspec/changes/pep-101-compare-by-branch/proposal.md b/openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/proposal.md similarity index 100% rename from openspec/changes/pep-101-compare-by-branch/proposal.md rename to openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/proposal.md diff --git a/openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/specs/delivery-pipeline/spec.md b/openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/specs/delivery-pipeline/spec.md new file mode 100644 index 00000000..f6e61f69 --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/specs/delivery-pipeline/spec.md @@ -0,0 +1,15 @@ +## ADDED Requirements + +### Requirement: Сбой проверки «нечего мержить» не блокирует приёмку +«Принять» SHALL сравнивать основную ветку с веткой головы PR по имени ветки (Gitea 1.22 не принимает SHA в compare) и SHALL мержить PR обычным путём, если сравнение в Gitea не удалось. + +#### Scenario: Сравнение по имени ветки +- **GIVEN** стори PEP-7 в ревью, PR из ветки «task/pep-7» с зелёными проверками и коммитами сверх «main» +- **WHEN** PM жмёт «Принять» +- **THEN** PR смержен, «main» указывает на голову PR, стори в «Готово» + +#### Scenario: Gitea не сравнила +- **GIVEN** стори PEP-7 в ревью, PR с зелёными проверками +- **AND** запрос сравнения веток в Gitea отвечает 404 +- **WHEN** PM жмёт «Принять» +- **THEN** PR мержится обычным путём, PM не видит ошибки сравнения diff --git a/openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/tasks.md b/openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/tasks.md new file mode 100644 index 00000000..a3e3092f --- /dev/null +++ b/openspec/changes/archive/2026-11-15-pep-101-compare-by-branch/tasks.md @@ -0,0 +1,3 @@ +- [x] 1.1 compare по ветке, ошибка не блокирует +- [x] 1.2 мок как Gitea 1.22 +- [x] 1.3 тесты PEP-101 в ci-feedback.test.ts: compare по SHA → 404, «Принять» мержит; упавший compare не блокирует мерж diff --git a/openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md b/openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md deleted file mode 100644 index 48808605..00000000 --- a/openspec/changes/pep-101-compare-by-branch/specs/delivery-pipeline/spec.md +++ /dev/null @@ -1,8 +0,0 @@ -## ADDED Requirements - -### Requirement: Сбой проверки «нечего мержить» не блокирует приёмку -«Принять» SHALL мержить PR, даже если сравнение веток в Gitea не удалось. - -#### Scenario: Gitea не сравнила -- **WHEN** запрос сравнения веток вернул ошибку -- **THEN** PR мержится обычным путём diff --git a/openspec/changes/pep-101-compare-by-branch/tasks.md b/openspec/changes/pep-101-compare-by-branch/tasks.md deleted file mode 100644 index 6dbcfe68..00000000 --- a/openspec/changes/pep-101-compare-by-branch/tasks.md +++ /dev/null @@ -1,2 +0,0 @@ -- [x] 1.1 compare по ветке, ошибка не блокирует -- [x] 1.2 мок как Gitea 1.22 diff --git a/openspec/specs/delivery-pipeline/spec.md b/openspec/specs/delivery-pipeline/spec.md index a8478a75..b3e85c1c 100644 --- a/openspec/specs/delivery-pipeline/spec.md +++ b/openspec/specs/delivery-pipeline/spec.md @@ -128,3 +128,17 @@ #### Scenario: Скриншоты не сняты - **WHEN** снять скриншот не удалось - **THEN** превью всё равно здоровое, карточка показывает ссылку без скриншотов + +### Requirement: Сбой проверки «нечего мержить» не блокирует приёмку +«Принять» SHALL сравнивать основную ветку с веткой головы PR по имени ветки (Gitea 1.22 не принимает SHA в compare) и SHALL мержить PR обычным путём, если сравнение в Gitea не удалось. + +#### Scenario: Сравнение по имени ветки +- **GIVEN** стори PEP-7 в ревью, PR из ветки «task/pep-7» с зелёными проверками и коммитами сверх «main» +- **WHEN** PM жмёт «Принять» +- **THEN** PR смержен, «main» указывает на голову PR, стори в «Готово» + +#### Scenario: Gitea не сравнила +- **GIVEN** стори PEP-7 в ревью, PR с зелёными проверками +- **AND** запрос сравнения веток в Gitea отвечает 404 +- **WHEN** PM жмёт «Принять» +- **THEN** PR мержится обычным путём, PM не видит ошибки сравнения diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts index 2163d923..0ab1f50b 100644 --- a/packages/testkit/test/ci-feedback.test.ts +++ b/packages/testkit/test/ci-feedback.test.ts @@ -237,6 +237,31 @@ describe("Гейт ревью и мержа", () => { assert.equal((await t.ref()).task.status, "done"); }); + test("PEP-101: Gitea compares branch names only (a SHA → 404) — «Принять» still merges", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success"); + const r = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo); + const client = core.giteaForBot(); + await assert.rejects(client.commitsAhead(t.proj.giteaOwner, t.proj.giteaRepo, "main", sha), /404|couldn't be found/); + await toReview(t); + assert.equal(await runner.mergeTaskPr(await t.ref(), client), "merged"); + assert.equal(r.pulls[0]!.merged, true); + assert.equal(gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, "main"), sha); + }); + + test("PEP-101: a failing compare never blocks the merge", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success"); + await toReview(t); + const client = core.giteaForBot(); + client.commitsAhead = async () => { throw new Error("Gitea 404: The target couldn't be found."); }; + assert.equal(await runner.mergeTaskPr(await t.ref(), client), "merged"); + assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, true); + assert.equal(gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, "main"), sha); + }); + test("review gate: the agent can't move a task to review with red or running checks", async () => { const t = await ciTask({ checks: CHECKS }); const sha = t.push(); -- 2.45.2 From 1c5a1b249be3dd53f647e151d46b08f52f7a5fb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 14:23:17 +0500 Subject: [PATCH 004/379] =?UTF-8?q?PEP-101:=20memory=20=E2=80=94=20Gitea?= =?UTF-8?q?=20compare=20takes=20branch=20names=20only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .peppa/memory.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.peppa/memory.md b/.peppa/memory.md index 0d84414d..8d8630aa 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -7,6 +7,7 @@ - Общая рабочая копия может стоять на чужой ветке — работай в `git worktree`; CLI из worktree против живой системы: `set -a; . /Users/telecom/Dev/Peppa/.env; set +a` и `/packages/cli/bin/peppa …`. - Один файл e2e: `env -u NODE_TEST_CONTEXT node --test --test-reporter=spec test/.test.ts` (внутри сессии Claude без этого вывод бинарный); CLI из теста с моком в том же процессе — только async execFile, execFileSync вешает мок. - node --test из шелла Claude Code молча ничего не запускает («run() is being called recursively») — в env висит NODE_TEST_CONTEXT; запускать `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test …` +- Gitea 1.22 `GET /compare/...` принимает только имена веток — SHA даёт 404 (PEP-101); mock-gitea ведёт себя так же. Сравнение — подсказка, не гейт: при ошибке мержить обычным путём. ## Решения - Репозитории платформы — в организации Gitea `peppa` (PEP-4): `peppa/peppa`, `peppa/template`; старые адреса `peppa-bot/…` живут редиректом — не создавать `peppa-bot/peppa|template` заново. Проект переносит `peppa project transfer `. -- 2.45.2 From 355c5b19b23d15008ba1811ae07aa1067808f8b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 14:25:03 +0500 Subject: [PATCH 005/379] =?UTF-8?q?PEP-98:=20i18n=20core=20=E2=80=94=20dic?= =?UTF-8?q?tionaries,=20localizeText,=20user=20locale,=20web=20provider,?= =?UTF-8?q?=20bot=20and=20push=20localization,=20i18n-check?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/bot/src/bot.ts | 43 +++- apps/web/app/(app)/actions.ts | 5 +- apps/web/app/auth/egov/complete/route.ts | 5 + apps/web/app/auth/google/callback/route.ts | 5 + apps/web/app/auth/link/route.ts | 5 + apps/web/app/layout.tsx | 17 +- apps/web/app/locale-actions.ts | 19 ++ apps/web/components/I18n.tsx | 53 ++++ apps/web/components/Sidebar.tsx | 47 ++-- apps/web/components/ThemeToggle.tsx | 4 +- apps/web/lib/i18n.ts | 38 +++ openspec/changes/pep-98-english-ui/design.md | 13 + packages/core/src/index.ts | 1 + packages/core/src/locale.ts | 50 ++++ packages/core/src/notifications.ts | 7 +- packages/shared/package.json | 3 +- packages/shared/src/i18n/en/common.ts | 58 +++++ packages/shared/src/i18n/en/index.ts | 6 + packages/shared/src/i18n/index.ts | 250 +++++++++++++++++++ packages/shared/src/i18n/kk.ts | 4 + scripts/i18n-check.ts | 106 ++++++++ 21 files changed, 705 insertions(+), 34 deletions(-) create mode 100644 apps/web/app/locale-actions.ts create mode 100644 apps/web/components/I18n.tsx create mode 100644 apps/web/lib/i18n.ts create mode 100644 packages/core/src/locale.ts create mode 100644 packages/shared/src/i18n/en/common.ts create mode 100644 packages/shared/src/i18n/en/index.ts create mode 100644 packages/shared/src/i18n/index.ts create mode 100644 packages/shared/src/i18n/kk.ts create mode 100644 scripts/i18n-check.ts diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 0da94323..ef9a461f 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -2,7 +2,8 @@ // alerts) to the paired chat and turns button presses / replies into answers delivered // back into the agent session. Telegram is an adapter over the DB, not a remote shell: // it can only answer a specific pending question or resume/stop the session it is about. -import { reportPlatformError } from "@peppa/core"; +import { reportPlatformError, telegramChatLocale } from "@peppa/core"; +import { localizeText } from "@peppa/shared/i18n"; import { accountUsageForUser, describeUsage, @@ -146,11 +147,38 @@ export function createBot(o: BotOptions) { const ownBots = new Map(); const ownByChat = new Map(); const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api; + // ── PEP-98: messages go out in the reader's language ───────────────────────────── + // Texts are rendered in Russian everywhere (core, runner, this file); right before the Bot API + // call the text, caption and button labels are translated for the chat's user. + const readerChat = new AsyncLocalStorage(); + const localizeParams = async (params: Record): Promise> => { + const chatId = typeof params.chat_id === "number" ? params.chat_id : readerChat.getStore(); + if (chatId == null) return params; + const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const); + if (locale === "ru") return params; + const tr = (v: unknown) => (typeof v === "string" ? localizeText(locale, v) : v); + const out: Record = { ...params, text: tr(params.text), caption: tr(params.caption) }; + if (params.text === undefined) delete out.text; + if (params.caption === undefined) delete out.caption; + const markup = params.reply_markup as { inline_keyboard?: { text: string }[][]; keyboard?: ({ text: string } | string)[][] } | undefined; + if (markup && typeof markup === "object") { + const btn = (b: B): B => (typeof b === "string" ? (tr(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: tr((b as { text: string }).text) } as B) : b); + out.reply_markup = { + ...markup, + ...(markup.inline_keyboard ? { inline_keyboard: markup.inline_keyboard.map((row) => row.map(btn)) } : {}), + ...(markup.keyboard ? { keyboard: markup.keyboard.map((row) => row.map(btn)) } : {}), + }; + } + return out; + }; /** The same surface as TelegramApi, routed to the right bot per call. */ const api = { - call: (method: string, params: Record = {}, timeoutMs?: number) => pick(params.chat_id).call(method, params, timeoutMs), - sendMessage: (chatId: number, text: string, extra: Record = {}) => pick(chatId).sendMessage(chatId, text, extra), - answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text), + call: async (method: string, params: Record = {}, timeoutMs?: number) => pick(params.chat_id).call(method, await localizeParams(params), timeoutMs), + sendMessage: async (chatId: number, text: string, extra: Record = {}) => { + const p = await localizeParams({ ...extra, chat_id: chatId, text }); + return pick(chatId).sendMessage(chatId, p.text as string, p); + }, + answerCallbackQuery: async (id: string, text?: string) => pick().answerCallbackQuery(id, text === undefined ? undefined : ((await localizeParams({ text })).text as string)), getFile: (fileId: string) => pick().getFile(fileId), downloadFile: (filePath: string) => pick().downloadFile(filePath), getMe: () => o.api.getMe(), @@ -695,6 +723,13 @@ export function createBot(o: BotOptions) { } async function handleUpdate(u: TgUpdate): Promise { + // PEP-98: the person who sent the update reads the toasts and replies without a chat_id. + const reader = u.callback_query?.from?.id ?? u.message?.from?.id ?? u.message?.chat?.id; + if (reader != null) return readerChat.run(reader, () => handleUpdateIn(u)); + return handleUpdateIn(u); + } + + async function handleUpdateIn(u: TgUpdate): Promise { const botUserId = via.getStore()?.userId; if (!(await claimUpdate(db, u.update_id, botUserId))) return; try { diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 65e9ed3b..21c3c71c 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -65,6 +65,7 @@ import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { asWebActor, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); const back = (f: FormData) => str(f, "back") || "/"; @@ -75,7 +76,9 @@ async function attempt(f: FormData, fn: () => Promise): Promise + - - {children} + + + {children} + ); diff --git a/apps/web/app/locale-actions.ts b/apps/web/app/locale-actions.ts new file mode 100644 index 00000000..057984e2 --- /dev/null +++ b/apps/web/app/locale-actions.ts @@ -0,0 +1,19 @@ +"use server"; + +import { forgetChatLocales, setUserLocale } from "@peppa/core"; +import { LOCALE_COOKIE, normalizeLocale } from "@peppa/shared/i18n"; +import { cookies } from "next/headers"; +import { currentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { localeCookieOptions } from "@/lib/i18n"; + +/** PEP-98: language switcher — cookie for everyone, plus the user's setting when logged in. */ +export async function setLanguage(value: string): Promise { + const locale = normalizeLocale(value); + (await cookies()).set(LOCALE_COOKIE, locale, localeCookieOptions); + const user = await currentUser(); + if (user) { + await setUserLocale(db, user.id, locale); + forgetChatLocales(); + } +} diff --git a/apps/web/components/I18n.tsx b/apps/web/components/I18n.tsx new file mode 100644 index 00000000..dc22fea1 --- /dev/null +++ b/apps/web/components/I18n.tsx @@ -0,0 +1,53 @@ +"use client"; + +// Interface language in client components (PEP-98): the root layout passes the locale, +// `useT()` gives a translator over the bundled dictionaries. +import { createContext, useContext, useMemo, useTransition, type ReactNode } from "react"; +import { useRouter } from "next/navigation"; +import { LOCALE_LABELS, LOCALES, translator, type Locale, type Translator } from "@peppa/shared/i18n"; +import { setLanguage } from "@/app/locale-actions"; +import { cn } from "@/lib/utils"; + +const LocaleContext = createContext("ru"); + +export function I18nProvider({ locale, children }: { locale: Locale; children: ReactNode }) { + return {children}; +} + +export function useLocale(): Locale { + return useContext(LocaleContext); +} + +export function useT(): Translator { + const locale = useLocale(); + return useMemo(() => translator(locale), [locale]); +} + +/** RU / EN / KZ: saves the cookie (and the user's choice when logged in), then re-renders. */ +export function LanguageSwitcher({ className }: { className?: string }) { + const current = useLocale(); + const t = useT(); + const router = useRouter(); + const [pending, start] = useTransition(); + return ( +
+ {LOCALES.map((l) => ( + + ))} +
+ ); +} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index c8125ae7..7dc3ef3c 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -7,6 +7,8 @@ import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; +import { useT } from "@/components/I18n"; +import { m } from "@peppa/shared/i18n"; interface Item { href: string; @@ -21,45 +23,46 @@ interface Item { } const ITEMS: Item[] = [ - { href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" }, - { href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats") }, - { href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, - { href: "/runners", label: "Работа агентов", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, - { href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true }, - { href: "/welcome", label: "О Пеппе", icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true }, - { href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") }, - { href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, - { href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, - { href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, - { href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, - { href: "/platform", label: "Платформа", icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, - { href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true }, - { href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") }, + { href: "/", label: m("Главная"), icon: House, match: (p) => p === "/", count: "questions" }, + { href: "/chats", label: m("Чаты"), icon: MessagesSquare, match: (p) => p.startsWith("/chats") }, + { href: "/projects", label: m("Проекты"), icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, + { href: "/runners", label: m("Работа агентов"), icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, + { href: "/team", label: m("Команда"), icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true }, + { href: "/welcome", label: m("О Пеппе"), icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true }, + { href: "/help", label: m("Помощь"), icon: LifeBuoy, match: (p) => p.startsWith("/help") }, + { href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, + { href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, + { href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, + { href: "/journal", label: m("Журнал"), icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, + { href: "/platform", label: m("Платформа"), icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, + { href: "/users", label: m("Пользователи"), icon: Users, match: (p) => p.startsWith("/users"), admin: true }, + { href: "/settings", label: m("Настройки"), icon: Settings, match: (p) => p.startsWith("/settings") }, ]; -const COUNT_TITLE = { questions: "вопросов ждут тебя", waitingRunners: "раннеров ждут тебя" }; +const COUNT_TITLE = { questions: m("{n} вопросов ждут тебя"), waitingRunners: m("{n} раннеров ждут тебя") }; /** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number>; superadmin?: boolean }) { const path = usePathname(); + const t = useT(); return (
- фабрика + {t("фабрика")} {/* PEP-52: the palette listens for clicks on [data-open-palette]. */}